diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml new file mode 100644 index 0000000..e47a880 --- /dev/null +++ b/.github/workflows/tests.yml @@ -0,0 +1,72 @@ +name: Tests + +on: + push: + branches: [ master ] + pull_request: + branches: [ master ] + +permissions: + contents: read + +jobs: + tests: + name: Symfony ${{ matrix.symfony }} / PHP ${{ matrix.php }}${{ matrix.deps == 'lowest' && ' / lowest deps' || '' }} + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + include: + - php: '7.4' + symfony: '3.4' + - php: '8.1' + symfony: '3.4' + - php: '7.4' + symfony: '4.4' + - php: '8.0' + symfony: '4.4' + - php: '8.3' + symfony: '4.4' + - php: '7.4' + symfony: '5.4' + - php: '8.0' + symfony: '5.4' + - php: '8.2' + symfony: '5.4' + - php: '8.4' + symfony: '5.4' + - php: '8.1' + symfony: '6.4' + - php: '8.2' + symfony: '6.4' + - php: '8.3' + symfony: '6.4' + - php: '8.4' + symfony: '6.4' + - php: '7.4' + symfony: '4.4' + deps: lowest + steps: + - uses: actions/checkout@v4 + + - name: Setup PHP + uses: shivammathur/setup-php@v2 + with: + php-version: ${{ matrix.php }} + coverage: none + tools: composer:v2 + + - name: Install dependencies + run: | + composer require \ + 'symfony/config:^${{ matrix.symfony }}' \ + 'symfony/console:^${{ matrix.symfony }}' \ + 'symfony/dependency-injection:^${{ matrix.symfony }}' \ + 'symfony/http-kernel:^${{ matrix.symfony }}' \ + 'symfony/yaml:^${{ matrix.symfony }}' \ + --no-update + composer require --dev 'symfony/framework-bundle:^${{ matrix.symfony }}' --no-update + composer update --prefer-dist --no-progress --no-security-blocking ${{ matrix.deps == 'lowest' && '--prefer-lowest --prefer-stable' || '' }} + + - name: PHPUnit + run: composer test diff --git a/.gitignore b/.gitignore index c690eca..e12ffe7 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,4 @@ vendor composer.phar composer.lock +.phpunit.result.cache diff --git a/CacheTagsBundle/Command/InvalidateTagCommand.php b/CacheTagsBundle/Command/InvalidateTagCommand.php index ea25ffc..58192ee 100644 --- a/CacheTagsBundle/Command/InvalidateTagCommand.php +++ b/CacheTagsBundle/Command/InvalidateTagCommand.php @@ -39,7 +39,7 @@ protected function configure() $this->setDescription('Invalidates tag(s)'); } - protected function execute(InputInterface $input, OutputInterface $output) + protected function execute(InputInterface $input, OutputInterface $output): int { $verbosity = $output->getVerbosity(); foreach ($input->getArgument(self::ARGUMENT_TAG) as $tag) @@ -51,5 +51,7 @@ protected function execute(InputInterface $input, OutputInterface $output) $this->invalidator->invalidate(new Plain($tag)); } + + return 0; } } diff --git a/CacheTagsBundle/DependencyInjection/Configuration.php b/CacheTagsBundle/DependencyInjection/Configuration.php index 579f38f..8f812d9 100644 --- a/CacheTagsBundle/DependencyInjection/Configuration.php +++ b/CacheTagsBundle/DependencyInjection/Configuration.php @@ -2,6 +2,7 @@ namespace lbarulski\CacheTagsBundle\DependencyInjection; +use Symfony\Component\Config\Definition\BaseNode; use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition; use Symfony\Component\Config\Definition\Builder\NodeDefinition; use Symfony\Component\Config\Definition\Builder\TreeBuilder; @@ -78,7 +79,18 @@ private function addVarnishNode(ArrayNodeDefinition $proxiesNode) $varnishOptions->children()->scalarNode('path')->defaultValue('/')->end(); $varnishOptions->children()->integerNode('timeout')->defaultValue(1)->end(); $varnishOptions->children()->scalarNode('header')->defaultValue('X-CACHE-TAG')->end(); - $varnishOptions->children()->scalarNode('host_header')->setDeprecated('The child node "%node%" at path "%path%" is deprecated. Add "Host" header via "headers" instead')->defaultNull()->end(); + $hostHeaderNode = $varnishOptions->children()->scalarNode('host_header'); + $hostHeaderDeprecation = 'The child node "%node%" at path "%path%" is deprecated. Add "Host" header via "headers" instead'; + // Symfony 5.1 added the package and version arguments; 6.0 requires them + if (method_exists(BaseNode::class, 'getDeprecation')) + { + $hostHeaderNode->setDeprecated('lbarulski/cache-tags-bundle', '2.0', $hostHeaderDeprecation); + } + else + { + $hostHeaderNode->setDeprecated($hostHeaderDeprecation); + } + $hostHeaderNode->defaultNull()->end(); $varnishOptions->children()->booleanNode('ssl_verify_peer')->defaultFalse()->end(); $varnishOptions->children()->arrayNode('headers') ->prototype('array') diff --git a/CacheTagsBundle/Listener/CacheTagListener.php b/CacheTagsBundle/Listener/CacheTagListener.php index 0681366..f873c9a 100644 --- a/CacheTagsBundle/Listener/CacheTagListener.php +++ b/CacheTagsBundle/Listener/CacheTagListener.php @@ -6,6 +6,7 @@ use lbarulski\CacheTagsBundle\Annotation\CacheTag\RequestAttribute; use lbarulski\CacheTagsBundle\Service\Repository; use lbarulski\CacheTagsBundle\Tag\Plain as PlainTag; +use Symfony\Component\HttpKernel\Event\ControllerEvent; use Symfony\Component\HttpKernel\Event\FilterControllerEvent; class CacheTagListener @@ -24,9 +25,9 @@ public function __construct(Repository $repository) } /** - * @param FilterControllerEvent $event + * @param FilterControllerEvent|ControllerEvent $event */ - public function requestAttribute(FilterControllerEvent $event) + public function requestAttribute($event) { $request = $event->getRequest(); $aliasName = $this->getAliasName(RequestAttribute::ALIAS); @@ -50,9 +51,9 @@ public function requestAttribute(FilterControllerEvent $event) } /** - * @param FilterControllerEvent $event + * @param FilterControllerEvent|ControllerEvent $event */ - public function plain(FilterControllerEvent $event) + public function plain($event) { $request = $event->getRequest(); $aliasName = $this->getAliasName(Plain::ALIAS); diff --git a/CacheTagsBundle/Listener/ResponseListener.php b/CacheTagsBundle/Listener/ResponseListener.php index 10f7277..1838889 100644 --- a/CacheTagsBundle/Listener/ResponseListener.php +++ b/CacheTagsBundle/Listener/ResponseListener.php @@ -9,7 +9,7 @@ use lbarulski\CacheTagsBundle\Service\Repository; use lbarulski\CacheTagsBundle\Service\Tagger; use Symfony\Component\HttpKernel\Event\FilterResponseEvent; -use Symfony\Component\HttpKernel\HttpKernelInterface; +use Symfony\Component\HttpKernel\Event\ResponseEvent; class ResponseListener { @@ -30,11 +30,12 @@ public function __construct(Repository $repository, Tagger $tagger) } /** - * @param FilterResponseEvent $event + * @param FilterResponseEvent|ResponseEvent $event */ - public function onKernelResponse(FilterResponseEvent $event) + public function onKernelResponse($event) { - if (HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType()) + // isMasterRequest() is removed in Symfony 6.0, isMainRequest() exists since 5.3 + if (!(method_exists($event, 'isMainRequest') ? $event->isMainRequest() : $event->isMasterRequest())) { return; } diff --git a/composer.json b/composer.json index 9b05a89..3731bc4 100644 --- a/composer.json +++ b/composer.json @@ -26,10 +26,25 @@ "php": "^7.4 || ^8.0", "doctrine/annotations": "1.*", "sensio/framework-extra-bundle": "^3 || ^4 || ^5 || ^6", - "symfony/dependency-injection": "^2.8 || ^3.0 || ^4.0", - "symfony/http-kernel": "^2.8 || ^3.0 || ^4.0", - "symfony/config": "^2.8 || ^3.0 || ^4.0", - "symfony/console": "^2.8 || ^3.0 || ^4.0" + "symfony/dependency-injection": "^2.8 || ^3.0 || ^4.0 || ^5.0 || ^6.0", + "symfony/http-kernel": "^2.8 || ^3.0 || ^4.0 || ^5.0 || ^6.0", + "symfony/config": "^2.8 || ^3.0 || ^4.0 || ^5.0 || ^6.0", + "symfony/console": "^2.8 || ^3.0 || ^4.0 || ^5.0 || ^6.0", + "symfony/yaml": "^2.8 || ^3.0 || ^4.0 || ^5.0 || ^6.0" + }, + "require-dev": { + "phpunit/phpunit": "^9.5", + "symfony/framework-bundle": "^3.4 || ^4.4 || ^5.4 || ^6.4" + }, + "autoload-dev": { + "psr-4": { + "lbarulski\\CacheTagsBundle\\Tests\\": "tests/" + } + }, + "scripts": { + "test": [ + "vendor/bin/phpunit -c phpunit.xml.dist" + ] }, "extra": { "branch-alias": { diff --git a/phpunit.xml.dist b/phpunit.xml.dist new file mode 100644 index 0000000..a63713d --- /dev/null +++ b/phpunit.xml.dist @@ -0,0 +1,12 @@ + + + + + tests + + + diff --git a/tests/ConfigurationTest.php b/tests/ConfigurationTest.php new file mode 100644 index 0000000..b17678a --- /dev/null +++ b/tests/ConfigurationTest.php @@ -0,0 +1,77 @@ +process([['response' => []]]); + + $this->assertSame('X-CACHE-TAGS', $config['response']['tag']); + } + + public function testVarnishProxyDefaults() + { + $config = $this->process([['proxies' => ['varnish' => [[]]]]]); + + $this->assertSame([ + 'host' => '127.0.0.1', + 'port' => 80, + 'path' => '/', + 'timeout' => 1, + 'header' => 'X-CACHE-TAG', + 'host_header' => null, + 'ssl_verify_peer' => false, + 'headers' => [], + ], $config['proxies']['varnish'][0]); + } + + public function testHostHeaderAndHeaders() + { + $config = $this->process([[ + 'response' => ['tag' => 'X-TAGS'], + 'proxies' => ['varnish' => [[ + 'host' => 'varnish.internal', + 'port' => 6081, + 'host_header' => 'www.example.com', + 'headers' => [['name' => 'X-Foo', 'value' => 'bar']], + ]]], + ]]); + + $this->assertSame('X-TAGS', $config['response']['tag']); + $varnish = $config['proxies']['varnish'][0]; + $this->assertSame('varnish.internal', $varnish['host']); + $this->assertSame(6081, $varnish['port']); + $this->assertSame('www.example.com', $varnish['host_header']); + $this->assertSame([['name' => 'X-Foo', 'value' => 'bar']], $varnish['headers']); + } + + public function testHeaderRequiresNameAndValue() + { + $this->expectException(InvalidConfigurationException::class); + + $this->process([['proxies' => ['varnish' => [['headers' => [['name' => 'X-Foo']]]]]]]); + } + + private function process(array $configs) + { + // host_header is deprecated; the deprecation notice is expected, not a failure. + set_error_handler(function ($level) { + return E_USER_DEPRECATED === $level; + }); + try + { + return (new Processor())->processConfiguration(new Configuration(), $configs); + } + finally + { + restore_error_handler(); + } + } +} diff --git a/tests/ContainerTest.php b/tests/ContainerTest.php new file mode 100644 index 0000000..c8af095 --- /dev/null +++ b/tests/ContainerTest.php @@ -0,0 +1,30 @@ +kernel->getContainer(); + + $this->assertInstanceOf(InvalidateTagCommand::class, $container->get('cache_tags.command.invalidate_tag')); + $this->assertTrue($container->has('cache_tags.tagger')); + $this->assertTrue($container->has('cache_tags.listener.invalidator')); + $this->assertSame('X-CACHE-TAGS', $container->getParameter('cache_tags.response.tag')); + } + + public function testEveryConfiguredVarnishProxyIsRegistered() + { + $proxies = $this->kernel->getContainer()->get('cache_tags.invalidator.proxy.manager')->getProxies(); + + $this->assertCount(2, $proxies); + foreach ($proxies as $proxy) + { + $this->assertInstanceOf(Varnish::class, $proxy); + } + } +} diff --git a/tests/Fixtures/FakeVarnish.php b/tests/Fixtures/FakeVarnish.php new file mode 100644 index 0000000..133243b --- /dev/null +++ b/tests/Fixtures/FakeVarnish.php @@ -0,0 +1,46 @@ +server = stream_socket_server('tcp://127.0.0.1:0', $errNo, $errStr); + if (false === $this->server) + { + throw new \RuntimeException($errStr, $errNo); + } + $this->port = (int) substr(strrchr(stream_socket_get_name($this->server, false), ':'), 1); + } + + public function getPort() + { + return $this->port; + } + + /** @return string[] raw requests received so far */ + public function getRequests() + { + $requests = []; + while ($connection = @stream_socket_accept($this->server, 0)) + { + $requests[] = stream_get_contents($connection); + fclose($connection); + } + + return $requests; + } + + public function close() + { + fclose($this->server); + } +} diff --git a/tests/Fixtures/FixtureController.php b/tests/Fixtures/FixtureController.php new file mode 100644 index 0000000..e22f748 --- /dev/null +++ b/tests/Fixtures/FixtureController.php @@ -0,0 +1,23 @@ +varnishProxies = $varnishProxies; + parent::__construct('test', true); + } + + public function registerBundles(): iterable + { + return [ + new FrameworkBundle(), + new SensioFrameworkExtraBundle(), + new CacheTagsBundle(), + ]; + } + + public function registerContainerConfiguration(LoaderInterface $loader): void + { + $loader->load(function (ContainerBuilder $container) { + $container->loadFromExtension('framework', [ + 'secret' => 'test', + 'annotations' => ['enabled' => true], + ]); + // Sensio registers the controller annotation listener only when a feature is enabled. + $container->loadFromExtension('sensio_framework_extra', [ + 'router' => ['annotations' => false], + 'request' => ['converters' => false], + 'view' => ['annotations' => false], + 'cache' => ['annotations' => true], + 'security' => ['annotations' => false], + ]); + $container->loadFromExtension('cache_tags', [ + 'response' => [], + 'proxies' => ['varnish' => $this->varnishProxies], + ]); + $container->register(FixtureController::class, FixtureController::class)->setPublic(true); + }); + } + + protected function build(ContainerBuilder $container): void + { + $container->addCompilerPass($this, PassConfig::TYPE_BEFORE_OPTIMIZATION); + } + + /** Exposes the bundle services so tests can fetch them from the compiled container. */ + public function process(ContainerBuilder $container): void + { + foreach ($container->getDefinitions() as $id => $definition) + { + if (0 === strpos($id, 'cache_tags.') && !$definition->isAbstract()) + { + $definition->setPublic(true); + } + } + } + + public function getCacheDir(): string + { + return sys_get_temp_dir() . '/cache-tags-bundle-tests/' . spl_object_hash($this) . '/cache'; + } + + public function getLogDir(): string + { + return sys_get_temp_dir() . '/cache-tags-bundle-tests/' . spl_object_hash($this) . '/logs'; + } +} diff --git a/tests/InvalidateCommandTest.php b/tests/InvalidateCommandTest.php new file mode 100644 index 0000000..31d59e8 --- /dev/null +++ b/tests/InvalidateCommandTest.php @@ -0,0 +1,48 @@ +runCommand(['command' => 'cache_tags:invalidate', 'tag' => ['article-1', 'article-2']], $output); + + $this->assertSame(0, $exitCode); + $this->assertStringContainsString('Invalidating tag', $output->fetch()); + + $first = $this->varnishes[0]->getRequests(); + $this->assertCount(2, $first); + $this->assertStringStartsWith("BAN / HTTP/1.1\r\nHost: 127.0.0.1\r\n", $first[0]); + $this->assertStringContainsString("\r\nX-CACHE-TAG: article-1\r\n", $first[0]); + $this->assertStringContainsString("\r\nX-CACHE-TAG: article-2\r\n", $first[1]); + $this->assertStringNotContainsString('X-Extra', $first[0]); + } + + public function testProxyOptionsAreUsedInTheRequest() + { + $this->runCommand(['command' => 'cache_tags:invalidate', 'tag' => ['article-1']], new BufferedOutput()); + + $second = $this->varnishes[1]->getRequests(); + $this->assertCount(1, $second); + $this->assertStringStartsWith("BAN / HTTP/1.1\r\nHost: varnish.example.com\r\n", $second[0]); + $this->assertStringContainsString("\r\nX-CUSTOM-TAG: article-1\r\n", $second[0]); + $this->assertStringContainsString("\r\nX-Extra: yes\r\n", $second[0]); + $this->assertStringContainsString("\r\nConnection: Close\r\n\r\n", $second[0]); + } + + private function runCommand(array $input, BufferedOutput $output) + { + $application = new Application($this->kernel); + $application->setAutoExit(false); + + return $application->run(new ArrayInput($input), $output); + } +} diff --git a/tests/KernelTestCase.php b/tests/KernelTestCase.php new file mode 100644 index 0000000..7c8eb94 --- /dev/null +++ b/tests/KernelTestCase.php @@ -0,0 +1,73 @@ +varnishes = [new FakeVarnish(), new FakeVarnish()]; + + $this->kernel = new TestKernel([ + [ + 'host' => '127.0.0.1', + 'port' => $this->varnishes[0]->getPort(), + 'timeout' => 2, + ], + [ + 'host' => '127.0.0.1', + 'port' => $this->varnishes[1]->getPort(), + 'timeout' => 2, + 'header' => 'X-CUSTOM-TAG', + 'host_header' => 'varnish.example.com', + 'headers' => [['name' => 'X-Extra', 'value' => 'yes']], + ], + ]); + + // host_header is deprecated on purpose; the deprecation must not fail the boot. + set_error_handler(function ($level) { + return E_USER_DEPRECATED === $level; + }); + try + { + $this->kernel->boot(); + } + finally + { + restore_error_handler(); + } + } + + protected function tearDown(): void + { + $this->kernel->shutdown(); + foreach ($this->varnishes as $varnish) + { + $varnish->close(); + } + $this->removeDir(dirname($this->kernel->getCacheDir())); + } + + private function removeDir($dir) + { + if (!is_dir($dir)) + { + return; + } + foreach (new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($dir, \FilesystemIterator::SKIP_DOTS), \RecursiveIteratorIterator::CHILD_FIRST) as $file) + { + $file->isDir() ? rmdir($file->getPathname()) : unlink($file->getPathname()); + } + rmdir($dir); + } +} diff --git a/tests/ListenerTest.php b/tests/ListenerTest.php new file mode 100644 index 0000000..ea81964 --- /dev/null +++ b/tests/ListenerTest.php @@ -0,0 +1,51 @@ +kernel->handle($this->request('tagged')); + + $this->assertSame('tagged', $response->getContent()); + $this->assertSame('article,article-42', $response->headers->get('X-CACHE-TAGS')); + } + + public function testPlainAnnotationFillsTheTaggerRepository() + { + $this->kernel->handle($this->request('tagged')); + + $tags = $this->kernel->getContainer()->get('cache_tags.tagger.repository')->getTags(); + $this->assertSame(['article', 'article-42'], array_keys($tags)); + } + + public function testResponseWithoutAnnotationHasNoTagHeader() + { + $response = $this->kernel->handle($this->request('untagged')); + + $this->assertFalse($response->headers->has('X-CACHE-TAGS')); + } + + public function testSubRequestIsNotTagged() + { + $this->kernel->handle($this->request('tagged')); + + $sub = $this->request('untagged'); + $response = $this->kernel->handle($sub, HttpKernelInterface::SUB_REQUEST); + + $this->assertFalse($response->headers->has('X-CACHE-TAGS')); + } + + private function request($action) + { + $request = Request::create('/'); + $request->attributes->set('_controller', FixtureController::class . '::' . $action); + + return $request; + } +}