refactor(compat): Prüfbausteine nach src/Compatibility, Matrix und ManifestCheck generisch

Requirement, Call, ConstantRequirement, Mirror, Problem, FeatureStatus, CompatibilityMatrix, Manifest, ManifestCheck sowie Fingerprints und LineDiff liegen jetzt im divi-freien Kern. Neu: GlobalRequirement, CompatibilityMatrix::fromProblems(), ManifestCheck-Option signatures, DiviManifestCheck::create() und DiviAreas. Divi-Verhalten unverändert.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Jan-Niclas Loosen
2026-11-06 12:03:30 +01:00
co-authored by Claude Opus 5.5
parent 9beb55e228
commit b511ef6348
92 changed files with 1185 additions and 636 deletions
+81
View File
@@ -0,0 +1,81 @@
<?php
declare(strict_types=1);
namespace LIT\MCP\Compatibility;
use ReflectionFunction;
use ReflectionMethod;
defined('ABSPATH') || exit;
/**
* One function or static method of a third-party plugin or theme that an adapter calls (spec §4.1), with the number
* of arguments the plugin passes. $args null: only its existence matters (a function the third-party code itself
* needs, e.g. et_() inside store_template in the Divi integration).
*/
final class Call implements Requirement
{
/** Key prefix of the signature fingerprints in the reference; no mirror ID starts with it. */
public const SIGNATURE_PREFIX = 'sig:';
/**
* @param string $symbol "function_name" or "Fully\Qualified\Class::method".
* @param list<Capability> $features [] = the default of the manifest.
*/
public function __construct(
public readonly string $symbol,
public readonly ?int $args = null,
private readonly array $features = []
) {
}
public function className(): ?string
{
return str_contains($this->symbol, '::') ? ltrim(explode('::', $this->symbol, 2)[0], '\\') : null;
}
/** The key of this call's signature fingerprint in the reference: "sig:" and the symbol without a leading backslash. */
public function signatureKey(): string
{
return self::SIGNATURE_PREFIX . ltrim($this->symbol, '\\');
}
public function member(): string
{
return str_contains($this->symbol, '::') ? explode('::', $this->symbol, 2)[1] : $this->symbol;
}
/** The function or method exists and takes the number of arguments the adapter passes. */
public function accepts(): bool
{
$class = $this->className();
if ($class === null) {
if (! function_exists($this->member())) {
return false;
}
$reflection = new ReflectionFunction($this->member());
} else {
if (! method_exists($class, $this->member())) {
return false;
}
$reflection = new ReflectionMethod($class, $this->member());
}
return $this->args === null
|| ($reflection->getNumberOfRequiredParameters() <= $this->args
&& ($reflection->isVariadic() || $reflection->getNumberOfParameters() >= $this->args));
}
public function features(): array
{
return $this->features;
}
public function label(): string
{
$class = $this->className();
return ($class === null ? '' : SourceFingerprint::shortName($class) . '::') . $this->member() . '()';
}
}
+230
View File
@@ -0,0 +1,230 @@
<?php
declare(strict_types=1);
namespace LIT\MCP\Compatibility;
defined('ABSPATH') || exit;
/**
* The release state of every capability of one integration (E1). A capability the constructor did not get a status
* for is incompatible (fail closed), so of() always answers. The overall state of the matrix is its worst state.
*/
final class CompatibilityMatrix
{
public const MISSING = 'Für diese Fähigkeit liegt kein Prüfergebnis vor.';
/** Where a release comes from: the plugin's list of tested versions, the site's database, the automatic check. */
public const SOURCE_CODE = 'code';
public const SOURCE_DATABASE = 'database';
public const SOURCE_AUTO = 'auto';
/** @var array<string, FeatureStatus> keyed by capability ID, in the order of the capabilities */
private array $features = [];
/**
* @param list<Capability> $capabilities
* @param array<string, FeatureStatus> $statuses keyed by capability ID
*/
public function __construct(array $capabilities, array $statuses)
{
foreach ($capabilities as $capability) {
$status = $statuses[$capability->id()] ?? null;
$this->features[$capability->id()] = $status instanceof FeatureStatus && $status->feature === $capability
? $status
: self::missing($capability);
}
}
private static function missing(Capability $capability): FeatureStatus
{
return new FeatureStatus($capability, ReleaseState::Incompatible, [self::MISSING]);
}
/** @param list<Capability> $capabilities */
public static function allReleased(array $capabilities, string $source = self::SOURCE_CODE): self
{
return self::uniform($capabilities, ReleaseState::Released, [], $source);
}
/** @param list<Capability> $capabilities */
public static function allIncompatible(array $capabilities, string $problem): self
{
return self::uniform($capabilities, ReleaseState::Incompatible, [$problem]);
}
/**
* Every capability in $state – the matrix of a status built without one (ReleaseStatus' constructor).
*
* @param list<Capability> $capabilities
* @param list<string> $problems
*/
public static function uniform(
array $capabilities,
ReleaseState $state,
array $problems = [],
?string $source = null
): self {
$released = $state === ReleaseState::Released;
$statuses = [];
foreach ($capabilities as $capability) {
$statuses[$capability->id()] = new FeatureStatus(
$capability,
$state,
$released ? [] : $problems,
$released ? ($source ?? self::SOURCE_CODE) : null
);
}
return new self($capabilities, $statuses);
}
/**
* The matrix the problems of a check add up to (spec §5.2–§5.4): per capability a hard problem (call, mirror,
* constant) makes it incompatible, released version or not; a released version releases every other one; without
* release the automatic release decides (changed signature: incompatible, missing reference: untested, no
* problem: released from SOURCE_AUTO), else it is untested.
*
* @param list<Capability> $capabilities
* @param list<Problem> $problems
* @param string|null $source SOURCE_CODE or SOURCE_DATABASE for a released version, else null.
* @param bool $automatic The automatic release applies (no release, known version, filter on).
*/
public static function fromProblems(array $capabilities, array $problems, ?string $source, bool $automatic): self
{
$statuses = [];
foreach ($capabilities as $capability) {
$concerning = array_values(array_filter(
$problems,
static fn (Problem $problem): bool => $problem->concerns($capability)
));
$statuses[$capability->id()] = self::statusOf($capability, $concerning, $source, $automatic);
}
return new self($capabilities, $statuses);
}
/** @param list<Problem> $problems The problems concerning $capability. */
private static function statusOf(
Capability $capability,
array $problems,
?string $source,
bool $automatic
): FeatureStatus {
$hard = array_filter($problems, static fn (Problem $problem): bool => $problem->isHard());
if ($hard !== []) {
return new FeatureStatus($capability, ReleaseState::Incompatible, self::labels($hard));
}
if ($source !== null) {
return new FeatureStatus($capability, ReleaseState::Released, [], $source);
}
if (! $automatic) {
return new FeatureStatus($capability, ReleaseState::Untested, self::labels($problems));
}
$changed = array_filter($problems, static fn (Problem $problem): bool => $problem->kind === Problem::SIGNATURE);
if ($changed !== []) {
return new FeatureStatus($capability, ReleaseState::Incompatible, self::labels($changed));
}
return $problems === []
? new FeatureStatus($capability, ReleaseState::Released, [], self::SOURCE_AUTO)
: new FeatureStatus($capability, ReleaseState::Untested, self::labels($problems));
}
/**
* @param array<int, Problem> $problems
* @return list<string>
*/
private static function labels(array $problems): array
{
return array_values(array_map(static fn (Problem $problem): string => $problem->label, $problems));
}
public function of(Capability $feature): FeatureStatus
{
return $this->features[$feature->id()] ?? self::missing($feature);
}
/** @param list<Capability> $features */
public function usable(array $features): bool
{
foreach ($features as $feature) {
if (! $this->of($feature)->usable()) {
return false;
}
}
return true;
}
/**
* The statuses of those of $features that are not usable – each once, in the order of $features. The one answer
* to "what locks this call" for the gates, the adapters and the
* refusals.
*
* @param list<Capability> $features
* @return list<FeatureStatus>
*/
public function locked(array $features): array
{
$locked = [];
foreach ($features as $feature) {
$status = $this->of($feature);
if (! $status->usable()) {
$locked[$feature->id()] = $status;
}
}
return array_values($locked);
}
/** @return list<FeatureStatus> */
public function unusable(): array
{
return array_values(array_filter(
$this->features,
static fn (FeatureStatus $status): bool => ! $status->usable()
));
}
/** Incompatible before untested before released. */
public function state(): ReleaseState
{
$states = array_map(static fn (FeatureStatus $status): ReleaseState => $status->state, $this->features);
return match (true) {
in_array(ReleaseState::Incompatible, $states, true) => ReleaseState::Incompatible,
in_array(ReleaseState::Untested, $states, true) => ReleaseState::Untested,
default => ReleaseState::Released,
};
}
/** The common source of a fully released matrix; null when not all released or the sources differ. */
public function source(): ?string
{
$sources = array_unique(array_map(
static fn (FeatureStatus $status): string => (string) $status->source,
$this->features
));
return $this->state() === ReleaseState::Released && count($sources) === 1 ? (string) reset($sources) : null;
}
/** @return list<string> Every problem label once, in feature order. */
public function problems(): array
{
$problems = [];
foreach ($this->features as $status) {
$problems = array_merge($problems, $status->problems);
}
return array_values(array_unique($problems));
}
/** @return list<array{id: string, label: string, state: string, problems: list<string>, source: ?string}> */
public function toArray(): array
{
return array_values(array_map(static fn (FeatureStatus $status): array => $status->toArray(), $this->features));
}
}
+26
View File
@@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace LIT\MCP\Compatibility;
defined('ABSPATH') || exit;
/** A constant of a third-party plugin or theme that an adapter reads (spec §4.1); it must be defined. */
final class ConstantRequirement implements Requirement
{
/** @param list<Capability> $features [] = the default of the manifest. */
public function __construct(public readonly string $name, private readonly array $features = [])
{
}
public function label(): string
{
return 'Konstante ' . $this->name;
}
public function features(): array
{
return $this->features;
}
}
+49
View File
@@ -0,0 +1,49 @@
<?php
declare(strict_types=1);
namespace LIT\MCP\Compatibility;
defined('ABSPATH') || exit;
/** The release state of one capability (E1): released (with its source), untested or incompatible. */
final class FeatureStatus
{
/**
* @param list<string> $problems Labels of the problems behind the state (Problem::$label).
* @param string|null $source For a released feature: CompatibilityMatrix::SOURCE_CODE, SOURCE_DATABASE or
* SOURCE_AUTO; null otherwise.
*/
public function __construct(
public readonly Capability $feature,
public readonly ReleaseState $state,
public readonly array $problems = [],
public readonly ?string $source = null
) {
}
public function usable(): bool
{
return $this->state === ReleaseState::Released;
}
/** @return array{id: string, label: string, state: string, problems: list<string>} For refusals (D6). */
public function summary(): array
{
return [
'id' => $this->feature->id(),
'label' => $this->feature->label(),
'state' => $this->state->value,
'problems' => $this->problems,
];
}
/**
* @return array{id: string, label: string, state: string, problems: list<string>, source: ?string}
* For lit-site-status and the admin tab.
*/
public function toArray(): array
{
return $this->summary() + ['source' => $this->source];
}
}
+32
View File
@@ -0,0 +1,32 @@
<?php
declare(strict_types=1);
namespace LIT\MCP\Compatibility;
defined('ABSPATH') || exit;
/** A global variable an adapter reads (e.g. a function-pointer or settings global of a plugin); it must be set. */
final class GlobalRequirement implements Requirement
{
/** @param list<Capability> $features [] = the default of the manifest. */
public function __construct(public readonly string $name, private readonly array $features = [])
{
}
public function label(): string
{
return 'Globale Variable ' . $this->name;
}
public function features(): array
{
return $this->features;
}
/** isset, not array_key_exists: a global that is null cannot be used by the adapter either. */
public function isSet(): bool
{
return isset($GLOBALS[$this->name]);
}
}
+85
View File
@@ -0,0 +1,85 @@
<?php
declare(strict_types=1);
namespace LIT\MCP\Compatibility;
defined('ABSPATH') || exit;
/** A small line diff (longest common subsequence) for wp lit-mcp divi-check --diff. */
final class LineDiff
{
/**
* @param list<string> $old
* @param list<string> $new
* @return list<string> " kept", "- removed", "+ added"; "…" between changes more than 2 × $context lines apart.
*/
public static function lines(array $old, array $new, int $context = 2): array
{
$operations = self::operations($old, $new);
$keep = [];
foreach ($operations as $i => [$op]) {
if ($op === ' ') {
continue;
}
for ($j = max(0, $i - $context); $j <= min(count($operations) - 1, $i + $context); ++$j) {
$keep[$j] = true;
}
}
$lines = [];
$last = null;
foreach ($operations as $i => [$op, $line]) {
if (! isset($keep[$i])) {
continue;
}
if ($last !== null && $i > $last + 1) {
$lines[] = '…';
}
$lines[] = $op . ' ' . $line;
$last = $i;
}
return $lines;
}
/**
* @param list<string> $a
* @param list<string> $b
* @return list<array{0: string, 1: string}>
*/
private static function operations(array $a, array $b): array
{
$n = count($a);
$m = count($b);
$lcs = array_fill(0, $n + 1, array_fill(0, $m + 1, 0));
for ($i = $n - 1; $i >= 0; --$i) {
for ($j = $m - 1; $j >= 0; --$j) {
$lcs[$i][$j] = $a[$i] === $b[$j] ? $lcs[$i + 1][$j + 1] + 1 : max($lcs[$i + 1][$j], $lcs[$i][$j + 1]);
}
}
$operations = [];
$i = 0;
$j = 0;
while ($i < $n && $j < $m) {
if ($a[$i] === $b[$j]) {
$operations[] = [' ', $a[$i]];
++$i;
++$j;
} elseif ($lcs[$i + 1][$j] >= $lcs[$i][$j + 1]) {
$operations[] = ['-', $a[$i++]];
} else {
$operations[] = ['+', $b[$j++]];
}
}
while ($i < $n) {
$operations[] = ['-', $a[$i++]];
}
while ($j < $m) {
$operations[] = ['+', $b[$j++]];
}
return $operations;
}
}
+93
View File
@@ -0,0 +1,93 @@
<?php
declare(strict_types=1);
namespace LIT\MCP\Compatibility;
defined('ABSPATH') || exit;
/**
* The external dependencies of one adapter (spec §4.1) – the single source for the compatibility checks, the release
* gate, the admin check and DiviBoundaryTest. Pure data, no WordPress calls. Only area and calls are needed; the
* other fields are optional (the Divi integration uses all of them).
*/
final class Manifest
{
/** @var list<ConstantRequirement> */
public readonly array $constants;
/**
* @param string $area Area label for reports (the Divi integration: DiviAreas).
* @param list<Call> $calls Functions and static methods the adapter calls.
* @param list<string|ConstantRequirement> $constants Constants it reads; a plain name stands for a
* ConstantRequirement without features of its own.
* @param list<string> $postTypes Post types it needs registered.
* @param list<string> $taxonomies Taxonomies it needs registered.
* @param list<string> $blockTypes Block types it needs (registered or known
* to the ManifestCheck knowsBlock closure).
* @param list<string> $keys Other names it uses as strings: meta keys, options,
* internal post types that need no registration check,
* query arguments.
* @param list<Mirror> $mirrors Functions whose storage logic it repeats.
* @param list<Capability> $features The features of every call, mirror and constant that names
* none itself (featuresOf()).
* @param list<GlobalRequirement> $globals Global variables it reads (isset check).
*/
public function __construct(
public readonly string $area,
public readonly array $calls = [],
array $constants = [],
public readonly array $postTypes = [],
public readonly array $taxonomies = [],
public readonly array $blockTypes = [],
public readonly array $keys = [],
public readonly array $mirrors = [],
public readonly array $features = [],
public readonly array $globals = []
) {
$this->constants = array_map(
static fn (string|ConstantRequirement $constant): ConstantRequirement => is_string($constant)
? new ConstantRequirement($constant)
: $constant,
array_values($constants)
);
}
/** @return list<Requirement> Calls, constants, mirrors and globals – everything the release gate checks as code. */
public function requirements(): array
{
return [...$this->calls, ...$this->constants, ...$this->mirrors, ...$this->globals];
}
/** @return list<Capability> The features $requirement names itself, else this manifest's default. */
public function featuresOf(Requirement $requirement): array
{
$own = $requirement->features();
return $own !== [] ? $own : $this->features;
}
/**
* @return list<string> Every external name the adapter's code may contain (DiviBoundaryTest): called functions and
* classes, constants, globals, post types, taxonomies, keys and the names of mirrored functions.
*/
public function names(): array
{
$names = [];
foreach ($this->calls as $call) {
$names[] = $call->className() ?? $call->member();
}
$constants = array_map(static fn (ConstantRequirement $constant): string => $constant->name, $this->constants);
$mirrored = array_map(static fn (Mirror $mirror): string => $mirror->function, $this->mirrors);
return array_values(array_unique(array_merge(
$names,
$constants,
array_map(static fn (GlobalRequirement $global): string => $global->name, $this->globals),
$this->postTypes,
$this->taxonomies,
$this->keys,
$mirrored
)));
}
}
+238
View File
@@ -0,0 +1,238 @@
<?php
declare(strict_types=1);
namespace LIT\MCP\Compatibility;
use Closure;
use LogicException;
use Throwable;
defined('ABSPATH') || exit;
/**
* The checks of all adapter manifests (spec §4.3), as label => check for reports, and as problems with their
* features for the release matrix (problems(), E1). Code checks (calls with the argument count the adapter passes
* and their signature, constants) and mirror checks decide the release gate; registration checks (post types,
* taxonomies, block types) depend on the request context (stage3 finding 6) and only show in reports.
*
* Not final so the resolver can be tested with a mock.
*/
class ManifestCheck
{
/**
* @param array<string, Manifest> $manifests Area key => manifest.
* @param array<string, string>|null $expected Mirror ID or "sig:<symbol>" => sha256; null = none known.
* @param (Closure(Mirror): ?string)|null $current Hash of the installed mirror, null = unreadable;
* no closure = every mirror is unreadable (a problem).
* @param (Closure(string): bool)|null $knowsBlock Whether a block type is known; required when a manifest
* has block types, which would otherwise pass unchecked.
* @param bool $signatures false = no signature checks: neither reference-missing
* nor signature problems (calls are still checked for
* existence and argument count).
* @throws LogicException When a manifest has block types but $knowsBlock is null.
*/
public function __construct(
private array $manifests,
private ?array $expected = null,
private ?Closure $current = null,
private ?Closure $knowsBlock = null,
private bool $signatures = true
) {
foreach ($manifests as $manifest) {
if ($manifest->blockTypes !== [] && $knowsBlock === null) {
throw new LogicException('block types need a knowsBlock closure, else they pass unchecked');
}
}
}
/** @return array<string, Closure(): bool> */
public function codeChecks(): array
{
$checks = [];
foreach ($this->manifests as $manifest) {
foreach ($manifest->calls as $call) {
$checks[$manifest->area . ': ' . $call->label()] = static fn (): bool => self::accepts($call);
}
foreach ($manifest->constants as $constant) {
$checks[$manifest->area . ': ' . $constant->label()] =
static fn (): bool => defined($constant->name);
}
foreach ($manifest->globals as $global) {
$checks[$manifest->area . ': ' . $global->label()] = static fn (): bool => $global->isSet();
}
}
return $checks;
}
/** @return array<string, Closure(): bool> */
public function mirrorChecks(): array
{
$checks = [];
foreach ($this->manifests as $manifest) {
foreach ($manifest->mirrors as $mirror) {
$checks[self::mirrorLabel($manifest, $mirror)] = fn (): bool => $this->matches($mirror);
}
}
return $checks;
}
/** @return array<string, Closure(): bool> */
public function registrationChecks(): array
{
$checks = [];
foreach ($this->manifests as $manifest) {
foreach ($manifest->postTypes as $type) {
$checks[$manifest->area . ': Post-Typ ' . $type] = static fn (): bool => post_type_exists($type);
}
foreach ($manifest->taxonomies as $taxonomy) {
$checks[$manifest->area . ': Taxonomie ' . $taxonomy] =
static fn (): bool => taxonomy_exists($taxonomy);
}
foreach ($this->knowsBlock === null ? [] : $manifest->blockTypes as $block) {
$checks[$manifest->area . ': Block-Typ ' . $block] = fn (): bool => ($this->knowsBlock)($block);
}
}
return $checks;
}
/**
* @param array<string, callable(): bool> $checks
* @return list<string> Labels of the checks that failed or threw.
*/
public static function failed(array $checks): array
{
$failed = [];
foreach ($checks as $label => $check) {
if (! self::passes($check)) {
$failed[] = (string) $label;
}
}
return $failed;
}
/** @return list<Problem> Code and mirror problems with their features – what the release matrix is built of. */
public function problems(): array
{
return array_merge($this->codeProblems(), $this->mirrorProblems());
}
/**
* Calls (missing or other argument count: call; no reference: reference-missing; other signature: signature;
* the last two only with signatures), constants and globals. Reflection only – cheap enough for every request.
*
* @return list<Problem>
*/
public function codeProblems(): array
{
$problems = [];
foreach ($this->manifests as $manifest) {
foreach ($manifest->calls as $call) {
$problem = $this->callProblem($manifest, $call);
if ($problem !== null) {
$problems[] = $problem;
}
}
foreach ($manifest->constants as $constant) {
if (! defined($constant->name)) {
$problems[] = new Problem(
$manifest->area . ': ' . $constant->label(),
$manifest->featuresOf($constant),
Problem::CONSTANT
);
}
}
foreach ($manifest->globals as $global) {
if (! $global->isSet()) {
$problems[] = new Problem(
$manifest->area . ': ' . $global->label(),
$manifest->featuresOf($global),
Problem::GLOBAL
);
}
}
}
return $problems;
}
/**
* Mirrors that differ from their reference, cannot be read or have no reference – kind mirror in every case:
* a mirror repeats how the third-party code writes, so it never runs unverified, whatever the release. Reads
* files; the resolver caches the result.
*
* @return list<Problem>
*/
public function mirrorProblems(): array
{
$problems = [];
foreach ($this->manifests as $manifest) {
foreach ($manifest->mirrors as $mirror) {
if (! self::passes(fn (): bool => $this->matches($mirror))) {
$problems[] = new Problem(
self::mirrorLabel($manifest, $mirror),
$manifest->featuresOf($mirror),
Problem::MIRROR
);
}
}
}
return $problems;
}
/** The function or method exists and takes the number of arguments the adapter passes. */
public static function accepts(Call $call): bool
{
return $call->accepts();
}
private function callProblem(Manifest $manifest, Call $call): ?Problem
{
$label = $manifest->area . ': ' . $call->label();
$features = $manifest->featuresOf($call);
if (! self::passes(static fn (): bool => self::accepts($call))) {
return new Problem($label, $features, Problem::CALL);
}
if (! $this->signatures) {
return null;
}
$expected = ($this->expected ?? [])[$call->signatureKey()] ?? null;
if ($expected === null) {
return new Problem($label . ' – Referenz der Signatur fehlt', $features, Problem::REFERENCE_MISSING);
}
return self::passes(static fn (): bool => SignatureFingerprint::of($call) === $expected)
? null
: new Problem($label . ' – Signatur geändert', $features, Problem::SIGNATURE);
}
/** The mirror's reference exists and the installed source has the same fingerprint. */
private function matches(Mirror $mirror): bool
{
$expected = ($this->expected ?? [])[$mirror->id] ?? null;
return $expected !== null && $this->current !== null && ($this->current)($mirror) === $expected;
}
private static function mirrorLabel(Manifest $manifest, Mirror $mirror): string
{
return sprintf('%s: Nachbau von %s – %s', $manifest->area, $mirror->label(), $mirror->what);
}
/** @param callable(): bool $check A check that throws failed. */
private static function passes(callable $check): bool
{
try {
return (bool) $check();
} catch (Throwable) {
return false;
}
}
}
+48
View File
@@ -0,0 +1,48 @@
<?php
declare(strict_types=1);
namespace LIT\MCP\Compatibility;
defined('ABSPATH') || exit;
/**
* A function of a third-party plugin or theme whose logic an adapter repeats instead of calling it (spec §4.1
* "mirrors"). Its fingerprint (SourceFingerprint) must match the one in fingerprints.json, else the third-party code
* changed what we copy.
*/
final class Mirror implements Requirement
{
/**
* @param string $id Key in fingerprints.json and name of its reference source (the Divi integration
* keeps them in tests/Fixtures/divi/reference/<id>.txt – an example, not a rule).
* @param string $file File of the third-party code, relative to its plugin or theme directory.
* @param string $function Function or method name.
* @param string|null $class Class of a method – the short name is enough (the file fixes where it
* lives, and a short name is no external name for DiviBoundaryTest); null for a
* function.
* @param string $what What the plugin repeats (German, for reports).
* @param list<Capability> $features [] = the default of the manifest.
*/
public function __construct(
public readonly string $id,
public readonly string $file,
public readonly string $function,
public readonly ?string $class,
public readonly string $what,
private readonly array $features = []
) {
}
public function features(): array
{
return $this->features;
}
public function label(): string
{
$class = $this->class === null ? '' : SourceFingerprint::shortName($this->class) . '::';
return $class . $this->function . '()';
}
}
+98
View File
@@ -0,0 +1,98 @@
<?php
declare(strict_types=1);
namespace LIT\MCP\Compatibility;
use Closure;
defined('ABSPATH') || exit;
/**
* One failed manifest check and the capabilities it concerns (Manifest::featuresOf()). The kind decides how the
* resolver weighs it (E1): call, mirror, constant and global lock their features for every version, released
* or not; signature and reference-missing only matter for a version without release (automatic release). A problem
* without features concerns every feature (fail closed).
*/
final class Problem
{
public const CALL = 'call';
public const SIGNATURE = 'signature';
public const MIRROR = 'mirror';
public const CONSTANT = 'constant';
public const GLOBAL = 'global';
public const REFERENCE_MISSING = 'reference-missing';
public const RESOLVER = 'resolver';
private const KINDS = [
self::CALL,
self::SIGNATURE,
self::MIRROR,
self::CONSTANT,
self::GLOBAL,
self::REFERENCE_MISSING,
self::RESOLVER,
];
private const HARD = [self::CALL, self::MIRROR, self::CONSTANT, self::GLOBAL, self::RESOLVER];
/**
* @param string $label German, e.g. "Seiten: et_x()" (the labels of ManifestCheck).
* @param list<Capability> $features
* @param string $kind One of the constants above.
*/
public function __construct(
public readonly string $label,
public readonly array $features,
public readonly string $kind
) {
}
/** Locks its features whatever the release (the third-party code no longer fits or a mirror differs). */
public function isHard(): bool
{
return in_array($this->kind, self::HARD, true);
}
public function concerns(Capability $feature): bool
{
return $this->features === [] || in_array($feature, $this->features, true);
}
/** @return array{label: string, kind: string, features: list<string>} For the transient. */
public function toArray(): array
{
return [
'label' => $this->label,
'kind' => $this->kind,
'features' => array_map(static fn (Capability $feature): string => $feature->id(), $this->features),
];
}
/**
* The problem of toArray(), or null for anything else (an unknown kind or feature included).
*
* @param Closure(string): ?Capability $capability Finds a capability by its ID, null for an unknown one.
*/
public static function fromArray(mixed $row, Closure $capability): ?self
{
if (
! is_array($row)
|| ! is_string($row['label'] ?? null)
|| ! in_array($row['kind'] ?? null, self::KINDS, true)
|| ! is_array($row['features'] ?? null)
) {
return null;
}
$features = [];
foreach ($row['features'] as $value) {
$feature = is_string($value) ? $capability($value) : null;
if ($feature === null) {
return null;
}
$features[] = $feature;
}
return new self($row['label'], $features, $row['kind']);
}
}
+15
View File
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace LIT\MCP\Compatibility;
defined('ABSPATH') || exit;
/** Spec §5.2. */
enum ReleaseState: string
{
case Released = 'released';
case Untested = 'untested';
case Incompatible = 'incompatible';
}
+25
View File
@@ -0,0 +1,25 @@
<?php
declare(strict_types=1);
namespace LIT\MCP\Compatibility;
defined('ABSPATH') || exit;
/**
* One thing an adapter needs from a third-party plugin or theme (a call, a mirrored function or a constant) and the
* features it serves.
*/
interface Requirement
{
/** Name for reports, e.g. "GlobalPreset::get_data()" (without the manifest area). */
public function label(): string;
/**
* The features this requirement serves itself; [] = the default of the manifest that lists it
* (Manifest::featuresOf() resolves that).
*
* @return list<Capability>
*/
public function features(): array;
}
+104
View File
@@ -0,0 +1,104 @@
<?php
declare(strict_types=1);
namespace LIT\MCP\Compatibility;
use ReflectionException;
use ReflectionFunction;
use ReflectionFunctionAbstract;
use ReflectionMethod;
use ReflectionParameter;
use ReflectionType;
defined('ABSPATH') || exit;
/**
* Fingerprint of the signature of one function or static method of a third-party plugin or theme (spec §4.2, E1 of
* the plan "Divi-Fähigkeiten"), read with Reflection from the running PHP process – so it needs the symbol to be
* loaded (in WordPress the plugin or theme is, once active) and never includes a file. The class of a method is
* autoloaded the way ManifestCheck::accepts() already does it.
*
* What the hash covers: function or method; for a method its visibility and whether it is static; per parameter the
* type (nullable and union included; no type reads as "mixed"), by reference, variadic and whether it is optional
* (has a default); the return type (none reads as "mixed"). What it leaves out:
* - Parameter names: the plugin passes every argument positionally (PHP 8 named arguments are never used),
* so a rename cannot break a call, and a harmless rename must not lock a feature.
* - Default values: they are expressions (constants, arrays) that Reflection may be unable to evaluate in some
* requests and that change spelling without changing meaning; only "has a default" matters for the number of
* arguments the plugin may omit.
* - The body: a changed body is no change of the interface (mirrors cover the code the plugin repeats).
*
* Type strings come from Reflection and differ between PHP versions (e.g. `iterable` reads as `Traversable|array`
* from 8.2). The reference was computed under PHP 8.4; another PHP version can therefore report a spurious signature
* problem – it only blocks the automatic release (fail closed), never releases; --update-reference regenerates it.
*/
final class SignatureFingerprint
{
/** sha256 of canonical(), null when the symbol does not exist or cannot be reflected. */
public static function of(Call $call): ?string
{
$canonical = self::canonical($call);
return $canonical === null ? null : hash('sha256', $canonical);
}
/**
* The text the hash is built from, e.g. "public static (int, array|string=, &mixed=, ...mixed): ?bool".
* Public for tests and diagnostics; null when the symbol does not exist.
*/
public static function canonical(Call $call): ?string
{
try {
$reflection = self::reflect($call);
} catch (ReflectionException) {
return null;
}
if ($reflection === null) {
return null;
}
return sprintf(
'%s (%s): %s',
self::kind($reflection),
implode(', ', array_map(self::parameter(...), $reflection->getParameters())),
self::type($reflection->getReturnType())
);
}
/** "function", or a method's visibility and "static" – a method that turns private or non-static breaks a call. */
private static function kind(ReflectionFunctionAbstract $reflection): string
{
if (! $reflection instanceof ReflectionMethod) {
return 'function';
}
$visibility = $reflection->isPublic() ? 'public' : ($reflection->isProtected() ? 'protected' : 'private');
return $reflection->isStatic() ? $visibility . ' static' : $visibility;
}
/** @throws ReflectionException */
private static function reflect(Call $call): ?ReflectionFunctionAbstract
{
$class = $call->className();
if ($class === null) {
return function_exists($call->member()) ? new ReflectionFunction($call->member()) : null;
}
return method_exists($class, $call->member()) ? new ReflectionMethod($class, $call->member()) : null;
}
private static function parameter(ReflectionParameter $parameter): string
{
return ($parameter->isPassedByReference() ? '&' : '')
. ($parameter->isVariadic() ? '...' : '')
. self::type($parameter->getType())
. ($parameter->isOptional() && ! $parameter->isVariadic() ? '=' : '');
}
private static function type(?ReflectionType $type): string
{
return $type === null ? 'mixed' : (string) $type;
}
}
+185
View File
@@ -0,0 +1,185 @@
<?php
declare(strict_types=1);
namespace LIT\MCP\Compatibility;
use RuntimeException;
defined('ABSPATH') || exit;
/**
* Fingerprint of one function or method of a third-party plugin or theme (spec §4.2), read with token_get_all(): the
* file is never included, so functions loaded only in some requests (e.g. Divi's theme-builder/api.php, admin-ajax
* only) are readable in every request. The hash covers the tokens from "function" to the closing brace without
* comments and whitespace – new comments or reformatting keep it, any code change changes it. $source is the verbatim
* text of those tokens for the human diff (wp lit-mcp divi-check --diff).
*/
final class SourceFingerprint
{
private const IGNORED = [T_WHITESPACE, T_COMMENT, T_DOC_COMMENT];
private const TYPES = [T_CLASS, T_TRAIT, T_INTERFACE, T_ENUM];
private function __construct(
public readonly string $hash,
public readonly string $source,
public readonly int $startLine,
public readonly int $endLine
) {
}
/** @throws RuntimeException When the file is unreadable or holds no such function. */
public static function of(string $file, string $function, ?string $class = null): self
{
// phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents -- Reading local PHP file, not remote content.
$source = is_file($file) && is_readable($file) ? file_get_contents($file) : false;
if (! is_string($source)) {
throw new RuntimeException(sprintf('%s is not readable', $file));
}
return self::fromSource($source, $function, $class) ?? throw new RuntimeException(sprintf(
'%s not found in %s',
$class === null ? $function . '()' : self::shortName($class) . '::' . $function . '()',
$file
));
}
/**
* The function $function outside every class body, or – with $class – the method $function declared directly
* in the class (trait, interface, enum) named like $class's last segment. The namespace is not compared: the
* file path of the manifest fixes where to look.
*/
public static function fromSource(string $source, string $function, ?string $class = null): ?self
{
$tokens = token_get_all($source);
$wanted = $class === null ? null : self::shortName($class);
$depth = 0;
/** @var list<array{0: int, 1: string}> $bodies Open class bodies: [brace depth, name]. */
$bodies = [];
$pending = null;
foreach ($tokens as $i => $token) {
$id = is_array($token) ? $token[0] : null;
$text = is_array($token) ? $token[1] : $token;
if ($id !== null && in_array($id, self::TYPES, true) && self::previousId($tokens, $i) !== T_DOUBLE_COLON) {
$pending = self::nextName($tokens, $i) ?? '';
continue;
}
if ($text === '{' || $id === T_CURLY_OPEN || $id === T_DOLLAR_OPEN_CURLY_BRACES) {
++$depth;
if ($pending !== null && $text === '{') {
$bodies[] = [$depth, $pending];
$pending = null;
}
continue;
}
if ($text === '}') {
if ($bodies !== [] && $bodies[count($bodies) - 1][0] === $depth) {
array_pop($bodies);
}
--$depth;
continue;
}
if ($id !== T_FUNCTION || self::previousId($tokens, $i) === T_USE) {
continue;
}
$name = self::nextName($tokens, $i);
if ($name === null || strcasecmp($name, $function) !== 0) {
continue;
}
$body = $bodies === [] ? null : $bodies[count($bodies) - 1];
$matches = $wanted === null
? $body === null
: $body !== null && $body[0] === $depth && strcasecmp($body[1], $wanted) === 0;
if ($matches) {
return self::capture($tokens, $i);
}
}
return null;
}
/** @param array<int, mixed> $tokens */
private static function capture(array $tokens, int $start): ?self
{
$startLine = (int) $tokens[$start][2];
$parts = [];
$verbatim = '';
$depth = 0;
$opened = false;
$count = count($tokens);
for ($i = $start; $i < $count; ++$i) {
$token = $tokens[$i];
$id = is_array($token) ? $token[0] : null;
$text = is_array($token) ? $token[1] : $token;
$verbatim .= $text;
if ($id === null || ! in_array($id, self::IGNORED, true)) {
$parts[] = $text;
}
if ($text === '{' || $id === T_CURLY_OPEN || $id === T_DOLLAR_OPEN_CURLY_BRACES) {
++$depth;
$opened = true;
} elseif ($text === '}') {
--$depth;
if ($opened && $depth === 0) {
return new self(
hash('sha256', implode(' ', $parts)),
$verbatim,
$startLine,
$startLine + substr_count($verbatim, "\n")
);
}
} elseif ($text === ';' && ! $opened) {
return null;
}
}
return null;
}
/** The next name after $i (skipping whitespace, comments and "&"), null when something else follows. */
private static function nextName(array $tokens, int $i): ?string
{
$count = count($tokens);
for ($j = $i + 1; $j < $count; ++$j) {
$token = $tokens[$j];
if (is_array($token) && in_array($token[0], self::IGNORED, true)) {
continue;
}
if ($token === '&' || (is_array($token) && $token[1] === '&')) {
continue;
}
return is_array($token) && $token[0] === T_STRING ? $token[1] : null;
}
return null;
}
/** Token ID of the previous significant token, null for a single-character token or none. */
private static function previousId(array $tokens, int $i): ?int
{
for ($j = $i - 1; $j >= 0; --$j) {
$token = $tokens[$j];
if (is_array($token) && in_array($token[0], self::IGNORED, true)) {
continue;
}
return is_array($token) ? $token[0] : null;
}
return null;
}
public static function shortName(string $class): string
{
$position = strrpos($class, '\\');
return $position === false ? $class : substr($class, $position + 1);
}
}