| 1 |
<?php |
| 2 |
|
| 3 |
if (!defined('ABSPATH')) { |
| 4 |
exit; |
| 5 |
} |
| 6 |
|
| 7 |
/** |
| 8 |
* Loads vendored AJAX request-contract schemas from disk. |
| 9 |
*/ |
| 10 |
class ABJ_404_Solution_AjaxRequestContractSchemaRepository { |
| 11 |
|
| 12 |
/** @var string */ |
| 13 |
private $schemaDirectory; |
| 14 |
|
| 15 |
/** @var array<string, array<string, mixed>|null> */ |
| 16 |
private $cache = array(); |
| 17 |
|
| 18 |
public function __construct(?string $schemaDirectory = null) { |
| 19 |
$this->schemaDirectory = $schemaDirectory ?? dirname(__DIR__, 2) . '/contracts/schemas'; |
| 20 |
} |
| 21 |
|
| 22 |
/** |
| 23 |
* @return array<string, mixed>|null |
| 24 |
*/ |
| 25 |
public function loadSchema(string $contractId): ?array { |
| 26 |
if (array_key_exists($contractId, $this->cache)) { |
| 27 |
return $this->cache[$contractId]; |
| 28 |
} |
| 29 |
|
| 30 |
if (!preg_match('/\Aajax-[a-z0-9-]+\z/', $contractId)) { |
| 31 |
$this->cache[$contractId] = null; |
| 32 |
return null; |
| 33 |
} |
| 34 |
|
| 35 |
$path = rtrim($this->schemaDirectory, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR |
| 36 |
. $contractId . '.schema.json'; |
| 37 |
$raw = is_file($path) ? file_get_contents($path) : false; |
| 38 |
if (!is_string($raw) || $raw === '') { |
| 39 |
$this->cache[$contractId] = null; |
| 40 |
return null; |
| 41 |
} |
| 42 |
|
| 43 |
$decoded = json_decode($raw, true); |
| 44 |
$schema = json_last_error() === JSON_ERROR_NONE |
| 45 |
? $this->asStringKeyedArray($decoded) : null; |
| 46 |
$this->cache[$contractId] = $schema; |
| 47 |
return $schema; |
| 48 |
} |
| 49 |
|
| 50 |
/** |
| 51 |
* @param mixed $value |
| 52 |
* @return array<string, mixed>|null |
| 53 |
*/ |
| 54 |
private function asStringKeyedArray($value): ?array { |
| 55 |
if (!is_array($value)) { |
| 56 |
return null; |
| 57 |
} |
| 58 |
|
| 59 |
$result = array(); |
| 60 |
foreach ($value as $key => $item) { |
| 61 |
if (!is_string($key)) { |
| 62 |
return null; |
| 63 |
} |
| 64 |
$result[$key] = $item; |
| 65 |
} |
| 66 |
return $result; |
| 67 |
} |
| 68 |
} |
| 69 |
|