Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit 8901c7e

Browse filesBrowse files
committed
feature #22046 [Asset] Adding a new version strategy that reads from a manifest JSON file (weaverryan)
This PR was squashed before being merged into the 3.3-dev branch (closes #22046). Discussion ---------- [Asset] Adding a new version strategy that reads from a manifest JSON file | Q | A | ------------- | --- | Branch? | master | Bug fix? | no | New feature? | yes | BC breaks? | no | Deprecations? | no | Tests pass? | yes | Fixed tickets | n/a | License | MIT | Doc PR | symfony/symfony-docs#7659 Hi guys! Often, when using a frontend task manager or bundler (e.g. webpack of gulp), the final assets are dumped with a version or content hash in the filename itself (e.g. main.123abc.css). To know what the correct, current hashed filename is, you'll dump a `manifest.json` file - e.g. ```json { "main.js": "main.123abc.js", "css/styles.css": "css/styles.555def.css" } ``` Examples: [gulp-rev](https://github.com/sindresorhus/gulp-rev) and [webpack-manifest-plugin](https://www.npmjs.com/package/webpack-manifest-plugin). This PR adds a new version strategy that will look up the asset path (e.g. `main.css`) in that file and return the final, versioned path. Some people may dump manifest files in other formats, but I think this catches the most common use-case (and you can always still create your own version strategy). I've written this to be "forgiving" - if a path doesn't exist in the manifest, the path is simply returned, unaltered. Another implementation *could* have been to add a new Twig filter (e.g. `{{ asset('main.css|manifest_path) }}`) - but I thought I'd try first using the existing versioning system. ## Usage ```yml # app/config/config.yml framework: # ... assets: # added validation prevents you from setting json_manifest_path AND version, for example json_manifest_path: '%kernel.root_dir%/../web/manifest.json' ``` ```twig {# someTemplate.html.twig #} {# use asset() just like normal #} <script src="{{ asset('js/main.js') }}"></script> ``` ## TODO * fabbot hates my invalid json syntax file... even though I tried to be clever and not give it a `.json` suffix :) Commits ------- 07fec2b [Asset] Adding a new version strategy that reads from a manifest JSON file
2 parents 869e68d + 07fec2b commit 8901c7e
Copy full SHA for 8901c7e

File tree

16 files changed

+264
-46
lines changed
Filter options

16 files changed

+264
-46
lines changed

‎.php_cs.dist

Copy file name to clipboardExpand all lines: .php_cs.dist
+2Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,5 +37,7 @@ return PhpCsFixer\Config::create()
3737
->notPath('Symfony/Bundle/FrameworkBundle/Tests/Templating/Helper/Resources/Custom/_name_entry_label.html.php')
3838
// explicit heredoc test
3939
->notPath('Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Resources/views/translation.html.php')
40+
// purposefully invalid JSON
41+
->notPath('Symfony/Component/Asset/Tests/fixtures/manifest-invalid.json')
4042
)
4143
;

‎src/Symfony/Bundle/FrameworkBundle/CHANGELOG.md

Copy file name to clipboardExpand all lines: src/Symfony/Bundle/FrameworkBundle/CHANGELOG.md
+2Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@ CHANGELOG
44
3.3.0
55
-----
66

7+
* Added a new new version strategy option called json_manifest_path
8+
that allows you to use the `JsonManifestVersionStrategy`.
79
* Added support for the `controller.service_arguments` tag, for injecting services into controllers' actions
810
* Deprecated `cache:clear` with warmup (always call it with `--no-warmup`)
911
* Deprecated the "framework.trusted_proxies" configuration option and the corresponding "kernel.trusted_proxies" parameter

‎src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Configuration.php

Copy file name to clipboardExpand all lines: src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Configuration.php
+26Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -551,6 +551,7 @@ private function addAssetsSection(ArrayNodeDefinition $rootNode)
551551
->scalarNode('version_strategy')->defaultNull()->end()
552552
->scalarNode('version')->defaultNull()->end()
553553
->scalarNode('version_format')->defaultValue('%%s?%%s')->end()
554+
->scalarNode('json_manifest_path')->defaultNull()->end()
554555
->scalarNode('base_path')->defaultValue('')->end()
555556
->arrayNode('base_urls')
556557
->requiresAtLeastOneElement()
@@ -567,6 +568,18 @@ private function addAssetsSection(ArrayNodeDefinition $rootNode)
567568
})
568569
->thenInvalid('You cannot use both "version_strategy" and "version" at the same time under "assets".')
569570
->end()
571+
->validate()
572+
->ifTrue(function ($v) {
573+
return isset($v['version_strategy']) && isset($v['json_manifest_path']);
574+
})
575+
->thenInvalid('You cannot use both "version_strategy" and "json_manifest_path" at the same time under "assets".')
576+
->end()
577+
->validate()
578+
->ifTrue(function ($v) {
579+
return isset($v['version']) && isset($v['json_manifest_path']);
580+
})
581+
->thenInvalid('You cannot use both "version" and "json_manifest_path" at the same time under "assets".')
582+
->end()
570583
->fixXmlConfig('package')
571584
->children()
572585
->arrayNode('packages')
@@ -582,6 +595,7 @@ private function addAssetsSection(ArrayNodeDefinition $rootNode)
582595
->end()
583596
->end()
584597
->scalarNode('version_format')->defaultNull()->end()
598+
->scalarNode('json_manifest_path')->defaultNull()->end()
585599
->scalarNode('base_path')->defaultValue('')->end()
586600
->arrayNode('base_urls')
587601
->requiresAtLeastOneElement()
@@ -598,6 +612,18 @@ private function addAssetsSection(ArrayNodeDefinition $rootNode)
598612
})
599613
->thenInvalid('You cannot use both "version_strategy" and "version" at the same time under "assets" packages.')
600614
->end()
615+
->validate()
616+
->ifTrue(function ($v) {
617+
return isset($v['version_strategy']) && isset($v['json_manifest_path']);
618+
})
619+
->thenInvalid('You cannot use both "version_strategy" and "json_manifest_path" at the same time under "assets" packages.')
620+
->end()
621+
->validate()
622+
->ifTrue(function ($v) {
623+
return isset($v['version']) && isset($v['json_manifest_path']);
624+
})
625+
->thenInvalid('You cannot use both "version" and "json_manifest_path" at the same time under "assets" packages.')
626+
->end()
601627
->end()
602628
->end()
603629
->end()

‎src/Symfony/Bundle/FrameworkBundle/DependencyInjection/FrameworkExtension.php

Copy file name to clipboardExpand all lines: src/Symfony/Bundle/FrameworkBundle/DependencyInjection/FrameworkExtension.php
+25-13Lines changed: 25 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -810,7 +810,7 @@ private function registerAssetsConfiguration(array $config, ContainerBuilder $co
810810
if ($config['version_strategy']) {
811811
$defaultVersion = new Reference($config['version_strategy']);
812812
} else {
813-
$defaultVersion = $this->createVersion($container, $config['version'], $config['version_format'], '_default');
813+
$defaultVersion = $this->createVersion($container, $config['version'], $config['version_format'], $config['json_manifest_path'], '_default');
814814
}
815815

816816
$defaultPackage = $this->createPackageDefinition($config['base_path'], $config['base_urls'], $defaultVersion);
@@ -820,11 +820,14 @@ private function registerAssetsConfiguration(array $config, ContainerBuilder $co
820820
foreach ($config['packages'] as $name => $package) {
821821
if (null !== $package['version_strategy']) {
822822
$version = new Reference($package['version_strategy']);
823-
} elseif (!array_key_exists('version', $package)) {
823+
} elseif (!array_key_exists('version', $package) && null === $package['json_manifest_path']) {
824+
// if neither version nor json_manifest_path are specified, use the default
824825
$version = $defaultVersion;
825826
} else {
827+
// let format fallback to main version_format
826828
$format = $package['version_format'] ?: $config['version_format'];
827-
$version = $this->createVersion($container, $package['version'], $format, $name);
829+
$version = isset($package['version']) ? $package['version'] : null;
830+
$version = $this->createVersion($container, $version, $format, $package['json_manifest_path'], $name);
828831
}
829832

830833
$container->setDefinition('assets._package_'.$name, $this->createPackageDefinition($package['base_path'], $package['base_urls'], $version));
@@ -856,20 +859,29 @@ private function createPackageDefinition($basePath, array $baseUrls, Reference $
856859
return $package;
857860
}
858861

859-
private function createVersion(ContainerBuilder $container, $version, $format, $name)
862+
private function createVersion(ContainerBuilder $container, $version, $format, $jsonManifestPath, $name)
860863
{
861-
if (null === $version) {
862-
return new Reference('assets.empty_version_strategy');
864+
// Configuration prevents $version and $jsonManifestPath from being set
865+
if (null !== $version) {
866+
$def = new ChildDefinition('assets.static_version_strategy');
867+
$def
868+
->replaceArgument(0, $version)
869+
->replaceArgument(1, $format)
870+
;
871+
$container->setDefinition('assets._version_'.$name, $def);
872+
873+
return new Reference('assets._version_'.$name);
863874
}
864875

865-
$def = new ChildDefinition('assets.static_version_strategy');
866-
$def
867-
->replaceArgument(0, $version)
868-
->replaceArgument(1, $format)
869-
;
870-
$container->setDefinition('assets._version_'.$name, $def);
876+
if (null !== $jsonManifestPath) {
877+
$def = new ChildDefinition('assets.json_manifest_version_strategy');
878+
$def->replaceArgument(0, $jsonManifestPath);
879+
$container->setDefinition('assets._version_'.$name, $def);
880+
881+
return new Reference('assets._version_'.$name);
882+
}
871883

872-
return new Reference('assets._version_'.$name);
884+
return new Reference('assets.empty_version_strategy');
873885
}
874886

875887
/**

‎src/Symfony/Bundle/FrameworkBundle/Resources/config/assets.xml

Copy file name to clipboardExpand all lines: src/Symfony/Bundle/FrameworkBundle/Resources/config/assets.xml
+4Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,10 @@
3939

4040
<service id="assets.empty_version_strategy" class="Symfony\Component\Asset\VersionStrategy\EmptyVersionStrategy" public="false" />
4141

42+
<service id="assets.json_manifest_version_strategy" class="Symfony\Component\Asset\VersionStrategy\JsonManifestVersionStrategy" abstract="true" public="false">
43+
<argument /> <!-- manifest path -->
44+
</service>
45+
4246
<service id="assets.preload_manager" class="Symfony\Component\Asset\Preload\PreloadManager" public="false" />
4347

4448
<service id="asset.preload_listener" class="Symfony\Component\Asset\EventListener\PreloadListener">

‎src/Symfony/Bundle/FrameworkBundle/Resources/config/schema/symfony-1.0.xsd

Copy file name to clipboardExpand all lines: src/Symfony/Bundle/FrameworkBundle/Resources/config/schema/symfony-1.0.xsd
+2Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,7 @@
131131
<xsd:attribute name="version-strategy" type="xsd:string" />
132132
<xsd:attribute name="version" type="xsd:string" />
133133
<xsd:attribute name="version-format" type="xsd:string" />
134+
<xsd:attribute name="json-manifest-path" type="xsd:string" />
134135
</xsd:complexType>
135136

136137
<xsd:complexType name="package">
@@ -143,6 +144,7 @@
143144
<xsd:attribute name="version-strategy" type="xsd:string" />
144145
<xsd:attribute name="version" type="xsd:string" />
145146
<xsd:attribute name="version-format" type="xsd:string" />
147+
<xsd:attribute name="json-manifest-path" type="xsd:string" />
146148
</xsd:complexType>
147149

148150
<xsd:complexType name="templating">

‎src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/ConfigurationTest.php

Copy file name to clipboardExpand all lines: src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/ConfigurationTest.php
+47-32Lines changed: 47 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
use PHPUnit\Framework\TestCase;
1515
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Configuration;
1616
use Symfony\Bundle\FullStack;
17+
use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException;
1718
use Symfony\Component\Config\Definition\Processor;
1819

1920
class ConfigurationTest extends TestCase
@@ -120,54 +121,67 @@ public function testAssetsCanBeEnabled()
120121
'base_path' => '',
121122
'base_urls' => array(),
122123
'packages' => array(),
124+
'json_manifest_path' => null,
123125
);
124126

125127
$this->assertEquals($defaultConfig, $config['assets']);
126128
}
127129

128130
/**
129-
* @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException
130-
* @expectedExceptionMessage You cannot use both "version_strategy" and "version" at the same time under "assets".
131+
* @dataProvider provideInvalidAssetConfigurationTests
131132
*/
132-
public function testInvalidVersionStrategy()
133+
public function testInvalidAssetsConfiguration(array $assetConfig, $expectedMessage)
133134
{
135+
$this->{method_exists($this, $_ = 'expectException') ? $_ : 'setExpectedException'}(
136+
InvalidConfigurationException::class,
137+
$expectedMessage
138+
);
139+
if (method_exists($this, 'expectExceptionMessage')) {
140+
$this->expectExceptionMessage($expectedMessage);
141+
}
142+
134143
$processor = new Processor();
135144
$configuration = new Configuration(true);
136145
$processor->processConfiguration($configuration, array(
137-
array(
138-
'assets' => array(
139-
'base_urls' => '//example.com',
140-
'version' => 1,
141-
'version_strategy' => 'foo',
146+
array(
147+
'assets' => $assetConfig,
142148
),
143-
),
144-
));
149+
));
145150
}
146151

147-
/**
148-
* @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException
149-
* @expectedExceptionMessage You cannot use both "version_strategy" and "version" at the same time under "assets" packages.
150-
*/
151-
public function testInvalidPackageVersionStrategy()
152+
public function provideInvalidAssetConfigurationTests()
152153
{
153-
$processor = new Processor();
154-
$configuration = new Configuration(true);
155-
156-
$processor->processConfiguration($configuration, array(
157-
array(
158-
'assets' => array(
159-
'base_urls' => '//example.com',
160-
'version' => 1,
161-
'packages' => array(
162-
'foo' => array(
163-
'base_urls' => '//example.com',
164-
'version' => 1,
165-
'version_strategy' => 'foo',
166-
),
167-
),
154+
// helper to turn config into embedded package config
155+
$createPackageConfig = function (array $packageConfig) {
156+
return array(
157+
'base_urls' => '//example.com',
158+
'version' => 1,
159+
'packages' => array(
160+
'foo' => $packageConfig,
168161
),
169-
),
170-
));
162+
);
163+
};
164+
165+
$config = array(
166+
'version' => 1,
167+
'version_strategy' => 'foo',
168+
);
169+
yield array($config, 'You cannot use both "version_strategy" and "version" at the same time under "assets".');
170+
yield array($createPackageConfig($config), 'You cannot use both "version_strategy" and "version" at the same time under "assets" packages.');
171+
172+
$config = array(
173+
'json_manifest_path' => '/foo.json',
174+
'version_strategy' => 'foo',
175+
);
176+
yield array($config, 'You cannot use both "version_strategy" and "json_manifest_path" at the same time under "assets".');
177+
yield array($createPackageConfig($config), 'You cannot use both "version_strategy" and "json_manifest_path" at the same time under "assets" packages.');
178+
179+
$config = array(
180+
'json_manifest_path' => '/foo.json',
181+
'version' => '1',
182+
);
183+
yield array($config, 'You cannot use both "version" and "json_manifest_path" at the same time under "assets".');
184+
yield array($createPackageConfig($config), 'You cannot use both "version" and "json_manifest_path" at the same time under "assets" packages.');
171185
}
172186

173187
protected static function getBundleDefaultConfig()
@@ -274,6 +288,7 @@ protected static function getBundleDefaultConfig()
274288
'base_path' => '',
275289
'base_urls' => array(),
276290
'packages' => array(),
291+
'json_manifest_path' => null,
277292
),
278293
'cache' => array(
279294
'pools' => array(),

‎src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/assets.php

Copy file name to clipboardExpand all lines: src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/assets.php
+3Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,9 @@
2424
'base_urls' => array('https://bar2.example.com'),
2525
'version_strategy' => 'assets.custom_version_strategy',
2626
),
27+
'json_manifest_strategy' => array(
28+
'json_manifest_path' => '/path/to/manifest.json',
29+
),
2730
),
2831
),
2932
));

‎src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/assets.xml

Copy file name to clipboardExpand all lines: src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/assets.xml
+1Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
<framework:package name="bar_version_strategy" version-strategy="assets.custom_version_strategy">
2222
<framework:base-url>https://bar_version_strategy.example.com</framework:base-url>
2323
</framework:package>
24+
<framework:package name="json_manifest_strategy" json-manifest-path="/path/to/manifest.json" />
2425
</framework:assets>
2526
</framework:config>
2627
</container>

‎src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/yml/assets.yml

Copy file name to clipboardExpand all lines: src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/yml/assets.yml
+2Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,3 +17,5 @@ framework:
1717
bar_version_strategy:
1818
base_urls: ["https://bar_version_strategy.example.com"]
1919
version_strategy: assets.custom_version_strategy
20+
json_manifest_strategy:
21+
json_manifest_path: '/path/to/manifest.json'

‎src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/FrameworkExtensionTest.php

Copy file name to clipboardExpand all lines: src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/FrameworkExtensionTest.php
+6-1Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -374,7 +374,7 @@ public function testAssets()
374374

375375
// packages
376376
$packages = $packages->getArgument(1);
377-
$this->assertCount(5, $packages);
377+
$this->assertCount(6, $packages);
378378

379379
$package = $container->getDefinition((string) $packages['images_path']);
380380
$this->assertPathPackage($container, $package, '/foo', 'SomeVersionScheme', '%%s?version=%%s');
@@ -390,6 +390,11 @@ public function testAssets()
390390

391391
$package = $container->getDefinition((string) $packages['bar_version_strategy']);
392392
$this->assertEquals('assets.custom_version_strategy', (string) $package->getArgument(1));
393+
394+
$package = $container->getDefinition((string) $packages['json_manifest_strategy']);
395+
$versionStrategy = $container->getDefinition((string) $package->getArgument(1));
396+
$this->assertEquals('assets.json_manifest_version_strategy', $versionStrategy->getParent());
397+
$this->assertEquals('/path/to/manifest.json', $versionStrategy->getArgument(0));
393398
}
394399

395400
public function testAssetsDefaultVersionStrategyAsService()

‎src/Symfony/Component/Asset/CHANGELOG.md

Copy file name to clipboardExpand all lines: src/Symfony/Component/Asset/CHANGELOG.md
+5Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,11 @@
11
CHANGELOG
22
=========
33

4+
3.3.0
5+
-----
6+
* Added `JsonManifestVersionStrategy` as a way to read final,
7+
versioned paths from a JSON manifest file.
8+
49
2.7.0
510
-----
611

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.