JsonBinaryArmoring.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. /*
  3. * This file is part of php-cache organization.
  4. *
  5. * (c) 2015 Aaron Scherer <aequasi@gmail.com>, Tobias Nyholm <tobias.nyholm@gmail.com>
  6. *
  7. * This source file is subject to the MIT license that is bundled
  8. * with this source code in the file LICENSE.
  9. */
  10. namespace Cache\Adapter\Common;
  11. /**
  12. * This trait provides common routines for safely encoding binary and non-UTF8 data in
  13. * JSON. This is needed for components that use JSON natively (currently, the MongoDB
  14. * adapter and EncryptedCachePool).
  15. *
  16. * @author Stephen Clouse <stephen.clouse@noaa.gov>
  17. */
  18. trait JsonBinaryArmoring
  19. {
  20. private static $ESCAPE_JSON_CHARACTERS = [
  21. "\x00", "\x01", "\x02", "\x03", "\x04", "\x05", "\x06", "\x07",
  22. "\x08", "\x09", "\x0A", "\x0B", "\x0C", "\x0D", "\x0E", "\x0F",
  23. "\x10", "\x11", "\x12", "\x13", "\x14", "\x15", "\x16", "\x17",
  24. "\x18", "\x19", "\x1A", "\x1B", "\x1C", "\x1D", "\x1E", "\x1F",
  25. ];
  26. private static $ENCODED_JSON_CHARACTERS = [
  27. '\u0000', '\u0001', '\u0002', '\u0003', '\u0004', '\u0005', '\u0006', '\u0007',
  28. '\u0008', '\u0009', '\u000A', '\u000B', '\u000C', '\u000D', '\u000E', '\u000F',
  29. '\u0010', '\u0011', '\u0012', '\u0013', '\u0014', '\u0015', '\u0016', '\u0017',
  30. '\u0018', '\u0019', '\u001A', '\u001B', '\u001C', '\u001D', '\u001E', '\u001F',
  31. ];
  32. /**
  33. * Armor a value going into a JSON document.
  34. *
  35. * @param string $value
  36. *
  37. * @return string
  38. */
  39. protected static function jsonArmor($value)
  40. {
  41. return str_replace(
  42. static::$ESCAPE_JSON_CHARACTERS,
  43. static::$ENCODED_JSON_CHARACTERS,
  44. utf8_encode($value)
  45. );
  46. }
  47. /**
  48. * De-armor a value from a JSON document.
  49. *
  50. * @param string $value
  51. *
  52. * @return string
  53. */
  54. protected static function jsonDeArmor($value)
  55. {
  56. return utf8_decode(str_replace(
  57. static::$ENCODED_JSON_CHARACTERS,
  58. static::$ESCAPE_JSON_CHARACTERS,
  59. $value
  60. ));
  61. }
  62. }