1 | <?php |
||
15 | class ToContainTextExpectation implements ExpectationInterface |
||
16 | { |
||
17 | private $expectationConfig; |
||
18 | private $httpClient; |
||
19 | |||
20 | 36 | public function __construct(array $expectationConfig, array $httpClientConfig = []) |
|
25 | |||
26 | 9 | public function run($actual, $expected = '') |
|
27 | { |
||
28 | 9 | if (!filter_var($actual, FILTER_VALIDATE_URL, FILTER_FLAG_PATH_REQUIRED)) { |
|
29 | 1 | throw new \InvalidArgumentException('The actual value provided is not a valid URL'); |
|
30 | } |
||
31 | |||
32 | 8 | $response = $this->httpClient->get( |
|
33 | 8 | $actual, |
|
34 | [ |
||
35 | 8 | 'allow_redirects' => false, |
|
36 | 8 | 'http_errors' => !$this->expectationConfig['allow_errors'], |
|
37 | 8 | 'timeout' => $this->expectationConfig['timeout'] |
|
38 | 8 | ] |
|
39 | 8 | ); |
|
40 | |||
41 | 7 | if (in_array($response->getHeader('Content-Type')[0], $this->expectationConfig['crawlable_types'])) { |
|
42 | 3 | if (!$this->crawlResponse($response->getBody(), $expected)) { |
|
43 | 1 | throw new Result\ExpectationFailedException(sprintf( |
|
44 | 1 | 'Expected %s to contain the text "%s", but wasn\'t found in the textual content of any element', |
|
45 | 1 | $actual, |
|
46 | $expected |
||
47 | 1 | )); |
|
48 | } |
||
49 | 6 | } elseif (!$this->findInString($response->getBody(), $expected)) { |
|
50 | 2 | throw new Result\ExpectationFailedException(sprintf( |
|
51 | 2 | 'Expected %s to contain the text "%s", but wasn\'t found in the response', |
|
52 | 2 | $actual, |
|
53 | $expected |
||
54 | 2 | )); |
|
55 | } |
||
56 | |||
57 | 4 | return sprintf( |
|
58 | 4 | 'Found the text "%s" on %s', |
|
59 | 4 | $expected, |
|
60 | $actual |
||
61 | 4 | ); |
|
62 | } |
||
63 | |||
64 | 3 | private function crawlResponse($response, $needle) |
|
76 | |||
77 | 7 | private function findInString($haystack, $needle) |
|
87 | } |
||
88 |