StringContainsInOrder.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. <?php
  2. namespace Hamcrest\Text;
  3. /*
  4. Copyright (c) 2009 hamcrest.org
  5. */
  6. use Hamcrest\Description;
  7. use Hamcrest\TypeSafeMatcher;
  8. /**
  9. * Tests if the value contains a series of substrings in a constrained order.
  10. */
  11. class StringContainsInOrder extends TypeSafeMatcher
  12. {
  13. private $_substrings;
  14. public function __construct(array $substrings)
  15. {
  16. parent::__construct(self::TYPE_STRING);
  17. $this->_substrings = $substrings;
  18. }
  19. protected function matchesSafely($item)
  20. {
  21. $fromIndex = 0;
  22. foreach ($this->_substrings as $substring) {
  23. if (false === $fromIndex = strpos($item, $substring, $fromIndex)) {
  24. return false;
  25. }
  26. }
  27. return true;
  28. }
  29. protected function describeMismatchSafely($item, Description $mismatchDescription)
  30. {
  31. $mismatchDescription->appendText('was ')->appendText($item);
  32. }
  33. public function describeTo(Description $description)
  34. {
  35. $description->appendText('a string containing ')
  36. ->appendValueList('', ', ', '', $this->_substrings)
  37. ->appendText(' in order')
  38. ;
  39. }
  40. /**
  41. * Matches if value contains $substrings in a constrained order.
  42. *
  43. * @factory ...
  44. */
  45. public static function stringContainsInOrder(/* args... */)
  46. {
  47. $args = func_get_args();
  48. if (isset($args[0]) && is_array($args[0])) {
  49. $args = $args[0];
  50. }
  51. return new self($args);
  52. }
  53. }