@@ -8,9 +8,15 @@ class MocoWriter
88
99 private $ jsonFile ;
1010
11- public function __construct ($ jsonFile )
11+ private $ hostname ;
12+
13+ private $ port ;
14+
15+ public function __construct ($ jsonFile , $ hostname , $ port )
1216 {
1317 $ this ->jsonFile = $ jsonFile ;
18+ $ this ->hostname = $ hostname ;
19+ $ this ->port = $ port ;
1420 }
1521
1622 public function mockHttpCall (array $ matchedRequest , array $ mockedResponse )
@@ -24,17 +30,33 @@ public function mockHttpCall(array $matchedRequest, array $mockedResponse)
2430 public function writeForMoco ()
2531 {
2632 file_put_contents ($ this ->jsonFile , json_encode ($ this ->payload ));
33+ // We need to wait for moco detecting the fixtures file changed
34+ // If not, we can perform a request on old configFile
2735 sleep (1 );
36+ $ this ->waitForMoco ();
2837 }
2938
3039 public function reset ()
3140 {
3241 $ this ->payload = [];
42+ // To avoid false positive by having the next scenario using moco response of the previous scenario
3343 $ this ->writeForMoco ();
3444 }
3545
36- public function getJsonFile ()
46+ private function waitForMoco ()
3747 {
38- return $ this ->jsonFile ;
48+ $ attempts = 0 ;
49+ $ max = 10 ;
50+ $ ip = gethostbyname ($ this ->hostname );
51+ while (false === @stream_socket_client ('tcp:// ' .$ ip .': ' .$ this ->port , $ errno , $ errstr , 5 ) && ($ attempts < $ max )) {
52+ usleep (200000 ); // 200ms
53+ $ attempts ++;
54+ }
55+
56+ if ($ max <= $ attempts ) {
57+ throw new \Exception (
58+ sprintf ('You should run moco by "bin/moco start -p %s -c %s" ' , $ this ->port , $ this ->jsonFile )
59+ );
60+ }
3961 }
4062}
0 commit comments