Skip to content

Commit

Permalink
Merge pull request #39 from maxhelias/compatibiliy-layer
Browse files Browse the repository at this point in the history
Bump project with symfony 5 compatibility
  • Loading branch information
pyrech authored Mar 2, 2020
2 parents 4519a08 + 8228846 commit bd07612
Show file tree
Hide file tree
Showing 20 changed files with 257 additions and 330 deletions.
29 changes: 12 additions & 17 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
language: php

php:
- 5.5
- 5.6
- 7.0
- 7.1
- 7.2
- 7.3

env:
Expand All @@ -15,21 +13,18 @@ env:
matrix:
fast_finish: true
include:
- php: 7.0
- php: 7.4
env: TARGET=cs_dry_run
- php: 5.5
env: COMPOSER_FLAGS="--prefer-lowest" SYMFONY_DEPRECATIONS_HELPER=weak
# test 2.7 LTS
- php: 5.6
env: SYMFONY_VERSION=2.7.*
# test 2.8 LTS
- php: 5.6
env: SYMFONY_VERSION=2.8.*
# test the latest stable 3.x release
- php: 5.6
env: SYMFONY_VERSION=^3.0
- php: 7.1
env: COMPOSER_FLAGS="--prefer-stable --prefer-lowest"
# test 4.4
- php: 7.4
env: SYMFONY_VERSION=4.4.*
# test the latest stable 5.x release
- php: 7.4
env: SYMFONY_VERSION=^5.0
# test the latest release (including beta releases)
- php: 7.3
- php: 7.4
env: DEPENDENCIES=beta

sudo: false
Expand All @@ -41,7 +36,7 @@ cache:
before_install:
- if [ "$DEPENDENCIES" = "beta" ]; then perl -pi -e 's/^}$/,"minimum-stability":"beta"}/' composer.json; fi;
- if [ "$SYMFONY_VERSION" != "" ]; then composer require "symfony/symfony:${SYMFONY_VERSION}" --no-update; fi;
- if [ "$TRAVIS_PHP_VERSION" != "hhvm" ]; then echo "memory_limit=2G" >> ~/.phpenv/versions/$(phpenv version-name)/etc/conf.d/travis.ini; fi;
- echo "memory_limit=-1" >> ~/.phpenv/versions/$(phpenv version-name)/etc/conf.d/travis.ini;

install: composer update --prefer-dist --no-interaction $COMPOSER_FLAGS

Expand Down
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
# Changes between versions

## 1.6.0 (not release yet)

* Added compatibility with Symfony 5.0
* Dropped compatibility with PHP < 7.1 and Symfony < 4.4

## 1.5.0 (2019-03-20)

* Added more GIFs
Expand Down
20 changes: 8 additions & 12 deletions Command/GifOptimizerCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,17 +24,17 @@ class GifOptimizerCommand extends Command
/**
* @var string The name of the command
*/
const COMMAND_NAME = 'jolicode:gifexception:optimize';
private const COMMAND_NAME = 'jolicode:gifexception:optimize';

/**
* @var string
*/
const DEFAULT_OPTIMIZATION_LEVEL = '-O3';
private const DEFAULT_OPTIMIZATION_LEVEL = '-O3';

/**
* @var int
*/
const DEFAULT_WIDTH = 145;
private const DEFAULT_WIDTH = 145;

/**
* @var Optimizer
Expand Down Expand Up @@ -98,7 +98,7 @@ protected function initialize(InputInterface $input, OutputInterface $output)
/**
* {@inheritdoc}
*/
protected function execute(InputInterface $input, OutputInterface $output)
protected function execute(InputInterface $input, OutputInterface $output): int
{
$imageDir = $input->getArgument('image_dir');

Expand Down Expand Up @@ -126,15 +126,11 @@ protected function execute(InputInterface $input, OutputInterface $output)
$percentage = 100 - (($optimizedFileSize / $originalFileSize) * 100);
$output->writeln(sprintf('<comment>Saving: %s%%</comment>', round($percentage)));
}

return 0;
}

/**
* @param $bytes
* @param bool $useStandard
*
* @return string
*/
private function formatBytes($bytes, $useStandard = true)
private function formatBytes(int $bytes, bool $useStandard = true): string
{
$unit = $useStandard ? 1024 : 1000;
if ($bytes <= $unit) {
Expand All @@ -144,6 +140,6 @@ private function formatBytes($bytes, $useStandard = true)
$pre = ($useStandard ? 'kMGTPE' : 'KMGTPE');
$pre = $pre[$exp - 1] . ($useStandard ? '' : 'i');

return sprintf('%.1f %sB', $bytes / pow($unit, $exp), $pre);
return sprintf('%.1f %sB', $bytes / ($unit ** $exp), $pre);
}
}
63 changes: 6 additions & 57 deletions DependencyInjection/GifExceptionExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,16 +11,12 @@

namespace Joli\GifExceptionBundle\DependencyInjection;

use Joli\GifExceptionBundle\Command\GifOptimizerCommand;
use Joli\GifExceptionBundle\EventListener\ReplaceImageListener;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\HttpKernel\KernelEvents;

class GifExceptionExtension extends Extension implements CompilerPassInterface
class GifExceptionExtension extends Extension
{
/**
* {@inheritdoc}
Expand All @@ -31,17 +27,8 @@ public function load(array $configs, ContainerBuilder $container)
return;
}

$definition = new Definition(GifOptimizerCommand::class);
$definition->addTag('console.command', [
'command' => GifOptimizerCommand::COMMAND_NAME, // Allow lazy loading
]);
$container->setDefinition(GifOptimizerCommand::class, $definition);

$definition = new Definition(ReplaceImageListener::class);
$definition->addTag('kernel.event_listener', [
'event' => KernelEvents::RESPONSE,
'priority' => -1000,
]);
$loader = new XmlFileLoader($container, new FileLocator(\dirname(__DIR__) . '/Resources/config'));
$loader->load('services.xml');

$gifs = [];

Expand All @@ -55,44 +42,6 @@ public function load(array $configs, ContainerBuilder $container)
$gifs['other'][] = basename($path);
}

// Set first argument. Next ones will be added by the compiler pass.
$definition->addArgument($gifs);
$container->setDefinition('gif_exception.listener.replace_image', $definition);
}

/**
* This CompilerPassInterface method completes the listener definition with
* the parameter and service coming from other bundles. It allows our
* bundle to be registered anytime before or after others.
*
* {@inheritdoc}
*/
public function process(ContainerBuilder $container)
{
if (!$container->getParameter('kernel.debug')) {
return;
}

$definition = $container->getDefinition('gif_exception.listener.replace_image');

// $container->setArgument($index, ...) was added in Symfony 3.3
$arguments = [
$definition->getArgument(0),
$container->getParameter('twig.exception_listener.controller'),
];

if ($container->has('assets.packages')) {
// New Asset component to generate asset url (SF >=2.8)
$arguments[] = new Reference('assets.packages');
$arguments[] = null;
} elseif ($container->has('templating.helper.assets')) {
// Old way of generating asset url (SF ~2.3)
// To remove when compatibility with Symfony 2.7 is dropped
$arguments[] = null;
$arguments[] = new Reference('templating.helper.assets');
$definition->setScope('request');
}

$definition->setArguments($arguments);
$container->getDefinition('gif_exception.listener.replace_image')->replaceArgument(0, $gifs);
}
}
93 changes: 29 additions & 64 deletions EventListener/ReplaceImageListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,13 @@
namespace Joli\GifExceptionBundle\EventListener;

use Symfony\Component\Asset\Packages;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Templating\Helper\CoreAssetsHelper;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;

class ReplaceImageListener
class ReplaceImageListener implements EventSubscriberInterface
{
const IMAGES_DIR = '../../Resources/public/images';
private const IMAGES_DIR = '../../Resources/public/images';

/** @var string[][] */
private $gifs;
Expand All @@ -29,29 +29,20 @@ class ReplaceImageListener
/** @var Packages */
private $packages;

/** @var CoreAssetsHelper */
private $coreAssetsHelper;

/**
* @param string[][] $gifs
* @param string $exceptionController
* @param Packages $packages
* @param CoreAssetsHelper $coreAssetsHelper
* @param string[][] $gifs
*/
public function __construct(array $gifs, $exceptionController, Packages $packages = null, CoreAssetsHelper $coreAssetsHelper = null)
public function __construct(array $gifs, string $exceptionController, Packages $packages = null)
{
$this->gifs = $gifs;
$this->exceptionController = $exceptionController;
$this->packages = $packages;
$this->coreAssetsHelper = $coreAssetsHelper;
}

/**
* Handle the response for exception and replace the little Phantom by a random Gif.
*
* @param FilterResponseEvent $event
*/
public function onKernelResponse(FilterResponseEvent $event)
public function onKernelResponse(ResponseEvent $event)
{
if ($event->isMasterRequest()
|| $event->getRequest()->attributes->get('_controller') !== $this->exceptionController) {
Expand All @@ -69,37 +60,29 @@ public function onKernelResponse(FilterResponseEvent $event)

$content = $event->getResponse()->getContent();

if (version_compare(Kernel::VERSION, '3.2', '<')) {
$content = preg_replace(
'/<img alt="Exception detected!" src=".*" \/>/',
sprintf('<img alt="Exception detected!" src="%s" data-gif style="width:145px" />', $url),
$content
);
} elseif (version_compare(Kernel::VERSION, '3.3', '<')) {
$content = preg_replace(
'@<svg xmlns="http://www.w3.org/2000/svg" width="112"(.*?)</svg>@ims',
sprintf('<img alt="Exception detected!" src="%s" data-gif style="width:145px" />', $url),
$content
);
} else {
$content = preg_replace(
'@<div class="exception-illustration hidden-xs-down">(.*?)</div>@ims',
sprintf('<div class="exception-illustration hidden-xs-down" style="opacity:1"><img alt="Exception detected!" src="%s" data-gif style="height:66px" /></div>', $url),
$content
);
}
$content = preg_replace(
'@<div class="exception-illustration hidden-xs-down">(.*?)</div>@ims',
sprintf('<div class="exception-illustration hidden-xs-down" style="opacity:1"><img alt="Exception detected!" src="%s" data-gif style="height:66px" /></div>', $url),
$content
);

$event->getResponse()->setContent($content);
}

/**
* {@inheritdoc}
*/
public static function getSubscribedEvents()
{
return [
KernelEvents::RESPONSE => ['onKernelResponse', -1000],
];
}

/**
* Return the gif folder for the given status code.
*
* @param int $statusCode
*
* @return string
*/
private function getGifDir($statusCode)
private function getGifDir(int $statusCode): string
{
if (\array_key_exists($statusCode, $this->gifs) && \count($this->gifs[$statusCode]) > 0) {
return $statusCode;
Expand All @@ -110,49 +93,31 @@ private function getGifDir($statusCode)

/**
* Return a random gif name for the given directory.
*
* @param string $dir
*
* @return string
*/
private function getRandomGif($dir)
private function getRandomGif(string $dir): string
{
$imageIndex = mt_rand(0, \count($this->gifs[$dir]) - 1);
$imageIndex = random_int(0, \count($this->gifs[$dir]) - 1);

return $this->gifs[$dir][$imageIndex];
}

/**
* Return a the url of given gif in the given directory.
*
* @param string $dir
* @param string $gif
*
* @return string
*/
private function getGifUrl($dir, $gif)
private function getGifUrl(string $dir, string $gif): string
{
return $this->generateUrl(sprintf('bundles/gifexception/images/%s/%s', $dir, $gif));
}

/**
* Generate an url in both Symfony 2 and Symfony 3+ compatible ways.
*
* @param string $url
*
* @return string
*/
private function generateUrl($url)
private function generateUrl(string $url): string
{
if ($this->packages) {
if (null !== $this->packages) {
return $this->packages->getUrl($url);
}

if ($this->coreAssetsHelper) {
// To remove when compatibility with Symfony 2.7 is dropped
return $this->coreAssetsHelper->getUrl($url);
}

return $url;
}
}
2 changes: 0 additions & 2 deletions GifExceptionBundle.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,5 @@ class GifExceptionBundle extends Bundle
public function build(ContainerBuilder $container)
{
parent::build($container);

$container->addCompilerPass($this->getContainerExtension());
}
}
Loading

0 comments on commit bd07612

Please sign in to comment.