diff --git a/.gitignore b/.gitignore index e9ecfc2..3c2d39c 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ *.iml .idea vendor/ -composer.lock \ No newline at end of file +composer.lock +/.php_cs.cache diff --git a/.php_cs b/.php_cs new file mode 100644 index 0000000..eaea487 --- /dev/null +++ b/.php_cs @@ -0,0 +1,27 @@ +setRiskyAllowed(true); +$config->setRules([ + '@PSR2' => true, + '@Symfony' => true, + 'array_syntax' => [ + 'syntax' => 'short', + ], + 'ordered_imports' => true, + 'php_unit_construct' => true, + 'php_unit_dedicate_assert' => true, + 'phpdoc_single_line_var_spacing' => true, + 'phpdoc_trim' => true, + 'psr4' => true, +]); + +$finder = PhpCsFixer\Finder::create(); +$finder->in([ + 'src', + 'tests', +]); + +$config->setFinder($finder); + +return $config; diff --git a/.travis.yml b/.travis.yml index 9f33f66..3c08678 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,55 +1,40 @@ language: php +sudo: false + +cache: + directories: + - $HOME/.composer/cache/files php: - - 5.3 - - 5.4 - - 5.5 - - 5.6 + - 7.3 + - 7.2 - 7.1 +env: + - COMPOSER_MEMORY_LIMIT=-1 before_install: - composer self-update - - if [[ "$TRAVIS_PHP_VERSION" != "hhvm" ]]; then echo "memory_limit = -1" >> ~/.phpenv/versions/$(phpenv version-name)/etc/conf.d/travis.ini; fi; - - composer require --no-update symfony/framework-bundle "$SYMFONY_VERSION" install: - - composer install --prefer-source - -script: vendor/bin/phpunit --configuration Tests/phpunit.xml + - composer install --prefer-dist --no-interaction -env: - - SYMFONY_VERSION=2.3.* - - SYMFONY_VERSION=2.7.* - - SYMFONY_VERSION=2.8.* +script: vendor/bin/phpunit -matrix: +jobs: include: - - php: 5.5 - env: SYMFONY_VERSION=3.0.* - - php: 5.6 - env: SYMFONY_VERSION=3.0.* - - php: 7.0 - env: SYMFONY_VERSION=3.0.* - - php: 7.1 - env: SYMFONY_VERSION=3.0.* - - - php: 7.0 - env: SYMFONY_VERSION=3.1.* - - php: 7.1 - env: SYMFONY_VERSION=3.1.* - - - php: 7.0 - env: SYMFONY_VERSION=3.2.* - - php: 7.1 - env: SYMFONY_VERSION=3.2.* - - - php: 7.1 - env: SYMFONY_VERSION=3.3.* - -sudo: false - -cache: - directories: - - $HOME/.composer/cache - + - stage: Test + php: 7.1 + name: prefer-lowest + env: + - SYMFONY_DEPRECATIONS_HELPER=disabled + install: + - composer remove --dev friendsofphp/php-cs-fixer --no-update + - composer update --no-interaction --prefer-dist --prefer-stable --prefer-lowest + - stage: Additional checks + name: Test coverage + script: phpdbg -qrr vendor/bin/phpunit --coverage-clover ./build/logs/clover.xml --coverage-text + after_success: + - php vendor/bin/php-coveralls -v + - name: Code style + script: vendor/bin/php-cs-fixer fix --verbose --dry-run diff --git a/README.markdown b/README.md similarity index 80% rename from README.markdown rename to README.md index 605de2d..57bd193 100644 --- a/README.markdown +++ b/README.md @@ -1,30 +1,35 @@ PsPdfBundle =========== -[![Build Status](https://secure.travis-ci.org/psliwa/PdfBundle.png?branch=master)](http://travis-ci.org/psliwa/PdfBundle) +[![Build Status](https://travis-ci.org/facile-it/PdfBundle.svg?branch=symfony4)](https://travis-ci.org/facile-it/PdfBundle) +[![Coverage Status](https://coveralls.io/repos/github/facile-it/PdfBundle/badge.svg?branch=symfony4)](https://coveralls.io/github/facile-it/PdfBundle?branch=symfony4) -This bundle integrates Symfony2 with [PHPPdf][1] library. Thanks to this bundle you can easily generate PDF or image (png, jpg) files. +This bundle is a fork of [psliwa/PdfBundle](https://github.com/psliwa/PdfBundle); this branch (`symfony4`) aims at updating all the dependencies of this bundle to make it work with Symfony 4 and Symfony Flex. To check on what has been done, look at [the relative milestone](https://github.com/facile-it/PdfBundle/milestone/1). + +This bundle integrates Symfony (3.4/4.x) with [PHPPdf][1] library. Thanks to this bundle you can easily generate PDF or image (png, jpg) files. Documentation of [PHPPdf][1] you can find on github (README file). Installation ------------ - - 1. Use composer. PsPdfBundle requires "minimum-stability" equals to dev. Run this command: - - composer require psliwa/pdf-bundle - - 2. Register bundle in AppKernel: - - //app/AppKernel.php - public function registerBundles() - { - return array( - // .. - new Ps\PdfBundle\PsPdfBundle(), - // .. - ); - } +1. Use composer +```bash +composer require psliwa/pdf-bundle +``` + +2. Register bundle in AppKernel: + +```php +//app/AppKernel.php +public function registerBundles() +{ + return [ + // .. + new Ps\PdfBundle\PsPdfBundle(), + // .. + ]; +} +``` Configuration ------------- diff --git a/Tests/Annotation/PdfTest.php b/Tests/Annotation/PdfTest.php deleted file mode 100644 index 50c7a23..0000000 --- a/Tests/Annotation/PdfTest.php +++ /dev/null @@ -1,62 +0,0 @@ -getMethodAnnotation($method, 'Ps\PdfBundle\Annotation\Pdf'); - - $this->assertNotNull($pdf); - } - - /** - * @test - * @dataProvider createAnnotationProvider - */ - public function createAnnotation(array $args, $expectedException) - { - try - { - $defaultArgs = array('stylesheet' => null, 'documentParserType' => 'xml', 'headers' => array(), 'enableCache' => false); - - $annotation = new Pdf($args); - - if($expectedException) - { - $this->fail('exception expected'); - } - - $expectedVars = $args + $defaultArgs; - - $this->assertEquals($expectedVars, get_object_vars($annotation)); - } - catch(\InvalidArgumentException $e) - { - if(!$expectedException) - { - $this->fail('unexpected exception'); - } - } - } - - public function createAnnotationProvider() - { - return array( - array(array(), false), - array(array('stylesheet' => 'stylesheet', 'documentParserType' => 'markdown'), false), - array(array('enableCache' => true, 'headers' => array('key' => 'value')), false), - array(array('unexistedArg' => 'value'), true), - ); - } -} \ No newline at end of file diff --git a/Tests/phpunit.xml b/Tests/phpunit.xml deleted file mode 100644 index ed1ad0f..0000000 --- a/Tests/phpunit.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - ./ - - - - - ./ - - - diff --git a/composer.json b/composer.json index efbeda5..b1131d7 100644 --- a/composer.json +++ b/composer.json @@ -1,6 +1,6 @@ { "name": "psliwa/pdf-bundle", - "description": "This bundle integrates Symfony2 with PHPPdf library.", + "description": "This bundle integrates Symfony 3.4/4 with PHPPdf library.", "keywords": ["PDF", "PHPPdf"], "type": "symfony-bundle", "license": "MIT", @@ -11,17 +11,34 @@ "email": "me@psliwa.org" } ], + "config": { + "preferred-install": "dist", + "sort-packages": true + }, "require": { - "php": ">=5.3.0", - "symfony/symfony": "~2.3|~3.0", + "php": "^7.1", + "doctrine/annotations": "^1.0", "psliwa/php-pdf": "^1.1.5", - "sensio/framework-extra-bundle": ">=2.0 <4.0.0" + "sensio/framework-extra-bundle": "^2|^3|^4|^5", + "symfony/config": "^3.4|^4.0", + "symfony/dependency-injection": "^3.4|^4.0", + "symfony/event-dispatcher": "^3.4|^4.0", + "symfony/framework-bundle": "^3.4|^4.0", + "symfony/http-foundation": "^3.4|^4.0", + "symfony/http-kernel": "^3.4|^4.0", + "symfony/templating": "^3.4|^4.0", + "twig/twig": "^1.0|^2.0" }, "require-dev": { - "phpunit/phpunit": ">=4,<6.0.0" + "friendsofphp/php-cs-fixer": "^2.15", + "php-coveralls/php-coveralls": "^2.1", + "phpunit/phpunit": "^7.5.11|^8.0", + "symfony/phpunit-bridge": "^4.2" }, "autoload": { - "psr-0": { "Ps\\PdfBundle": "" } + "psr-4": { "Ps\\PdfBundle\\": "src" } }, - "target-dir": "Ps/PdfBundle" + "autoload-dev": { + "psr-4": { "Ps\\PdfBundle\\Tests\\": "tests" } + } } diff --git a/phpunit.xml b/phpunit.xml new file mode 100644 index 0000000..09041da --- /dev/null +++ b/phpunit.xml @@ -0,0 +1,26 @@ + + + + + + + + + + ./src + + + + + + ./tests + + + diff --git a/Annotation/Pdf.php b/src/Annotation/Pdf.php similarity index 74% rename from Annotation/Pdf.php rename to src/Annotation/Pdf.php index 8fd08c0..830f863 100644 --- a/Annotation/Pdf.php +++ b/src/Annotation/Pdf.php @@ -11,32 +11,29 @@ use Doctrine\Common\Annotations\Annotation; /** - * Pdf annotation - * + * Pdf annotation. + * * @Annotation + * * @author Piotr Śliwa */ class Pdf { public $stylesheet; public $documentParserType = 'xml'; - public $headers = array(); + public $headers = []; public $enableCache = false; public function __construct(array $values) { $currentValues = get_object_vars($this); - - foreach($values as $key => $value) - { - if(array_key_exists($key, $currentValues)) - { + + foreach ($values as $key => $value) { + if (array_key_exists($key, $currentValues)) { $this->$key = $value; - } - else - { + } else { throw new \InvalidArgumentException(sprintf('Argument "%s" for @Pdf() annotation is unsupported.', $key)); } } } -} \ No newline at end of file +} diff --git a/Controller/ExampleController.php b/src/Controller/ExampleController.php similarity index 70% rename from Controller/ExampleController.php rename to src/Controller/ExampleController.php index 1948e35..8a474cd 100644 --- a/Controller/ExampleController.php +++ b/src/Controller/ExampleController.php @@ -8,14 +8,14 @@ namespace Ps\PdfBundle\Controller; -use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; -use Symfony\Component\HttpFoundation\Response; -use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Ps\PdfBundle\Annotation\Pdf; +use Symfony\Bundle\FrameworkBundle\Controller\Controller; +use Symfony\Component\HttpFoundation\Response; +use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; /** - * Controller with examples - * + * Controller with examples. + * * @author Piotr Śliwa */ class ExampleController extends Controller @@ -24,25 +24,25 @@ public function indexAction() { return $this->render('PsPdfBundle:Example:index.html.twig'); } - + public function usingFacadeDirectlyAction() { $facade = $this->get('ps_pdf.facade'); $response = new Response(); - $this->render('PsPdfBundle:Example:usingFacadeDirectly.pdf.twig', array(), $response); - + $this->render('PsPdfBundle:Example:usingFacadeDirectly.pdf.twig', [], $response); + $xml = $response->getContent(); - + $content = $facade->render($xml); - - return new Response($content, 200, array('content-type' => 'application/pdf')); + + return new Response($content, 200, ['content-type' => 'application/pdf']); } /** - * Possible custom headers and external stylesheet file - * + * Possible custom headers and external stylesheet file. + * * @Pdf( - * headers={"Expires"="Sat, 1 Jan 2000 12:00:00 GMT"}, + * headers={"Expires"="Sat, 1 Jan 2000 12:00:00 GMT"}, * stylesheet="PsPdfBundle:Example:pdfStylesheet.xml.twig", * enableCache=true * ) @@ -50,25 +50,24 @@ public function usingFacadeDirectlyAction() public function usingAutomaticFormatGuessingAction($name) { $format = $this->get('request')->get('_format'); - - return $this->render(sprintf('PsPdfBundle:Example:usingAutomaticFormatGuessing.%s.twig', $format), array( + + return $this->render(sprintf('PsPdfBundle:Example:usingAutomaticFormatGuessing.%s.twig', $format), [ 'name' => $name, - )); + ]); } - + /** - * Standard examples of PHPPdf library + * Standard examples of PHPPdf library. */ public function examplesAction() { $kernelRootDir = $this->container->getParameter('kernel.root_dir'); - - $propablyPhpPdfExamplesFilePaths = array($kernelRootDir.'/../vendor/PHPPdf/examples/index.php', $kernelRootDir.'/../vendor/psliwa/php-pdf/examples/index.php'); - foreach($propablyPhpPdfExamplesFilePaths as $propablyPhpPdfExamplesFilePath) - { - if(file_exists($propablyPhpPdfExamplesFilePath)) - { + $kernelProjectDir = $this->container->getParameter('kernel.project_dir'); + $propablyPhpPdfExamplesFilePaths = [$kernelProjectDir.'/vendor/PHPPdf/examples/index.php', $kernelProjectDir.'/vendor/psliwa/php-pdf/examples/index.php']; + + foreach ($propablyPhpPdfExamplesFilePaths as $propablyPhpPdfExamplesFilePath) { + if (file_exists($propablyPhpPdfExamplesFilePath)) { require $propablyPhpPdfExamplesFilePath; exit(); } @@ -76,7 +75,7 @@ public function examplesAction() throw new NotFoundHttpException('File with PHPPdf examples not found.'); } - + /** * @Pdf( * headers={"Expires"="Sat, 1 Jan 2000 12:00:00 GMT"}, @@ -86,7 +85,7 @@ public function examplesAction() public function markdownAction() { $format = $this->get('request')->get('_format'); - + return $this->render(sprintf('PsPdfBundle:Example:markdown.%s.twig', $format)); } } diff --git a/DependencyInjection/Configuration.php b/src/DependencyInjection/Configuration.php similarity index 84% rename from DependencyInjection/Configuration.php rename to src/DependencyInjection/Configuration.php index dfb7b79..1d5fd87 100644 --- a/DependencyInjection/Configuration.php +++ b/src/DependencyInjection/Configuration.php @@ -12,22 +12,24 @@ use Symfony\Component\Config\Definition\ConfigurationInterface; /** - * Configuration definition class - * + * Configuration definition class. + * * @author Piotr Śliwa */ class Configuration implements ConfigurationInterface { - public function getConfigTreeBuilder() + public function getConfigTreeBuilder() { - $treeBuilder = new TreeBuilder(); - $rootNode = $treeBuilder->root('ps_pdf'); - + $treeBuilder = new TreeBuilder('ps_pdf'); + $rootNode = \method_exists(TreeBuilder::class, 'getRootNode') + ? $treeBuilder->getRootNode() + : $treeBuilder->root('ps_pdf'); + $rootNode->children() ->arrayNode('cache') ->children() ->variableNode('options') - ->defaultValue(array()) + ->defaultValue([]) ->end() ->scalarNode('type') ->defaultValue('File') @@ -62,4 +64,4 @@ public function getConfigTreeBuilder() return $treeBuilder; } -} \ No newline at end of file +} diff --git a/DependencyInjection/PsPdfExtension.php b/src/DependencyInjection/PsPdfExtension.php similarity index 75% rename from DependencyInjection/PsPdfExtension.php rename to src/DependencyInjection/PsPdfExtension.php index 1373960..34465ea 100644 --- a/DependencyInjection/PsPdfExtension.php +++ b/src/DependencyInjection/PsPdfExtension.php @@ -10,28 +10,27 @@ use Symfony\Component\Config\Definition\Processor; use Symfony\Component\Config\FileLocator; +use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Loader\XmlFileLoader; use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\HttpKernel\DependencyInjection\Extension; -use Symfony\Component\DependencyInjection\ContainerBuilder; - /** - * Extenstion class - * + * Extenstion class. + * * @author Piotr Śliwa */ class PsPdfExtension extends Extension { public function load(array $config, ContainerBuilder $container) - { + { $config = $this->getConfig($config); - + $this->loadDefaults($container); - + $this->setConfigIntoContainer($container, $config); } - + private function getConfig(array $config) { $configurationProcessor = new Processor(); @@ -39,24 +38,21 @@ private function getConfig(array $config) return $configurationProcessor->processConfiguration($configuration, $config); } - + private function loadDefaults(ContainerBuilder $container) { $loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); - + $loader->load('pdf.xml'); // TODO: Go back to xml configuration when bumping the requirement to Symfony >=2.6 $facadeDefinition = $container->getDefinition('ps_pdf.facade'); $facadeBuilderDefinition = $container->getDefinition('ps_pdf.facade_builder'); - if(method_exists('Symfony\\Component\\DependencyInjection\\Definition', 'setFactory')) - { - $facadeDefinition->setFactory(array(new Reference('ps_pdf.facade_builder'), 'build')); - $facadeBuilderDefinition->setFactory(array('PHPPdf\\Core\\FacadeBuilder', 'create')); - } - else - { + if (method_exists('Symfony\\Component\\DependencyInjection\\Definition', 'setFactory')) { + $facadeDefinition->setFactory([new Reference('ps_pdf.facade_builder'), 'build']); + $facadeBuilderDefinition->setFactory(['PHPPdf\\Core\\FacadeBuilder', 'create']); + } else { $facadeDefinition->setFactoryService('ps_pdf.facade_builder'); $facadeDefinition->setFactoryMethod('build'); @@ -64,40 +60,37 @@ private function loadDefaults(ContainerBuilder $container) $facadeBuilderDefinition->setFactoryMethod('create'); } } - + private function setConfigIntoContainer(ContainerBuilder $container, array $config) { - $this->setGenericConfig($container, $config, 'ps_pdf.%s', array('nodes_file', 'fonts_file', 'complex_attributes_file', 'colors_file', 'use_cache_in_stylesheet', 'markdown_stylesheet_filepath', 'markdown_document_template_filepath', 'document_parser_type')); + $this->setGenericConfig($container, $config, 'ps_pdf.%s', ['nodes_file', 'fonts_file', 'complex_attributes_file', 'colors_file', 'use_cache_in_stylesheet', 'markdown_stylesheet_filepath', 'markdown_document_template_filepath', 'document_parser_type']); - if(isset($config['cache'])) - { - $this->setGenericConfig($container, $config['cache'], 'ps_pdf.cache.%s', array('type', 'options')); + if (isset($config['cache'])) { + $this->setGenericConfig($container, $config['cache'], 'ps_pdf.cache.%s', ['type', 'options']); } } - + private function setGenericConfig(ContainerBuilder $container, array $config, $format, array $options) { - foreach($options as $name) - { - if(null !== $config[$name]) - { + foreach ($options as $name) { + if (null !== $config[$name]) { $container->setParameter(sprintf($format, $name), $config[$name]); } } } - + public function getNamespace() { return 'http://ohey.pl/phppdf/schema/dic/'.$this->getAlias(); } - + public function getXsdValidationBasePath() { return false; } - + public function getAlias() { return 'ps_pdf'; } -} \ No newline at end of file +} diff --git a/EventListener/PdfListener.php b/src/EventListener/PdfListener.php similarity index 73% rename from EventListener/PdfListener.php rename to src/EventListener/PdfListener.php index 64f995c..68f7d69 100644 --- a/EventListener/PdfListener.php +++ b/src/EventListener/PdfListener.php @@ -8,24 +8,21 @@ namespace Ps\PdfBundle\EventListener; +use Doctrine\Common\Annotations\Reader; use PHPPdf\Cache\Cache; +use PHPPdf\Core\FacadeBuilder; use Ps\PdfBundle\Annotation\Pdf as PdfAnnotation; +use Ps\PdfBundle\Reflection\Factory; use Symfony\Component\HttpFoundation\Request; -use PHPPdf\Core\Facade; -use Symfony\Component\HttpKernel\Exception\HttpException; -use PHPPdf\Core\FacadeBuilder; -use Symfony\Component\Templating\EngineInterface; -use Symfony\Component\HttpKernel\Event\GetResponseEvent; -use Symfony\Component\HttpKernel\Event\FilterResponseEvent; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Event\FilterControllerEvent; -use Ps\PdfBundle\Reflection\Factory; -use Doctrine\Common\Annotations\Reader; +use Symfony\Component\HttpKernel\Event\FilterResponseEvent; +use Symfony\Component\Templating\EngineInterface; /** * This listener will replace reponse content by pdf document's content if Pdf annotations is found. * Also adds proper headers to response object. - * + * * @author Piotr Śliwa */ class PdfListener @@ -35,7 +32,7 @@ class PdfListener private $reflectionFactory; private $templatingEngine; private $cache; - + public function __construct(FacadeBuilder $pdfFacadeBuilder, Reader $annotationReader, Factory $reflectionFactory, EngineInterface $templatingEngine, Cache $cache) { $this->pdfFacadeBuilder = $pdfFacadeBuilder; @@ -44,99 +41,86 @@ public function __construct(FacadeBuilder $pdfFacadeBuilder, Reader $annotationR $this->templatingEngine = $templatingEngine; $this->cache = $cache; } - + public function onKernelController(FilterControllerEvent $event) { - $request = $event->getRequest(); + $request = $event->getRequest(); $format = $request->get('_format'); - - if($format != 'pdf' || !is_array($controller = $event->getController()) || !$controller) - { + + if ('pdf' != $format || !is_array($controller = $event->getController()) || !$controller) { return; } - + $method = $this->reflectionFactory->createMethod($controller[0], $controller[1]); - + $annotation = $this->annotationReader->getMethodAnnotation($method, 'Ps\PdfBundle\Annotation\Pdf'); - - if($annotation) - { + + if ($annotation) { $request->attributes->set('_pdf', $annotation); - } + } } - + public function onKernelResponse(FilterResponseEvent $event) { $request = $event->getRequest(); - - if(!($annotation = $request->attributes->get('_pdf'))) - { + + if (!($annotation = $request->attributes->get('_pdf'))) { return; } - + $response = $event->getResponse(); - - if($response->getStatusCode() > 299) - { + + if ($response->getStatusCode() > 299) { return; } $stylesheetContent = null; - if($stylesheet = $annotation->stylesheet) - { + if ($stylesheet = $annotation->stylesheet) { $stylesheetContent = $this->templatingEngine->render($stylesheet); } - - $content = $this->getPdfContent($annotation, $response, $request, $stylesheetContent); + + $content = $this->getPdfContent($annotation, $response, $request, $stylesheetContent); $headers = (array) $annotation->headers; $headers['content-length'] = strlen($content); - foreach($headers as $key => $value) - { + foreach ($headers as $key => $value) { $response->headers->set($key, $value); } $response->setContent($content); } - + private function getPdfContent(PdfAnnotation $pdfAnnotation, Response $response, Request $request, $stylesheetContent) { - try - { + try { $responseContent = $response->getContent(); - + $pdfContent = null; - - if($pdfAnnotation->enableCache) - { + + if ($pdfAnnotation->enableCache) { $cacheKey = md5($responseContent.$stylesheetContent); - - if($this->cache->test($cacheKey)) - { + + if ($this->cache->test($cacheKey)) { $pdfContent = $this->cache->load($cacheKey); } } - if($pdfContent === null) - { + if (null === $pdfContent) { $pdfFacade = $this->pdfFacadeBuilder->setDocumentParserType($pdfAnnotation->documentParserType) ->build(); - - $pdfContent = $pdfFacade->render($responseContent, $stylesheetContent); - - if($pdfAnnotation->enableCache) - { + + $pdfContent = $pdfFacade->render($responseContent, $stylesheetContent); + + if ($pdfAnnotation->enableCache) { $this->cache->save($pdfContent, $cacheKey); } } - + return $pdfContent; - } - catch(\Exception $e) - { + } catch (\Exception $e) { $request->setRequestFormat('html'); $response->headers->set('content-type', 'text/html'); throw $e; } } -} \ No newline at end of file +} diff --git a/EventListener/PdfRequestListener.php b/src/EventListener/PdfRequestListener.php similarity index 99% rename from EventListener/PdfRequestListener.php rename to src/EventListener/PdfRequestListener.php index 9047f09..baef5c7 100644 --- a/EventListener/PdfRequestListener.php +++ b/src/EventListener/PdfRequestListener.php @@ -12,7 +12,6 @@ /** * Register a new 'pdf' format associated to mime type pdf. - * */ class PdfRequestListener { diff --git a/PHPPdf/Util/BundleBasedStringFilter.php b/src/PHPPdf/Util/BundleBasedStringFilter.php similarity index 77% rename from PHPPdf/Util/BundleBasedStringFilter.php rename to src/PHPPdf/Util/BundleBasedStringFilter.php index 3ddeff6..ae3d9fc 100644 --- a/PHPPdf/Util/BundleBasedStringFilter.php +++ b/src/PHPPdf/Util/BundleBasedStringFilter.php @@ -8,21 +8,21 @@ namespace Ps\PdfBundle\PHPPdf\Util; -use Symfony\Component\HttpKernel\KernelInterface; use PHPPdf\Util\StringFilter; +use Symfony\Component\HttpKernel\KernelInterface; /** * Class that provides support for bundle based path translations. - * + * * Example: * %SomeBundle:someFile.xml% will be replaced by "path/to/SomeBundle/Resources/someFile.xml" - * + * * @author Piotr Śliwa */ class BundleBasedStringFilter implements StringFilter { private $kernel; - + public function __construct(KernelInterface $kernel = null) { $this->kernel = $kernel; @@ -30,27 +30,24 @@ public function __construct(KernelInterface $kernel = null) public function filter($value) { - if(!$this->kernel) - { + if (!$this->kernel) { return $value; } - - if(preg_match_all('/\%(.+Bundle):(.+)\%/U', $value, $matches)) - { - $searches = array(); - $replacements = array(); - foreach($matches[1] as $index => $bundleName) - { + + if (preg_match_all('/\%(.+Bundle):(.+)\%/U', $value, $matches)) { + $searches = []; + $replacements = []; + foreach ($matches[1] as $index => $bundleName) { $bundle = $this->kernel->getBundle($bundleName); $path = $bundle->getPath(); - + $searches[] = $matches[0][$index]; $replacements[] = $path.'/Resources/'.$matches[2][$index]; } - + $value = str_replace($searches, $replacements, $value); } - + return $value; } -} \ No newline at end of file +} diff --git a/PsPdfBundle.php b/src/PsPdfBundle.php similarity index 82% rename from PsPdfBundle.php rename to src/PsPdfBundle.php index a1bf96f..8317d87 100644 --- a/PsPdfBundle.php +++ b/src/PsPdfBundle.php @@ -11,8 +11,8 @@ use Symfony\Component\HttpKernel\Bundle\Bundle; /** - * This bundle provides integration with PHPPdf library - * + * This bundle provides integration with PHPPdf library. + * * @author Piotr Śliwa */ class PsPdfBundle extends Bundle diff --git a/Reflection/Factory.php b/src/Reflection/Factory.php similarity index 89% rename from Reflection/Factory.php rename to src/Reflection/Factory.php index ceda921..5f0b090 100644 --- a/Reflection/Factory.php +++ b/src/Reflection/Factory.php @@ -10,7 +10,7 @@ /** * Simple factory method for reflection objects created in order to testing. - * + * * @author Piotr Śliwa */ class Factory @@ -18,19 +18,18 @@ class Factory public function createMethod($objectOrClass, $methodName) { $class = is_object($objectOrClass) ? get_class($objectOrClass) : (string) $objectOrClass; - + $class = $this->getUserClass($class); return new \ReflectionMethod($class, $methodName); } - + private function getUserClass($class) { - if(class_exists('CG\Core\ClassUtils', true)) - { + if (class_exists('CG\Core\ClassUtils', true)) { return \CG\Core\ClassUtils::getUserClass($class); } return $class; } -} \ No newline at end of file +} diff --git a/Resources/config/pdf.xml b/src/Resources/config/pdf.xml similarity index 100% rename from Resources/config/pdf.xml rename to src/Resources/config/pdf.xml diff --git a/Resources/config/routing.yml b/src/Resources/config/routing.yml similarity index 100% rename from Resources/config/routing.yml rename to src/Resources/config/routing.yml diff --git a/Resources/views/Example/index.html.twig b/src/Resources/views/Example/index.html.twig similarity index 100% rename from Resources/views/Example/index.html.twig rename to src/Resources/views/Example/index.html.twig diff --git a/Resources/views/Example/markdown.pdf.twig b/src/Resources/views/Example/markdown.pdf.twig similarity index 100% rename from Resources/views/Example/markdown.pdf.twig rename to src/Resources/views/Example/markdown.pdf.twig diff --git a/Resources/views/Example/pdfStylesheet.xml.twig b/src/Resources/views/Example/pdfStylesheet.xml.twig similarity index 100% rename from Resources/views/Example/pdfStylesheet.xml.twig rename to src/Resources/views/Example/pdfStylesheet.xml.twig diff --git a/Resources/views/Example/usingAutomaticFormatGuessing.html.twig b/src/Resources/views/Example/usingAutomaticFormatGuessing.html.twig similarity index 100% rename from Resources/views/Example/usingAutomaticFormatGuessing.html.twig rename to src/Resources/views/Example/usingAutomaticFormatGuessing.html.twig diff --git a/Resources/views/Example/usingAutomaticFormatGuessing.pdf.twig b/src/Resources/views/Example/usingAutomaticFormatGuessing.pdf.twig similarity index 100% rename from Resources/views/Example/usingAutomaticFormatGuessing.pdf.twig rename to src/Resources/views/Example/usingAutomaticFormatGuessing.pdf.twig diff --git a/Resources/views/Example/usingFacadeDirectly.pdf.twig b/src/Resources/views/Example/usingFacadeDirectly.pdf.twig similarity index 100% rename from Resources/views/Example/usingFacadeDirectly.pdf.twig rename to src/Resources/views/Example/usingFacadeDirectly.pdf.twig diff --git a/Templating/ImageLocator.php b/src/Templating/ImageLocator.php similarity index 67% rename from Templating/ImageLocator.php rename to src/Templating/ImageLocator.php index 9273ed1..c66f561 100644 --- a/Templating/ImageLocator.php +++ b/src/Templating/ImageLocator.php @@ -11,25 +11,29 @@ use Symfony\Component\HttpKernel\Kernel; /** - * Image locator - * + * Image locator. + * * @author Piotr Sliwa */ class ImageLocator implements ImageLocatorInterface { + /** @var Kernel */ private $kernel; - + + /** @var string */ + private $rootDir; + public function __construct(Kernel $kernel) { $this->kernel = $kernel; } - + /** * Converts image logical name in "BundleName:image-name.extension" format to absolute file path. - * + * * @return string file path - * - * @throws /InvalidArgumentException If bundle does not exist. + * + * @throws /InvalidArgumentException If bundle does not exist */ public function getImagePath($logicalImageName) { @@ -37,17 +41,26 @@ public function getImagePath($logicalImageName) // add support for ::$imagePath syntax as in twig // @see http://symfony.com/doc/current/book/page_creation.html#optional-step-3-create-the-template - if($pos === false || $pos === 0) - { - return $this->kernel->getRootDir() . '/Resources/public/images/' . ltrim($logicalImageName, ':'); + if (false === $pos || 0 === $pos) { + return $this->getRootDir().'/Resources/public/images/'.ltrim($logicalImageName, ':'); } - $bundleName = substr($logicalImageName, 0, $pos); + $bundleName = substr($logicalImageName, 0, $pos); $imageName = substr($logicalImageName, $pos + 1); - + $bundle = $this->kernel->getBundle($bundleName); $bundlePath = $bundle->getPath(); - + return $bundlePath.'/Resources/public/images/'.$imageName; } + + private function getRootDir(): string + { + if (null === $this->rootDir) { + $r = new \ReflectionObject($this->kernel); + $this->rootDir = \dirname($r->getFileName()); + } + + return $this->rootDir; + } } diff --git a/Templating/ImageLocatorInterface.php b/src/Templating/ImageLocatorInterface.php similarity index 95% rename from Templating/ImageLocatorInterface.php rename to src/Templating/ImageLocatorInterface.php index b13d59c..219ba0e 100644 --- a/Templating/ImageLocatorInterface.php +++ b/src/Templating/ImageLocatorInterface.php @@ -3,7 +3,7 @@ namespace Ps\PdfBundle\Templating; /** - * Image locator + * Image locator. * * @author Piotr Sliwa */ @@ -14,7 +14,7 @@ interface ImageLocatorInterface * * @return string file path * - * @throws /InvalidArgumentException If bundle does not exist. + * @throws /InvalidArgumentException If bundle does not exist */ public function getImagePath($logicalImageName); } diff --git a/Twig/Extensions/Extension/PdfExtension.php b/src/Twig/Extensions/Extension/PdfExtension.php similarity index 82% rename from Twig/Extensions/Extension/PdfExtension.php rename to src/Twig/Extensions/Extension/PdfExtension.php index b2df9ca..7a387f4 100644 --- a/Twig/Extensions/Extension/PdfExtension.php +++ b/src/Twig/Extensions/Extension/PdfExtension.php @@ -11,31 +11,31 @@ use Ps\PdfBundle\Templating\ImageLocatorInterface; /** - * Twig extension - * + * Twig extension. + * * @author Piotr Śliwa */ class PdfExtension extends \Twig_Extension { private $imageLocator; - + public function __construct(ImageLocatorInterface $imageLocator) { $this->imageLocator = $imageLocator; } - + public function getFunctions() { - return array( - new \Twig_SimpleFunction('pdf_image', array($this, 'getImagePath')), - ); + return [ + new \Twig_SimpleFunction('pdf_image', [$this, 'getImagePath']), + ]; } - + public function getName() { return 'ps_pdf'; } - + public function getImagePath($logicalImageName) { return $this->imageLocator->getImagePath($logicalImageName); diff --git a/tests/Annotation/PdfTest.php b/tests/Annotation/PdfTest.php new file mode 100644 index 0000000..0091932 --- /dev/null +++ b/tests/Annotation/PdfTest.php @@ -0,0 +1,57 @@ +getMethodAnnotation($method, Pdf::class); + + $this->assertNotNull($pdf); + } + + /** + * @test + * @dataProvider createAnnotationProvider + */ + public function createAnnotation(array $args, bool $expectedException) + { + $defaultArgs = [ + 'stylesheet' => null, + 'documentParserType' => 'xml', + 'headers' => [], + 'enableCache' => false, + ]; + + if ($expectedException) { + $this->expectException(\Exception::class); + } + + $annotation = new Pdf($args); + + $expectedVars = $args + $defaultArgs; + + $this->assertEquals($expectedVars, get_object_vars($annotation)); + } + + public function createAnnotationProvider() + { + return [ + [[], false], + [['stylesheet' => 'stylesheet', 'documentParserType' => 'markdown'], false], + [['enableCache' => true, 'headers' => ['key' => 'value']], false], + [['unexistedArg' => 'value'], true], + ]; + } +} diff --git a/Tests/DependencyInjection/PsPdfExtensionTest.php b/tests/DependencyInjection/PsPdfExtensionTest.php similarity index 81% rename from Tests/DependencyInjection/PsPdfExtensionTest.php rename to tests/DependencyInjection/PsPdfExtensionTest.php index 22aa4b7..801d837 100644 --- a/Tests/DependencyInjection/PsPdfExtensionTest.php +++ b/tests/DependencyInjection/PsPdfExtensionTest.php @@ -2,18 +2,22 @@ namespace Ps\PdfBundle\Tests\DependencyInjection; -use Symfony\Component\DependencyInjection\ContainerBuilder; +use PHPPdf\Cache\Cache; +use PHPPdf\Core\Facade; +use PHPPdf\Core\FacadeBuilder; +use PHPUnit\Framework\TestCase; use Ps\PdfBundle\DependencyInjection\PsPdfExtension; +use Symfony\Component\DependencyInjection\ContainerBuilder; -class PsPdfExtensionTest extends \PHPUnit_Framework_TestCase +class PsPdfExtensionTest extends TestCase { private $extension; - - public function setUp() + + protected function setUp(): void { $this->extension = new PsPdfExtension(); } - + /** * @test */ @@ -21,15 +25,15 @@ public function insertFacadeObjectIntoContainer() { $container = new ContainerBuilder(); $container->setParameter('kernel.cache_dir', __DIR__.'/'); - - $this->extension->load(array(), $container); - + + $this->extension->load([], $container); + $this->assertTrue($container->has('ps_pdf.facade')); $facade = $container->get('ps_pdf.facade'); - - $this->assertInstanceOf('PHPPdf\Core\Facade', $facade); + + $this->assertInstanceOf(Facade::class, $facade); } - + /** * @test */ @@ -37,15 +41,15 @@ public function insertFacadeBuilderObjectIntoContainer() { $container = new ContainerBuilder(); $container->setParameter('kernel.cache_dir', __DIR__.'/'); - - $this->extension->load(array(), $container); - + + $this->extension->load([], $container); + $this->assertTrue($container->has('ps_pdf.facade_builder')); $builder = $container->get('ps_pdf.facade_builder'); - - $this->assertInstanceOf('PHPPdf\Core\FacadeBuilder', $builder); + + $this->assertInstanceOf(FacadeBuilder::class, $builder); } - + /** * @test */ @@ -53,15 +57,15 @@ public function insertCacheObjectIntoContainer() { $container = new ContainerBuilder(); $container->setParameter('kernel.cache_dir', __DIR__.'/'); - - $this->extension->load(array(), $container); - + + $this->extension->load([], $container); + $this->assertTrue($container->has('ps_pdf.cache')); $cache = $container->get('ps_pdf.cache'); - - $this->assertInstanceOf('PHPPdf\Cache\Cache', $cache); + + $this->assertInstanceOf(Cache::class, $cache); } - + /** * @test */ @@ -69,27 +73,27 @@ public function setContainerParametersIfPassed() { $container = new ContainerBuilder(); $container->setParameter('kernel.cache_dir', __DIR__.'/'); - $config = array( - array( + $config = [ + [ 'nodes_file' => 'nodes file', 'fonts_file' => 'some file', 'complex_attributes_file' => 'some another file', 'colors_file' => 'colors file', - 'cache' => array( + 'cache' => [ 'type' => 'some type', - 'options' => array( + 'options' => [ 'custom_option' => 'value', - ), - ), + ], + ], 'use_cache_in_stylesheet' => true, 'markdown_stylesheet_filepath' => 'path1', 'markdown_document_template_filepath' => 'path2', 'document_parser_type' => 'markdown', - ), - ); + ], + ]; $this->extension->load($config, $container); - + $this->assertEquals($config[0]['nodes_file'], $container->getParameter('ps_pdf.nodes_file')); $this->assertEquals($config[0]['colors_file'], $container->getParameter('ps_pdf.colors_file')); $this->assertEquals($config[0]['fonts_file'], $container->getParameter('ps_pdf.fonts_file')); @@ -101,4 +105,4 @@ public function setContainerParametersIfPassed() $this->assertEquals($config[0]['markdown_document_template_filepath'], $container->getParameter('ps_pdf.markdown_document_template_filepath')); $this->assertEquals($config[0]['document_parser_type'], $container->getParameter('ps_pdf.document_parser_type')); } -} \ No newline at end of file +} diff --git a/Tests/EventListener/PdfListenerTest.php b/tests/EventListener/PdfListenerTest.php similarity index 73% rename from Tests/EventListener/PdfListenerTest.php rename to tests/EventListener/PdfListenerTest.php index 192994b..d1ba47b 100644 --- a/Tests/EventListener/PdfListenerTest.php +++ b/tests/EventListener/PdfListenerTest.php @@ -1,18 +1,24 @@ pdfFacadeBuilder = $this->getMockBuilder('PHPPdf\Core\FacadeBuilder') + $this->pdfFacadeBuilder = $this->getMockBuilder(FacadeBuilder::class) ->disableOriginalConstructor() - ->setMethods(array('build', 'setDocumentParserType')) + ->setMethods(['build', 'setDocumentParserType']) ->getMock(); - - $this->pdfFacade = $this->getMockBuilder('PHPPdf\Core\Facade') + + $this->pdfFacade = $this->getMockBuilder(Facade::class) ->disableOriginalConstructor() - ->setMethods(array('render')) + ->setMethods(['render']) ->getMock(); - - $this->templatingEngine = $this->getMockBuilder('Symfony\Component\Templating\EngineInterface') - ->setMethods(array('render', 'supports', 'exists')) + + $this->templatingEngine = $this->getMockBuilder(EngineInterface::class) + ->setMethods(['render', 'supports', 'exists']) ->getMock(); - - $this->reflactionFactory = $this->getMockBuilder('Ps\PdfBundle\Reflection\Factory') - ->setMethods(array('createMethod')) + + $this->reflactionFactory = $this->getMockBuilder(Factory::class) + ->setMethods(['createMethod']) ->getMock(); - $this->annotationReader = $this->getMockBuilder('Doctrine\Common\Annotations\Reader') - ->setMethods(array('getMethodAnnotations', 'getMethodAnnotation', 'getClassAnnotations', 'getClassAnnotation', 'getPropertyAnnotations', 'getPropertyAnnotation')) + $this->annotationReader = $this->getMockBuilder(Reader::class) + ->setMethods(['getMethodAnnotations', 'getMethodAnnotation', 'getClassAnnotations', 'getClassAnnotation', 'getPropertyAnnotations', 'getPropertyAnnotation']) ->getMock(); - - $this->cache = $this->getMockBuilder('PHPPdf\Cache\Cache')->getMock(); + + $this->cache = $this->getMockBuilder(Cache::class)->getMock(); $this->listener = new PdfListener($this->pdfFacadeBuilder, $this->annotationReader, $this->reflactionFactory, $this->templatingEngine, $this->cache); - - $this->request = $this->getMockBuilder('Symfony\Component\HttpFoundation\Request') - ->setMethods(array('get')) + + $this->request = $this->getMockBuilder(Request::class) + ->setMethods(['get']) ->getMock(); $this->requestAttributes = $this->getMockBuilder('stdClass') - ->setMethods(array('set', 'get')) + ->setMethods(['set', 'get']) ->getMock(); - + $this->request->attributes = $this->requestAttributes; - - $this->controllerEvent = $this->getMockBuilder('Symfony\Component\HttpKernel\Event\FilterControllerEvent') - ->setMethods(array('setController', 'getController', 'getRequest')) + + $this->controllerEvent = $this->getMockBuilder(FilterControllerEvent::class) + ->setMethods(['setController', 'getController', 'getRequest']) ->disableOriginalConstructor() ->getMock(); - + $this->controllerEvent->expects($this->any()) ->method('getRequest') ->will($this->returnValue($this->request)); } - + /** * @test * @dataProvider annotationProvider @@ -78,168 +84,155 @@ public function setUp() public function setAnnotationObjectToRequestIfRequestFormatIsPdfAndAnnotationExists($annotation, $format, $shouldControllerBeenSet) { $objectStub = new FileLocator(); - $controllerStub = array($objectStub, 'locate'); + $controllerStub = [$objectStub, 'locate']; $methodStub = new \ReflectionMethod($controllerStub[0], $controllerStub[1]); $this->request->expects($this->once()) ->method('get') ->with('_format') ->will($this->returnValue($format)); - + $this->controllerEvent->expects($this->any()) ->method('getController') ->will($this->returnValue($controllerStub)); - - if($format == 'pdf') - { + + if ('pdf' == $format) { $this->reflactionFactory->expects($this->once()) ->method('createMethod') ->with($controllerStub[0], $controllerStub[1]) ->will($this->returnValue($methodStub)); - + $this->annotationReader->expects($this->once()) ->method('getMethodAnnotation') ->with($methodStub, 'Ps\PdfBundle\Annotation\Pdf') ->will($this->returnValue($annotation)); - } - else - { + } else { $this->reflactionFactory->expects($this->never()) ->method('createMethod'); - + $this->annotationReader->expects($this->never()) ->method('getMethodAnnotation'); } - - if($shouldControllerBeenSet) - { + + if ($shouldControllerBeenSet) { $this->requestAttributes->expects($this->once()) ->method('set') ->with('_pdf', $annotation); - } - else - { + } else { $this->requestAttributes->expects($this->never()) ->method('set'); } - + $this->listener->onKernelController($this->controllerEvent); } - + public function annotationProvider() { - $annotation = new Pdf(array()); - - return array( - array($annotation, 'pdf', true), - array(null, 'pdf', false), - array($annotation, 'html', false), - ); + $annotation = new Pdf([]); + + return [ + [$annotation, 'pdf', true], + [null, 'pdf', false], + [$annotation, 'html', false], + ]; } - + /** * @test */ public function donotInvokePdfRenderingOnViewEventWhenResponseStatusIsError() { - $annotation = new Pdf(array()); + $annotation = new Pdf([]); $this->requestAttributes->expects($this->once()) ->method('get') ->with('_pdf') ->will($this->returnValue($annotation)); - + $responseStub = new Response(); - $responseStub->setStatusCode(300); + $responseStub->setStatusCode(300); $event = new FilterResponseEventStub($this->request, $responseStub); - + $this->pdfFacadeBuilder->expects($this->never()) ->method('build'); - + $this->listener->onKernelResponse($event); } - + /** * @test * @dataProvider booleanPairProvider */ public function invokePdfRenderingOnViewEvent($enableCache, $freshCache) { - $annotation = new Pdf(array('enableCache' => $enableCache)); + $annotation = new Pdf(['enableCache' => $enableCache]); $this->requestAttributes->expects($this->once()) ->method('get') ->with('_pdf') ->will($this->returnValue($annotation)); - + $contentStub = 'stub'; $responseContent = 'controller result stub'; $responseStub = new Response($responseContent); - if($enableCache) - { + if ($enableCache) { $cacheKey = md5($responseContent); $this->cache->expects($this->once()) ->method('test') ->with($cacheKey) ->will($this->returnValue($freshCache)); - - if($freshCache) - { + + if ($freshCache) { $this->cache->expects($this->once()) ->method('load') ->with($cacheKey) ->will($this->returnValue($contentStub)); - } - else - { + } else { $this->cache->expects($this->never()) ->method('load'); - + $this->expectPdfFacadeBuilding($annotation); - + $this->pdfFacade->expects($this->once()) ->method('render') ->with($responseContent) ->will($this->returnValue($contentStub)); - + $this->cache->expects($this->once()) ->method('save') ->with($contentStub, $cacheKey); } - } - else - { - foreach(array('test', 'load', 'save') as $method) - { + } else { + foreach (['test', 'load', 'save'] as $method) { $this->cache->expects($this->never()) ->method($method); } - + $this->expectPdfFacadeBuilding($annotation); - + $this->pdfFacade->expects($this->once()) ->method('render') ->with($responseContent) ->will($this->returnValue($contentStub)); } - + $event = new FilterResponseEventStub($this->request, $responseStub); - + $this->listener->onKernelResponse($event); - + $response = $event->getResponse(); - + $this->assertEquals($contentStub, $response->getContent()); } - + public function booleanPairProvider() { - return array( - array(false, false), - array(true, true), - array(true, false), - ); + return [ + [false, false], + [true, true], + [true, false], + ]; } - + private function expectPdfFacadeBuilding(Pdf $annotation) { $this->pdfFacadeBuilder->expects($this->once()) @@ -248,79 +241,76 @@ private function expectPdfFacadeBuilding(Pdf $annotation) ->will($this->returnValue($this->pdfFacadeBuilder)); $this->pdfFacadeBuilder->expects($this->once()) ->method('build') - ->will($this->returnValue($this->pdfFacade)); + ->will($this->returnValue($this->pdfFacade)); } - + /** * @test */ public function setResponseContentTypeAndRequestFormatOnException() { - $annotation = new Pdf(array('enableCache' => false)); + $annotation = new Pdf(['enableCache' => false]); $this->requestAttributes->expects($this->once()) ->method('get') ->with('_pdf') ->will($this->returnValue($annotation)); - + $this->expectPdfFacadeBuilding($annotation); $exception = new ParseException(); - + $this->pdfFacade->expects($this->once()) ->method('render') ->will($this->throwException($exception)); $responseStub = new Response(); $event = new FilterResponseEventStub($this->request, $responseStub); - - try - { + + try { $this->listener->onKernelResponse($event); $this->fail('exception expected'); - } - catch(ParseException $e) - { + } catch (ParseException $e) { $this->assertEquals('text/html', $responseStub->headers->get('content-type')); $this->assertEquals('html', $this->request->getRequestFormat('pdf')); } } - + /** * @test */ public function useStylesheetFromAnnotation() { $stylesheetPath = 'some path'; - - $annotation = new Pdf(array('stylesheet' => $stylesheetPath, 'enableCache' => false)); + + $annotation = new Pdf(['stylesheet' => $stylesheetPath, 'enableCache' => false]); $this->requestAttributes->expects($this->once()) ->method('get') ->with('_pdf') ->will($this->returnValue($annotation)); - + $stylesheetContent = 'stylesheet content'; - + $this->templatingEngine->expects($this->once()) ->method('render') ->with($stylesheetPath) ->will($this->returnValue($stylesheetContent)); - + $this->pdfFacadeBuilder->expects($this->once()) ->method('setDocumentParserType') ->with($annotation->documentParserType) ->will($this->returnValue($this->pdfFacadeBuilder)); $this->pdfFacadeBuilder->expects($this->once()) ->method('build') - ->will($this->returnValue($this->pdfFacade)); - + ->will($this->returnValue($this->pdfFacade)); + $this->pdfFacade->expects($this->once()) ->method('render') ->with($this->anything(), $stylesheetContent); - - $event = new FilterResponseEventStub($this->request, new Response()); + + $event = new FilterResponseEventStub($this->request, new Response()); $this->listener->onKernelResponse($event); } - + /** * @test */ @@ -330,14 +320,14 @@ public function breakInvocationIfControllerIsEmpty() ->method('get') ->with('_format') ->will($this->returnValue('pdf')); - + $this->controllerEvent->expects($this->once()) ->method('getController') - ->will($this->returnValue(array())); - + ->will($this->returnValue([])); + $this->reflactionFactory->expects($this->never()) ->method('createMethod'); - + $this->listener->onKernelController($this->controllerEvent); } } @@ -346,25 +336,25 @@ class FilterResponseEventStub extends FilterResponseEvent { private $request; private $response; - + public function __construct($request, $response) { $this->request = $request; $this->response = $response; } - + public function getResponse() { return $this->response; } - + public function setResponse(Response $response) { $this->response = $response; } - public function getRequest() + public function getRequest() { return $this->request; } -} \ No newline at end of file +} diff --git a/Tests/PHPPdf/Util/BundleBasedStringFilterTest.php b/tests/PHPPdf/Util/BundleBasedStringFilterTest.php similarity index 51% rename from Tests/PHPPdf/Util/BundleBasedStringFilterTest.php rename to tests/PHPPdf/Util/BundleBasedStringFilterTest.php index 79e700b..dcbf7c1 100644 --- a/Tests/PHPPdf/Util/BundleBasedStringFilterTest.php +++ b/tests/PHPPdf/Util/BundleBasedStringFilterTest.php @@ -2,56 +2,58 @@ namespace Ps\PdfBundle\Tests\PHPPdf\Util; +use PHPUnit\Framework\TestCase; use Ps\PdfBundle\PHPPdf\Util\BundleBasedStringFilter; +use Symfony\Component\HttpKernel\Bundle\BundleInterface; +use Symfony\Component\HttpKernel\KernelInterface; -class BundleBasedStringFilterTest extends \PHPUnit_Framework_TestCase +class BundleBasedStringFilterTest extends TestCase { private $filter; private $kernel; - - public function setUp() + + protected function setUp(): void { - $this->kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\KernelInterface')->getMock(); + $this->kernel = $this->getMockBuilder(KernelInterface::class)->getMock(); $this->filter = new BundleBasedStringFilter($this->kernel); } - + /** * @test * @dataProvider replaceBundleVariablesProvider */ public function replaceBundleVariables($string, $expectedString, array $expectedBundles) { - foreach($expectedBundles as $at => $bundle) - { + foreach ($expectedBundles as $at => $bundle) { list($bundleName, $bundlePath) = $bundle; - - $bundleMock = $this->getMockBuilder('\Symfony\Component\HttpKernel\Bundle\BundleInterface')->getMock(); + + $bundleMock = $this->getMockBuilder(BundleInterface::class)->getMock(); $bundleMock->expects($this->once()) ->method('getPath') ->will($this->returnValue($bundlePath)); - + $this->kernel->expects($this->at($at)) ->method('getBundle') ->with($bundleName) ->will($this->returnValue($bundleMock)); } - + $actualString = $this->filter->filter($string); - + $this->assertEquals($expectedString, $actualString); } - + public function replaceBundleVariablesProvider() { - return array( - array('some text', 'some text', array()), - array('text text %SomeBundle:file.xml% text text', 'text text path/Resources/file.xml text text', array( - array('SomeBundle', 'path'), - )), - array('text text %SomeBundle:file1.xml% text %SomeBundle:file2.xml% text', 'text text path/Resources/file1.xml text path/Resources/file2.xml text', array( - array('SomeBundle', 'path'), - array('SomeBundle', 'path'), - )), - ); + return [ + ['some text', 'some text', []], + ['text text %SomeBundle:file.xml% text text', 'text text path/Resources/file.xml text text', [ + ['SomeBundle', 'path'], + ]], + ['text text %SomeBundle:file1.xml% text %SomeBundle:file2.xml% text', 'text text path/Resources/file1.xml text path/Resources/file2.xml text', [ + ['SomeBundle', 'path'], + ['SomeBundle', 'path'], + ]], + ]; } -} \ No newline at end of file +} diff --git a/Tests/Templating/ImageLocatorTest.php b/tests/Templating/ImageLocatorTest.php similarity index 52% rename from Tests/Templating/ImageLocatorTest.php rename to tests/Templating/ImageLocatorTest.php index 2121e21..e2ea8af 100644 --- a/Tests/Templating/ImageLocatorTest.php +++ b/tests/Templating/ImageLocatorTest.php @@ -2,36 +2,36 @@ namespace Ps\PdfBundle\Tests\Templating; +use PHPUnit\Framework\TestCase; use Ps\PdfBundle\Templating\ImageLocator; +use Symfony\Component\HttpKernel\Bundle\Bundle; +use Symfony\Component\HttpKernel\Kernel; -class ImageLocatorTest extends \PHPUnit_Framework_TestCase +class ImageLocatorTest extends TestCase { private $kernel; - private $locator; - - protected function setup() + + protected function setup(): void { - $this->kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\Kernel') - ->setMethods(array('getBundle', 'registerBundles', 'registerContainerConfiguration', 'getRootDir')) + $this->kernel = $this->getMockBuilder(Kernel::class) + ->setMethods(['getBundle', 'registerBundles', 'registerContainerConfiguration', 'getRootDir']) ->disableOriginalConstructor() ->getMock(); - - $this->locator = new ImageLocator($this->kernel); } - + /** * @test * @dataProvider dataProvider */ - public function getImagePathSuccessfullyWhenBundleExists($bundleName, $imageName) + public function getImagePathSuccessfullyWhenBundleExists($bundleName, $imageName): void { - $bundle = $this->getMockBuilder('Symfony\Component\HttpKernel\Bundle\Bundle') - ->setMethods(array('getPath')) + $bundle = $this->getMockBuilder(Bundle::class) + ->setMethods(['getPath']) ->disableOriginalConstructor() ->getMock(); - + $bundlePath = 'some/bundle/path'; - + $imageLogicalName = sprintf('%s:%s', $bundleName, $imageName); $expectedImagePath = $bundlePath.'/Resources/public/images/'.$imageName; @@ -39,56 +39,63 @@ public function getImagePathSuccessfullyWhenBundleExists($bundleName, $imageName ->method('getBundle') ->with($bundleName) ->will($this->returnValue($bundle)); - + $bundle->expects($this->once()) ->method('getPath') ->will($this->returnValue($bundlePath)); - - $this->assertEquals($expectedImagePath, $this->locator->getImagePath($imageLogicalName)); + + $locator = new ImageLocator($this->kernel); + + $this->assertEquals($expectedImagePath, $locator->getImagePath($imageLogicalName)); } - - public function dataProvider() + + public function dataProvider(): array { - return array( - array('SomeBundle', 'some-image.jpg'), - array('SomeBundle', 'dir/some:image.jpg'), - ); + return [ + ['SomeBundle', 'some-image.jpg'], + ['SomeBundle', 'dir/some:image.jpg'], + ]; } /** * @test - * @expectedException InvalidArgumentException */ - public function throwExceptionIfBundleDoesNotExist() + public function throwExceptionIfBundleDoesNotExist(): void { $this->kernel->expects($this->once()) ->method('getBundle') ->will($this->throwException(new \InvalidArgumentException())); - - $this->locator->getImagePath('unexistedBundle:someImage.jpg'); + + $this->expectException(\InvalidArgumentException::class); + + $locator = new ImageLocator($this->kernel); + + $locator->getImagePath('unexistedBundle:someImage.jpg'); } - + /** * @test */ public function getImagePathFromGlobalResourcesWhenBundleNameIsEmpty() { - $rootDir = 'some/root/dir'; + $r = new \ReflectionObject($this->kernel); + $rootDir = \dirname($r->getFileName()); $imageName = 'some/image/name.jpg'; - $prefixes = array('', ':', '::'); - - $this->kernel->expects($this->exactly(count($prefixes))) + $prefixes = ['', ':', '::']; + + $this->kernel->expects($this->atMost(1)) ->method('getRootDir') ->will($this->returnValue($rootDir)); - + $this->kernel->expects($this->never()) ->method('getBundle'); $expectedPath = $rootDir.'/Resources/public/images/'.$imageName; - - foreach($prefixes as $prefix) - { - $this->assertEquals($expectedPath, $this->locator->getImagePath($prefix.$imageName)); - } + + $locator = new ImageLocator($this->kernel); + + foreach ($prefixes as $prefix) { + $this->assertEquals($expectedPath, $locator->getImagePath($prefix.$imageName)); + } } -} \ No newline at end of file +}