|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Codeception\Constraint; |
| 6 | + |
| 7 | +use Codeception\Lib\Console\Message; |
| 8 | +use PHPUnit\Framework\Constraint\Constraint; |
| 9 | + |
| 10 | +use function codecept_output_dir; |
| 11 | +use function mb_stripos; |
| 12 | +use function mb_strlen; |
| 13 | +use function mb_substr; |
| 14 | +use function preg_replace; |
| 15 | +use function sprintf; |
| 16 | +use function strtr; |
| 17 | +use function trim; |
| 18 | + |
| 19 | +class Page extends Constraint |
| 20 | +{ |
| 21 | + /** |
| 22 | + * @var string |
| 23 | + */ |
| 24 | + protected $uri; |
| 25 | + /** |
| 26 | + * @var string |
| 27 | + */ |
| 28 | + protected $string; |
| 29 | + |
| 30 | + public function __construct(string $string, string $uri = '') |
| 31 | + { |
| 32 | + $this->string = $this->normalizeText($string); |
| 33 | + $this->uri = $uri; |
| 34 | + } |
| 35 | + |
| 36 | + /** |
| 37 | + * Evaluates the constraint for parameter $other. Returns true if the |
| 38 | + * constraint is met, false otherwise. |
| 39 | + * |
| 40 | + * @param string $other Value or object to evaluate. |
| 41 | + * @return bool |
| 42 | + */ |
| 43 | + protected function matches($other): bool |
| 44 | + { |
| 45 | + $other = $this->normalizeText($other); |
| 46 | + return mb_stripos($other, $this->string, 0, 'UTF-8') !== false; |
| 47 | + } |
| 48 | + |
| 49 | + private function normalizeText(string $text): string |
| 50 | + { |
| 51 | + $text = strtr($text, "\r\n", " "); |
| 52 | + return trim(preg_replace('/\\s{2,}/', ' ', $text)); |
| 53 | + } |
| 54 | + |
| 55 | + /** |
| 56 | + * Returns a string representation of the constraint. |
| 57 | + */ |
| 58 | + public function toString(): string |
| 59 | + { |
| 60 | + return sprintf( |
| 61 | + 'contains "%s"', |
| 62 | + $this->string |
| 63 | + ); |
| 64 | + } |
| 65 | + |
| 66 | + /** |
| 67 | + * @param string $pageContent |
| 68 | + */ |
| 69 | + protected function failureDescription($pageContent): string |
| 70 | + { |
| 71 | + $message = $this->uriMessage('on page'); |
| 72 | + $message->append("\n--> "); |
| 73 | + $message->append(mb_substr($pageContent, 0, 300, 'utf-8')); |
| 74 | + if (mb_strlen($pageContent, 'utf-8') > 300) { |
| 75 | + $debugMessage = new Message( |
| 76 | + "[Content too long to display. See complete response in '" . codecept_output_dir() . "' directory]" |
| 77 | + ); |
| 78 | + $message->append("\n")->append($debugMessage); |
| 79 | + } |
| 80 | + $message->append("\n--> "); |
| 81 | + return $message->getMessage() . $this->toString(); |
| 82 | + } |
| 83 | + |
| 84 | + protected function uriMessage(string $onPage = ''): Message |
| 85 | + { |
| 86 | + if (!$this->uri) { |
| 87 | + return new Message(''); |
| 88 | + } |
| 89 | + $message = new Message($this->uri); |
| 90 | + $message->prepend(" {$onPage} "); |
| 91 | + return $message; |
| 92 | + } |
| 93 | +} |
0 commit comments