|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types = 1); |
| 4 | + |
| 5 | +namespace ScriptDevelopment\PhpstanWarroomRules\Rules; |
| 6 | + |
| 7 | +use Illuminate\Database\Eloquent\Builder as EloquentBuilder; |
| 8 | +use Illuminate\Database\Query\Builder as QueryBuilder; |
| 9 | +use PhpParser\Node; |
| 10 | +use PhpParser\Node\Expr; |
| 11 | +use PhpParser\Node\Expr\MethodCall; |
| 12 | +use PhpParser\Node\Expr\StaticCall; |
| 13 | +use PhpParser\Node\Identifier; |
| 14 | +use PhpParser\Node\Scalar\String_; |
| 15 | +use PHPStan\Analyser\Scope; |
| 16 | +use PHPStan\Rules\Rule; |
| 17 | +use PHPStan\Rules\RuleErrorBuilder; |
| 18 | +use PHPStan\Type\ObjectType; |
| 19 | + |
| 20 | +use function mb_stripos; |
| 21 | + |
| 22 | +/** |
| 23 | + * Forbids `Builder->truncate()` calls where the fluent chain's most recent |
| 24 | + * `table()` invocation targets a Log-named table (string-literal first |
| 25 | + * argument containing `"log"` / `"logs"`, case-insensitive substring match). |
| 26 | + * |
| 27 | + * Doctrine source: ADR-0001 §Append-only — audit records have no UPDATE, no |
| 28 | + * DELETE; `truncate()` is the bluntest delete and bypasses Eloquent events, |
| 29 | + * observers, and audit triggers entirely. |
| 30 | + * |
| 31 | + * Sibling rule to `LogRule`. Shares the `logRule.logModification` identifier |
| 32 | + * so consumer `phpstan.neon` `ignoreErrors` entries cover the whole |
| 33 | + * append-only doctrine with one entry. Closes the structural gap deliberately |
| 34 | + * deferred from PR #7 (issue #8): `LogRule` matches on Log-named class |
| 35 | + * receivers, but `DB::table('logs')->truncate()` carries no Log-named class |
| 36 | + * reference — the receiver is `Illuminate\Database\Query\Builder` (or |
| 37 | + * `Illuminate\Database\Eloquent\Builder` for `Model::query()->truncate()`), |
| 38 | + * and the "Log-ness" lives in a string-literal argument to a prior `table()` |
| 39 | + * call in the same fluent chain. |
| 40 | + * |
| 41 | + * Detection (all three must hold to fire): |
| 42 | + * 1. The `MethodCall` name is `truncate`. |
| 43 | + * 2. The receiver type is a (subtype of) `Illuminate\Database\Query\Builder` |
| 44 | + * or `Illuminate\Database\Eloquent\Builder` — type-based via |
| 45 | + * `ObjectType::isSuperTypeOf()`, not property-name string matching. |
| 46 | + * 3. Walking back through the chain, the most recent `table()` call (whether |
| 47 | + * `MethodCall` like `$db->table('x')` or `StaticCall` like |
| 48 | + * `DB::table('x')`) has a `Scalar\String_` first argument whose value |
| 49 | + * matches `'log'` / `'logs'` case-insensitively. |
| 50 | + * |
| 51 | + * Variable table names (`$t = 'logs'; DB::table($t)->truncate()`) are out of |
| 52 | + * scope — would require value-flow analysis. Acceptable miss; rely on |
| 53 | + * reviewer + consumer-side `phpstan.neon` `ignoreErrors`. |
| 54 | + * |
| 55 | + * Eloquent\Builder chains that set the table via `from('logs')` rather than |
| 56 | + * `table('logs')` are also out of scope — `from()` is Eloquent's fluent |
| 57 | + * vocabulary and is not recognised by the chain-walk. Model-property-driven |
| 58 | + * tables (`$table = 'audit_logs'` on the Model class) are likewise an |
| 59 | + * acceptable miss because the table name does not appear in the call chain. |
| 60 | + * The Eloquent\Builder receiver-type branch remains live for the rare but |
| 61 | + * coherent shape `$eloquentBuilder->table('logs')->truncate()`. |
| 62 | + * |
| 63 | + * Substring matching is intentionally broad. False positives on tables named |
| 64 | + * `catalog`, `blog`, `terminology`, or domain tables that include `log` in |
| 65 | + * the name should be suppressed per-territory via `phpstan.neon` |
| 66 | + * `ignoreErrors`, scoped to the offending path. Same convention as `LogRule`. |
| 67 | + * |
| 68 | + * @implements Rule<MethodCall> |
| 69 | + */ |
| 70 | +final class LogBuilderTruncateRule implements Rule |
| 71 | +{ |
| 72 | + private const string QUERY_BUILDER_FQCN = QueryBuilder::class; |
| 73 | + |
| 74 | + private const string ELOQUENT_BUILDER_FQCN = EloquentBuilder::class; |
| 75 | + |
| 76 | + private const array LOG_NEEDLES = ['log', 'logs']; |
| 77 | + |
| 78 | + private const string TABLE_SETTING_METHOD = 'table'; |
| 79 | + |
| 80 | + public function getNodeType(): string |
| 81 | + { |
| 82 | + return MethodCall::class; |
| 83 | + } |
| 84 | + |
| 85 | + public function processNode(Node $node, Scope $scope): array |
| 86 | + { |
| 87 | + if (!$node->name instanceof Identifier || $node->name->toString() !== 'truncate') { |
| 88 | + return []; |
| 89 | + } |
| 90 | + |
| 91 | + if (!$this->receiverIsBuilder($node, $scope)) { |
| 92 | + return []; |
| 93 | + } |
| 94 | + |
| 95 | + if (!$this->chainTargetsLogNamedTable($node->var)) { |
| 96 | + return []; |
| 97 | + } |
| 98 | + |
| 99 | + return [ |
| 100 | + RuleErrorBuilder::message('Logs should not be updated or deleted.') |
| 101 | + ->identifier('logRule.logModification') |
| 102 | + ->build(), |
| 103 | + ]; |
| 104 | + } |
| 105 | + |
| 106 | + /** |
| 107 | + * Type-based receiver gate: `$scope->getType($node->var)` must be a |
| 108 | + * (subtype of) `Illuminate\Database\Query\Builder` or |
| 109 | + * `Illuminate\Database\Eloquent\Builder`. Mirrors the canonical pattern |
| 110 | + * in `EnforceAuditSnapshotOnRetryRule::receiverIsConnectionInterface()`. |
| 111 | + */ |
| 112 | + private function receiverIsBuilder(MethodCall $node, Scope $scope): bool |
| 113 | + { |
| 114 | + $receiverType = $scope->getType($node->var); |
| 115 | + $queryBuilderType = new ObjectType(self::QUERY_BUILDER_FQCN); |
| 116 | + |
| 117 | + if ($queryBuilderType->isSuperTypeOf($receiverType)->yes()) { |
| 118 | + return true; |
| 119 | + } |
| 120 | + |
| 121 | + $eloquentBuilderType = new ObjectType(self::ELOQUENT_BUILDER_FQCN); |
| 122 | + |
| 123 | + return $eloquentBuilderType->isSuperTypeOf($receiverType)->yes(); |
| 124 | + } |
| 125 | + |
| 126 | + /** |
| 127 | + * Walk back through the fluent chain looking for the most recent |
| 128 | + * `table()` call (`MethodCall` or `StaticCall`). Inspect its first |
| 129 | + * argument: fire on a Log-named `Scalar\String_`; otherwise (variable, |
| 130 | + * concat, function call) do not fire. If no `table()` call is found in |
| 131 | + * the chain, do not fire. |
| 132 | + */ |
| 133 | + private function chainTargetsLogNamedTable(Expr $receiver): bool |
| 134 | + { |
| 135 | + $current = $receiver; |
| 136 | + |
| 137 | + while ($current instanceof MethodCall || $current instanceof StaticCall) { |
| 138 | + if ( |
| 139 | + $current->name instanceof Identifier |
| 140 | + && $current->name->toString() === self::TABLE_SETTING_METHOD |
| 141 | + ) { |
| 142 | + return $this->firstArgIsLogNamedString($current); |
| 143 | + } |
| 144 | + |
| 145 | + if ($current instanceof MethodCall) { |
| 146 | + $current = $current->var; |
| 147 | + |
| 148 | + continue; |
| 149 | + } |
| 150 | + |
| 151 | + // StaticCall is a root — its arguments are inspected above; if |
| 152 | + // its name is not `table` the chain has no earlier hops to walk. |
| 153 | + return false; |
| 154 | + } |
| 155 | + |
| 156 | + return false; |
| 157 | + } |
| 158 | + |
| 159 | + private function firstArgIsLogNamedString(MethodCall|StaticCall $call): bool |
| 160 | + { |
| 161 | + if (!isset($call->args[0]) || !$call->args[0] instanceof Node\Arg) { |
| 162 | + return false; |
| 163 | + } |
| 164 | + |
| 165 | + $value = $call->args[0]->value; |
| 166 | + |
| 167 | + if (!$value instanceof String_) { |
| 168 | + return false; |
| 169 | + } |
| 170 | + |
| 171 | + foreach (self::LOG_NEEDLES as $needle) { |
| 172 | + if (mb_stripos($value->value, $needle) !== false) { |
| 173 | + return true; |
| 174 | + } |
| 175 | + } |
| 176 | + |
| 177 | + return false; |
| 178 | + } |
| 179 | +} |
0 commit comments