IdenticalBinaryExpectation.php 1.9KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. <?php
  2. /**
  3. * A binary safe string comparison.
  4. * @package Swift
  5. * @subpackage Tests
  6. * @author Chris Corbyn
  7. */
  8. class Swift_Tests_IdenticalBinaryExpectation extends SimpleExpectation
  9. {
  10. /**
  11. * The subject to compare with.
  12. * @var string
  13. * @access private
  14. */
  15. private $_left;
  16. /**
  17. * Creates a new IdenticalBinaryExpectation comparing with $left.
  18. * @param string $left hand side of comparison
  19. * @param string $message for expecation
  20. */
  21. public function __construct($left, $message = '%s')
  22. {
  23. parent::__construct($message);
  24. $this->_left = $left;
  25. }
  26. /**
  27. * Get the given string of bytes as a stirng of Hexadecimal sequences.
  28. * @param string $binary
  29. * @return string
  30. */
  31. public function asHexString($binary)
  32. {
  33. $hex = '';
  34. $bytes = unpack('H*', $binary);
  35. foreach ($bytes as &$byte) {
  36. $byte = strtoupper($byte);
  37. }
  38. return implode('', $bytes);
  39. }
  40. /**
  41. * Test that the passed subject ($right) is identical to $left.
  42. * @param string $right, subject
  43. * @return boolean
  44. */
  45. public function test($right)
  46. {
  47. $aHex = $this->asHexString($this->_left);
  48. $bHex = $this->asHexString($right);
  49. return $aHex === $bHex;
  50. }
  51. /**
  52. * Get the message depending upon whether this expectation is satisfied.
  53. * @param $right subject to compare against
  54. * @return string
  55. */
  56. public function testMessage($right)
  57. {
  58. if ($this->test($right)) {
  59. return 'Identical binary expectation [' . $this->asHexString($right) . ']';
  60. } else {
  61. $this->_dumper=new SimpleDumper();
  62. return 'Identical binary expectation fails ' .
  63. $this->_dumper->describeDifference(
  64. $this->asHexString($this->_left),
  65. $this->asHexString($right)
  66. );
  67. }
  68. }
  69. }