Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix @include variable scoping #11

Merged
merged 6 commits into from
Feb 21, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"type": "phpstan-extension",
"require": {
"php": "^8.0",
"phpstan/phpstan": "^1.4.4",
"phpstan/phpstan": "^1.4.6",
"illuminate/view": "^8.82 || ^9",
"symplify/template-phpstan-compiler": "^10.0.20",
"illuminate/filesystem": "^8.82 || ^9.0",
Expand All @@ -13,7 +13,7 @@
"require-dev": {
"phpunit/phpunit": "^9.5",
"roave/security-advisories": "dev-latest",
"orchestra/testbench": "^6.24",
"orchestra/testbench": "^6.24 || ^7.0",
"doctrine/coding-standard": "^9.0",
"symplify/easy-testing": "^10.0"
},
Expand Down
3 changes: 2 additions & 1 deletion config/extension.neon
Original file line number Diff line number Diff line change
Expand Up @@ -37,4 +37,5 @@ services:
- Vural\PHPStanBladeRule\Compiler\BladeToPHPCompiler
- Vural\PHPStanBladeRule\Compiler\PhpContentExtractor
- Vural\PHPStanBladeRule\PHPParser\NodeVisitor\BladeLineNumberNodeVisitor
- class: Vural\PHPStanBladeRule\Support\DirectoryHelper
- Vural\PHPStanBladeRule\PHPParser\ConvertArrayStringToArray
- Vural\PHPStanBladeRule\Support\DirectoryHelper
12 changes: 11 additions & 1 deletion phpstan-baseline.neon
Original file line number Diff line number Diff line change
Expand Up @@ -35,13 +35,23 @@ parameters:
count: 1
path: tests/Compiler/PhpContentExtractorTest.php

-
message: "#^Method Vural\\\\PHPStanBladeRule\\\\Tests\\\\PHPParser\\\\ConvertArrayStringToArrayTest\\:\\:greenProvider\\(\\) return type has no value type specified in iterable type Generator\\.$#"
count: 1
path: tests/PHPParser/ConvertArrayStringToArrayTest.php

-
message: "#^Method Vural\\\\PHPStanBladeRule\\\\Tests\\\\PHPParser\\\\ConvertArrayStringToArrayTest\\:\\:redProvider\\(\\) return type has no value type specified in iterable type Generator\\.$#"
count: 1
path: tests/PHPParser/ConvertArrayStringToArrayTest.php

-
message: "#^Parameter \\#1 \\$rules of class Vural\\\\PHPStanBladeRule\\\\Rules\\\\BladeRule constructor expects array\\<PHPStan\\\\Rules\\\\Rule\\<PhpParser\\\\Node\\>\\>, array\\{PHPStan\\\\Rules\\\\Operators\\\\InvalidBinaryOperationRule\\} given\\.$#"
count: 1
path: tests/Rules/BladeViewRuleTest.php

-
message: "#^Parameter \\#1 \\$rules of class Vural\\\\PHPStanBladeRule\\\\Rules\\\\BladeRule constructor expects array\\<PHPStan\\\\Rules\\\\Rule\\<PhpParser\\\\Node\\>\\>, array\\{PHPStan\\\\Rules\\\\Operators\\\\InvalidBinaryOperationRule, PHPStan\\\\Rules\\\\Cast\\\\EchoRule\\} given\\.$#"
message: "#^Parameter \\#1 \\$rules of class Vural\\\\PHPStanBladeRule\\\\Rules\\\\BladeRule constructor expects array\\<PHPStan\\\\Rules\\\\Rule\\<PhpParser\\\\Node\\>\\>, array\\{PHPStan\\\\Rules\\\\Operators\\\\InvalidBinaryOperationRule, PHPStan\\\\Rules\\\\Cast\\\\EchoRule, PHPStan\\\\Rules\\\\Variables\\\\DefinedVariableRule\\} given\\.$#"
count: 1
path: tests/Rules/LaravelViewFunctionRuleTest.php

56 changes: 51 additions & 5 deletions src/Compiler/BladeToPHPCompiler.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,17 +24,26 @@
use Symplify\TemplatePHPStanCompiler\ValueObject\VariableAndType;
use Throwable;
use Vural\PHPStanBladeRule\Blade\PhpLineToTemplateLineResolver;
use Vural\PHPStanBladeRule\PHPParser\ConvertArrayStringToArray;
use Vural\PHPStanBladeRule\PHPParser\NodeVisitor\AddLoopVarTypeToForeachNodeVisitor;
use Vural\PHPStanBladeRule\PHPParser\NodeVisitor\RemoveEnvVariableNodeVisitor;
use Vural\PHPStanBladeRule\PHPParser\NodeVisitor\RemoveEscapeFunctionNodeVisitor;
use Vural\PHPStanBladeRule\ValueObject\IncludedViewAndVariables;
use Vural\PHPStanBladeRule\ValueObject\PhpFileContentsWithLineMap;

use function array_keys;
use function array_map;
use function array_merge;
use function getcwd;
use function implode;
use function in_array;
use function preg_match_all;
use function preg_quote;
use function preg_replace;
use function sprintf;
use function trim;

use const PHP_EOL;

final class BladeToPHPCompiler
{
Expand Down Expand Up @@ -63,10 +72,11 @@ public function __construct(
private FileNameAndLineNumberAddingPreCompiler $preCompiler,
private PhpLineToTemplateLineResolver $phpLineToTemplateLineResolver,
private PhpContentExtractor $phpContentExtractor,
private ConvertArrayStringToArray $convertArrayStringToArray,
private array $components = [],
) {
$parserFactory = new ParserFactory();
$this->parser = $parserFactory->create(ParserFactory::PREFER_PHP7);
$this->parser = $parserFactory->create(ParserFactory::ONLY_PHP7);

// Disable component rendering
$this->compiler->withoutComponentTags();
Expand All @@ -89,11 +99,13 @@ public function compileContent(string $filePath, string $fileContents, array $va

$includes = $this->getIncludes($rawPhpContent);

$allVariablesList = array_map(static fn (VariableAndType $variableAndType) => $variableAndType->getVariable(), $variablesAndTypes);

// Recursively fetch and compile includes
while ($includes !== []) {
foreach ($includes as $include) {
try {
$includedFilePath = $this->fileViewFinder->find($include);
$includedFilePath = $this->fileViewFinder->find($include->getIncludedViewName());
$includedFileContents = $this->fileSystem->get($includedFilePath);

$preCompiledContents = $this->preCompiler->setFileName($includedFilePath)->compileString($includedFileContents);
Expand All @@ -106,7 +118,31 @@ public function compileContent(string $filePath, string $fileContents, array $va
$includedContent = '';
}

$rawPhpContent = preg_replace(sprintf(self::VIEW_INCLUDE_REPLACE_REGEX, preg_quote($include)), $includedContent, $rawPhpContent) ?? $rawPhpContent;
$usePlaceholder = 'use(%s)';

$includedContentPlaceHolder = <<<STRING
(function () %s {
%s
%s
});
STRING;

$includedViewVariables = implode(PHP_EOL, array_map(static fn (string $key, string $value) => '$' . $key . ' = ' . $value . ';', array_keys($include->getVariablesAndValues()), $include->getVariablesAndValues()));

$rawPhpContent = preg_replace(sprintf(self::VIEW_INCLUDE_REPLACE_REGEX, preg_quote($include->getIncludedViewName())), sprintf(
$includedContentPlaceHolder,
sprintf($usePlaceholder, implode(', ', array_map(static fn (string $variable) => '$' . $variable, $allVariablesList))),
$includedViewVariables,
$includedContent
), $rawPhpContent) ?? $rawPhpContent;

foreach ($include->getVariablesAndValues() as $variable => $value) {
if (in_array($variable, $allVariablesList, true)) {
continue;
}

$allVariablesList[] = $variable;
}
}

$includes = $this->getIncludes($rawPhpContent);
Expand Down Expand Up @@ -162,12 +198,22 @@ private function traverseStmtsWithVisitors(array $stmts, array $nodeVisitors): a
return $nodeTraverser->traverse($stmts);
}

/** @return string[] */
/** @return IncludedViewAndVariables[] */
private function getIncludes(string $compiled): array
{
preg_match_all(self::VIEW_INCLUDE_REGEX, $compiled, $includes);

return $includes[1];
$return = [];

foreach ($includes[1] as $i => $include) {
$arrayString = trim($includes[2][$i], ' ,');

$array = $this->convertArrayStringToArray->convert($arrayString);

$return[] = new IncludedViewAndVariables($include, $array);
}

return $return;
}

private function setupBladeComponents(): void
Expand Down
25 changes: 24 additions & 1 deletion src/Compiler/PhpContentExtractor.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,11 @@

use function array_map;
use function array_unshift;
use function explode;
use function implode;
use function preg_match;
use function preg_match_all;
use function rtrim;
use function str_replace;
use function str_starts_with;
use function strip_tags;
Expand All @@ -24,12 +27,15 @@ final class PhpContentExtractor
*/
private const PHP_OPEN_CLOSE_TAGS_REGEX = '#^(/\*\* file: .*?, line: \d+ \*/)(?!\s?/\*\* file: ).*?<\?php(.*?)\?>$#ms';

private const TEMPLATE_FILE_NAME_AND_LINE_NUMBER_STRICT_REGEX = '#^(/\*\* file: .*?, line: \d+ \*/)$#m';

/**
* @param string $bladeCompiledContent This should be the string that is pre-compiled for Blade and then compiled by Blade.
*/
public function extract(string $bladeCompiledContent, bool $addPHPOpeningTag = true): string
{
$bladeCompiledContent = $this->removeHtmlTags($bladeCompiledContent);
$bladeCompiledContent = $this->removeEmptyLines($bladeCompiledContent);

preg_match_all(self::PHP_OPEN_CLOSE_TAGS_REGEX, $bladeCompiledContent, $matches);

Expand All @@ -41,7 +47,7 @@ public function extract(string $bladeCompiledContent, bool $addPHPOpeningTag = t
$matches[1][$key] = $matches[1][$key - 1];
}

$phpContents = array_map(static fn ($a, $b) => $a . $b, $matches[1], $matches[2]);
$phpContents = array_map(static fn ($a, $b) => $a . rtrim($b), $matches[1], $matches[2]);

if ($phpContents !== [] && $addPHPOpeningTag) {
array_unshift($phpContents, '<?php');
Expand All @@ -65,4 +71,21 @@ private function removeHtmlTags(string $input): string

return str_replace('">', '', $strippedInput);
}

private function removeEmptyLines(string $bladeCompiledContent): string
{
$lines = explode(PHP_EOL, $bladeCompiledContent);

foreach ($lines as $key => $line) {
$trimmedLine = trim($line);

if (! preg_match(self::TEMPLATE_FILE_NAME_AND_LINE_NUMBER_STRICT_REGEX, $trimmedLine)) {
continue;
}

unset($lines[$key]);
}

return implode(PHP_EOL, $lines);
}
}
85 changes: 85 additions & 0 deletions src/PHPParser/ConvertArrayStringToArray.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
<?php

declare(strict_types=1);

namespace Vural\PHPStanBladeRule\PHPParser;

use PhpParser\ConstExprEvaluationException;
use PhpParser\ConstExprEvaluator;
use PhpParser\Node\Expr;
use PhpParser\Node\Stmt\Expression;
use PhpParser\Parser;
use PhpParser\ParserFactory;
use PhpParser\PrettyPrinter\Standard;

use function assert;
use function count;
use function is_string;

/**
* This class converts the string `['foo' => 'bar', 'bar' => 'baz']` to actual PHP array `['foo' => 'bar', 'bar' => 'baz']`
*/
final class ConvertArrayStringToArray
{
private Parser $parser;

public function __construct(private Standard $printer, private ConstExprEvaluator $constExprEvaluator)
{
$parserFactory = new ParserFactory();
$this->parser = $parserFactory->create(ParserFactory::ONLY_PHP7);
}

/** @return array<string, string> */
public function convert(string $array): array
{
$array = '<?php ' . $array . ';';

$stmts = $this->parser->parse($array);

if ($stmts === null || count($stmts) !== 1) {
return [];
}

if (! $stmts[0] instanceof Expression) {
return [];
}

if (! $stmts[0]->expr instanceof Expr\Array_) {
return [];
}

$array = $stmts[0]->expr;
assert($array instanceof Expr\Array_);

$result = [];

foreach ($array->items as $item) {
assert($item instanceof Expr\ArrayItem);

if ($item->key === null) {
continue;
}

$key = $this->resolveKey($item->key);

if (! is_string($key)) {
continue;
}

$value = $this->printer->prettyPrintExpr($item->value);

$result[$key] = $value;
}

return $result;
}

private function resolveKey(Expr $expr): mixed
{
try {
return $this->constExprEvaluator->evaluateDirectly($expr);
} catch (ConstExprEvaluationException) {
return null;
}
}
}
26 changes: 26 additions & 0 deletions src/ValueObject/IncludedViewAndVariables.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?php

declare(strict_types=1);

namespace Vural\PHPStanBladeRule\ValueObject;

final class IncludedViewAndVariables
{
/** @param array<string, string> $variablesAndValues */
public function __construct(private string $includedViewName, private array $variablesAndValues)
{
}

/**
* @return array<string, string>
*/
public function getVariablesAndValues(): array
{
return $this->variablesAndValues;
}

public function getIncludedViewName(): string
{
return $this->includedViewName;
}
}
5 changes: 4 additions & 1 deletion tests/Compiler/BladeToPHPCompilerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use Illuminate\View\Compilers\BladeCompiler;
use Illuminate\View\FileViewFinder;
use Iterator;
use PhpParser\ConstExprEvaluator;
use PhpParser\PrettyPrinter\Standard;
use PHPUnit\Framework\TestCase;
use Symplify\EasyTesting\DataProvider\StaticFixtureFinder;
Expand All @@ -20,6 +21,7 @@
use Vural\PHPStanBladeRule\Compiler\BladeToPHPCompiler;
use Vural\PHPStanBladeRule\Compiler\FileNameAndLineNumberAddingPreCompiler;
use Vural\PHPStanBladeRule\Compiler\PhpContentExtractor;
use Vural\PHPStanBladeRule\PHPParser\ConvertArrayStringToArray;
use Vural\PHPStanBladeRule\PHPParser\NodeVisitor\BladeLineNumberNodeVisitor;

use function sys_get_temp_dir;
Expand Down Expand Up @@ -47,7 +49,8 @@ protected function setUp(): void
new FileViewFinder($fileSystem, $templatePaths),
new FileNameAndLineNumberAddingPreCompiler($templatePaths),
new PhpLineToTemplateLineResolver(new BladeLineNumberNodeVisitor()),
new PhpContentExtractor()
new PhpContentExtractor(),
new ConvertArrayStringToArray(new Standard(), new ConstExprEvaluator()),
);

// Setup the variable names and types that'll be available to all templates
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,4 @@
</div>
-----
<?php
/** file: foo.blade.php, line: 1 */
/** file: foo.blade.php, line: 2 */ echo e($foo);
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,5 @@
</div>
-----
<?php
/** file: foo.blade.php, line: 1 */
/** file: foo.blade.php, line: 2 */ echo e(/** file: foo.blade.php, line: 3 */ $foo
/** file: foo.blade.php, line: 4 */);
Loading