| 1 |
<?php |
| 2 |
|
| 3 |
namespace Extendify\Agent; |
| 4 |
|
| 5 |
defined('ABSPATH') || die('No direct access.'); |
| 6 |
|
| 7 |
// Shared by the read and write halves so they can never resolve a |
| 8 |
// different block for the same TagBlocks id. |
| 9 |
class PostBlockFinder |
| 10 |
{ |
| 11 |
// phpcs:ignore PSR12.Properties.ConstantVisibility.NotFound |
| 12 |
const REF_KEY = 'extendifyBlockRef'; |
| 13 |
|
| 14 |
// Stamps survive splices and reorders, so ids stay resolvable while a |
| 15 |
// batch reshapes the tree. serialize_blocks ignores the extra key. |
| 16 |
public static function stamp(array $blocks): array |
| 17 |
{ |
| 18 |
$seq = 0; |
| 19 |
$walk = function (array $list) use (&$walk, &$seq) { |
| 20 |
foreach ($list as $i => $block) { |
| 21 |
if (empty($block['blockName'])) { |
| 22 |
continue; |
| 23 |
} |
| 24 |
|
| 25 |
// Untagged at render time — skip whole, uncounted, to match. |
| 26 |
if (in_array($block['blockName'], TagBlocks::$ignored, true)) { |
| 27 |
continue; |
| 28 |
} |
| 29 |
|
| 30 |
$seq++; |
| 31 |
$list[$i][self::REF_KEY] = $seq; |
| 32 |
if (!empty($block['innerBlocks'])) { |
| 33 |
$list[$i]['innerBlocks'] = $walk($block['innerBlocks']); |
| 34 |
} |
| 35 |
} |
| 36 |
return $list; |
| 37 |
}; |
| 38 |
return $walk($blocks); |
| 39 |
} |
| 40 |
|
| 41 |
// Path elements alternate index / 'innerBlocks' / index … |
| 42 |
public static function pathByRef(array $blocks, int $ref) |
| 43 |
{ |
| 44 |
foreach ($blocks as $i => $block) { |
| 45 |
if (($block[self::REF_KEY] ?? null) === $ref) { |
| 46 |
return [$i]; |
| 47 |
} |
| 48 |
if (!empty($block['innerBlocks']) && is_array($block['innerBlocks'])) { |
| 49 |
$childPath = self::pathByRef($block['innerBlocks'], $ref); |
| 50 |
if ($childPath !== null) { |
| 51 |
return array_merge([$i, 'innerBlocks'], $childPath); |
| 52 |
} |
| 53 |
} |
| 54 |
} |
| 55 |
return null; |
| 56 |
} |
| 57 |
|
| 58 |
public static function find(array $blocks, int $targetId) |
| 59 |
{ |
| 60 |
$path = self::pathByRef(self::stamp($blocks), $targetId); |
| 61 |
if ($path === null) { |
| 62 |
return null; |
| 63 |
} |
| 64 |
|
| 65 |
$node = $blocks; |
| 66 |
foreach ($path as $key) { |
| 67 |
$node = $node[$key]; |
| 68 |
} |
| 69 |
return ['block' => $node, 'path' => $path]; |
| 70 |
} |
| 71 |
} |
| 72 |
|