Skip to content

Commit 4674b52

Browse files
StephenClouseNyholm
authored andcommitted
Fix issues with binary data being stored (#188)
* Ignore binary integration tests for Void adapter * Add common trait for armoring binary data in JSON * Armor binary data in MongoDB adapter * Armor binary data in encryption layer * Update IntegrationSimpleCacheTest.php
1 parent 2c30311 commit 4674b52

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed

JsonBinaryArmoring.php

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

0 commit comments

Comments
 (0)