Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

[FrameworkBundle] Wire PhpArrayAdapter with a new cache warmer for annotations #18533

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Bundle\FrameworkBundle\CacheWarmer;

use Doctrine\Common\Annotations\CachedReader;
use Doctrine\Common\Annotations\Reader;
use Psr\Cache\CacheItemPoolInterface;
use Symfony\Component\Cache\Adapter\AdapterInterface;
use Symfony\Component\Cache\Adapter\ArrayAdapter;
use Symfony\Component\Cache\Adapter\PhpArrayAdapter;
use Symfony\Component\Cache\Adapter\ProxyAdapter;
use Symfony\Component\Cache\DoctrineProvider;
use Symfony\Component\HttpKernel\CacheWarmer\CacheWarmerInterface;

/**
* Warms up annotation caches for classes found in composer's autoload class map
* and declared in DI bundle extensions using the addAnnotatedClassesToCache method.
*
* @author Titouan Galopin <galopintitouan@gmail.com>
*/
class AnnotationsCacheWarmer implements CacheWarmerInterface
{
private $annotationReader;
private $phpArrayFile;
private $fallbackPool;

/**
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same here (the IDE is able to guess it using the contructor type hint).

* @param Reader $annotationReader
* @param string $phpArrayFile The PHP file where annotations are cached.
* @param CacheItemPoolInterface $fallbackPool The pool where runtime-discovered annotations are cached.
*/
public function __construct(Reader $annotationReader, $phpArrayFile, CacheItemPoolInterface $fallbackPool)
{
$this->annotationReader = $annotationReader;
$this->phpArrayFile = $phpArrayFile;
if (!$fallbackPool instanceof AdapterInterface) {
$fallbackPool = new ProxyAdapter($fallbackPool);
}
$this->fallbackPool = $fallbackPool;
}

/**
* {@inheritdoc}
*/
public function warmUp($cacheDir)
{
$adapter = new PhpArrayAdapter($this->phpArrayFile, $this->fallbackPool);
$annotatedClassPatterns = $cacheDir.'/annotations.map';

if (!is_file($annotatedClassPatterns)) {
$adapter->warmUp(array());

return;
}

$annotatedClasses = include $annotatedClassPatterns;

$arrayPool = new ArrayAdapter(0, false);
$reader = new CachedReader($this->annotationReader, new DoctrineProvider($arrayPool));

foreach ($annotatedClasses as $class) {
$this->readAllComponents($reader, $class);
}

$values = $arrayPool->getValues();
$adapter->warmUp($values);

foreach ($values as $k => $v) {
$item = $this->fallbackPool->getItem($k);
$this->fallbackPool->saveDeferred($item->set($v));
}
$this->fallbackPool->commit();
}

/**
* {@inheritdoc}
*/
public function isOptional()
{
return true;
}

private function readAllComponents(Reader $reader, $class)
{
$reflectionClass = new \ReflectionClass($class);
$reader->getClassAnnotations($reflectionClass);

foreach ($reflectionClass->getMethods() as $reflectionMethod) {
$reader->getMethodAnnotations($reflectionMethod);
}

foreach ($reflectionClass->getProperties() as $reflectionProperty) {
$reader->getPropertyAnnotations($reflectionProperty);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -594,7 +594,7 @@ private function addAnnotationsSection(ArrayNodeDefinition $rootNode)
->info('annotation configuration')
->addDefaultsIfNotSet()
->children()
->scalarNode('cache')->defaultValue('file')->end()
->scalarNode('cache')->defaultValue('php_array')->end()
->scalarNode('file_cache_dir')->defaultValue('%kernel.cache_dir%/annotations')->end()
->booleanNode('debug')->defaultValue($this->debug)->end()
->end()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,14 @@ public function load(array $configs, ContainerBuilder $container)
$definition->replaceArgument(1, null);
}

$this->addAnnotatedClassesToCompile(array(
'**Bundle\\Controller\\',
'**Bundle\\Entity\\',

// Added explicitly so that we don't rely on the class map being dumped to make it work
'Symfony\\Bundle\\FrameworkBundle\\Controller\\Controller',
));

$this->addClassesToCompile(array(
'Symfony\\Component\\Config\\ConfigCache',
'Symfony\\Component\\Config\\FileLocator',
Expand Down Expand Up @@ -906,8 +914,22 @@ private function registerAnnotationsConfiguration(array $config, ContainerBuilde
$loader->load('annotations.xml');

if ('none' !== $config['cache']) {
if ('file' === $config['cache']) {
$cacheService = $config['cache'];

if ('php_array' === $config['cache']) {
$cacheService = 'annotations.cache';

// Enable warmer only if PHP array is used for cache
$definition = $container->findDefinition('annotations.cache_warmer');
$definition->addTag('kernel.cache_warmer');

$this->addClassesToCompile(array(
'Symfony\Component\Cache\Adapter\PhpArrayAdapter',
'Symfony\Component\Cache\DoctrineProvider',
));
} elseif ('file' === $config['cache']) {
$cacheDir = $container->getParameterBag()->resolveValue($config['file_cache_dir']);

if (!is_dir($cacheDir) && false === @mkdir($cacheDir, 0777, true) && !is_dir($cacheDir)) {
throw new \RuntimeException(sprintf('Could not create cache directory "%s".', $cacheDir));
}
Expand All @@ -916,11 +938,13 @@ private function registerAnnotationsConfiguration(array $config, ContainerBuilde
->getDefinition('annotations.filesystem_cache')
->replaceArgument(0, $cacheDir)
;

$cacheService = 'annotations.filesystem_cache';
}

$container
->getDefinition('annotations.cached_reader')
->replaceArgument(1, new Reference('file' !== $config['cache'] ? $config['cache'] : 'annotations.filesystem_cache'))
->replaceArgument(1, new Reference($cacheService))
->replaceArgument(2, $config['debug'])
->addAutowiringType(Reader::class)
;
Expand Down Expand Up @@ -1130,10 +1154,8 @@ private function registerCacheConfiguration(array $config, ContainerBuilder $con
}

$this->addClassesToCompile(array(
'Psr\Cache\CacheItemInterface',
'Psr\Cache\CacheItemPoolInterface',
'Symfony\Component\Cache\Adapter\AdapterInterface',
'Symfony\Component\Cache\Adapter\AbstractAdapter',
'Symfony\Component\Cache\Adapter\ApcuAdapter',
'Symfony\Component\Cache\Adapter\FilesystemAdapter',
'Symfony\Component\Cache\CacheItem',
));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,22 @@
<argument /><!-- Cache-Directory -->
</service>

<service id="annotations.cache_warmer" class="Symfony\Bundle\FrameworkBundle\CacheWarmer\AnnotationsCacheWarmer" public="false">
<argument type="service" id="annotations.reader" />
<argument>%kernel.cache_dir%/annotations.php</argument>
<argument type="service" id="cache.annotations" />
</service>

<service id="annotations.cache" class="Symfony\Component\Cache\DoctrineProvider" public="false">
<argument type="service">
<service class="Symfony\Component\Cache\Adapter\PhpArrayAdapter">
<factory class="Symfony\Component\Cache\Adapter\PhpArrayAdapter" method="create" />
<argument>%kernel.cache_dir%/annotations.php</argument>
<argument type="service" id="cache.annotations" />
</service>
</argument>
</service>

<service id="annotation_reader" alias="annotations.reader" />
</services>
</container>
4 changes: 4 additions & 0 deletions 4 src/Symfony/Bundle/FrameworkBundle/Resources/config/cache.xml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@
<tag name="cache.pool" />
</service>

<service id="cache.annotations" parent="cache.system" public="false">
<tag name="cache.pool" />
</service>

<service id="cache.adapter.system" class="Symfony\Component\Cache\Adapter\AdapterInterface" abstract="true">
<factory class="Symfony\Component\Cache\Adapter\AbstractAdapter" method="createSystemCache" />
<tag name="cache.pool" clearer="cache.default_clearer" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -214,7 +214,7 @@ protected static function getBundleDefaultConfig()
'cache' => 'validator.mapping.cache.symfony',
),
'annotations' => array(
'cache' => 'file',
'cache' => 'php_array',
'file_cache_dir' => '%kernel.cache_dir%/annotations',
'debug' => true,
),
Expand Down
4 changes: 2 additions & 2 deletions 4 src/Symfony/Bundle/FrameworkBundle/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,13 @@
"require": {
"php": ">=5.5.9",
"symfony/asset": "~2.8|~3.0",
"symfony/cache": "~3.1",
"symfony/cache": "~3.2",
"symfony/class-loader": "~3.2",
"symfony/dependency-injection": "~3.2",
"symfony/config": "~2.8|~3.0",
"symfony/event-dispatcher": "~2.8|~3.0",
"symfony/http-foundation": "~3.1",
"symfony/http-kernel": "~3.1.2|~3.2",
"symfony/http-kernel": "~3.2",
"symfony/polyfill-mbstring": "~1.0",
"symfony/filesystem": "~2.8|~3.0",
"symfony/finder": "~2.8|~3.0",
Expand Down
14 changes: 12 additions & 2 deletions 14 src/Symfony/Component/Cache/Adapter/ArrayAdapter.php
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ function ($key, $value, $isHit) use ($defaultLifetime) {
public function getItem($key)
{
if (!$isHit = $this->hasItem($key)) {
$value = null;
$this->values[$key] = $value = null;
} elseif ($this->storeSerialized) {
$value = unserialize($this->values[$key]);
} else {
Expand All @@ -79,6 +79,16 @@ public function getItems(array $keys = array())
return $this->generateItems($keys, time());
}

/**
* Returns all cached values, with cache miss as null.
*
* @return array
*/
public function getValues()
{
return $this->values;
}

/**
* {@inheritdoc}
*/
Expand Down Expand Up @@ -183,7 +193,7 @@ private function generateItems(array $keys, $now)

foreach ($keys as $key) {
if (!$isHit = isset($this->expiries[$key]) && ($this->expiries[$key] >= $now || !$this->deleteItem($key))) {
$value = null;
$this->values[$key] = $value = null;
} elseif ($this->storeSerialized) {
$value = unserialize($this->values[$key]);
} else {
Expand Down
26 changes: 26 additions & 0 deletions 26 src/Symfony/Component/Cache/Tests/Adapter/ArrayAdapterTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,30 @@ public function createCachePool($defaultLifetime = 0)
{
return new ArrayAdapter($defaultLifetime);
}

public function testGetValuesHitAndMiss()
{
/** @var ArrayAdapter $cache */
$cache = $this->createCachePool();

// Hit
$item = $cache->getItem('foo');
$item->set('4711');
$cache->save($item);

$fooItem = $cache->getItem('foo');
$this->assertTrue($fooItem->isHit());
$this->assertEquals('4711', $fooItem->get());

// Miss (should be present as NULL in $values)
$cache->getItem('bar');

$values = $cache->getValues();

$this->assertCount(2, $values);
$this->assertArrayHasKey('foo', $values);
$this->assertSame(serialize('4711'), $values['foo']);
$this->assertArrayHasKey('bar', $values);
$this->assertNull($values['bar']);
}
}
Loading
Morty Proxy This is a proxified and sanitized view of the page, visit original site.