Skip to content

Add annotation reader cache #818

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 11 commits into from
33 changes: 26 additions & 7 deletions src/Config/Parser/AnnotationParser.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,28 @@

use Doctrine\Common\Annotations\AnnotationReader;
use Doctrine\Common\Annotations\AnnotationRegistry;
use Doctrine\Common\Annotations\CachedReader;
use Doctrine\Common\Annotations\Reader;
use Doctrine\Common\Cache\ApcuCache;
use Doctrine\Common\Cache\PhpFileCache;
use Overblog\GraphQLBundle\Config\Parser\MetadataParser\MetadataParser;
use ReflectionClass;
use ReflectionMethod;
use ReflectionProperty;
use Reflector;
use RuntimeException;
use function apcu_enabled;
use function class_exists;
use function extension_loaded;
use function implode;
use function md5;
use function sys_get_temp_dir;

class AnnotationParser extends MetadataParser
{
public const METADATA_FORMAT = '@%s';

protected static ?AnnotationReader $annotationReader = null;
protected static Reader $annotationReader;

protected static function getMetadatas(Reflector $reflector): array
{
Expand All @@ -32,18 +42,27 @@ protected static function getMetadatas(Reflector $reflector): array
return [];
}

protected static function getAnnotationReader(): AnnotationReader
protected static function getAnnotationReader(): Reader
{
if (null === self::$annotationReader) {
if (!class_exists(AnnotationReader::class) ||
!class_exists(AnnotationRegistry::class)) {
if (!isset(self::$annotationReader)) {
if (!class_exists(AnnotationReader::class) || !class_exists(AnnotationRegistry::class)) {
// @codeCoverageIgnoreStart
throw new RuntimeException('In order to use graphql annotation, you need to require doctrine annotations');
throw new RuntimeException("In order to use annotations, you need to install 'doctrine/annotations' first. See: 'https://www.doctrine-project.org/projects/annotations.html'");
// @codeCoverageIgnoreEnd
}

AnnotationRegistry::registerLoader('class_exists');
self::$annotationReader = new AnnotationReader();
$cacheKey = md5(__DIR__);
// @codeCoverageIgnoreStart
if (extension_loaded('apcu') && apcu_enabled()) {
$annotationCache = new ApcuCache();
} else {
$annotationCache = new PhpFileCache(implode(DIRECTORY_SEPARATOR, [sys_get_temp_dir(), $cacheKey]));
}
// @codeCoverageIgnoreEnd
$annotationCache->setNamespace($cacheKey);

self::$annotationReader = new CachedReader(new AnnotationReader(), $annotationCache, true);
}

return self::$annotationReader;
Expand Down