CrawlerSelectorTextContains.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\DomCrawler\Test\Constraint;
  11. use PHPUnit\Framework\Constraint\Constraint;
  12. use Symfony\Component\DomCrawler\Crawler;
  13. final class CrawlerSelectorTextContains extends Constraint
  14. {
  15. private $selector;
  16. private $expectedText;
  17. private $hasNode = false;
  18. private $nodeText;
  19. public function __construct(string $selector, string $expectedText)
  20. {
  21. $this->selector = $selector;
  22. $this->expectedText = $expectedText;
  23. }
  24. /**
  25. * {@inheritdoc}
  26. */
  27. public function toString(): string
  28. {
  29. if ($this->hasNode) {
  30. return sprintf('the text "%s" of the node matching selector "%s" contains "%s"', $this->nodeText, $this->selector, $this->expectedText);
  31. }
  32. return sprintf('the Crawler has a node matching selector "%s"', $this->selector);
  33. }
  34. /**
  35. * @param Crawler $crawler
  36. *
  37. * {@inheritdoc}
  38. */
  39. protected function matches($crawler): bool
  40. {
  41. $crawler = $crawler->filter($this->selector);
  42. if (!\count($crawler)) {
  43. $this->hasNode = false;
  44. return false;
  45. }
  46. $this->hasNode = true;
  47. $this->nodeText = $crawler->text(null, true);
  48. return false !== mb_strpos($this->nodeText, $this->expectedText);
  49. }
  50. /**
  51. * @param Crawler $crawler
  52. *
  53. * {@inheritdoc}
  54. */
  55. protected function failureDescription($crawler): string
  56. {
  57. return $this->toString();
  58. }
  59. }