php-matcher icon indicating copy to clipboard operation
php-matcher copied to clipboard

Make possible to use assertMatchesPattern in static methods

Open alexander-schranz opened this issue 3 years ago • 2 comments

Sometimes I get into cases where I want to use the assertMatchesPattern like other assertions in a static method.

Maybe the assertMatchesPattern could be changed from:

    protected function assertMatchesPattern($pattern, $value, string $message = '') : void
    {
        TestCase::assertThat($value, self::matchesPattern($pattern, $this->backtrace), $message);
    }
    protected function static assertMatchesPattern($pattern, $value, string $message = '', ?Backtrace $backtrace = null) : void
    {
        TestCase::assertThat($value, self::matchesPattern($pattern, ?Backtrace $backtrace = null), $message);
    }

As it would be a bc break it could only be done in a new major release.

alexander-schranz avatar May 04 '22 09:05 alexander-schranz

hey, could you share some more context about those use cases? Maybe some simple code examples if possible? (even very simplified)

norberttech avatar May 04 '22 10:05 norberttech

It was something like this:

public function testTest(): string
{
    $html = static::getAsyncMessage();
    
    HtmlJsonMatcher::assertHtml(<<<JSON
    
JSON, $html, 'list');
}
class HtmlJsonMatcher {
     use PHPMatcherAssertions;
    
     public static function assertHtml($expectedJsonPattern, string $html, string $variable): void
     {
        // some other asserts
     
        // extract javascript variable to match against the created component
        preg_match_all('/(<script>([\s\S^?]+?)var ' . $variable . ' =)([\s\S^?]+?)<\/script>/', $text, $matches);
        $content = trim(trim($matches[3][0]), ';');
        // convert javascript object to json via json5 library
        $contentJson = json_encode(json5_decode($content), \JSON_PRETTY_PRINT);

        // following fails while assertMatchesPattern is not able to be used in a static method
        self::assertMatchesPattern($expectedJson, $contentJson);
        
        // more asserts
     }
}

Sure it is possible to move things and not relay on static method here. But as all other assertions of PHPUnit are able to be used in static methods it would be nice to have possibility to use also assertMatchesPattern in static methods.

alexander-schranz avatar May 04 '22 11:05 alexander-schranz