PluginProbe
404 Solution / trunk
404 Solution vtrunk
4.3.5 4.3.4 4.3.3 4.3.2 4.3.1 4.3.0 4.2.0 4.1.19 4.1.18 4.1.17 4.1.16 4.1.15 4.1.13 4.1.12 4.1.11 4.1.10 4.1.9 4.1.8 4.1.7 4.1.6 4.1.5 4.1.4 4.1.3 trunk 2.30.0 All 109 releases
404-solution / includes / ajax / AjaxRequestContractSchemaRepository.php

AjaxRequestContractSchemaRepository.php in 404 Solution trunk, at includes/ajax/AjaxRequestContractSchemaRepository.php

69 lines 1.8 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
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