diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..59a4480 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,34 @@ +# Changelog + +## 1.2.0 + +### Added + +- The PHPStan rule `html.classAsString`. It reports a check that a string holds a utility of + Tailwind with `[ ]` or after a variant, for example `toContain('lg:grid-cols-4')` or + `expect(str_contains($html, 'lg:flex'))->toBeTrue()`. The message names `toHaveSelectorClass()` + and `assertHtmlSelectorClass()`. See the README, section PHPStan. +- The parameter `htmlAssertions.camelCaseClasses`. When it is `true`, the rule also reports a class + in camelCase. The default is `false`. +- `html.markupAsString` also reads `assertStringContainsStringIgnoringCase`, + `assertStringNotContainsStringIgnoringCase`, `assertStringContainsStringIgnoringLineEndings`, + `assertStringStartsNotWith`, `assertStringEndsNotWith`, `Str::doesntContain` and `Str::isMatch`. + +### Fixed + +- `html.markupAsString` reported a call with `?->` two times. It now reports it one time. +- `composer.json` requires `ext-mbstring`. The package used `mb_trim()` already, which needs the + extension also with `symfony/polyfill-php84`. + +### Upgrade + +- `extension.neon` loads the new rule. No change to the configuration is necessary. A project with + `^1.1` gets it at its next `composer update`, and PHPStan can then report new errors. + `html.markupAsString` can also report new errors in the calls that it now reads. +- To turn the new rule off, ignore its identifier: + + ```neon + parameters: + ignoreErrors: + - identifier: html.classAsString + ``` diff --git a/README.md b/README.md index 0edac19..f851fc2 100644 --- a/README.md +++ b/README.md @@ -34,7 +34,7 @@ Each part of the package acts at one step of the loop in which an agent writes a | Step | Part | |---|---| | Before the agent writes | A [Laravel Boost](#laravel-boost) skill gives the agent the checks and the rules for selectors. | -| When the agent checks its work | The [PHPStan rule](#phpstan) `html.markupAsString` stops a check of markup as a string and says what to use instead. | +| When the agent checks its work | The [PHPStan rules](#phpstan) `html.markupAsString` and `html.classAsString` report a check of markup or of a class as a string and say what to use instead. | | When a test fails | The [message](#when-a-check-fails) names the region, what was asked, what was found, and shows the HTML of the region. The agent can fix the test without a browser. | | In an existing suite | A [Rector rule](#rector) rewrites the mechanical forms of crawler code. | @@ -46,7 +46,7 @@ The package has four parts: |---|---|---| | PHPUnit | `SorgeIt\PhpunitPestHtmlAssertions\PHPUnit` | the constraints, `Html` (a page or a region of it) and the `AssertsHtml` trait | | Pest | `SorgeIt\PhpunitPestHtmlAssertions\Pest` | the expectations and the function `html()` | -| PHPStan | `SorgeIt\PhpunitPestHtmlAssertions\PHPStan` | the rule `html.markupAsString`, which reports a check of markup as a string | +| PHPStan | `SorgeIt\PhpunitPestHtmlAssertions\PHPStan` | the rules `html.markupAsString` and `html.classAsString`, which report a check of markup or of a class as a string | | Rector | `SorgeIt\PhpunitPestHtmlAssertions\Rector` | a rule that rewrites the mechanical forms of crawler code | ## Requirements @@ -54,6 +54,7 @@ The package has four parts: - PHP 8.3, 8.4 or 8.5 - PHPUnit 12.5 or 13 - Pest 4 or 5, optional, for the expectations +- the PHP extensions `dom` and `mbstring` - Symfony DomCrawler and CssSelector 7.4 or 8.1 The CI tests three stacks: PHP 8.3 with PHPUnit 12, Pest 4, Laravel 12 and Symfony 7.4; PHP 8.4 with @@ -252,35 +253,113 @@ Escape a colon or a dot in an attribute name: `[wire\:model="name"]`, `[wire\:po ## PHPStan With `phpstan/extension-installer`, `extension.neon` loads automatically. Without it, include -`vendor/sorge-it/phpunit-pest-html-assertions/extension.neon`. In a directory named `tests` or -`Tests`, the rule `html.markupAsString` reports: +`vendor/sorge-it/phpunit-pest-html-assertions/extension.neon`. Two rules read the files in a +directory named `tests` or `Tests`: -- `assertSeeHtml`, `assertDontSeeHtml`, `assertSeeHtmlInOrder`, `assertSeeInOrder`, always; +| Rule | Reports | Use instead | +|---|---|---| +| `html.markupAsString` | a check of markup as a string: `assertSeeHtml('')`, `toContain('')`. Markup is a tag (also in a regular expression, `]*>`), an attribute of HTML with its value, or -the name of a `data-*` or `wire:` attribute. After `[` it is a CSS selector and not reported. +the name of a `data-*` or `wire:` attribute. After `[`, it is a CSS selector and not reported. -The rule reads literals, so it does not see everything: `mb_substr_count($html, 'bg-red-500')` -holds a class and no markup, and passes. +### A class as a string -A check that compares a string on purpose, for example the byte contract of a function that rewrites -markup, says so on its line. PHPStan asks for the reason and reports the line when it no longer -matches: +`html.classAsString` reports a check that a string holds a class. Such a check passes when the class +is anywhere: on another element, inside a longer class, in a script or in a comment. + +```php +expect($html)->toContain('lg:grid-cols-4'); // reported +expect(str_contains($html, 'lg:grid-cols-4'))->toBeTrue(); // reported +expect($html)->toHaveSelectorClass('[data-highlights]', 'lg:grid-cols-4'); // the element has the class +``` + +It reports a check when all of these are true: + +- **The check searches a string, or checks the result of a search.** `toBe` compares the whole + string and is not read. A search is read only as the value of a check: + `expect(substr_count($html, 'lg:flex'))->toBe(2)`, `$this->assertTrue(Str::contains($html, 'lg:flex'))`. + A search in an `if` or in a closure is not a check. A cut (`Str::after`) is not read: its result + does not tell whether it found its text. +- **The check passes when the class is found.** A negative check is not reported: + `->not->toContain()`, `assertStringNotContainsString()`, `expect(str_contains(…))->toBeFalse()`, + `assertSame(0, substr_count(…))`, `Str::doesntContain()`. It fails when the class is anywhere, so it + is stricter than a check of the DOM. A check that does not say found or absent is not reported + either: `toBeBool()`, `toBe($value)`, `toBeTruthy()` on a position, which is 0 at the start of the + string, and `toEqual(0)` or `assertEquals(0, …)`, which also pass for `false`. +- **The searched value is a string,** also `string|false` from `getContent()` or `?string`. An array, + a collection or `mixed` is not reported. A call that reads the class attribute directly, + `$element->getAttribute('class')`, is not reported. A variable, a cast or `?? ''` around it is + reported. +- **Each word of the literal can be in a `class` attribute, and one word is a utility of Tailwind:** + with a value in `[ ]` (`max-w-[90rem]`), or after a variant (`lg:grid-cols-4`, `hover:underline`, + `group-hover/item:underline`, `data-[state=open]:block`, `@md:flex`, `lg:flex!`). After a variant, + the utility has a digit, a `-`, a `/` or `[ ]`, or it is a known word such as `flex`. So + `after:today`, `first:name` and `mailto:` are not classes. A value of letters alone in `[ ]` is a + key: `errors-[name]`. +- **The literal has no markup.** A literal with markup is for `html.markupAsString`. + +The rule joins a literal with a variable before it reads it: `"lg:grid-cols-{$n}"` is a class, +`"after:{$date}"` is not. It reads a regular expression without its delimiters, `toMatch('/lg:flex/')`. +A pattern with other syntax is not read: a character class, a group, an alternative, a quantifier, +an anchor or an escape such as `\b`. + +A plain word (`flex`), kebab-case (`header-grid`) and a custom property (`--row-bg: #fff`) are not +reported. In tests, the first two are often a header value, a slug or text. For a custom property in +a `style` attribute, use `toHaveSelectorAttributeContaining()`: the rule cannot tell that attribute +from CSS text. + +A project that writes its classes in camelCase (`headerNav`) can turn on that form. In other +projects, camelCase in a test is usually a name of JavaScript or PHP. + +```neon +parameters: + htmlAssertions: + camelCaseClasses: true +``` + +### Ignore a line on purpose + +A check that compares a string on purpose gets an ignore comment on its line. Write the reason in +parentheses. PHPStan reports the comment when the rule no longer reports the line: ```php expect($rewritten)->toBe($expected); // @phpstan-ignore html.markupAsString (the rewriter keeps every other byte) +expect($script)->toContain('lg:hidden'); // @phpstan-ignore html.classAsString (the script adds the class) ``` -A suite that PHPStan reads at no other level can read its tests at level 0 for this rule alone. +### What the rules do not see + +- A string in a variable: `$needle = 'lg:flex'; expect($html)->toContain($needle);`. +- A class without a variant or `[ ]`: `expect(mb_substr_count($html, 'bg-red-500'))->toBe(1)`. Neither + rule reports it. +- A search whose result goes into a variable first. + +A project that does not check its tests with PHPStan can check them at level 0 for these rules. ## Rector diff --git a/composer.json b/composer.json index a347388..12a2066 100644 --- a/composer.json +++ b/composer.json @@ -1,6 +1,6 @@ { "name": "sorge-it/phpunit-pest-html-assertions", - "description": "HTML assertions for PHPUnit and Pest: check rendered HTML with CSS selectors, never as a string. With a PHPStan rule and a Rector rule.", + "description": "HTML assertions for PHPUnit and Pest: check rendered HTML with CSS selectors, never as a string. With two PHPStan rules and a Rector rule.", "type": "library", "license": "MIT", "keywords": ["phpunit", "pest", "html", "dom", "css-selector", "assertions", "laravel", "livewire", "symfony", "typo3", "laravel-boost", "ai-agents"], @@ -18,6 +18,7 @@ "require": { "php": "^8.3", "ext-dom": "*", + "ext-mbstring": "*", "phpunit/phpunit": "^12.5|^13.2", "symfony/css-selector": "^7.4|^8.1", "symfony/dom-crawler": "^7.4|^8.1", @@ -38,7 +39,7 @@ }, "suggest": { "pestphp/pest": "Adds the checks as expectations and the function html().", - "phpstan/phpstan": "Reports a check of markup as a string, through extension.neon.", + "phpstan/phpstan": "Reports a check of markup or of a class as a string, through extension.neon.", "rector/rector": "Rewrites the mechanical forms of crawler code to the tools of this package." }, "autoload": { diff --git a/composer.lock b/composer.lock index 3b1cf0a..546b81c 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "af1694dccea6984968bbf5827e974bc7", + "content-hash": "1caa03f3bbc90f8832eba1dc76e43cfd", "packages": [ { "name": "myclabs/deep-copy", @@ -7614,7 +7614,8 @@ "prefer-lowest": false, "platform": { "php": "^8.3", - "ext-dom": "*" + "ext-dom": "*", + "ext-mbstring": "*" }, "platform-dev": {}, "plugin-api-version": "2.9.0" diff --git a/extension.neon b/extension.neon index 18149d4..037b40e 100644 --- a/extension.neon +++ b/extension.neon @@ -1,2 +1,20 @@ +parameters: + htmlAssertions: + # Reports a class in camelCase too. Only for a project that names its classes so. + camelCaseClasses: false + +parametersSchema: + htmlAssertions: structure([ + camelCaseClasses: bool() + ]) + rules: - SorgeIt\PhpunitPestHtmlAssertions\PHPStan\MarkupAsStringRule + +services: + - + class: SorgeIt\PhpunitPestHtmlAssertions\PHPStan\ClassAsStringRule + arguments: + camelCaseClasses: %htmlAssertions.camelCaseClasses% + tags: + - phpstan.rules.rule diff --git a/fixtures/NotATest.php b/fixtures/NotATest.php index 611a734..01c3d66 100644 --- a/fixtures/NotATest.php +++ b/fixtures/NotATest.php @@ -4,11 +4,12 @@ namespace SorgeIt\PhpunitPestHtmlAssertions\Fixtures; -/** Analysed by MarkupAsStringRuleTest, never run: code outside a tests directory may compare markup. */ +/** Analysed by MarkupAsStringRuleTest and ClassAsStringRuleTest, never run: code outside a tests directory may compare markup. */ final class NotATest { - public function render(object $response): void + public function render(object $response, string $html): void { $response->assertSeeHtml(''); + str_contains($html, 'lg:flex'); } } diff --git a/resources/boost/skills/phpunit-pest-html-assertions/SKILL.md b/resources/boost/skills/phpunit-pest-html-assertions/SKILL.md index a8910cd..99954e6 100644 --- a/resources/boost/skills/phpunit-pest-html-assertions/SKILL.md +++ b/resources/boost/skills/phpunit-pest-html-assertions/SKILL.md @@ -1,6 +1,6 @@ --- name: phpunit-pest-html-assertions -description: "Checks rendered HTML in PHPUnit and Pest tests with CSS selectors, never as a string. Activate when a test checks the HTML of a response, a Blade view or component, a Livewire component, a TYPO3 or Symfony response, or a string of markup; when a test uses assertSee, assertSeeHtml, toContain or a regular expression on HTML; when a test reads text or attributes from a page; or when PHPStan reports html.markupAsString." +description: "Checks rendered HTML in PHPUnit and Pest tests with CSS selectors, never as a string. Activate when a test checks the HTML of a response, a Blade view or component, a Livewire component, a TYPO3 or Symfony response, or a string of markup; when a test uses assertSee, assertSeeHtml, toContain or a regular expression on HTML; when a test reads text or attributes from a page; or when PHPStan reports html.markupAsString or html.classAsString." license: MIT metadata: author: sorge-it @@ -10,7 +10,8 @@ metadata: ## Rules -- Check HTML through the DOM with a CSS selector. Never compare markup as a string: no `assertSee`, `assertSeeHtml`, `toContain('x` in ``. @@ -95,3 +96,24 @@ In plain PHP: `Html::of($value)->within($selector)`, `->frame()`, `->matches()`, ## Text Text is compared with white space collapsed and trimmed. The text of a `script`, `style`, `template`, `noscript` or `head` inside the node does not count. + +## PHPStan + +Two rules report a string check in a test. Replace the check. Do not change the code only to stop the report: + +| Rule | Reports | Use instead | +|---|---|---| +| `html.markupAsString` | markup in a string check: `assertSeeHtml('')`, `toContain('toBeTrue()` | `toHaveSelectorClass()` or `assertHtmlSelectorClass()` | + +```php +expect($response)->toHaveSelectorClass('[data-highlights]', 'lg:grid-cols-4'); +``` + +Ignore a line only when the string is not HTML, or when the test compares a string on purpose. Give the reason: + +```php +expect($script)->toContain('lg:hidden'); // @phpstan-ignore html.classAsString (the script adds the class) +``` + +A project whose classes are in camelCase (`headerNav`) sets `parameters.htmlAssertions.camelCaseClasses: true` in `phpstan.neon`. Then `html.classAsString` also reports those classes. diff --git a/src/PHPStan/ClassAsStringRule.php b/src/PHPStan/ClassAsStringRule.php new file mode 100644 index 0000000..1ff9d05 --- /dev/null +++ b/src/PHPStan/ClassAsStringRule.php @@ -0,0 +1,551 @@ +, subject?: array{int, string}, variadic?: true, equality?: true, pattern?: true, negative?: true, result?: string} + * + * @implements Rule + */ +final readonly class ClassAsStringRule implements Rule +{ + public const string IDENTIFIER = 'html.classAsString'; + + /** What a check of Pest without an argument says about its value. */ + private const array CLAIMS = [ + 'tobetrue' => 'true', 'tobetruthy' => 'truthy', 'tobefalse' => 'false', 'tobefalsy' => 'falsy', + 'tobenull' => 'null', 'tobeempty' => 'empty', 'tobeint' => 'int', + ]; + + /** Checks of Pest that compare their value with an expected literal, and the name of that parameter. */ + private const array COMPARISONS = [ + 'tobe' => 'expected', 'toequal' => 'expected', 'tobegreaterthan' => 'expected', 'tobegreaterthanorequal' => 'expected', + 'tobelessthan' => 'expected', 'tobelessthanorequal' => 'expected', 'tohavecount' => 'count', + ]; + + /** + * Assertions of PHPUnit that check a value: the parameter of the value, the claim or the + * comparison, the parameter of the expected literal, and whether the assertion negates it. + */ + private const array ASSERTIONS = [ + 'asserttrue' => [0, 'condition', 'true'], + 'assertfalse' => [0, 'condition', 'false'], + 'assertnottrue' => [0, 'condition', 'not true'], + 'assertnotfalse' => [0, 'condition', 'not false'], + 'assertnull' => [0, 'actual', 'null'], + 'assertnotnull' => [0, 'actual', 'not null'], + 'assertempty' => [0, 'actual', 'empty'], + 'assertnotempty' => [0, 'actual', 'not empty'], + 'assertsame' => [1, 'actual', 'tobe', 'expected'], + 'assertequals' => [1, 'actual', 'toequal', 'expected'], + 'assertnotsame' => [1, 'actual', 'tobe', 'expected', true], + 'assertnotequals' => [1, 'actual', 'toequal', 'expected', true], + 'assertgreaterthan' => [1, 'actual', 'tobegreaterthan', 'minimum'], + 'assertgreaterthanorequal' => [1, 'actual', 'tobegreaterthanorequal', 'minimum'], + 'assertlessthan' => [1, 'actual', 'tobelessthan', 'maximum'], + 'assertlessthanorequal' => [1, 'actual', 'tobelessthanorequal', 'maximum'], + 'assertcount' => [1, 'haystack', 'tohavecount', 'expectedCount'], + ]; + + /** The claim that a negated check makes. A claim that is not listed says nothing when negated: `not->toBe(2)`. */ + private const array NEGATIONS = [ + 'true' => 'not true', 'false' => 'not false', 'truthy' => 'falsy', 'falsy' => 'truthy', 'null' => 'not null', + 'empty' => 'not empty', 'int' => 'not int', 'zero' => 'not zero', 'positive' => 'below one', 'below one' => 'positive', + 'no text' => 'any text', 'count zero' => 'count positive', + 'loose true' => 'not loose true', 'loose false' => 'not loose false', 'loose null' => 'not loose null', + 'loose zero' => 'not loose zero', 'loose empty' => 'not loose empty', + ]; + + /** + * Whether a claim about the result of a search means that it found its text: by the kind of + * the result. A claim that is not listed says neither: `toBeTruthy()` on a position, which is + * 0 at the start of the string, or `toEqual(0)`, which is also true for `false`. + */ + private const array FOUND = [ + 'bool' => [ + 'true' => true, 'truthy' => true, 'not false' => true, 'not empty' => true, 'loose true' => true, 'not loose false' => true, + 'not loose null' => true, 'not loose zero' => true, 'not loose empty' => true, + 'false' => false, 'falsy' => false, 'not true' => false, 'empty' => false, 'not loose true' => false, 'loose false' => false, + 'loose null' => false, 'loose zero' => false, 'loose empty' => false, + ], + 'position' => [ + 'int' => true, 'zero' => true, 'number' => true, 'positive' => true, 'not false' => true, 'not loose false' => true, + 'not loose null' => true, 'not loose zero' => true, 'not loose empty' => true, + 'false' => false, 'not int' => false, 'loose empty' => false, + ], + 'count' => [ + 'number' => true, 'positive' => true, 'truthy' => true, 'not zero' => true, 'not empty' => true, 'loose true' => true, + 'not loose false' => true, 'not loose null' => true, 'not loose zero' => true, + 'zero' => false, 'below one' => false, 'falsy' => false, 'empty' => false, 'not loose true' => false, 'loose false' => false, + 'loose null' => false, 'loose zero' => false, + ], + 'string' => [ + 'truthy' => true, 'not empty' => true, 'text' => true, 'any text' => true, 'loose true' => true, 'not loose false' => true, + 'not loose null' => true, 'not loose empty' => true, + 'falsy' => false, 'empty' => false, 'no text' => false, 'not loose true' => false, 'loose false' => false, 'loose null' => false, + 'loose empty' => false, + ], + 'collection' => ['not empty' => true, 'count positive' => true, 'empty' => false, 'count zero' => false], + ]; + + /** Methods of a Pest expectation that keep the value they check. */ + private const array KEEPS_VALUE = ['when', 'unless']; + + /** Stands for a variable in a literal. It completes only a utility that has a form of Tailwind already. */ + private const string PLACEHOLDER = 'x'; + + /** A variant of Tailwind: a known name, a name that a group of variants starts with, or an arbitrary variant. */ + private const string VARIANT = '(?:sm|md|lg|xl|2xl|hover|focus|focus-within|focus-visible|active|visited|target|disabled|enabled' + .'|checked|indeterminate|default|required|valid|invalid|in-range|out-of-range|placeholder-shown|autofill|read-only|open' + .'|empty|first|last|only|odd|even|first-of-type|last-of-type|only-of-type|before|after|placeholder|file|marker|selection' + .'|first-line|first-letter|backdrop|dark|print|portrait|landscape|ltr|rtl|motion-safe|motion-reduce|contrast-more' + .'|contrast-less|forced-colors|starting|inert|user-valid|user-invalid|noscript' + .'|(?:max|min)-(?:sm|md|lg|xl|2xl|\[[^\]\s]+\])' + .'|(?:group|peer)-(?:[a-z][a-z-]*|\[[^\]\s]+\])(?:/[a-z0-9_-]+)?' + .'|(?:aria|data|has|not|in|supports)-(?:[a-z][a-z-]*|\[[^\]\s]+\])' + .'|nth(?:-last)?(?:-of-type)?-(?:\d+|\[[^\]\s]+\])' + .'|@(?:max-|min-)?(?:3xs|2xs|xs|sm|md|lg|xl|[2-7]xl|\[[^\]\s]+\])(?:/[a-z0-9_-]+)?' + .'|\*\*?|\[[&@][^\]\s]*\])'; + + /** A utility of Tailwind after its variants, with `!`, `-` and `/`, or an arbitrary property. */ + private const string VARIANT_TOKEN = '~^(?:'.self::VARIANT.':)+!?-?(?[a-z][a-z0-9-]*(?:-\[(?![A-Za-z]+\])[^\]\s]+\])?(?:/[a-z0-9.\[\]]+)?|\[[a-z][a-z-]*:[^\]\s]+\])!?$~'; + + /** A utility of Tailwind with an arbitrary value in `[ ]`. A word alone in it is a key: `errors-[name]`. */ + private const string BRACKET_TOKEN = '~^!?-?[a-z][a-z0-9-]*-\[(?![A-Za-z]+\])[^\]\s]+\](?:/[a-z0-9.\[\]]+)?!?$~'; + + /** A class in camelCase. Outside of a project that names its classes so, it is mostly a name of JS or PHP. */ + private const string CAMEL_CASE_TOKEN = '~^[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]*$~'; + + /** A token that can stand in a class attribute but also in text: `flex`, `header-grid`. */ + private const string PLAIN_TOKEN = '~^!?-?[a-z][a-z0-9-]*!?$~'; + + /** + * Utilities of one word. After a variant, a word that is not one of them is text: + * `after:today` is a rule of validation, `first:name` a key. + */ + private const array ONE_WORD_UTILITIES = [ + 'flex', 'grid', 'block', 'inline', 'hidden', 'contents', 'table', 'container', 'static', 'fixed', 'absolute', + 'relative', 'sticky', 'visible', 'invisible', 'collapse', 'underline', 'overline', 'italic', 'uppercase', + 'lowercase', 'capitalize', 'truncate', 'border', 'rounded', 'shadow', 'outline', 'ring', 'blur', 'grow', + 'shrink', 'transition', 'transform', 'isolate', 'antialiased', 'invert', 'grayscale', 'sepia', 'filter', + 'ordinal', 'resize', 'prose', 'contain', 'columns', + ]; + + public function __construct(private bool $camelCaseClasses = false) {} + + public function getNodeType(): string + { + return CallLike::class; + } + + /** @return list */ + public function processNode(Node $node, Scope $scope): array + { + $name = StringCalls::nameOf($node); + + if (preg_match('~[/\\\\]tests[/\\\\]~i', $scope->getFile()) !== 1 || $node->isFirstClassCallable() || $name === null) { + return []; + } + + $method = mb_strtolower($name); + + // The line of the call, not the line of `expect()`: a chain holds many checks. + return array_values(array_filter([ + $this->checksString($node, $method, $scope) ? $this->error($name, $this->lineOf($node)) : null, + $this->checkedRead($node, $method, $scope), + ])); + } + + private function error(string $name, int $line): IdentifierRuleError + { + return RuleErrorBuilder::message(sprintf('%s() searches a string for a class: ask the element with toHaveSelectorClass() or assertHtmlSelectorClass().', $name)) + ->identifier(self::IDENTIFIER) + ->line($line) + ->tip('When the string is not HTML, add // @phpstan-ignore html.classAsString ().') + ->build(); + } + + private function lineOf(CallLike $node): int + { + return ($node instanceof MethodCall || $node instanceof NullsafeMethodCall || $node instanceof StaticCall) ? $node->name->getStartLine() : $node->getStartLine(); + } + + /** A positive check of Pest or PHPUnit that a string holds a class. */ + private function checksString(CallLike $node, string $method, Scope $scope): bool + { + /** @var Parameters|null $parameters */ + $parameters = StringCalls::STRING_CHECKS[$method] ?? null; + + if ($parameters === null || isset($parameters['equality']) || isset($parameters['negative'])) { + return false; + } + + $arguments = array_values($node->getArgs()); + + if (str_starts_with($method, 'assert')) { + $subject = isset($parameters['subject']) ? StringCalls::argument($arguments, ...$parameters['subject'])?->value : null; + + return $subject instanceof Expr && $this->isHtml($subject, $scope->getType($subject)) + && $this->holdsClasses($this->needles($arguments, $parameters), $parameters); + } + + $value = $node instanceof MethodCall && ! $this->isProperty($node->var, 'not') ? $this->expectedValue($node) : null; + + return $value !== null && $this->isHtml($value['each'] ? null : $value['expr'], $this->typeOfValue($value, $scope)) + && $this->holdsClasses($this->needles($arguments, $parameters), $parameters); + } + + /** + * A search (`str_contains`, `Str::contains`, `preg_match`) whose result a check says is + * found. A search outside a check is not read, and a cut (`Str::after`) never: its result + * does not tell whether it found its text. + */ + private function checkedRead(CallLike $node, string $method, Scope $scope): ?IdentifierRuleError + { + [$result, $claim] = $this->resultOf($node, $method) ?? [null, null]; + $negated = $result instanceof BooleanNot; + $result = $result instanceof BooleanNot ? $result->expr : $result; + + $readName = $result instanceof CallLike ? StringCalls::nameOf($result) : null; + $read = $result instanceof CallLike && $readName !== null ? $this->readOf($result, mb_strtolower($readName), $scope) : null; + $kind = $read['parameters']['result'] ?? null; + + // `!` turns only a bool into its opposite: `! strpos(…)` is also true at position 0. + $claim = $negated ? ($kind === 'bool' && $claim !== null ? self::NEGATIONS[$claim] ?? null : null) : $claim; + $found = $kind !== null && $claim !== null ? self::FOUND[$kind][$claim] ?? null : null; + + if ($read === null || $found === null || $found === isset($read['parameters']['negative'])) { + return null; + } + + return $this->isHtml($read['subject'], $read['type']) + && $this->holdsClasses($this->needles($read['arguments'], $read['parameters']), $read['parameters']) + ? $this->error($readName, $this->lineOf($result)) + : null; + } + + /** + * The value a check reads and what the check claims about it, as the keys of FOUND. Null + * when the call is no such check or makes no claim. + * + * @return array{Expr, string}|null + */ + private function resultOf(CallLike $node, string $method): ?array + { + $arguments = array_values($node->getArgs()); + + if (isset(self::ASSERTIONS[$method])) { + $assertion = self::ASSERTIONS[$method]; + $value = StringCalls::argument($arguments, $assertion[0], $assertion[1])?->value; + $claim = isset($assertion[3]) + ? $this->compared($assertion[2], StringCalls::argument($arguments, 0, $assertion[3])?->value) + : $assertion[2]; + $claim = isset($assertion[4]) && $claim !== null ? self::NEGATIONS[$claim] ?? null : $claim; + + return $value instanceof Expr && $claim !== null ? [$value, $claim] : null; + } + + if (! $node instanceof MethodCall) { + return null; + } + + $negated = $this->isProperty($node->var, 'not'); + $start = $negated && $node->var instanceof PropertyFetch ? $node->var->var : $node->var; + $value = $this->startsChain($start) && $start instanceof CallLike ? ($start->getArgs()[0] ?? null)?->value : null; + + $claim = self::CLAIMS[$method] ?? (isset(self::COMPARISONS[$method]) + ? $this->compared($method, StringCalls::argument($arguments, 0, self::COMPARISONS[$method])?->value) + : null); + $claim = $negated && $claim !== null ? self::NEGATIONS[$claim] ?? null : $claim; + + return $value instanceof Expr && $claim !== null ? [$value, $claim] : null; + } + + /** What a comparison with an expected literal claims: `toBe(0)` claims zero, `toBeGreaterThan(0)` a positive number. */ + private function compared(string $comparison, ?Expr $expected): ?string + { + $number = $expected instanceof Int_ ? $expected->value : null; + $constant = $expected instanceof ConstFetch ? $expected->name->toLowerString() : null; + // `toEqual` compares loosely: `false == 0`, `false == ''` and `null == 0` are true. + $loose = $comparison === 'toequal' ? 'loose ' : ''; + + return match (true) { + $comparison === 'tobe' || $comparison === 'toequal' => match (true) { + in_array($constant, ['true', 'false', 'null'], true) => $loose.$constant, + $number !== null => $number === 0 ? $loose.'zero' : 'number', + $expected instanceof String_ && $expected->value === '' => $loose === '' ? 'no text' : 'loose empty', + $expected instanceof String_ => 'text', + default => null, + }, + $number === null => null, + $comparison === 'tohavecount' => $number === 0 ? 'count zero' : 'count positive', + $comparison === 'tobegreaterthan' => 'positive', + $comparison === 'tobegreaterthanorequal' => $number >= 1 ? 'positive' : null, + $comparison === 'tobelessthan' => $number === 1 ? 'below one' : null, + $comparison === 'tobelessthanorequal' => $number === 0 ? 'below one' : null, + default => null, + }; + } + + /** + * A search of PHP, of `Str` or of Laravel's `Stringable`: its parameters, its arguments and + * the string it searches. A collection is `Stringable` too, by its `__toString()`, so only + * the class of Laravel counts. + * + * @return array{parameters: Parameters, arguments: list, subject: Expr, type: Type}|null + */ + private function readOf(CallLike $read, string $method, Scope $scope): ?array + { + $arguments = array_values($read->getArgs()); + $object = $read instanceof MethodCall || $read instanceof NullsafeMethodCall; + + /** @var Parameters|null $parameters */ + $parameters = match (true) { + $read instanceof FuncCall => StringCalls::FUNCTIONS[$method] ?? null, + $read instanceof StaticCall => $read->class instanceof Name && $scope->resolveName($read->class) === Str::class ? StringCalls::STRING_READS[$method] ?? null : null, + $object => (new ObjectType(Stringable::class))->isSuperTypeOf(TypeCombinator::removeNull($scope->getType($read->var)))->yes() + ? $this->withoutSubject(StringCalls::STRING_READS[$method] ?? null) + : null, + default => null, + }; + + $subject = match (true) { + $parameters === null => null, + $object => $read->var, + default => isset($parameters['subject']) ? StringCalls::argument($arguments, ...$parameters['subject'])?->value : null, + }; + + return $parameters !== null && $subject instanceof Expr + ? ['parameters' => $parameters, 'arguments' => $arguments, 'subject' => $subject, 'type' => $object ? new StringType : $scope->getType($subject)] + : null; + } + + /** + * The parameters of a method of `Stringable`: the object is the subject, so each later + * parameter moves one place forward. + * + * @param Parameters|null $parameters + * @return Parameters|null + */ + private function withoutSubject(?array $parameters): ?array + { + if ($parameters === null || ! isset($parameters['subject'])) { + return $parameters; + } + + $subject = $parameters['subject'][0]; + $parameters['needles'] = array_map(fn (array $needle): array => [$needle[0] > $subject ? $needle[0] - 1 : $needle[0], $needle[1]], $parameters['needles']); + unset($parameters['subject']); + + // `Stringable::match()` returns a `Stringable`, and an object is always truthy. + if (($parameters['result'] ?? null) === 'string') { + unset($parameters['result']); + } + + return $parameters; + } + + /** + * The value a check of Pest reads: the argument of `expect()` or `and()`, and whether the + * check reads one element of it after `each`. Null when the chain changes the value. + * + * @return array{expr: Expr, each: bool}|null + */ + private function expectedValue(MethodCall $check): ?array + { + $each = false; + $link = $check->var; + + while (! $this->startsChain($link)) { + $each = $each || $this->isProperty($link, 'each'); + $link = $this->previousLink($link); + + if (! $link instanceof Expr) { + return null; + } + } + + $value = $link instanceof CallLike ? ($link->getArgs()[0] ?? null)?->value : null; + + return $value instanceof Expr ? ['expr' => $value, 'each' => $each] : null; + } + + /** @param array{expr: Expr, each: bool} $value */ + private function typeOfValue(array $value, Scope $scope): Type + { + $type = $scope->getType($value['expr']); + + return $value['each'] ? $type->getIterableValueType() : $type; + } + + /** `expect($value)` or `->and($value)`. */ + private function startsChain(Expr $link): bool + { + return ($link instanceof FuncCall && $link->name instanceof Name && mb_strtolower($link->name->getLast()) === 'expect') + || ($link instanceof MethodCall && $link->name instanceof Identifier && $link->name->toLowerString() === 'and'); + } + + /** The link before `->not`, `->each`, another check or a method that keeps the value; null after any other link. */ + private function previousLink(Expr $link): ?Expr + { + return match (true) { + $link instanceof PropertyFetch => $this->isProperty($link, 'not') || $this->isProperty($link, 'each') ? $link->var : null, + $link instanceof MethodCall && $link->name instanceof Identifier => str_starts_with($link->name->toLowerString(), 'to') || in_array($link->name->toLowerString(), self::KEEPS_VALUE, true) ? $link->var : null, + default => null, + }; + } + + private function isProperty(Expr $link, string $name): bool + { + return $link instanceof PropertyFetch && $link->name instanceof Identifier && $link->name->toLowerString() === $name; + } + + /** + * A string, also `string|false` from `getContent()` and `?string`, that is not the value of a + * class attribute: `$element->getAttribute('class')` holds classes and no HTML. + */ + private function isHtml(?Expr $subject, Type $type): bool + { + $readsClassAttribute = $subject instanceof CallLike && ! $subject->isFirstClassCallable() + && array_any($subject->getArgs(), fn (Arg $argument): bool => $argument->value instanceof String_ && mb_strtolower($argument->value->value) === 'class'); + + return ! $readsClassAttribute && TypeCombinator::removeNull(TypeCombinator::remove($type, new ConstantBooleanType(false)))->isString()->yes(); + } + + /** + * The arguments a call searches for: every argument of a variadic check, else each named parameter. + * + * @param list $arguments + * @param Parameters $parameters + * @return list + */ + private function needles(array $arguments, array $parameters): array + { + if (isset($parameters['variadic'])) { + return array_map(fn (Arg $argument): Expr => $argument->value, array_values(array_filter($arguments, fn (Arg $argument): bool => ! $argument->name instanceof Identifier))); + } + + return array_values(array_filter(array_map( + fn (array $needle): ?Expr => StringCalls::argument($arguments, ...$needle)?->value, + $parameters['needles'], + ))); + } + + /** + * @param list $needles + * @param Parameters $parameters + */ + private function holdsClasses(array $needles, array $parameters): bool + { + return array_any($needles, fn (Expr $needle): bool => array_any( + $this->texts($needle), + fn (string $text): bool => $this->namesClasses(isset($parameters['pattern']) ? $this->patternBody($text) : $text), + )); + } + + /** + * The texts an argument searches for: a string, the values of an array, and an interpolated + * string or a concatenation with a placeholder for each variable. Not the keys of an array. + * + * @return list + */ + private function texts(Expr $needle): array + { + if ($needle instanceof Array_) { + return array_merge([], ...array_map(fn (?ArrayItem $item): array => $item instanceof ArrayItem ? $this->texts($item->value) : [], $needle->items)); + } + + $text = $this->joined($needle); + + return $text === null ? [] : [$text]; + } + + /** The text of an expression with a placeholder for each variable, or null when no literal is in it. */ + private function joined(Expr $part): ?string + { + return match (true) { + $part instanceof String_ => $part->value, + $part instanceof InterpolatedString => array_any($part->parts, fn (Node $piece): bool => $piece instanceof InterpolatedStringPart) + ? implode('', array_map(fn (Node $piece): string => $piece instanceof InterpolatedStringPart ? $piece->value : self::PLACEHOLDER, $part->parts)) + : null, + $part instanceof Concat => $this->joined($part->left) === null && $this->joined($part->right) === null + ? null + : ($this->joined($part->left) ?? self::PLACEHOLDER).($this->joined($part->right) ?? self::PLACEHOLDER), + default => null, + }; + } + + /** The body of a regular expression without its delimiters, flags and the escapes of punctuation; null when it is more than a literal. */ + private function patternBody(string $pattern): ?string + { + $open = mb_substr($pattern, 0, 1); + $close = ['(' => ')', '{' => '}', '[' => ']', '<' => '>'][$open] ?? $open; + $end = mb_strrpos($pattern, $close); + $body = preg_match('~^[^\w\s\\\\]$~', $open) === 1 && $end !== false && $end > 0 ? mb_substr($pattern, 1, $end - 1) : $pattern; + + // A character class, a group, an alternative, a quantifier or an anchor that is not escaped. + return preg_match('~(? $this->isTailwind($token) || preg_match(self::CAMEL_CASE_TOKEN, $token) === 1 || preg_match(self::PLAIN_TOKEN, $token) === 1) + && array_any($tokens, fn (string $token): bool => $this->isTailwind($token) || ($this->camelCaseClasses && preg_match(self::CAMEL_CASE_TOKEN, $token) === 1)); + } + + /** A utility with `[ ]`, or a utility after a variant that has a digit, a `-`, a `/`, `[ ]`, or is a known word. */ + private function isTailwind(string $token): bool + { + if (preg_match(self::BRACKET_TOKEN, $token) === 1) { + return true; + } + + return preg_match(self::VARIANT_TOKEN, $token, $match) === 1 + && (preg_match('~[\d\[/-]~', $match['utility']) === 1 || in_array($match['utility'], self::ONE_WORD_UTILITIES, true)); + } +} diff --git a/src/PHPStan/MarkupAsStringRule.php b/src/PHPStan/MarkupAsStringRule.php index 7759ac9..d475238 100644 --- a/src/PHPStan/MarkupAsStringRule.php +++ b/src/PHPStan/MarkupAsStringRule.php @@ -11,9 +11,7 @@ use PhpParser\Node\Expr\ConstFetch; use PhpParser\Node\Expr\FuncCall; use PhpParser\Node\Expr\MethodCall; -use PhpParser\Node\Expr\NullsafeMethodCall; use PhpParser\Node\Expr\StaticCall; -use PhpParser\Node\Identifier; use PhpParser\Node\InterpolatedStringPart; use PhpParser\Node\Name; use PhpParser\Node\Scalar\String_; @@ -34,40 +32,21 @@ final class MarkupAsStringRule implements Rule { public const string IDENTIFIER = 'html.markupAsString'; - /** Laravel and Livewire checks that compare markup as a string, whatever they are given. */ - private const array MARKUP_CHECKS = ['assertseehtml', 'assertdontseehtml', 'assertseehtmlinorder', 'assertseeinorder']; - - /** Laravel checks that compare markup where their second argument turns escaping off. */ - private const array UNESCAPED_CHECKS = ['assertsee', 'assertdontsee']; - - /** Checks of Pest and PHPUnit that compare or search a string. */ - private const array STRING_CHECKS = [ - 'tocontain', 'tobe', 'tostartwith', 'toendwith', 'tomatch', - 'assertstringcontainsstring', 'assertstringnotcontainsstring', 'assertstringstartswith', 'assertstringendswith', - 'assertmatchesregularexpression', 'assertdoesnotmatchregularexpression', - ]; - - /** Methods of `Str` and of its `Stringable` that cut or search a string. */ - private const array STRING_READS = [ - 'after', 'afterlast', 'before', 'beforelast', 'between', 'betweenfirst', - 'contains', 'containsall', 'startswith', 'endswith', 'substrcount', 'match', 'matchall', 'test', - ]; - - /** Functions of PHP that search a string. */ - private const array FUNCTIONS = [ - 'preg_match', 'preg_match_all', 'str_contains', 'str_starts_with', 'str_ends_with', - 'strpos', 'stripos', 'mb_strpos', 'mb_stripos', 'substr_count', 'mb_substr_count', - ]; - /** * An opening or closing tag (also in a regular expression), an attribute of * HTML with its value, or the name of a `data-*` or `wire:` attribute. After * `[` it is a CSS selector, not markup. */ - private const string MARKUP = '\[]|$)' + public const string MARKUP = '\[]|$)' .'|(?')`. */ private const string READ_MARKUP = self::MARKUP.'|^[<>]$'; @@ -95,7 +74,7 @@ public function processNode(Node $node, Scope $scope): array private function findMessage(CallLike $node, Scope $scope): ?string { - $name = $this->nameOf($node); + $name = StringCalls::nameOf($node); if ($name === null) { return null; @@ -105,22 +84,13 @@ private function findMessage(CallLike $node, Scope $scope): ?string $arguments = $node->getArgs(); return match (true) { - $node instanceof FuncCall => in_array($method, self::FUNCTIONS, true) && $this->holdsMarkup($arguments, self::MARKUP) + $node instanceof FuncCall => array_key_exists($method, StringCalls::FUNCTIONS) && $this->holdsMarkup($arguments, self::MARKUP) ? sprintf('%s() reads HTML as a string: its literal holds a tag or an attribute.', $name) : null, in_array($method, self::MARKUP_CHECKS, true) => sprintf('%s() checks markup as a string.', $name), in_array($method, self::UNESCAPED_CHECKS, true) && $this->turnsEscapingOff($arguments) => sprintf('%s() with escaping off checks markup as a string.', $name), - in_array($method, self::STRING_CHECKS, true) && $this->holdsMarkup($arguments, self::MARKUP) => sprintf('%s() checks markup as a string: its literal holds a tag or an attribute.', $name), - in_array($method, self::STRING_READS, true) && $this->readsAString($node, $scope) && $this->holdsMarkup($arguments, self::READ_MARKUP) => sprintf('%s() reads HTML as a string: its literal holds a tag or an attribute.', $name), - default => null, - }; - } - - private function nameOf(CallLike $node): ?string - { - return match (true) { - ($node instanceof MethodCall || $node instanceof NullsafeMethodCall || $node instanceof StaticCall) && $node->name instanceof Identifier => $node->name->toString(), - $node instanceof FuncCall && $node->name instanceof Name => $node->name->toString(), + array_key_exists($method, StringCalls::STRING_CHECKS) && $this->holdsMarkup($arguments, self::MARKUP) => sprintf('%s() checks markup as a string: its literal holds a tag or an attribute.', $name), + array_key_exists($method, StringCalls::STRING_READS) && $this->readsAString($node, $scope) && $this->holdsMarkup($arguments, self::READ_MARKUP) => sprintf('%s() reads HTML as a string: its literal holds a tag or an attribute.', $name), default => null, }; } @@ -130,7 +100,8 @@ private function readsAString(CallLike $node, Scope $scope): bool { return match (true) { $node instanceof StaticCall => $node->class instanceof Name && $scope->resolveName($node->class) === Str::class, - $node instanceof MethodCall, $node instanceof NullsafeMethodCall => true, + // A `?->` call reaches the rule twice: as itself and as a `MethodCall`. + $node instanceof MethodCall => true, default => false, }; } diff --git a/src/PHPStan/StringCalls.php b/src/PHPStan/StringCalls.php new file mode 100644 index 0000000..1d7ee82 --- /dev/null +++ b/src/PHPStan/StringCalls.php @@ -0,0 +1,103 @@ + ['needles' => [[0, 'needles']], 'variadic' => true], + 'tobe' => ['needles' => [[0, 'expected']], 'equality' => true], + 'tostartwith' => ['needles' => [[0, 'expected']]], + 'toendwith' => ['needles' => [[0, 'expected']]], + 'tomatch' => ['needles' => [[0, 'expression']], 'pattern' => true], + 'assertstringcontainsstring' => ['needles' => [[0, 'needle']], 'subject' => [1, 'haystack']], + 'assertstringcontainsstringignoringcase' => ['needles' => [[0, 'needle']], 'subject' => [1, 'haystack']], + 'assertstringcontainsstringignoringlineendings' => ['needles' => [[0, 'needle']], 'subject' => [1, 'haystack']], + 'assertstringnotcontainsstring' => ['needles' => [[0, 'needle']], 'subject' => [1, 'haystack'], 'negative' => true], + 'assertstringnotcontainsstringignoringcase' => ['needles' => [[0, 'needle']], 'subject' => [1, 'haystack'], 'negative' => true], + 'assertstringstartswith' => ['needles' => [[0, 'prefix']], 'subject' => [1, 'string']], + 'assertstringstartsnotwith' => ['needles' => [[0, 'prefix']], 'subject' => [1, 'string'], 'negative' => true], + 'assertstringendswith' => ['needles' => [[0, 'suffix']], 'subject' => [1, 'string']], + 'assertstringendsnotwith' => ['needles' => [[0, 'suffix']], 'subject' => [1, 'string'], 'negative' => true], + 'assertmatchesregularexpression' => ['needles' => [[0, 'pattern']], 'subject' => [1, 'string'], 'pattern' => true], + 'assertdoesnotmatchregularexpression' => ['needles' => [[0, 'pattern']], 'subject' => [1, 'string'], 'pattern' => true, 'negative' => true], + ]; + + /** Methods of `Str` and of its `Stringable` that cut or search a string. */ + public const array STRING_READS = [ + 'after' => ['needles' => [[1, 'search']], 'subject' => [0, 'subject'], 'result' => 'cut'], + 'afterlast' => ['needles' => [[1, 'search']], 'subject' => [0, 'subject'], 'result' => 'cut'], + 'before' => ['needles' => [[1, 'search']], 'subject' => [0, 'subject'], 'result' => 'cut'], + 'beforelast' => ['needles' => [[1, 'search']], 'subject' => [0, 'subject'], 'result' => 'cut'], + 'between' => ['needles' => [[1, 'from'], [2, 'to']], 'subject' => [0, 'subject'], 'result' => 'cut'], + 'betweenfirst' => ['needles' => [[1, 'from'], [2, 'to']], 'subject' => [0, 'subject'], 'result' => 'cut'], + 'contains' => ['needles' => [[1, 'needles']], 'subject' => [0, 'haystack'], 'result' => 'bool'], + 'containsall' => ['needles' => [[1, 'needles']], 'subject' => [0, 'haystack'], 'result' => 'bool'], + 'doesntcontain' => ['needles' => [[1, 'needles']], 'subject' => [0, 'haystack'], 'negative' => true, 'result' => 'bool'], + 'startswith' => ['needles' => [[1, 'needles']], 'subject' => [0, 'haystack'], 'result' => 'bool'], + 'endswith' => ['needles' => [[1, 'needles']], 'subject' => [0, 'haystack'], 'result' => 'bool'], + 'substrcount' => ['needles' => [[1, 'needle']], 'subject' => [0, 'haystack'], 'result' => 'count'], + 'match' => ['needles' => [[0, 'pattern']], 'subject' => [1, 'subject'], 'pattern' => true, 'result' => 'string'], + 'matchall' => ['needles' => [[0, 'pattern']], 'subject' => [1, 'subject'], 'pattern' => true, 'result' => 'collection'], + 'ismatch' => ['needles' => [[0, 'pattern']], 'subject' => [1, 'value'], 'pattern' => true, 'result' => 'bool'], + 'test' => ['needles' => [[0, 'pattern']], 'subject' => [1, 'subject'], 'pattern' => true, 'result' => 'bool'], + ]; + + /** Functions of PHP that search a string. */ + public const array FUNCTIONS = [ + 'preg_match' => ['needles' => [[0, 'pattern']], 'subject' => [1, 'subject'], 'pattern' => true, 'result' => 'count'], + 'preg_match_all' => ['needles' => [[0, 'pattern']], 'subject' => [1, 'subject'], 'pattern' => true, 'result' => 'count'], + 'str_contains' => ['needles' => [[1, 'needle']], 'subject' => [0, 'haystack'], 'result' => 'bool'], + 'str_starts_with' => ['needles' => [[1, 'needle']], 'subject' => [0, 'haystack'], 'result' => 'bool'], + 'str_ends_with' => ['needles' => [[1, 'needle']], 'subject' => [0, 'haystack'], 'result' => 'bool'], + 'strpos' => ['needles' => [[1, 'needle']], 'subject' => [0, 'haystack'], 'result' => 'position'], + 'stripos' => ['needles' => [[1, 'needle']], 'subject' => [0, 'haystack'], 'result' => 'position'], + 'mb_strpos' => ['needles' => [[1, 'needle']], 'subject' => [0, 'haystack'], 'result' => 'position'], + 'mb_stripos' => ['needles' => [[1, 'needle']], 'subject' => [0, 'haystack'], 'result' => 'position'], + 'substr_count' => ['needles' => [[1, 'needle']], 'subject' => [0, 'haystack'], 'result' => 'count'], + 'mb_substr_count' => ['needles' => [[1, 'needle']], 'subject' => [0, 'haystack'], 'result' => 'count'], + ]; + + /** The name of the method or function a call names literally, else null. */ + public static function nameOf(CallLike $node): ?string + { + return match (true) { + ($node instanceof MethodCall || $node instanceof NullsafeMethodCall || $node instanceof StaticCall) && $node->name instanceof Identifier => $node->name->toString(), + // `use function PHPUnit\Framework\assertTrue` makes the name fully qualified. + $node instanceof FuncCall && $node->name instanceof Name => $node->name->getLast(), + default => null, + }; + } + + /** + * The argument for a parameter: by its name, else at its position when that argument has no name. + * + * @param list $arguments + */ + public static function argument(array $arguments, int $position, string $name): ?Arg + { + $named = array_find($arguments, fn (Arg $argument): bool => $argument->name?->toString() === $name); + $positional = $arguments[$position] ?? null; + + return $named ?? ($positional?->name === null ? $positional : null); + } +} diff --git a/tests/PHPStan/ClassAsStringRuleCamelCaseTest.php b/tests/PHPStan/ClassAsStringRuleCamelCaseTest.php new file mode 100644 index 0000000..fa1e0e6 --- /dev/null +++ b/tests/PHPStan/ClassAsStringRuleCamelCaseTest.php @@ -0,0 +1,36 @@ + + */ +final class ClassAsStringRuleCamelCaseTest extends RuleTestCase +{ + /** @return list */ + #[Override] + public static function getAdditionalConfigFiles(): array + { + return [__DIR__.'/../../extension.neon', __DIR__.'/data/camel-case.neon']; + } + + public function test_it_reports_a_class_in_camel_case_when_the_parameter_is_on(): void + { + $this->analyse([ClassAsStringRuleTest::FIXTURE], ClassAsStringRuleTest::errors(camelCase: true)); + } + + #[Override] + protected function getRule(): Rule + { + return self::getContainer()->getByType(ClassAsStringRule::class); + } +} diff --git a/tests/PHPStan/ClassAsStringRuleTest.php b/tests/PHPStan/ClassAsStringRuleTest.php new file mode 100644 index 0000000..90b3ea4 --- /dev/null +++ b/tests/PHPStan/ClassAsStringRuleTest.php @@ -0,0 +1,53 @@ + */ +final class ClassAsStringRuleTest extends RuleTestCase +{ + public const string FIXTURE = __DIR__.'/data/tests/ClassChecks.php'; + + public const string TIP = 'When the string is not HTML, add // @phpstan-ignore html.classAsString ().'; + + /** + * The errors the fixture names: a line that ends in `// name() reported` is reported for that + * call, `reported with camelCase` only when that form is on. + * + * @return list + */ + public static function errors(bool $camelCase): array + { + $errors = []; + + foreach (file(self::FIXTURE) ?: [] as $index => $line) { + if (preg_match('~// (\w+)\(\) reported( with camelCase)?~', $line, $match) === 1 && ($camelCase || ! isset($match[2]))) { + $errors[] = [sprintf('%s() searches a string for a class: ask the element with toHaveSelectorClass() or assertHtmlSelectorClass().', $match[1]), $index + 1, self::TIP]; + } + } + + return $errors; + } + + public function test_it_reports_each_search_of_a_string_for_a_class_in_a_test(): void + { + $this->analyse([self::FIXTURE], self::errors(camelCase: false)); + } + + public function test_it_leaves_code_outside_the_tests_alone(): void + { + $this->analyse([__DIR__.'/../../fixtures/NotATest.php'], []); + } + + #[Override] + protected function getRule(): Rule + { + return new ClassAsStringRule; + } +} diff --git a/tests/PHPStan/MarkupAsStringRuleTest.php b/tests/PHPStan/MarkupAsStringRuleTest.php index 649f7fc..d2f4d86 100644 --- a/tests/PHPStan/MarkupAsStringRuleTest.php +++ b/tests/PHPStan/MarkupAsStringRuleTest.php @@ -46,6 +46,11 @@ public function test_it_reports_each_check_of_markup_as_a_string_in_a_test(): vo $read('preg_match_all', 44), $read('str_contains', 46), $read('mb_substr_count', 47), + $check('assertStringContainsStringIgnoringCase', 50), + $check('assertStringStartsNotWith', 51), + $read('doesntContain', 52), + $read('isMatch', 53), + $read('contains', 54), ]); } diff --git a/tests/PHPStan/data/camel-case.neon b/tests/PHPStan/data/camel-case.neon new file mode 100644 index 0000000..a6fcb84 --- /dev/null +++ b/tests/PHPStan/data/camel-case.neon @@ -0,0 +1,3 @@ +parameters: + htmlAssertions: + camelCaseClasses: true diff --git a/tests/PHPStan/data/tests/ClassChecks.php b/tests/PHPStan/data/tests/ClassChecks.php new file mode 100644 index 0000000..9e07480 --- /dev/null +++ b/tests/PHPStan/data/tests/ClassChecks.php @@ -0,0 +1,182 @@ + $map */ + public function forms(string $html, array $map, int $n): void + { + expect($html)->toContain('max-w-[90rem]'); // toContain() reported: a utility with [ ] + expect($html)->toContain('lg:grid-cols-4'); // toContain() reported: a utility after a variant + expect($html)->toContain('hover:underline'); // toContain() reported: a known word after a variant + expect($html)->toContain('md:-mt-4'); // toContain() reported: a negative utility + expect($html)->toContain('hover:bg-black/50'); // toContain() reported: an opacity + expect($html)->toContain('lg:!mt-4 lg:flex!'); // toContain() reported: important, before and after + expect($html)->toContain('group-hover:underline'); // toContain() reported: a group of variants + expect($html)->toContain('group-hover/item:underline'); // toContain() reported: a named group + expect($html)->toContain('peer-checked/name:block'); // toContain() reported: a named peer + expect($html)->toContain('focus-within:ring-2'); // toContain() reported + expect($html)->toContain('aria-checked:bg-blue-500'); // toContain() reported + expect($html)->toContain('data-active:flex'); // not reported: a data-* name, for html.markupAsString + expect($html)->toContain('data-[state=open]:block'); // toContain() reported: an arbitrary data variant + expect($html)->toContain('has-[:checked]:bg-blue-500'); // toContain() reported + expect($html)->toContain('max-md:hidden'); // toContain() reported: a breakpoint range + expect($html)->toContain('@md:flex'); // toContain() reported: a container query + expect($html)->toContain('[&>li]:mt-2'); // toContain() reported: an arbitrary variant + expect($html)->toContain('*:p-2'); // toContain() reported: the children + expect($html)->toContain('nth-3:underline'); // toContain() reported + expect($html)->toContain('lg:[mask-type:luminance]'); // toContain() reported: an arbitrary property + expect($html)->toContain('headerRowInner max-w-[90rem] flex'); // toContain() reported: a list of classes + expect($html)->toContain("lg:grid-cols-{$n}"); // toContain() reported: interpolated + expect($html)->toContain("lg:{$n}"); // not reported: a variable after a variant is no utility yet + expect($html)->toContain("after:{$n}"); // not reported: a rule of validation with a variable + expect($html)->toContain("{$n}-[{$n}]"); // not reported: variables in brackets + expect($html)->toContain('max-w-[90rem] '.$map['x']); // toContain() reported: concatenated + expect($html)->toContain('lg:'.'flex'); // toContain() reported: joined before the check + expect($html)->toContain('headerNav'); // toContain() reported with camelCase + expect($html)->toContain('header-grid'); // not reported: kebab-case + expect($html)->toContain('hidden'); // not reported: a plain word + expect($html)->toContain('All rights reserved.'); // not reported: text + expect($html)->toContain('Projekte flex'); // not reported: text and a word + expect($html)->toContain("Projekte {$n}"); // not reported: text and a variable + expect($html)->toContain('mailto:info@example.test'); // not reported: a URL scheme + expect($html)->toContain('https://example.test/lg:x'); // not reported: a URL + expect($html)->toContain('Leak:'); // not reported: a word with a colon + expect($html)->toContain('10:30'); // not reported: a time + expect($html)->toContain('C:\temp'); // not reported: a path + expect($html)->toContain('after:today'); // not reported: a rule of validation + expect($html)->toContain('first:name'); // not reported: a key and a value + expect($html)->toContain('aria-label:foo'); // not reported: no utility after the colon + expect($html)->toContain('max-width:none'); // not reported: CSS + expect($html)->toContain('min-height:auto'); // not reported: CSS + expect($html)->toContain('[data-state=open]'); // not reported: a CSS selector + expect($html)->toContain('errors-[name]'); // not reported: a word in brackets is a key + expect($html)->toContain('--row-bg: #f5f5f5'); // not reported: a custom property + expect($html)->toContain('data-x lg:flex'); // not reported: markup, for html.markupAsString + expect($html)->toContain($map['lg:flex']); // not reported: the key of an array + } + + /** @param array $map */ + public function subjects(string $html, string|false $content, ?string $maybe, mixed $value, DOMElement $element): void + { + expect(['x'])->toBeArray()->and($html)->toContain('sm:flex'); // toContain() reported: the value of and() + expect([$html])->each->toContain('md:flex'); // toContain() reported: one element after each + expect($content)->toContain('xl:flex'); // toContain() reported: string|false + expect($maybe)->toContain('xl:flex'); // toContain() reported: ?string + expect($html)->when(true, fn ($e) => $e)->toContain('lg:flex'); // toContain() reported: when() keeps the value + expect($html) + ->toContain('Review') + ->toContain('hover:underline'); // toContain() reported: on the line of the check + expect($html)->not->toContain('lg:grid-cols-4'); // not reported: negated + expect($html)->toBe('lg:flex'); // not reported: equality + expect(['lg:flex'])->toContain('lg:flex'); // not reported: an array + expect($value)->toContain('lg:flex'); // not reported: mixed + expect($html)->json()->toContain('lg:flex'); // not reported: the chain changes the value + expect($element->getAttribute('class'))->toContain('lg:flex'); // not reported: the value of a class attribute + } + + public function checks(string $html): void + { + expect($html)->toStartWith('lg:flex'); // toStartWith() reported + expect($html)->toEndWith('lg:flex'); // toEndWith() reported + expect($html)->toMatch('/lg:flex/'); // toMatch() reported: the body of the pattern + expect($html)->toMatch('~max-w-\[90rem\]~'); // toMatch() reported: escapes removed + expect($html)->toMatch('/lg:grid-cols-\d+/'); // not reported: a real pattern + expect($html)->toMatch('/item-[0-9]/'); // not reported: a character class + expect($html)->toStartWith('Review', 'lg:flex'); // not reported: the message + $this->assertStringContainsString('lg:flex', $html); // assertStringContainsString() reported + self::assertStringContainsString('lg:flex', $html); // assertStringContainsString() reported + $this->assertStringContainsStringIgnoringCase('lg:flex', $html); // assertStringContainsStringIgnoringCase() reported + $this->assertStringContainsStringIgnoringLineEndings('lg:flex', $html); // assertStringContainsStringIgnoringLineEndings() reported + $this->assertStringStartsWith('lg:flex', $html); // assertStringStartsWith() reported + $this->assertStringEndsWith('lg:flex', $html); // assertStringEndsWith() reported + $this->assertMatchesRegularExpression('#lg:flex#i', $html); // assertMatchesRegularExpression() reported + $this->assertStringContainsString(haystack: $html, needle: 'lg:flex'); // assertStringContainsString() reported: named + $this->assertStringContainsString(haystack: 'sm:flex', needle: $html); // not reported: the literal is the haystack + $this->assertStringContainsString('Review', $html, 'lg:flex'); // not reported: the message + $this->assertStringNotContainsString('lg:flex', $html); // not reported: negative + $this->assertStringNotContainsStringIgnoringCase('lg:flex', $html); // not reported: negative + $this->assertStringStartsNotWith('lg:flex', $html); // not reported: negative + $this->assertStringEndsNotWith('lg:flex', $html); // not reported: negative + $this->assertDoesNotMatchRegularExpression('/lg:flex/', $html); // not reported: negative + } + + public function reads(string $html, Stringable $text, ?Stringable $maybe, Collection $items, DOMElement $element): void + { + expect(str_contains($html, 'lg:flex'))->toBeTrue(); // str_contains() reported: found + expect(str_contains(needle: 'lg:flex', haystack: $html))->toBeTrue(); // str_contains() reported: named + expect(strpos($html, 'lg:flex'))->not->toBeFalse(); // strpos() reported: not false is found + expect(stripos($html, 'lg:flex'))->toBeInt(); // stripos() reported + expect(substr_count($html, 'lg:flex'))->toBe(2); // substr_count() reported: a count + expect(preg_match('/lg:flex/', $html))->toBe(1); // preg_match() reported + expect(Str::contains($html, ['lg:flex', 'md:flex']))->toBeTrue(); // contains() reported: an array of needles + expect(Str::startsWith($html, 'lg:flex'))->toBeTrue(); // startsWith() reported + expect(Str::after($html, 'lg:flex'))->toContain('Review'); // not reported: a cut does not tell found from absent + expect(Str::between($html, 'lg:flex', 'md:flex'))->toBeString(); // not reported: a cut + expect(Str::match('/lg:flex/', $html))->not->toBeEmpty(); // match() reported: the pattern comes first + expect($text->contains('lg:flex'))->toBeTrue(); // contains() reported: a Stringable + expect($maybe?->contains('lg:flex'))->toBeTrue(); // contains() reported: once for ?-> + $this->assertTrue(str_contains($html, 'lg:flex')); // str_contains() reported + $this->assertSame(1, preg_match('/lg:flex/', $html)); // preg_match() reported + $this->assertNotSame(0, substr_count($html, 'lg:flex')); // substr_count() reported: not zero is found + $this->assertGreaterThan(0, mb_substr_count($html, 'lg:flex')); // mb_substr_count() reported + $this->assertNotFalse(mb_strpos($html, 'lg:flex')); // mb_strpos() reported + expect(substr_count($html, 'lg:flex'))->toBeGreaterThan(0); // substr_count() reported + expect(strpos($html, 'lg:flex'))->toBe(0); // strpos() reported: position 0 is found + $this->assertSame(0, strpos($html, 'lg:flex')); // strpos() reported: position 0 is found + expect(Str::matchAll('/lg:flex/', $html))->toHaveCount(2); // matchAll() reported: a collection of matches + $this->assertCount(1, Str::matchAll('/lg:flex/', $html)); // matchAll() reported + expect(! str_contains($html, 'lg:flex'))->toBeFalse(); // str_contains() reported: not false is found + expect(substr_count($html, 'lg:flex'))->toBeLessThan(1); // not reported: absent + expect(substr_count($html, 'lg:flex'))->toBeLessThanOrEqual(0); // not reported: absent + $this->assertLessThan(1, substr_count($html, 'lg:flex')); // not reported: absent + expect(strpos($html, 'lg:flex'))->toBeTruthy(); // not reported: position 0 is falsy, the check says neither + expect(! strpos($html, 'lg:flex'))->toBeFalse(); // not reported: ! on a position says neither + expect(str_contains($html, 'lg:flex'))->toBeBool()->toBeFalse(); // not reported: toBeBool() makes no claim + expect(str_contains($html, 'lg:flex'))->and(true)->toBeTrue(); // not reported: and() starts a new value + expect(str_contains($html, 'lg:flex'))->toBe($n > 0); // not reported: no literal to compare + expect(Str::after($html, 'lg:flex'))->toBe($html); // not reported: a cut + assertTrue(Str::contains($html, 'lg:flex')); // contains() reported: an imported function of PHPUnit + expect(str_contains($html, 'lg:flex'))->toEqual(true); // str_contains() reported: loosely true + $this->assertNotEquals(0, substr_count($html, 'lg:flex')); // substr_count() reported: loosely not zero + expect(Str::match('/lg:flex/', $html))->not->toBe(''); // match() reported: some text + expect(Str::matchAll('/lg:flex/', $html))->not->toHaveCount(0); // matchAll() reported + $this->assertEquals(0, strpos($html, 'lg:flex')); // not reported: false == 0, the check also passes when absent + expect(strpos($html, 'lg:flex'))->toEqual(0); // not reported: false == 0 + $this->assertGreaterThanOrEqual(0, strpos($html, 'lg:flex')); // not reported: false >= 0 + expect(substr_count($html, 'lg:flex'))->toEqual(0); // not reported: absent + expect(substr_count($html, 'lg:flex'))->not->toBe(''); // not reported: a count is never '' + expect(Str::of($html)->match('/lg:flex/'))->toBeTruthy(); // not reported: a Stringable is always truthy + expect(Str::matchAll('/lg:flex/', $html))->toBeGreaterThan(0); // not reported: a collection is always greater than 0 + expect(str_contains($html, 'lg:flex'))->toBeFalse(); // not reported: absent + expect(str_contains($html, 'lg:flex'))->not->toBeTrue(); // not reported: absent + expect(substr_count($html, 'lg:flex'))->toBe(0); // not reported: absent + expect(Str::doesntContain($html, 'lg:flex'))->toBeTrue(); // not reported: a negative search + $this->assertFalse(str_contains($html, 'lg:flex')); // not reported: absent + $this->assertTrue(! str_contains($html, 'lg:flex')); // not reported: negated + $this->assertSame(0, substr_count($html, 'lg:flex')); // not reported: absent + $this->assertNull(Str::match('/lg:flex/', $html) ?: null); // not reported: no search in the subject + expect(Str::matchAll('/x/', 'lg:flex'))->not->toBeEmpty(); // not reported: the literal is the subject + expect($items->contains('lg:flex'))->toBeTrue(); // not reported: a collection + expect(str_contains($element->getAttribute('class'), 'lg:flex'))->toBeTrue(); // not reported: a class attribute + str_contains($html, 'lg:flex'); // not reported: no check + if (str_contains($html, 'lg:flex')) { // not reported: a branch, no check + $items->filter(fn (string $url): bool => Str::contains($url, 'lg:flex')); // not reported: a filter + } + } +} diff --git a/tests/PHPStan/data/tests/StringChecks.php b/tests/PHPStan/data/tests/StringChecks.php index 4e14492..72a6b46 100644 --- a/tests/PHPStan/data/tests/StringChecks.php +++ b/tests/PHPStan/data/tests/StringChecks.php @@ -9,7 +9,7 @@ /** Analysed by MarkupAsStringRuleTest, never run. Each line names whether the rule reports it. */ final class StringChecks { - public function check(object $response, object $expectation, string $html, string $id): void + public function check(object $response, object $expectation, string $html, string $id, ?object $text = null): void { $response->assertSeeHtml(''); // reported $response->assertDontSeeHtml('x'); // reported: the call itself is the problem @@ -47,5 +47,10 @@ public function check(object $response, object $expectation, string $html, strin mb_substr_count($html, 'bg-blue-500" data-dot'); // reported mb_strpos($html, 'Review'); // text: not reported $expectation->toContain('[data-name="Ben"]'); // a CSS selector: not reported + $this->assertStringContainsStringIgnoringCase('', $html); // reported + $this->assertStringStartsNotWith('/', $html); // reported + $text?->contains('
  • '); // reported once } }