Page.php 2.0 KB

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