Skip to content

Instantly share code, notes, and snippets.

@alexander-schranz
Created July 24, 2018 09:57
Show Gist options
  • Save alexander-schranz/25e3971d889af687d3fee7d6becbc864 to your computer and use it in GitHub Desktop.
Save alexander-schranz/25e3971d889af687d3fee7d6becbc864 to your computer and use it in GitHub Desktop.
Automatic versioning update on npm run build
<?php
namespace AppBundle\DependencyInjection;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Extension\PrependExtensionInterface;
use Symfony\Component\DependencyInjection\Loader;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
/**
* This class loads and manages the configuration for this bundle.
*/
class AppExtension extends Extension implements PrependExtensionInterface
{
/**
* {@inheritdoc}
*/
public function prepend(ContainerBuilder $container)
{
if ($container->hasExtension('framework')) {
if (!$container->hasParameter('asset_build_version')) {
$version = $this->getPackageVersion();
$container->setParameter('asset_build_version', $version);
}
$debug = $container->getParameter('kernel.debug');
$container->prependExtensionConfig(
'framework',
[
'assets' => [
'packages' => [
'static' => [
'version' => $container->getParameter('asset_build_version'),
'version_format' => ($debug ? '%%s' : '%%s?v=%%s'),
],
],
],
]
);
}
}
/**
* Get package version.
*
* @return string
*/
private function getPackageVersion()
{
$version = '0.0.0';
$packageJsonPath = __DIR__ . '/../package.json';
if (file_exists($packageJsonPath)) {
$packageJson = json_decode(file_get_contents($packageJsonPath), true);
$version = $packageJson['version'];
}
return $version;
}
/**
* {@inheritdoc}
*/
public function load(array $configs, ContainerBuilder $container)
{
$loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));
$loader->load('services.xml');
}
}
/*
Package.json
{
"name": "app-bundle",
"version": "1.0.0",
"private": true,
"license": "ISC",
"scripts": {
"info": "npm-scripts-info",
"build": "npm run build:css && npm run build:js && npm run update:version",
"build:css": "...",
"build:js": "...",
"update:version": "npm version patch --git-tag-version false"
}
}
*/
/*
Twig:
<link rel="stylesheet" href="{{ asset('/bundles/app/css/main.css', 'static') }}" />
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment