|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Codeception\Constraint; |
| 6 | + |
| 7 | +use Codeception\Exception\ElementNotFound; |
| 8 | +use Codeception\Lib\Console\Message; |
| 9 | +use DOMElement; |
| 10 | +use PHPUnit\Framework\ExpectationFailedException; |
| 11 | +use SebastianBergmann\Comparator\ComparisonFailure; |
| 12 | +use Symfony\Component\DomCrawler\Crawler as SymfonyDomCrawler; |
| 13 | + |
| 14 | +use function strpos; |
| 15 | + |
| 16 | +class Crawler extends Page |
| 17 | +{ |
| 18 | + /** |
| 19 | + * @param SymfonyDomCrawler $nodes |
| 20 | + * @return bool |
| 21 | + */ |
| 22 | + protected function matches($nodes): bool |
| 23 | + { |
| 24 | + if (!$nodes->count()) { |
| 25 | + return false; |
| 26 | + } |
| 27 | + if ($this->string === '') { |
| 28 | + return true; |
| 29 | + } |
| 30 | + |
| 31 | + foreach ($nodes as $node) { |
| 32 | + if (parent::matches($node->nodeValue)) { |
| 33 | + return true; |
| 34 | + } |
| 35 | + } |
| 36 | + return false; |
| 37 | + } |
| 38 | + |
| 39 | + /** |
| 40 | + * @param SymfonyDomCrawler $nodes |
| 41 | + * @param string $selector |
| 42 | + * @param ComparisonFailure|null $comparisonFailure |
| 43 | + */ |
| 44 | + protected function fail($nodes, $selector, ComparisonFailure $comparisonFailure = null): void |
| 45 | + { |
| 46 | + if (!$nodes->count()) { |
| 47 | + throw new ElementNotFound($selector, 'Element located either by name, CSS or XPath'); |
| 48 | + } |
| 49 | + |
| 50 | + $output = "Failed asserting that any element by '{$selector}'"; |
| 51 | + $output .= $this->uriMessage('on page'); |
| 52 | + $output .= " "; |
| 53 | + |
| 54 | + if ($nodes->count() < 10) { |
| 55 | + $output .= $this->nodesList($nodes); |
| 56 | + } else { |
| 57 | + $message = new Message("[total %s elements]"); |
| 58 | + $output .= $message->with($nodes->count())->getMessage(); |
| 59 | + } |
| 60 | + $output .= "\ncontains text '{$this->string}'"; |
| 61 | + |
| 62 | + throw new ExpectationFailedException( |
| 63 | + $output, |
| 64 | + $comparisonFailure |
| 65 | + ); |
| 66 | + } |
| 67 | + |
| 68 | + /** |
| 69 | + * @param DOMElement[] $other |
| 70 | + * @return string |
| 71 | + */ |
| 72 | + protected function failureDescription($other): string |
| 73 | + { |
| 74 | + $description = ''; |
| 75 | + foreach ($other as $o) { |
| 76 | + $description .= parent::failureDescription($o->textContent); |
| 77 | + } |
| 78 | + return $description; |
| 79 | + } |
| 80 | + |
| 81 | + protected function nodesList(SymfonyDomCrawler $domCrawler, string $contains = null): string |
| 82 | + { |
| 83 | + $output = ''; |
| 84 | + foreach ($domCrawler as $node) { |
| 85 | + if ($contains && strpos($node->nodeValue, $contains) === false) { |
| 86 | + continue; |
| 87 | + } |
| 88 | + $output .= "\n+ " . $node->C14N(); |
| 89 | + } |
| 90 | + return $output; |
| 91 | + } |
| 92 | +} |
0 commit comments