RedisCommandConstraint.php 2.5 KB

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