From f42d2cc5321c9a5fc43bb8a6ed837f3231abc24e Mon Sep 17 00:00:00 2001 From: Dmitriy Larionov Date: Thu, 30 Mar 2017 19:55:44 +0500 Subject: [PATCH] init BxOptimize --- .gitignore | 7 +++ composer.json | 32 +++++++++++ lib/Finder/FilesFinder.php | 39 +++++++++++++ lib/Finder/FinderInterface.php | 23 ++++++++ lib/Handler/CssHandler.php | 24 ++++++++ lib/Handler/Handler.php | 46 ++++++++++++++++ lib/Handler/HandlerInterface.php | 30 ++++++++++ lib/Handler/HandlerProcessor.php | 94 ++++++++++++++++++++++++++++++++ lib/Handler/ImageHandler.php | 26 +++++++++ lib/Install/Installer.php | 60 ++++++++++++++++++++ lib/Install/bxoptimize | 20 +++++++ lib/Optimizer.php | 68 +++++++++++++++++++++++ lib/OptimizerInterface.php | 23 ++++++++ lib/cli/SymfonyOptimize.php | 52 ++++++++++++++++++ 14 files changed, 544 insertions(+) create mode 100644 .gitignore create mode 100644 composer.json create mode 100644 lib/Finder/FilesFinder.php create mode 100644 lib/Finder/FinderInterface.php create mode 100644 lib/Handler/CssHandler.php create mode 100644 lib/Handler/Handler.php create mode 100644 lib/Handler/HandlerInterface.php create mode 100644 lib/Handler/HandlerProcessor.php create mode 100644 lib/Handler/ImageHandler.php create mode 100644 lib/Install/Installer.php create mode 100644 lib/Install/bxoptimize create mode 100644 lib/Optimizer.php create mode 100644 lib/OptimizerInterface.php create mode 100644 lib/cli/SymfonyOptimize.php diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..f55b917 --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +/vendor/ +/images/ +/bin/ +index.php +composer.lock +composer.phar +.php_cs.cache \ No newline at end of file diff --git a/composer.json b/composer.json new file mode 100644 index 0000000..f6fbab3 --- /dev/null +++ b/composer.json @@ -0,0 +1,32 @@ +{ + "name": "dumkaaa/bxoptimize", + "description": "", + "type": "library", + "license": "MIT", + "minimum-stability": "dev", + "require": { + "php": ">=5.5.9", + "symfony/console": "^3.2" + }, + "require-dev": { + }, + "autoload": { + "psr-4": { + "Dumkaaa\\BxOptimize\\": "lib/" + } + }, + "scripts": { + "bxoptimize-scripts": [ + "Dumkaaa\\BxOptimize\\Install\\Installer::getBinaries" + ], + "post-install-cmd": [ + "@bxoptimize-scripts" + ], + "post-update-cmd": [ + "@bxoptimize-scripts" + ] + }, + "bin": [ + "bin/bxoptimize" + ] +} diff --git a/lib/Finder/FilesFinder.php b/lib/Finder/FilesFinder.php new file mode 100644 index 0000000..dc8752a --- /dev/null +++ b/lib/Finder/FilesFinder.php @@ -0,0 +1,39 @@ +path = $path; + + } + + /** + * {@inheritdoc} + */ + public function findFiles($path = null) + { + $path = $path ?: $this->path; + $basePath = $_SERVER['DOCUMENT_ROOT']; + + return new \RecursiveIteratorIterator( + new \RecursiveDirectoryIterator($basePath . '/' . $path) + ); + } +} \ No newline at end of file diff --git a/lib/Finder/FinderInterface.php b/lib/Finder/FinderInterface.php new file mode 100644 index 0000000..b62660a --- /dev/null +++ b/lib/Finder/FinderInterface.php @@ -0,0 +1,23 @@ +files as $file) { + print(get_class() . " обрабатывает файл: $file\n"); + } + // TODO: Implement handleQueue() method. + } +} \ No newline at end of file diff --git a/lib/Handler/Handler.php b/lib/Handler/Handler.php new file mode 100644 index 0000000..efac4cf --- /dev/null +++ b/lib/Handler/Handler.php @@ -0,0 +1,46 @@ +validExt); + } + + /** + * {@inheritdoc} + */ + public function queueFile($file) + { + $this->files[] = $file; + } + /** + * {@inheritdoc} + */ + public function handleQueue() + { + foreach ($this->files as $file) { + print(get_class() . " обрабатывает файл: $file\n"); + } + // TODO: Implement handleQueue() method. + } +} diff --git a/lib/Handler/HandlerInterface.php b/lib/Handler/HandlerInterface.php new file mode 100644 index 0000000..ddd4bef --- /dev/null +++ b/lib/Handler/HandlerInterface.php @@ -0,0 +1,30 @@ + __NAMESPACE__ . '\ImageHandler', + //'css' => __NAMESPACE__ . '\CssHandler', + ]; + + /** @var array Включенные обработчики */ + protected $handlers = []; + + + /** + * Включаем либо обработчики из переданного набора, либо все стандартные + * @param array $handlers + */ + public function __construct(array $handlers) + { + is_array($handlers) + ? $this->enableHandlers($handlers) + : $this->enableHandlers($this->defaultHandlers); + } + + /** + * Включает обработчики из массива + * @param array $handlers + */ + public function enableHandlers(array $handlers) + { + //убираем возможные дубликаты + $handlers = array_unique(array_map('strtolower', $handlers)); + + //включаем + foreach ($handlers as $handler) { + $this->enableHandler($handler); + } + } + + /** + * Включает обработчик из списка доступных обработчиков + * @param string $key Ключ-имя обработчика + * @throws \Exception + */ + public function enableHandler($key) + { + if(!$key) { + throw new \Exception("Не передан ключ обработчика"); + } else { + $key = strtolower(trim($key)); + } + + if(isset($this->defaultHandlers[$key])) { + $this->handlers[$key] = new $this->defaultHandlers[$key]; + } else { + throw new \Exception("Обработчик $key не найден"); + } + } + + /** + * Возврашает включенные обработчики + * @return array + */ + public function getHandlers() + { + return $this->handlers; + } + + + /** + * Добавляет новый обработчик и сразу включает его + * @param string $key Ключ-имя обработчика + * @param string $classname Класс обработчика + * @param bool $replace Заменять, если уже есть такой обработчик + * @return bool + */ + public function addHandler($key, $classname, $replace = false) + { + $return = false; + + if(!isset($this->handlers[$key]) || $replace) { + $this->handlers[$key] = new $classname; + $return = true; + } + + return $return; + } + +} \ No newline at end of file diff --git a/lib/Handler/ImageHandler.php b/lib/Handler/ImageHandler.php new file mode 100644 index 0000000..482c4ed --- /dev/null +++ b/lib/Handler/ImageHandler.php @@ -0,0 +1,26 @@ +files as $file) { + print(get_class() . " обрабатывает файл: $file\n"); + } + // TODO: Implement handleQueue() method. + } +} \ No newline at end of file diff --git a/lib/Install/Installer.php b/lib/Install/Installer.php new file mode 100644 index 0000000..4210dbc --- /dev/null +++ b/lib/Install/Installer.php @@ -0,0 +1,60 @@ + "gifsicle", + "png" => "optipng", + "jpg" => "jpegtran", + "pngquant" => "pngquant", + //"webp" => "cwebp", + ]; + + protected static $extByPlatforms = [ + //"win" => ".exe", + "linux" => "-linux", + //"freebsd" => "-fbsd", + //"darwin" => "-mac", + //"sunos" => "-sol", + ]; + + + /** + * Скачивает бинарники и кладёт их в папку bin/ + * @param Event $event + */ + public static function getBinaries(Event $event) + { + $dir = self::getRootPath().'/bin'; + + if(!file_exists($dir)) + { + mkdir($dir); + } + + $event->getIO()->write("Setup binaries to $dir :"); + + foreach (self::$extByPlatforms as $ext) { + foreach (self::$tools as $tool) { + file_put_contents( + $dir . '/' . $tool, + fopen('https://github.com/nosilver4u/ewww-image-optimizer/raw/master/binaries/' . $tool . $ext, 'r') + ); + $event->getIO()->write($tool . $ext); + } + } + + $event->getIO()->write('Setup binaries complete.'); + } + + public static function getRootPath() + { + return dirname(__DIR__); + } +} \ No newline at end of file diff --git a/lib/Install/bxoptimize b/lib/Install/bxoptimize new file mode 100644 index 0000000..4fa004c --- /dev/null +++ b/lib/Install/bxoptimize @@ -0,0 +1,20 @@ +#!/usr/bin/env php +add(new \Dumkaaa\BxOptimize\Cli\SymfonyOptimize()); + +$application->run(); \ No newline at end of file diff --git a/lib/Optimizer.php b/lib/Optimizer.php new file mode 100644 index 0000000..1d97d72 --- /dev/null +++ b/lib/Optimizer.php @@ -0,0 +1,68 @@ +finder = $finder; + $this->handlers = $handler->getHandlers(); + } + + /** + * {@inheritdoc} + */ + public function optimize() + { + $this->findFiles(); + $this->setQueue(); + $this->handleQueue(); + + } + + private function setQueue() + { + /** @var HandlerInterface $handler */ + foreach ($this->handlers as $handler) { + foreach ($this->files as $file) { + if (!$handler->canHandleFile($file)) { + continue; + } else { + $handler->queueFile($file); + break; + } + } + } + } + + private function handleQueue() + { + /** @var HandlerInterface $handler */ + foreach ($this->handlers as $handler) { + $handler->handleQueue(); + } + } + + private function findFiles() + { + $this->files = $this->finder->findFiles(); + } + +} \ No newline at end of file diff --git a/lib/OptimizerInterface.php b/lib/OptimizerInterface.php new file mode 100644 index 0000000..af172fa --- /dev/null +++ b/lib/OptimizerInterface.php @@ -0,0 +1,23 @@ +setName('bxoptimize:optimize') + ->setDescription('Set up optimization') + ->addArgument( + 'path', + InputArgument::REQUIRED, + 'Path to find files' + ) + ->addArgument( + 'handlers', + InputArgument::IS_ARRAY, + 'Array of optimizators to set up' + ); + } + + + protected function execute(InputInterface $input, OutputInterface $output) + { + $path = $input->getArgument('path'); + $handlers = $input->getArgument('handlers'); + + + var_dump($path); + var_dump($handlers); + try { + $finder = new \Dumkaaa\BxOptimize\Finder\FilesFinder($path); + $handler = new \Dumkaaa\BxOptimize\Handler\HandlerProcessor($handlers); + + $optimizer = new \Dumkaaa\BxOptimize\Optimizer($finder, $handler); + $optimizer->optimize(); + + $output->writeln('BxOptimization set up.'); + + } catch (\Exception $e) { + $output->writeln(''.get_class($e).': '.$e->getMessage().''); + } + } + +} \ No newline at end of file