Skip to content

[AssetMapper] Adding "excluded_patterns" option #50291

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

Merged
merged 1 commit into from
May 12, 2023
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
Original file line number Diff line number Diff line change
Expand Up @@ -821,6 +821,7 @@ private function addAssetMapperSection(ArrayNodeDefinition $rootNode, callable $
->info('Asset Mapper configuration')
->{$enableIfStandalone('symfony/asset-mapper', AssetMapper::class)}()
->fixXmlConfig('path')
->fixXmlConfig('excluded_pattern')
->fixXmlConfig('extension')
->fixXmlConfig('importmap_script_attribute')
->children()
Expand Down Expand Up @@ -856,6 +857,11 @@ private function addAssetMapperSection(ArrayNodeDefinition $rootNode, callable $
->end()
->prototype('scalar')->end()
->end()
->arrayNode('excluded_patterns')
->info('Array of glob patterns of asset file paths that should not be in the asset mapper')
->prototype('scalar')->end()
->example(['*/assets/build/*', '*/*_.scss'])
->end()
->booleanNode('server')
->info('If true, a "dev server" will return the assets from the public directory (true in "debug" mode only by default)')
->defaultValue($this->debug)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
use Symfony\Component\Finder\Finder;
use Symfony\Component\Finder\Glob;
use Symfony\Component\Form\ChoiceList\Factory\CachingFactoryDecorator;
use Symfony\Component\Form\Extension\HtmlSanitizer\Type\TextTypeHtmlSanitizerExtension;
use Symfony\Component\Form\Form;
Expand Down Expand Up @@ -1277,8 +1278,14 @@ private function registerAssetMapperConfiguration(array $config, ContainerBuilde
$paths[$dir] = sprintf('bundles/%s', preg_replace('/bundle$/', '', strtolower($name)));
}
}
$excludedPathPatterns = [];
foreach ($config['excluded_patterns'] as $path) {
$excludedPathPatterns[] = Glob::toRegex($path, true, false);
}

$container->getDefinition('asset_mapper.repository')
->setArgument(0, $paths);
->setArgument(0, $paths)
->setArgument(2, $excludedPathPatterns);

$publicDirName = $this->getPublicDirectoryName($container);
$container->getDefinition('asset_mapper.public_assets_path_resolver')
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
->args([
abstract_arg('array of asset mapper paths'),
param('kernel.project_dir'),
abstract_arg('array of excluded path patterns'),
])

->set('asset_mapper.public_assets_path_resolver', PublicAssetsPathResolver::class)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,7 @@
<xsd:complexType name="asset_mapper">
<xsd:sequence>
<xsd:element name="path" type="asset_mapper_path" minOccurs="0" maxOccurs="unbounded" />
<xsd:element name="excluded-pattern" type="xsd:string" minOccurs="0" maxOccurs="unbounded" />
<xsd:element name="server" type="xsd:boolean" minOccurs="0" />
<xsd:element name="public_prefix" type="xsd:string" minOccurs="0" />
<xsd:element name="strict-mode" type="xsd:boolean" minOccurs="0" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@ public function testAssetMapperCanBeEnabled()
$defaultConfig = [
'enabled' => true,
'paths' => [],
'excluded_patterns' => [],
'server' => true,
'public_prefix' => '/assets/',
'strict_mode' => true,
Expand Down Expand Up @@ -615,6 +616,7 @@ protected static function getBundleDefaultConfig()
'asset_mapper' => [
'enabled' => !class_exists(FullStack::class),
'paths' => [],
'excluded_patterns' => [],
'server' => true,
'public_prefix' => '/assets/',
'strict_mode' => true,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
<framework:asset-mapper>
<framework:path>assets/</framework:path>
<framework:path namespace="my_namespace">assets2/</framework:path>
<framework:excluded-pattern>*/*.scss</framework:excluded-pattern>
<framework:server>true</framework:server>
<framework:public_prefix>/assets_path/</framework:public_prefix>
<framework:strict-mode>true</framework:strict-mode>
Expand Down
27 changes: 25 additions & 2 deletions src/Symfony/Component/AssetMapper/AssetMapperRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,8 @@ class AssetMapperRepository
*/
public function __construct(
private readonly array $paths,
private readonly string $projectRootDir
private readonly string $projectRootDir,
private readonly array $excludedPathPatterns = [],
) {
}

Expand All @@ -54,7 +55,7 @@ public function find(string $logicalPath): ?string
}

$file = rtrim($path, '/').'/'.$localLogicalPath;
if (is_file($file)) {
if (is_file($file) && !$this->isExcluded($file)) {
return realpath($file);
}
}
Expand All @@ -70,6 +71,10 @@ public function findLogicalPath(string $filesystemPath): ?string

$filesystemPath = realpath($filesystemPath);

if ($this->isExcluded($filesystemPath)) {
return null;
}

foreach ($this->getDirectories() as $path => $namespace) {
if (!str_starts_with($filesystemPath, $path)) {
continue;
Expand Down Expand Up @@ -104,6 +109,10 @@ public function all(): array
continue;
}

if ($this->isExcluded($file->getPathname())) {
continue;
}

/** @var RecursiveDirectoryIterator $innerIterator */
$innerIterator = $iterator->getInnerIterator();
$logicalPath = ($namespace ? rtrim($namespace, '/').'/' : '').$innerIterator->getSubPathName();
Expand Down Expand Up @@ -160,4 +169,18 @@ private function normalizeLogicalPath(string $logicalPath): string
{
return ltrim(str_replace('\\', '/', $logicalPath), '/\\');
}

private function isExcluded(string $filesystemPath): bool
{
// normalize Windows slashes and remove trailing slashes
$filesystemPath = rtrim(str_replace('\\', '/', $filesystemPath), '/');

foreach ($this->excludedPathPatterns as $pattern) {
if (preg_match($pattern, $filesystemPath)) {
return true;
}
}

return false;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

use PHPUnit\Framework\TestCase;
use Symfony\Component\AssetMapper\AssetMapperRepository;
use Symfony\Component\Finder\Glob;

class AssetMapperRepositoryTest extends TestCase
{
Expand Down Expand Up @@ -128,4 +129,36 @@ public function testAllWithNamespaces()

$this->assertEquals($normalizedExpectedAllAssets, $normalizedActualAssets);
}

public function testExcludedPaths()
{
$excludedPatterns = [
'*/subdir/*',
'*/*3.css',
'*/*.digested.*',
];
$excludedGlobs = array_map(function ($pattern) {
// globbed equally in FrameworkExtension
return Glob::toRegex($pattern, true, false);
}, $excludedPatterns);
$repository = new AssetMapperRepository([
'dir1' => '',
'dir2' => '',
'dir3' => '',
], __DIR__.'/fixtures', $excludedGlobs);

$expectedAssets = [
'file1.css',
'file2.js',
'file4.js',
'test.gif.foo',
];

$actualAssets = array_keys($repository->all());
sort($actualAssets);
$this->assertEquals($expectedAssets, $actualAssets);

$this->assertNull($repository->find('file3.css'));
$this->assertNull($repository->findLogicalPath(__DIR__.'/fixtures/dir2/file3.css'));
}
}
1 change: 1 addition & 0 deletions src/Symfony/Component/AssetMapper/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
"symfony/asset": "^5.4|^6.0",
"symfony/browser-kit": "^5.4|^6.0",
"symfony/console": "^5.4|^6.0",
"symfony/finder": "^5.4|^6.0",
"symfony/framework-bundle": "^6.3",
"symfony/http-foundation": "^5.4|^6.0",
"symfony/http-kernel": "^5.4|^6.0"
Expand Down