| 1 |
<?php |
| 2 |
/* |
| 3 |
* This file is part of the ManageWP Worker plugin. |
| 4 |
* |
| 5 |
* (c) ManageWP LLC <contact@managewp.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 |
|
| 11 |
class MWP_Http_JsonResponse extends MWP_Http_Response |
| 12 |
{ |
| 13 |
public function __construct($content, $statusCode = 200, array $headers = array()) |
| 14 |
{ |
| 15 |
$headers['content-type'] = 'application/json'; |
| 16 |
parent::__construct($content, $statusCode, $headers); |
| 17 |
} |
| 18 |
|
| 19 |
public function getContentAsString() |
| 20 |
{ |
| 21 |
$content = json_encode($this->content); |
| 22 |
|
| 23 |
if (!is_string($content)) { |
| 24 |
$invalidValues = array(); |
| 25 |
$this->fixUtf8($this->content, $invalidValues); |
| 26 |
|
| 27 |
if (is_array($this->content) && count($invalidValues) > 0) { |
| 28 |
$this->content['utf8FixedPaths'] = $invalidValues; |
| 29 |
} |
| 30 |
|
| 31 |
$content = json_encode($this->content); |
| 32 |
} |
| 33 |
|
| 34 |
return "\n" . $content; |
| 35 |
} |
| 36 |
|
| 37 |
private function fixUtf8(&$structure, array &$found = array(), &$walkedRefs = array(), array $path = array('_')) |
| 38 |
{ |
| 39 |
switch ($type = gettype($structure)) { |
| 40 |
case 'string': |
| 41 |
if (!seems_utf8($structure)) { |
| 42 |
$found[implode('.', $path)] = urlencode($structure); |
| 43 |
$structure = utf8_encode($structure); |
| 44 |
} |
| 45 |
break; |
| 46 |
/** @noinspection PhpMissingBreakStatementInspection */ |
| 47 |
case 'object': |
| 48 |
// Handle recursion. |
| 49 |
// __PHP_Incomplete_Class will return false on is_object() call. Luckily, we can still get its object hash. |
| 50 |
$objectHash = spl_object_hash($structure); |
| 51 |
if (isset($walkedRefs[$objectHash])) { |
| 52 |
break; |
| 53 |
} |
| 54 |
$walkedRefs[$objectHash] = true; |
| 55 |
// Fall through. |
| 56 |
case 'array': |
| 57 |
// Object and array are by default traversable. |
| 58 |
foreach ($structure as $key => &$value) { |
| 59 |
$valuePath = $path; |
| 60 |
$valuePath[] = $key; |
| 61 |
$this->fixUtf8($value, $found, $walkedRefs, $valuePath); |
| 62 |
} |
| 63 |
break; |
| 64 |
} |
| 65 |
} |
| 66 |
} |
| 67 |
|