RedisCommandConstraint.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. <?php
  2. /*
  3. * This file is part of the Predis package.
  4. *
  5. * (c) Daniele Alessandri <suppakilla@gmail.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. use Predis\Command\CommandInterface;
  11. use SebastianBergmann\Exporter\Exporter;
  12. /**
  13. * Constraint that verifies a redis command.
  14. */
  15. class RedisCommandConstraint extends \PHPUnit_Framework_Constraint
  16. {
  17. protected $commandID;
  18. protected $arguments;
  19. /**
  20. * @param string|CommandInterface $command Expected command ID or instance.
  21. * @param array $arguments Expected command arguments.
  22. */
  23. public function __construct($command = null, array $arguments = null)
  24. {
  25. if ($command instanceof CommandInterface) {
  26. $this->commandID = strtoupper($command->getId());
  27. $this->arguments = $arguments ?: $command->getArguments();
  28. } else {
  29. $this->commandID = strtoupper($command);
  30. $this->arguments = $arguments;
  31. }
  32. }
  33. /**
  34. * {@inheritdoc}
  35. */
  36. public function matches($other)
  37. {
  38. if (!$other instanceof CommandInterface) {
  39. return false;
  40. }
  41. if ($this->commandID && strtoupper($other->getId()) !== $this->commandID) {
  42. return false;
  43. }
  44. if ($this->arguments !== null) {
  45. $otherArguments = $other->getArguments();
  46. if (count($this->arguments) !== count($otherArguments)) {
  47. return false;
  48. }
  49. for ($i = 0; $i < count($this->arguments); ++$i) {
  50. if (((string) $this->arguments[$i]) !== ((string) $otherArguments[$i])) {
  51. return false;
  52. }
  53. }
  54. }
  55. return true;
  56. }
  57. /**
  58. * {@inheritdoc}
  59. *
  60. * @todo Improve output using diff when expected and actual arguments of a
  61. * command do not match.
  62. */
  63. public function toString()
  64. {
  65. $exporter = new Exporter();
  66. $string = 'is a Redis command';
  67. if ($this->commandID) {
  68. $string .= " with ID '{$this->commandID}'";
  69. }
  70. if ($this->arguments) {
  71. $string .= " and the following arguments:\n\n";
  72. $string .= $exporter->export($this->arguments);
  73. }
  74. return $string;
  75. }
  76. /**
  77. * {@inheritdoc}
  78. */
  79. protected function failureDescription($other)
  80. {
  81. $string = is_object($other) ? get_class($other) : $other;
  82. return "$string {$this->toString()}";
  83. }
  84. }