IdenticalBinaryExpectation.php 1.8KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. {
  37. $byte = strtoupper($byte);
  38. }
  39. return implode('', $bytes);
  40. }
  41. /**
  42. * Test that the passed subject ($right) is identical to $left.
  43. * @param string $right, subject
  44. * @return boolean
  45. */
  46. public function test($right)
  47. {
  48. $aHex = $this->asHexString($this->_left);
  49. $bHex = $this->asHexString($right);
  50. return $aHex === $bHex;
  51. }
  52. /**
  53. * Get the message depending upon whether this expectation is satisfied.
  54. * @param $right subject to compare against
  55. * @return string
  56. */
  57. public function testMessage($right)
  58. {
  59. if ($this->test($right))
  60. {
  61. return 'Identical binary expectation [' . $this->asHexString($right) . ']';
  62. }
  63. else
  64. {
  65. $this->_dumper=new SimpleDumper();
  66. return 'Identical binary expectation fails ' .
  67. $this->_dumper->describeDifference(
  68. $this->asHexString($this->_left),
  69. $this->asHexString($right)
  70. );
  71. }
  72. }
  73. }