repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
goaop/framework
src/Aop/Framework/AbstractInterceptor.php
AbstractInterceptor.unserializeAdvice
public static function unserializeAdvice(array $adviceData): Closure { $aspectName = $adviceData['class']; $methodName = $adviceData['method']; if (!isset(static::$localAdvicesCache["$aspectName->$methodName"])) { $aspect = AspectKernel::getInstance()->getContainer()->getAspect($aspectName); $refMethod = new ReflectionMethod($aspectName, $methodName); $advice = $refMethod->getClosure($aspect); static::$localAdvicesCache["$aspectName->$methodName"] = $advice; } return static::$localAdvicesCache["$aspectName->$methodName"]; }
php
public static function unserializeAdvice(array $adviceData): Closure { $aspectName = $adviceData['class']; $methodName = $adviceData['method']; if (!isset(static::$localAdvicesCache["$aspectName->$methodName"])) { $aspect = AspectKernel::getInstance()->getContainer()->getAspect($aspectName); $refMethod = new ReflectionMethod($aspectName, $methodName); $advice = $refMethod->getClosure($aspect); static::$localAdvicesCache["$aspectName->$methodName"] = $advice; } return static::$localAdvicesCache["$aspectName->$methodName"]; }
[ "public", "static", "function", "unserializeAdvice", "(", "array", "$", "adviceData", ")", ":", "Closure", "{", "$", "aspectName", "=", "$", "adviceData", "[", "'class'", "]", ";", "$", "methodName", "=", "$", "adviceData", "[", "'method'", "]", ";", "if",...
Unserialize an advice @param array $adviceData Information about advice
[ "Unserialize", "an", "advice" ]
train
https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Aop/Framework/AbstractInterceptor.php#L98-L112
goaop/framework
src/Aop/Framework/AbstractInterceptor.php
AbstractInterceptor.serialize
final public function serialize(): string { $vars = array_filter(get_object_vars($this)); $vars['adviceMethod'] = static::serializeAdvice($this->adviceMethod); return serialize($vars); }
php
final public function serialize(): string { $vars = array_filter(get_object_vars($this)); $vars['adviceMethod'] = static::serializeAdvice($this->adviceMethod); return serialize($vars); }
[ "final", "public", "function", "serialize", "(", ")", ":", "string", "{", "$", "vars", "=", "array_filter", "(", "get_object_vars", "(", "$", "this", ")", ")", ";", "$", "vars", "[", "'adviceMethod'", "]", "=", "static", "::", "serializeAdvice", "(", "$"...
Serializes an interceptor into string representation
[ "Serializes", "an", "interceptor", "into", "string", "representation" ]
train
https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Aop/Framework/AbstractInterceptor.php#L133-L139
goaop/framework
src/Aop/Framework/AbstractInterceptor.php
AbstractInterceptor.unserialize
final public function unserialize($serialized): void { $vars = unserialize($serialized, ['allowed_classes' => false]); $vars['adviceMethod'] = static::unserializeAdvice($vars['adviceMethod']); foreach ($vars as $key => $value) { $this->$key = $value; } }
php
final public function unserialize($serialized): void { $vars = unserialize($serialized, ['allowed_classes' => false]); $vars['adviceMethod'] = static::unserializeAdvice($vars['adviceMethod']); foreach ($vars as $key => $value) { $this->$key = $value; } }
[ "final", "public", "function", "unserialize", "(", "$", "serialized", ")", ":", "void", "{", "$", "vars", "=", "unserialize", "(", "$", "serialized", ",", "[", "'allowed_classes'", "=>", "false", "]", ")", ";", "$", "vars", "[", "'adviceMethod'", "]", "=...
Unserialize an interceptor from the string @param string $serialized The string representation of the object.
[ "Unserialize", "an", "interceptor", "from", "the", "string" ]
train
https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Aop/Framework/AbstractInterceptor.php#L146-L153
goaop/framework
src/Instrument/Transformer/FilterInjectorTransformer.php
FilterInjectorTransformer.configure
protected static function configure(AspectKernel $kernel, string $filterName, CachePathManager $cacheManager): void { if (self::$kernel !== null) { throw new RuntimeException('Filter injector can be configured only once.'); } self::$kernel = $kernel; self::$options = $kernel->getOptions(); self::$filterName = $filterName; self::$cachePathManager = $cacheManager; }
php
protected static function configure(AspectKernel $kernel, string $filterName, CachePathManager $cacheManager): void { if (self::$kernel !== null) { throw new RuntimeException('Filter injector can be configured only once.'); } self::$kernel = $kernel; self::$options = $kernel->getOptions(); self::$filterName = $filterName; self::$cachePathManager = $cacheManager; }
[ "protected", "static", "function", "configure", "(", "AspectKernel", "$", "kernel", ",", "string", "$", "filterName", ",", "CachePathManager", "$", "cacheManager", ")", ":", "void", "{", "if", "(", "self", "::", "$", "kernel", "!==", "null", ")", "{", "thr...
Static configurator for filter
[ "Static", "configurator", "for", "filter" ]
train
https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Instrument/Transformer/FilterInjectorTransformer.php#L66-L75
goaop/framework
src/Instrument/Transformer/FilterInjectorTransformer.php
FilterInjectorTransformer.rewrite
public static function rewrite($originalResource, string $originalDir = ''): string { static $appDir, $cacheDir, $debug; if ($appDir === null) { extract(self::$options, EXTR_IF_EXISTS); } $resource = (string) $originalResource; if ($resource[0] !== '/') { $shouldCheckExistence = true; $resource = PathResolver::realpath($resource, $shouldCheckExistence) ?: PathResolver::realpath("{$originalDir}/{$resource}", $shouldCheckExistence) ?: $originalResource; } $cachedResource = self::$cachePathManager->getCachePathForResource($resource); // If the cache is disabled or no cache yet, then use on-fly method if (!$cacheDir || $debug || !file_exists($cachedResource)) { return self::PHP_FILTER_READ . self::$filterName . '/resource=' . $resource; } return $cachedResource; }
php
public static function rewrite($originalResource, string $originalDir = ''): string { static $appDir, $cacheDir, $debug; if ($appDir === null) { extract(self::$options, EXTR_IF_EXISTS); } $resource = (string) $originalResource; if ($resource[0] !== '/') { $shouldCheckExistence = true; $resource = PathResolver::realpath($resource, $shouldCheckExistence) ?: PathResolver::realpath("{$originalDir}/{$resource}", $shouldCheckExistence) ?: $originalResource; } $cachedResource = self::$cachePathManager->getCachePathForResource($resource); // If the cache is disabled or no cache yet, then use on-fly method if (!$cacheDir || $debug || !file_exists($cachedResource)) { return self::PHP_FILTER_READ . self::$filterName . '/resource=' . $resource; } return $cachedResource; }
[ "public", "static", "function", "rewrite", "(", "$", "originalResource", ",", "string", "$", "originalDir", "=", "''", ")", ":", "string", "{", "static", "$", "appDir", ",", "$", "cacheDir", ",", "$", "debug", ";", "if", "(", "$", "appDir", "===", "nul...
Replace source path with correct one This operation can check for cache, can rewrite paths, add additional filters and much more @param string $originalResource Initial resource to include @param string $originalDir Path to the directory from where include was called for resolving relative resources
[ "Replace", "source", "path", "with", "correct", "one" ]
train
https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Instrument/Transformer/FilterInjectorTransformer.php#L85-L108
goaop/framework
src/Instrument/Transformer/FilterInjectorTransformer.php
FilterInjectorTransformer.transform
public function transform(StreamMetaData $metadata): string { $includeExpressionFinder = new NodeFinderVisitor([Include_::class]); // TODO: move this logic into walkSyntaxTree(Visitor $nodeVistor) method $traverser = new NodeTraverser(); $traverser->addVisitor($includeExpressionFinder); $traverser->traverse($metadata->syntaxTree); /** @var Include_[] $includeExpressions */ $includeExpressions = $includeExpressionFinder->getFoundNodes(); if (empty($includeExpressions)) { return self::RESULT_ABSTAIN; } foreach ($includeExpressions as $includeExpression) { $startPosition = $includeExpression->getAttribute('startTokenPos'); $endPosition = $includeExpression->getAttribute('endTokenPos'); $metadata->tokenStream[$startPosition][1] .= ' \\' . __CLASS__ . '::rewrite('; if ($metadata->tokenStream[$startPosition+1][0] === T_WHITESPACE) { unset($metadata->tokenStream[$startPosition+1]); } $metadata->tokenStream[$endPosition][1] .= ', __DIR__)'; } return self::RESULT_TRANSFORMED; }
php
public function transform(StreamMetaData $metadata): string { $includeExpressionFinder = new NodeFinderVisitor([Include_::class]); // TODO: move this logic into walkSyntaxTree(Visitor $nodeVistor) method $traverser = new NodeTraverser(); $traverser->addVisitor($includeExpressionFinder); $traverser->traverse($metadata->syntaxTree); /** @var Include_[] $includeExpressions */ $includeExpressions = $includeExpressionFinder->getFoundNodes(); if (empty($includeExpressions)) { return self::RESULT_ABSTAIN; } foreach ($includeExpressions as $includeExpression) { $startPosition = $includeExpression->getAttribute('startTokenPos'); $endPosition = $includeExpression->getAttribute('endTokenPos'); $metadata->tokenStream[$startPosition][1] .= ' \\' . __CLASS__ . '::rewrite('; if ($metadata->tokenStream[$startPosition+1][0] === T_WHITESPACE) { unset($metadata->tokenStream[$startPosition+1]); } $metadata->tokenStream[$endPosition][1] .= ', __DIR__)'; } return self::RESULT_TRANSFORMED; }
[ "public", "function", "transform", "(", "StreamMetaData", "$", "metadata", ")", ":", "string", "{", "$", "includeExpressionFinder", "=", "new", "NodeFinderVisitor", "(", "[", "Include_", "::", "class", "]", ")", ";", "// TODO: move this logic into walkSyntaxTree(Visit...
Wrap all includes into rewrite filter @return string See RESULT_XXX constants in the interface
[ "Wrap", "all", "includes", "into", "rewrite", "filter" ]
train
https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Instrument/Transformer/FilterInjectorTransformer.php#L115-L144
goaop/framework
src/Aop/Support/DefaultPointcutAdvisor.php
DefaultPointcutAdvisor.getAdvice
public function getAdvice(): Advice { $advice = parent::getAdvice(); if (($advice instanceof Interceptor) && ($this->pointcut->getKind() & PointFilter::KIND_DYNAMIC)) { $advice = new DynamicInvocationMatcherInterceptor( $this->pointcut, $advice ); } return $advice; }
php
public function getAdvice(): Advice { $advice = parent::getAdvice(); if (($advice instanceof Interceptor) && ($this->pointcut->getKind() & PointFilter::KIND_DYNAMIC)) { $advice = new DynamicInvocationMatcherInterceptor( $this->pointcut, $advice ); } return $advice; }
[ "public", "function", "getAdvice", "(", ")", ":", "Advice", "{", "$", "advice", "=", "parent", "::", "getAdvice", "(", ")", ";", "if", "(", "(", "$", "advice", "instanceof", "Interceptor", ")", "&&", "(", "$", "this", "->", "pointcut", "->", "getKind",...
{@inheritdoc}
[ "{" ]
train
https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Aop/Support/DefaultPointcutAdvisor.php#L46-L57
goaop/framework
src/Instrument/ClassLoading/SourceTransformingLoader.php
SourceTransformingLoader.register
public static function register(string $filterId = self::FILTER_IDENTIFIER): void { if (!empty(self::$filterId)) { throw new RuntimeException('Stream filter already registered'); } $result = stream_filter_register($filterId, __CLASS__); if ($result === false) { throw new RuntimeException('Stream filter was not registered'); } self::$filterId = $filterId; }
php
public static function register(string $filterId = self::FILTER_IDENTIFIER): void { if (!empty(self::$filterId)) { throw new RuntimeException('Stream filter already registered'); } $result = stream_filter_register($filterId, __CLASS__); if ($result === false) { throw new RuntimeException('Stream filter was not registered'); } self::$filterId = $filterId; }
[ "public", "static", "function", "register", "(", "string", "$", "filterId", "=", "self", "::", "FILTER_IDENTIFIER", ")", ":", "void", "{", "if", "(", "!", "empty", "(", "self", "::", "$", "filterId", ")", ")", "{", "throw", "new", "RuntimeException", "("...
Register current loader as stream filter in PHP @throws RuntimeException If registration was failed
[ "Register", "current", "loader", "as", "stream", "filter", "in", "PHP" ]
train
https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Instrument/ClassLoading/SourceTransformingLoader.php#L61-L72
goaop/framework
src/Instrument/ClassLoading/SourceTransformingLoader.php
SourceTransformingLoader.filter
public function filter($in, $out, &$consumed, $closing) { while ($bucket = stream_bucket_make_writeable($in)) { $this->data .= $bucket->data; } if ($closing || feof($this->stream)) { $consumed = strlen($this->data); // $this->stream contains pointer to the source $metadata = new StreamMetaData($this->stream, $this->data); self::transformCode($metadata); $bucket = stream_bucket_new($this->stream, $metadata->source); stream_bucket_append($out, $bucket); return PSFS_PASS_ON; } return PSFS_FEED_ME; }
php
public function filter($in, $out, &$consumed, $closing) { while ($bucket = stream_bucket_make_writeable($in)) { $this->data .= $bucket->data; } if ($closing || feof($this->stream)) { $consumed = strlen($this->data); // $this->stream contains pointer to the source $metadata = new StreamMetaData($this->stream, $this->data); self::transformCode($metadata); $bucket = stream_bucket_new($this->stream, $metadata->source); stream_bucket_append($out, $bucket); return PSFS_PASS_ON; } return PSFS_FEED_ME; }
[ "public", "function", "filter", "(", "$", "in", ",", "$", "out", ",", "&", "$", "consumed", ",", "$", "closing", ")", "{", "while", "(", "$", "bucket", "=", "stream_bucket_make_writeable", "(", "$", "in", ")", ")", "{", "$", "this", "->", "data", "...
{@inheritdoc}
[ "{" ]
train
https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Instrument/ClassLoading/SourceTransformingLoader.php#L91-L111
goaop/framework
src/Instrument/ClassLoading/SourceTransformingLoader.php
SourceTransformingLoader.transformCode
public static function transformCode(StreamMetaData $metadata): void { foreach (self::$transformers as $transformer) { $result = $transformer->transform($metadata); if ($result === SourceTransformer::RESULT_ABORTED) { break; } } }
php
public static function transformCode(StreamMetaData $metadata): void { foreach (self::$transformers as $transformer) { $result = $transformer->transform($metadata); if ($result === SourceTransformer::RESULT_ABORTED) { break; } } }
[ "public", "static", "function", "transformCode", "(", "StreamMetaData", "$", "metadata", ")", ":", "void", "{", "foreach", "(", "self", "::", "$", "transformers", "as", "$", "transformer", ")", "{", "$", "result", "=", "$", "transformer", "->", "transform", ...
Transforms source code by passing it through all transformers
[ "Transforms", "source", "code", "by", "passing", "it", "through", "all", "transformers" ]
train
https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Instrument/ClassLoading/SourceTransformingLoader.php#L124-L132
goaop/framework
demos/Demo/Aspect/FunctionInterceptorAspect.php
FunctionInterceptorAspect.aroundArrayFunctions
public function aroundArrayFunctions(FunctionInvocation $invocation) { echo 'Calling Around Interceptor for ', $invocation, ' with arguments: ', json_encode($invocation->getArguments()), PHP_EOL; return $invocation->proceed(); }
php
public function aroundArrayFunctions(FunctionInvocation $invocation) { echo 'Calling Around Interceptor for ', $invocation, ' with arguments: ', json_encode($invocation->getArguments()), PHP_EOL; return $invocation->proceed(); }
[ "public", "function", "aroundArrayFunctions", "(", "FunctionInvocation", "$", "invocation", ")", "{", "echo", "'Calling Around Interceptor for '", ",", "$", "invocation", ",", "' with arguments: '", ",", "json_encode", "(", "$", "invocation", "->", "getArguments", "(", ...
This advice intercepts an access to the array_*** function in Demo\Example\ namespace @param FunctionInvocation $invocation @Around("execution(Demo\Example\array_*(*))") @return mixed
[ "This", "advice", "intercepts", "an", "access", "to", "the", "array_", "***", "function", "in", "Demo", "\\", "Example", "\\", "namespace" ]
train
https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/demos/Demo/Aspect/FunctionInterceptorAspect.php#L33-L42
goaop/framework
src/Core/GeneralAspectLoaderExtension.php
GeneralAspectLoaderExtension.supports
public function supports(Aspect $aspect, $reflection, $metaInformation = null): bool { return $metaInformation instanceof Annotation\Interceptor || $metaInformation instanceof Annotation\Pointcut; }
php
public function supports(Aspect $aspect, $reflection, $metaInformation = null): bool { return $metaInformation instanceof Annotation\Interceptor || $metaInformation instanceof Annotation\Pointcut; }
[ "public", "function", "supports", "(", "Aspect", "$", "aspect", ",", "$", "reflection", ",", "$", "metaInformation", "=", "null", ")", ":", "bool", "{", "return", "$", "metaInformation", "instanceof", "Annotation", "\\", "Interceptor", "||", "$", "metaInformat...
Checks if loader is able to handle specific point of aspect @param Aspect $aspect Instance of aspect @param mixed|\ReflectionClass|\ReflectionMethod|\ReflectionProperty $reflection Reflection of point @param mixed|null $metaInformation Additional meta-information, e.g. annotation for method @return boolean true if extension is able to create an advisor from reflection and metaInformation
[ "Checks", "if", "loader", "is", "able", "to", "handle", "specific", "point", "of", "aspect" ]
train
https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Core/GeneralAspectLoaderExtension.php#L58-L62
goaop/framework
src/Core/GeneralAspectLoaderExtension.php
GeneralAspectLoaderExtension.load
public function load(Aspect $aspect, Reflector $reflection, $metaInformation = null): array { $loadedItems = []; $pointcut = $this->parsePointcut($aspect, $reflection, $metaInformation->value); $methodId = get_class($aspect) . '->' . $reflection->name; $adviceCallback = $reflection->getClosure($aspect); switch (true) { // Register a pointcut by its name case ($metaInformation instanceof Annotation\Pointcut): $loadedItems[$methodId] = $pointcut; break; case ($pointcut instanceof Pointcut): $advice = $this->getInterceptor($metaInformation, $adviceCallback); $loadedItems[$methodId] = new DefaultPointcutAdvisor($pointcut, $advice); break; default: throw new UnexpectedValueException('Unsupported pointcut class: ' . get_class($pointcut)); } return $loadedItems; }
php
public function load(Aspect $aspect, Reflector $reflection, $metaInformation = null): array { $loadedItems = []; $pointcut = $this->parsePointcut($aspect, $reflection, $metaInformation->value); $methodId = get_class($aspect) . '->' . $reflection->name; $adviceCallback = $reflection->getClosure($aspect); switch (true) { // Register a pointcut by its name case ($metaInformation instanceof Annotation\Pointcut): $loadedItems[$methodId] = $pointcut; break; case ($pointcut instanceof Pointcut): $advice = $this->getInterceptor($metaInformation, $adviceCallback); $loadedItems[$methodId] = new DefaultPointcutAdvisor($pointcut, $advice); break; default: throw new UnexpectedValueException('Unsupported pointcut class: ' . get_class($pointcut)); } return $loadedItems; }
[ "public", "function", "load", "(", "Aspect", "$", "aspect", ",", "Reflector", "$", "reflection", ",", "$", "metaInformation", "=", "null", ")", ":", "array", "{", "$", "loadedItems", "=", "[", "]", ";", "$", "pointcut", "=", "$", "this", "->", "parsePo...
Loads definition from specific point of aspect into the container @param Aspect $aspect Instance of aspect @param Reflector|ReflectionMethod $reflection Reflection of point @param mixed|null $metaInformation Additional meta-information, e.g. annotation for method @return array|Pointcut[]|Advisor[] @throws UnexpectedValueException
[ "Loads", "definition", "from", "specific", "point", "of", "aspect", "into", "the", "container" ]
train
https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Core/GeneralAspectLoaderExtension.php#L75-L99
goaop/framework
src/Core/GeneralAspectLoaderExtension.php
GeneralAspectLoaderExtension.getInterceptor
protected function getInterceptor(BaseInterceptor $metaInformation, Closure $adviceCallback): Interceptor { $adviceOrder = $metaInformation->order; $pointcutExpression = $metaInformation->value; switch (true) { case ($metaInformation instanceof Annotation\Before): return new Framework\BeforeInterceptor($adviceCallback, $adviceOrder, $pointcutExpression); case ($metaInformation instanceof Annotation\After): return new Framework\AfterInterceptor($adviceCallback, $adviceOrder, $pointcutExpression); case ($metaInformation instanceof Annotation\Around): return new Framework\AroundInterceptor($adviceCallback, $adviceOrder, $pointcutExpression); case ($metaInformation instanceof Annotation\AfterThrowing): return new Framework\AfterThrowingInterceptor($adviceCallback, $adviceOrder, $pointcutExpression); default: throw new UnexpectedValueException('Unsupported method meta class: ' . get_class($metaInformation)); } }
php
protected function getInterceptor(BaseInterceptor $metaInformation, Closure $adviceCallback): Interceptor { $adviceOrder = $metaInformation->order; $pointcutExpression = $metaInformation->value; switch (true) { case ($metaInformation instanceof Annotation\Before): return new Framework\BeforeInterceptor($adviceCallback, $adviceOrder, $pointcutExpression); case ($metaInformation instanceof Annotation\After): return new Framework\AfterInterceptor($adviceCallback, $adviceOrder, $pointcutExpression); case ($metaInformation instanceof Annotation\Around): return new Framework\AroundInterceptor($adviceCallback, $adviceOrder, $pointcutExpression); case ($metaInformation instanceof Annotation\AfterThrowing): return new Framework\AfterThrowingInterceptor($adviceCallback, $adviceOrder, $pointcutExpression); default: throw new UnexpectedValueException('Unsupported method meta class: ' . get_class($metaInformation)); } }
[ "protected", "function", "getInterceptor", "(", "BaseInterceptor", "$", "metaInformation", ",", "Closure", "$", "adviceCallback", ")", ":", "Interceptor", "{", "$", "adviceOrder", "=", "$", "metaInformation", "->", "order", ";", "$", "pointcutExpression", "=", "$"...
Returns an interceptor instance by meta-type annotation and closure @throws UnexpectedValueException For unsupported annotations
[ "Returns", "an", "interceptor", "instance", "by", "meta", "-", "type", "annotation", "and", "closure" ]
train
https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Core/GeneralAspectLoaderExtension.php#L106-L126
goaop/framework
src/Aop/Support/LazyPointcutAdvisor.php
LazyPointcutAdvisor.getPointcut
public function getPointcut(): Pointcut { if ($this->pointcut === null) { // Inject these dependencies and make them lazy! /** @var Pointcut\PointcutLexer $lexer */ $lexer = $this->container->get('aspect.pointcut.lexer'); /** @var Pointcut\PointcutParser $parser */ $parser = $this->container->get('aspect.pointcut.parser'); $tokenStream = $lexer->lex($this->pointcutExpression); $this->pointcut = $parser->parse($tokenStream); } return $this->pointcut; }
php
public function getPointcut(): Pointcut { if ($this->pointcut === null) { // Inject these dependencies and make them lazy! /** @var Pointcut\PointcutLexer $lexer */ $lexer = $this->container->get('aspect.pointcut.lexer'); /** @var Pointcut\PointcutParser $parser */ $parser = $this->container->get('aspect.pointcut.parser'); $tokenStream = $lexer->lex($this->pointcutExpression); $this->pointcut = $parser->parse($tokenStream); } return $this->pointcut; }
[ "public", "function", "getPointcut", "(", ")", ":", "Pointcut", "{", "if", "(", "$", "this", "->", "pointcut", "===", "null", ")", "{", "// Inject these dependencies and make them lazy!", "/** @var Pointcut\\PointcutLexer $lexer */", "$", "lexer", "=", "$", "this", ...
Get the Pointcut that drives this advisor.
[ "Get", "the", "Pointcut", "that", "drives", "this", "advisor", "." ]
train
https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Aop/Support/LazyPointcutAdvisor.php#L54-L70
goaop/framework
src/Console/Command/DebugWeavingCommand.php
DebugWeavingCommand.execute
protected function execute(InputInterface $input, OutputInterface $output) { $this->loadAspectKernel($input, $output); $io = new SymfonyStyle($input, $output); $io->title('Weaving debug information'); $cachePathManager = $this->aspectKernel->getContainer()->get('aspect.cache.path.manager'); $warmer = new CacheWarmer($this->aspectKernel, new NullOutput()); $warmer->warmUp(); $proxies = $this->getProxies($cachePathManager); $cachePathManager->clearCacheState(); $warmer->warmUp(); $errors = 0; foreach ($this->getProxies($cachePathManager) as $path => $content) { if (!isset($proxies[$path])) { $io->error(sprintf('Proxy on path "%s" is generated on second "warmup" pass.', $path)); $errors++; continue; } if (isset($proxies[$path]) && $proxies[$path] !== $content) { $io->error(sprintf('Proxy on path "%s" is weaved differnlty on second "warmup" pass.', $path)); $errors++; continue; } $io->note(sprintf('Proxy on path "%s" is consistently weaved.', $path)); } if ($errors > 0) { $io->error(sprintf('Weaving is unstable, there are %s reported error(s).', $errors)); return $errors; } $io->success('Weaving is stable, there are no errors reported.'); }
php
protected function execute(InputInterface $input, OutputInterface $output) { $this->loadAspectKernel($input, $output); $io = new SymfonyStyle($input, $output); $io->title('Weaving debug information'); $cachePathManager = $this->aspectKernel->getContainer()->get('aspect.cache.path.manager'); $warmer = new CacheWarmer($this->aspectKernel, new NullOutput()); $warmer->warmUp(); $proxies = $this->getProxies($cachePathManager); $cachePathManager->clearCacheState(); $warmer->warmUp(); $errors = 0; foreach ($this->getProxies($cachePathManager) as $path => $content) { if (!isset($proxies[$path])) { $io->error(sprintf('Proxy on path "%s" is generated on second "warmup" pass.', $path)); $errors++; continue; } if (isset($proxies[$path]) && $proxies[$path] !== $content) { $io->error(sprintf('Proxy on path "%s" is weaved differnlty on second "warmup" pass.', $path)); $errors++; continue; } $io->note(sprintf('Proxy on path "%s" is consistently weaved.', $path)); } if ($errors > 0) { $io->error(sprintf('Weaving is unstable, there are %s reported error(s).', $errors)); return $errors; } $io->success('Weaving is stable, there are no errors reported.'); }
[ "protected", "function", "execute", "(", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ")", "{", "$", "this", "->", "loadAspectKernel", "(", "$", "input", ",", "$", "output", ")", ";", "$", "io", "=", "new", "SymfonyStyle", "(", ...
{@inheritDoc}
[ "{" ]
train
https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Console/Command/DebugWeavingCommand.php#L50-L91
goaop/framework
src/Console/Command/DebugWeavingCommand.php
DebugWeavingCommand.getProxies
private function getProxies(CachePathManager $cachePathManager): array { $path = $cachePathManager->getCacheDir() . '/_proxies'; $iterator = new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $path, FilesystemIterator::SKIP_DOTS | FilesystemIterator::UNIX_PATHS ), RecursiveIteratorIterator::CHILD_FIRST ); $proxies = []; /** * @var \SplFileInfo $splFileInfo */ foreach ($iterator as $splFileInfo) { if ($splFileInfo->isFile()) { $proxies[$splFileInfo->getPathname()] = file_get_contents($splFileInfo->getPathname()); } } return $proxies; }
php
private function getProxies(CachePathManager $cachePathManager): array { $path = $cachePathManager->getCacheDir() . '/_proxies'; $iterator = new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $path, FilesystemIterator::SKIP_DOTS | FilesystemIterator::UNIX_PATHS ), RecursiveIteratorIterator::CHILD_FIRST ); $proxies = []; /** * @var \SplFileInfo $splFileInfo */ foreach ($iterator as $splFileInfo) { if ($splFileInfo->isFile()) { $proxies[$splFileInfo->getPathname()] = file_get_contents($splFileInfo->getPathname()); } } return $proxies; }
[ "private", "function", "getProxies", "(", "CachePathManager", "$", "cachePathManager", ")", ":", "array", "{", "$", "path", "=", "$", "cachePathManager", "->", "getCacheDir", "(", ")", ".", "'/_proxies'", ";", "$", "iterator", "=", "new", "RecursiveIteratorItera...
Gets Go! AOP generated proxy classes (paths and their contents) from the cache.
[ "Gets", "Go!", "AOP", "generated", "proxy", "classes", "(", "paths", "and", "their", "contents", ")", "from", "the", "cache", "." ]
train
https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Console/Command/DebugWeavingCommand.php#L96-L119
goaop/framework
src/Aop/Pointcut/CFlowBelowMethodPointcut.php
CFlowBelowMethodPointcut.matches
public function matches($point, $context = null, $instance = null, array $arguments = null): bool { // With single parameter (statically) always matches if ($instance === null) { return true; } $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS); foreach ($trace as $stackFrame) { if (!isset($stackFrame['class'])) { continue; } $refClass = new ReflectionClass($stackFrame['class']); if (!$this->internalClassFilter->matches($refClass)) { continue; } $refMethod = $refClass->getMethod($stackFrame['function']); if ($this->internalPointFilter->matches($refMethod)) { return true; } } return false; }
php
public function matches($point, $context = null, $instance = null, array $arguments = null): bool { // With single parameter (statically) always matches if ($instance === null) { return true; } $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS); foreach ($trace as $stackFrame) { if (!isset($stackFrame['class'])) { continue; } $refClass = new ReflectionClass($stackFrame['class']); if (!$this->internalClassFilter->matches($refClass)) { continue; } $refMethod = $refClass->getMethod($stackFrame['function']); if ($this->internalPointFilter->matches($refMethod)) { return true; } } return false; }
[ "public", "function", "matches", "(", "$", "point", ",", "$", "context", "=", "null", ",", "$", "instance", "=", "null", ",", "array", "$", "arguments", "=", "null", ")", ":", "bool", "{", "// With single parameter (statically) always matches", "if", "(", "$...
Performs matching of point of code @param mixed $point Specific part of code, can be any Reflection class @param null|mixed $context Related context, can be class or namespace @param null|string|object $instance Invocation instance or string for static calls @param null|array $arguments Dynamic arguments for method
[ "Performs", "matching", "of", "point", "of", "code" ]
train
https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Aop/Pointcut/CFlowBelowMethodPointcut.php#L58-L81
goaop/framework
src/Aop/Pointcut/MagicMethodPointcut.php
MagicMethodPointcut.matches
public function matches($point, $context = null, $instance = null, array $arguments = null): bool { // With single parameter (statically) always matches for __call, __callStatic if ($instance === null) { return ($point->name === '__call' || $point->name === '__callStatic'); } if (!$this->modifierFilter->matches($point)) { return false; } // for __call and __callStatic method name is the first argument on invocation [$methodName] = $arguments; return ($methodName === $this->methodName) || (bool) preg_match("/^(?:{$this->regexp})$/", $methodName); }
php
public function matches($point, $context = null, $instance = null, array $arguments = null): bool { // With single parameter (statically) always matches for __call, __callStatic if ($instance === null) { return ($point->name === '__call' || $point->name === '__callStatic'); } if (!$this->modifierFilter->matches($point)) { return false; } // for __call and __callStatic method name is the first argument on invocation [$methodName] = $arguments; return ($methodName === $this->methodName) || (bool) preg_match("/^(?:{$this->regexp})$/", $methodName); }
[ "public", "function", "matches", "(", "$", "point", ",", "$", "context", "=", "null", ",", "$", "instance", "=", "null", ",", "array", "$", "arguments", "=", "null", ")", ":", "bool", "{", "// With single parameter (statically) always matches for __call, __callSta...
Performs matching of point of code @param mixed $point Specific part of code, can be any Reflection class @param null|mixed $context Related context, can be class or namespace @param null|string|object $instance Invocation instance or string for static calls @param null|array $arguments Dynamic arguments for method
[ "Performs", "matching", "of", "point", "of", "code" ]
train
https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Aop/Pointcut/MagicMethodPointcut.php#L63-L78
goaop/framework
src/Instrument/Transformer/StreamMetaData.php
StreamMetaData.getSource
private function getSource(): string { $transformedSource = ''; foreach ($this->tokenStream as $token) { $transformedSource .= $token[1] ?? $token; } return $transformedSource; }
php
private function getSource(): string { $transformedSource = ''; foreach ($this->tokenStream as $token) { $transformedSource .= $token[1] ?? $token; } return $transformedSource; }
[ "private", "function", "getSource", "(", ")", ":", "string", "{", "$", "transformedSource", "=", "''", ";", "foreach", "(", "$", "this", "->", "tokenStream", "as", "$", "token", ")", "{", "$", "transformedSource", ".=", "$", "token", "[", "1", "]", "??...
Returns source code directly from tokens
[ "Returns", "source", "code", "directly", "from", "tokens" ]
train
https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Instrument/Transformer/StreamMetaData.php#L142-L150
goaop/framework
src/Instrument/Transformer/StreamMetaData.php
StreamMetaData.setSource
private function setSource(string $newSource): void { $rawTokens = token_get_all($newSource); foreach ($rawTokens as $index => $rawToken) { $this->tokenStream[$index] = is_array($rawToken) ? $rawToken : [T_STRING, $rawToken]; } }
php
private function setSource(string $newSource): void { $rawTokens = token_get_all($newSource); foreach ($rawTokens as $index => $rawToken) { $this->tokenStream[$index] = is_array($rawToken) ? $rawToken : [T_STRING, $rawToken]; } }
[ "private", "function", "setSource", "(", "string", "$", "newSource", ")", ":", "void", "{", "$", "rawTokens", "=", "token_get_all", "(", "$", "newSource", ")", ";", "foreach", "(", "$", "rawTokens", "as", "$", "index", "=>", "$", "rawToken", ")", "{", ...
Sets the new source for this file @TODO: Unfortunately, AST won't be changed, so please be accurate during transformation @param string $newSource
[ "Sets", "the", "new", "source", "for", "this", "file" ]
train
https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Instrument/Transformer/StreamMetaData.php#L159-L165
goaop/framework
src/Aop/Support/SimpleNamespaceFilter.php
SimpleNamespaceFilter.matches
public function matches($ns, $context = null, $instance = null, array $arguments = null): bool { $isNamespaceIsObject = ($ns === (object) $ns); if ($isNamespaceIsObject && !$ns instanceof ReflectionFileNamespace) { return false; } $nsName = ($ns instanceof ReflectionFileNamespace) ? $ns->getName() : $ns; return ($nsName === $this->nsName) || (bool) preg_match("/^(?:{$this->regexp})$/", $nsName); }
php
public function matches($ns, $context = null, $instance = null, array $arguments = null): bool { $isNamespaceIsObject = ($ns === (object) $ns); if ($isNamespaceIsObject && !$ns instanceof ReflectionFileNamespace) { return false; } $nsName = ($ns instanceof ReflectionFileNamespace) ? $ns->getName() : $ns; return ($nsName === $this->nsName) || (bool) preg_match("/^(?:{$this->regexp})$/", $nsName); }
[ "public", "function", "matches", "(", "$", "ns", ",", "$", "context", "=", "null", ",", "$", "instance", "=", "null", ",", "array", "$", "arguments", "=", "null", ")", ":", "bool", "{", "$", "isNamespaceIsObject", "=", "(", "$", "ns", "===", "(", "...
{@inheritdoc}
[ "{" ]
train
https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Aop/Support/SimpleNamespaceFilter.php#L52-L63
goaop/framework
src/Aop/Support/AnnotatedReflectionMethod.php
AnnotatedReflectionMethod.getReader
private static function getReader(): Reader { if (self::$annotationReader === null) { self::$annotationReader = AspectKernel::getInstance()->getContainer()->get('aspect.annotation.reader'); } return self::$annotationReader; }
php
private static function getReader(): Reader { if (self::$annotationReader === null) { self::$annotationReader = AspectKernel::getInstance()->getContainer()->get('aspect.annotation.reader'); } return self::$annotationReader; }
[ "private", "static", "function", "getReader", "(", ")", ":", "Reader", "{", "if", "(", "self", "::", "$", "annotationReader", "===", "null", ")", "{", "self", "::", "$", "annotationReader", "=", "AspectKernel", "::", "getInstance", "(", ")", "->", "getCont...
Returns an annotation reader
[ "Returns", "an", "annotation", "reader" ]
train
https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Aop/Support/AnnotatedReflectionMethod.php#L49-L56
goaop/framework
src/Aop/Pointcut/PointcutGrammar.php
PointcutGrammar.getNodeToStringConverter
private function getNodeToStringConverter(): Closure { return function (...$nodes) { $value = ''; foreach ($nodes as $node) { if (is_scalar($node)) { $value .= $node; } else { $value .= $node->getValue(); } } return $value; }; }
php
private function getNodeToStringConverter(): Closure { return function (...$nodes) { $value = ''; foreach ($nodes as $node) { if (is_scalar($node)) { $value .= $node; } else { $value .= $node->getValue(); } } return $value; }; }
[ "private", "function", "getNodeToStringConverter", "(", ")", ":", "Closure", "{", "return", "function", "(", "...", "$", "nodes", ")", "{", "$", "value", "=", "''", ";", "foreach", "(", "$", "nodes", "as", "$", "node", ")", "{", "if", "(", "is_scalar",...
Returns callable for converting node(s) to the string
[ "Returns", "callable", "for", "converting", "node", "(", "s", ")", "to", "the", "string" ]
train
https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Aop/Pointcut/PointcutGrammar.php#L354-L368
goaop/framework
src/Instrument/ClassLoading/CacheWarmer.php
CacheWarmer.warmUp
public function warmUp(): void { $options = $this->aspectKernel->getOptions(); if (empty($options['cacheDir'])) { throw new InvalidArgumentException('Cache warmer require the `cacheDir` options to be configured'); } $enumerator = new Enumerator($options['appDir'], $options['includePaths'], $options['excludePaths']); $iterator = $enumerator->enumerate(); $total = iterator_count($iterator); $this->output->writeln(sprintf('Total <info>%s</info> files to process.', $total)); $this->output->writeln(''); $iterator->rewind(); set_error_handler(function ($errno, $errstr, $errfile, $errline) { throw new ErrorException($errstr, $errno, 0, $errfile, $errline); }); $errors = []; $displayException = function (Throwable $exception, string $path) use (&$errors) { $this->output->writeln(sprintf('<fg=white;bg=red;options=bold>[ERR]</>: %s', $path)); $errors[$path] = $exception->getMessage(); }; foreach ($iterator as $file) { $path = $file->getRealPath(); try { // This will trigger creation of cache file_get_contents(FilterInjectorTransformer::PHP_FILTER_READ . SourceTransformingLoader::FILTER_IDENTIFIER . '/resource=' . $path ); $this->output->writeln(sprintf('<fg=green;options=bold>[OK]</>: <comment>%s</comment>', $path)); } catch (Throwable $e) { $displayException($e, $path); } } restore_error_handler(); if ($this->output->isVerbose()) { foreach ($errors as $path => $error) { $this->output->writeln(sprintf('<fg=white;bg=red;options=bold>[ERR]</>: File "%s" is not processed correctly due to exception: "%s".', $path, $error)); } } $this->output->writeln(''); $this->output->writeln(sprintf('<fg=green;>[DONE]</>: Total processed %s, %s errors.', $total, count($errors))); }
php
public function warmUp(): void { $options = $this->aspectKernel->getOptions(); if (empty($options['cacheDir'])) { throw new InvalidArgumentException('Cache warmer require the `cacheDir` options to be configured'); } $enumerator = new Enumerator($options['appDir'], $options['includePaths'], $options['excludePaths']); $iterator = $enumerator->enumerate(); $total = iterator_count($iterator); $this->output->writeln(sprintf('Total <info>%s</info> files to process.', $total)); $this->output->writeln(''); $iterator->rewind(); set_error_handler(function ($errno, $errstr, $errfile, $errline) { throw new ErrorException($errstr, $errno, 0, $errfile, $errline); }); $errors = []; $displayException = function (Throwable $exception, string $path) use (&$errors) { $this->output->writeln(sprintf('<fg=white;bg=red;options=bold>[ERR]</>: %s', $path)); $errors[$path] = $exception->getMessage(); }; foreach ($iterator as $file) { $path = $file->getRealPath(); try { // This will trigger creation of cache file_get_contents(FilterInjectorTransformer::PHP_FILTER_READ . SourceTransformingLoader::FILTER_IDENTIFIER . '/resource=' . $path ); $this->output->writeln(sprintf('<fg=green;options=bold>[OK]</>: <comment>%s</comment>', $path)); } catch (Throwable $e) { $displayException($e, $path); } } restore_error_handler(); if ($this->output->isVerbose()) { foreach ($errors as $path => $error) { $this->output->writeln(sprintf('<fg=white;bg=red;options=bold>[ERR]</>: File "%s" is not processed correctly due to exception: "%s".', $path, $error)); } } $this->output->writeln(''); $this->output->writeln(sprintf('<fg=green;>[DONE]</>: Total processed %s, %s errors.', $total, count($errors))); }
[ "public", "function", "warmUp", "(", ")", ":", "void", "{", "$", "options", "=", "$", "this", "->", "aspectKernel", "->", "getOptions", "(", ")", ";", "if", "(", "empty", "(", "$", "options", "[", "'cacheDir'", "]", ")", ")", "{", "throw", "new", "...
Warms up cache
[ "Warms", "up", "cache" ]
train
https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Instrument/ClassLoading/CacheWarmer.php#L51-L104
goaop/framework
src/Aop/Support/InheritanceClassFilter.php
InheritanceClassFilter.matches
public function matches($class, $context = null, $instance = null, array $arguments = null): bool { if (!$class instanceof ReflectionClass) { return false; } return $class->isSubclassOf($this->parentClass) || \in_array($this->parentClass, $class->getInterfaceNames()); }
php
public function matches($class, $context = null, $instance = null, array $arguments = null): bool { if (!$class instanceof ReflectionClass) { return false; } return $class->isSubclassOf($this->parentClass) || \in_array($this->parentClass, $class->getInterfaceNames()); }
[ "public", "function", "matches", "(", "$", "class", ",", "$", "context", "=", "null", ",", "$", "instance", "=", "null", ",", "array", "$", "arguments", "=", "null", ")", ":", "bool", "{", "if", "(", "!", "$", "class", "instanceof", "ReflectionClass", ...
Performs matching of point of code @param mixed $class Specific part of code, can be any Reflection class @param null|mixed $context Related context, can be class or namespace @param null|string|object $instance Invocation instance or string for static calls @param null|array $arguments Dynamic arguments for method
[ "Performs", "matching", "of", "point", "of", "code" ]
train
https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Aop/Support/InheritanceClassFilter.php#L43-L50
goaop/framework
src/Console/Command/BaseAspectCommand.php
BaseAspectCommand.loadAspectKernel
protected function loadAspectKernel(InputInterface $input, OutputInterface $output): void { $loader = $input->getArgument('loader'); $path = stream_resolve_include_path($loader); if (!is_readable($path)) { throw new InvalidArgumentException("Invalid loader path: {$loader}"); } ob_start(); include_once $path; ob_clean(); if (!class_exists(AspectKernel::class, false)) { $message = "Kernel was not initialized yet, please configure it in the {$path}"; throw new InvalidArgumentException($message); } $this->aspectKernel = AspectKernel::getInstance(); }
php
protected function loadAspectKernel(InputInterface $input, OutputInterface $output): void { $loader = $input->getArgument('loader'); $path = stream_resolve_include_path($loader); if (!is_readable($path)) { throw new InvalidArgumentException("Invalid loader path: {$loader}"); } ob_start(); include_once $path; ob_clean(); if (!class_exists(AspectKernel::class, false)) { $message = "Kernel was not initialized yet, please configure it in the {$path}"; throw new InvalidArgumentException($message); } $this->aspectKernel = AspectKernel::getInstance(); }
[ "protected", "function", "loadAspectKernel", "(", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ")", ":", "void", "{", "$", "loader", "=", "$", "input", "->", "getArgument", "(", "'loader'", ")", ";", "$", "path", "=", "stream_resolv...
Loads aspect kernel. Aspect kernel is loaded by executing loader and fetching singleton instance. If your application environment initializes aspect kernel differently, you may modify this method to get aspect kernel suitable to your needs.
[ "Loads", "aspect", "kernel", "." ]
train
https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Console/Command/BaseAspectCommand.php#L50-L68
goaop/framework
src/Core/AspectKernel.php
AspectKernel.init
public function init(array $options = []) { if ($this->wasInitialized) { return; } $this->options = $this->normalizeOptions($options); define('AOP_ROOT_DIR', $this->options['appDir']); define('AOP_CACHE_DIR', $this->options['cacheDir']); /** @var $container AspectContainer */ $container = $this->container = new $this->options['containerClass']; $container->set('kernel', $this); $container->set('kernel.interceptFunctions', $this->hasFeature(Features::INTERCEPT_FUNCTIONS)); $container->set('kernel.options', $this->options); SourceTransformingLoader::register(); foreach ($this->registerTransformers() as $sourceTransformer) { SourceTransformingLoader::addTransformer($sourceTransformer); } // Register kernel resources in the container for debug mode if ($this->options['debug']) { $this->addKernelResourcesToContainer($container); } AopComposerLoader::init($this->options, $container); // Register all AOP configuration in the container $this->configureAop($container); $this->wasInitialized = true; }
php
public function init(array $options = []) { if ($this->wasInitialized) { return; } $this->options = $this->normalizeOptions($options); define('AOP_ROOT_DIR', $this->options['appDir']); define('AOP_CACHE_DIR', $this->options['cacheDir']); /** @var $container AspectContainer */ $container = $this->container = new $this->options['containerClass']; $container->set('kernel', $this); $container->set('kernel.interceptFunctions', $this->hasFeature(Features::INTERCEPT_FUNCTIONS)); $container->set('kernel.options', $this->options); SourceTransformingLoader::register(); foreach ($this->registerTransformers() as $sourceTransformer) { SourceTransformingLoader::addTransformer($sourceTransformer); } // Register kernel resources in the container for debug mode if ($this->options['debug']) { $this->addKernelResourcesToContainer($container); } AopComposerLoader::init($this->options, $container); // Register all AOP configuration in the container $this->configureAop($container); $this->wasInitialized = true; }
[ "public", "function", "init", "(", "array", "$", "options", "=", "[", "]", ")", "{", "if", "(", "$", "this", "->", "wasInitialized", ")", "{", "return", ";", "}", "$", "this", "->", "options", "=", "$", "this", "->", "normalizeOptions", "(", "$", "...
Init the kernel and make adjustments @param array $options Associative array of options for kernel
[ "Init", "the", "kernel", "and", "make", "adjustments" ]
train
https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Core/AspectKernel.php#L92-L125
goaop/framework
src/Core/AspectKernel.php
AspectKernel.normalizeOptions
protected function normalizeOptions(array $options): array { $options = array_replace($this->getDefaultOptions(), $options); $options['cacheDir'] = PathResolver::realpath($options['cacheDir']); if (!$options['cacheDir']) { throw new \RuntimeException('You need to provide valid cache directory for Go! AOP framework.'); } $options['excludePaths'][] = $options['cacheDir']; $options['excludePaths'][] = __DIR__ . '/../'; $options['appDir'] = PathResolver::realpath($options['appDir']); $options['cacheFileMode'] = (int) $options['cacheFileMode']; $options['includePaths'] = PathResolver::realpath($options['includePaths']); $options['excludePaths'] = PathResolver::realpath($options['excludePaths']); return $options; }
php
protected function normalizeOptions(array $options): array { $options = array_replace($this->getDefaultOptions(), $options); $options['cacheDir'] = PathResolver::realpath($options['cacheDir']); if (!$options['cacheDir']) { throw new \RuntimeException('You need to provide valid cache directory for Go! AOP framework.'); } $options['excludePaths'][] = $options['cacheDir']; $options['excludePaths'][] = __DIR__ . '/../'; $options['appDir'] = PathResolver::realpath($options['appDir']); $options['cacheFileMode'] = (int) $options['cacheFileMode']; $options['includePaths'] = PathResolver::realpath($options['includePaths']); $options['excludePaths'] = PathResolver::realpath($options['excludePaths']); return $options; }
[ "protected", "function", "normalizeOptions", "(", "array", "$", "options", ")", ":", "array", "{", "$", "options", "=", "array_replace", "(", "$", "this", "->", "getDefaultOptions", "(", ")", ",", "$", "options", ")", ";", "$", "options", "[", "'cacheDir'"...
Normalizes options for the kernel @param array $options List of options
[ "Normalizes", "options", "for", "the", "kernel" ]
train
https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Core/AspectKernel.php#L186-L204
goaop/framework
src/Core/AspectKernel.php
AspectKernel.registerTransformers
protected function registerTransformers(): array { $cacheManager = $this->getContainer()->get('aspect.cache.path.manager'); $filterInjector = new FilterInjectorTransformer($this, SourceTransformingLoader::getId(), $cacheManager); $magicTransformer = new MagicConstantTransformer($this); $sourceTransformers = function () use ($filterInjector, $magicTransformer, $cacheManager) { $transformers = []; if ($this->hasFeature(Features::INTERCEPT_INITIALIZATIONS)) { $transformers[] = new ConstructorExecutionTransformer(); } if ($this->hasFeature(Features::INTERCEPT_INCLUDES)) { $transformers[] = $filterInjector; } $transformers[] = new SelfValueTransformer($this); $transformers[] = new WeavingTransformer( $this, $this->container->get('aspect.advice_matcher'), $cacheManager, $this->container->get('aspect.cached.loader') ); $transformers[] = $magicTransformer; return $transformers; }; return [ new CachingTransformer($this, $sourceTransformers, $cacheManager) ]; }
php
protected function registerTransformers(): array { $cacheManager = $this->getContainer()->get('aspect.cache.path.manager'); $filterInjector = new FilterInjectorTransformer($this, SourceTransformingLoader::getId(), $cacheManager); $magicTransformer = new MagicConstantTransformer($this); $sourceTransformers = function () use ($filterInjector, $magicTransformer, $cacheManager) { $transformers = []; if ($this->hasFeature(Features::INTERCEPT_INITIALIZATIONS)) { $transformers[] = new ConstructorExecutionTransformer(); } if ($this->hasFeature(Features::INTERCEPT_INCLUDES)) { $transformers[] = $filterInjector; } $transformers[] = new SelfValueTransformer($this); $transformers[] = new WeavingTransformer( $this, $this->container->get('aspect.advice_matcher'), $cacheManager, $this->container->get('aspect.cached.loader') ); $transformers[] = $magicTransformer; return $transformers; }; return [ new CachingTransformer($this, $sourceTransformers, $cacheManager) ]; }
[ "protected", "function", "registerTransformers", "(", ")", ":", "array", "{", "$", "cacheManager", "=", "$", "this", "->", "getContainer", "(", ")", "->", "get", "(", "'aspect.cache.path.manager'", ")", ";", "$", "filterInjector", "=", "new", "FilterInjectorTran...
Returns list of source transformers, that will be applied to the PHP source @return SourceTransformer[] @internal This method is internal and should not be used outside this project
[ "Returns", "list", "of", "source", "transformers", "that", "will", "be", "applied", "to", "the", "PHP", "source" ]
train
https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Core/AspectKernel.php#L217-L246
goaop/framework
src/Core/AspectKernel.php
AspectKernel.addKernelResourcesToContainer
protected function addKernelResourcesToContainer(AspectContainer $container): void { $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2); $refClass = new ReflectionObject($this); $container->addResource($trace[1]['file']); $container->addResource($refClass->getFileName()); }
php
protected function addKernelResourcesToContainer(AspectContainer $container): void { $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2); $refClass = new ReflectionObject($this); $container->addResource($trace[1]['file']); $container->addResource($refClass->getFileName()); }
[ "protected", "function", "addKernelResourcesToContainer", "(", "AspectContainer", "$", "container", ")", ":", "void", "{", "$", "trace", "=", "debug_backtrace", "(", "DEBUG_BACKTRACE_IGNORE_ARGS", ",", "2", ")", ";", "$", "refClass", "=", "new", "ReflectionObject", ...
Add resources of kernel to the container
[ "Add", "resources", "of", "kernel", "to", "the", "container" ]
train
https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Core/AspectKernel.php#L251-L258
goaop/framework
src/Aop/Pointcut/MatchInheritedPointcut.php
MatchInheritedPointcut.matches
public function matches($point, $context = null, $instance = null, array $arguments = null): bool { if (!$context instanceof ReflectionClass) { return false; } $isPointMethod = $point instanceof ReflectionMethod; $isPointProperty = $point instanceof ReflectionProperty; if (!$isPointMethod && !$isPointProperty) { return false; } $declaringClassName = $point->getDeclaringClass()->name; return $context->name !== $declaringClassName && $context->isSubclassOf($declaringClassName); }
php
public function matches($point, $context = null, $instance = null, array $arguments = null): bool { if (!$context instanceof ReflectionClass) { return false; } $isPointMethod = $point instanceof ReflectionMethod; $isPointProperty = $point instanceof ReflectionProperty; if (!$isPointMethod && !$isPointProperty) { return false; } $declaringClassName = $point->getDeclaringClass()->name; return $context->name !== $declaringClassName && $context->isSubclassOf($declaringClassName); }
[ "public", "function", "matches", "(", "$", "point", ",", "$", "context", "=", "null", ",", "$", "instance", "=", "null", ",", "array", "$", "arguments", "=", "null", ")", ":", "bool", "{", "if", "(", "!", "$", "context", "instanceof", "ReflectionClass"...
Performs matching of point of code @param mixed $point Specific part of code, can be any Reflection class @param null|mixed $context Related context, can be class or namespace @param null|string|object $instance Invocation instance or string for static calls @param null|array $arguments Dynamic arguments for method
[ "Performs", "matching", "of", "point", "of", "code" ]
train
https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Aop/Pointcut/MatchInheritedPointcut.php#L35-L50
goaop/framework
src/Instrument/Transformer/CachingTransformer.php
CachingTransformer.transform
public function transform(StreamMetaData $metadata): string { $originalUri = $metadata->uri; $processingResult = self::RESULT_ABSTAIN; $cacheUri = $this->cacheManager->getCachePathForResource($originalUri); // Guard to disable overwriting of original files if ($cacheUri === $originalUri) { return self::RESULT_ABORTED; } $lastModified = filemtime($originalUri); $cacheState = $this->cacheManager->queryCacheState($originalUri); $cacheModified = $cacheState ? $cacheState['filemtime'] : 0; if ($cacheModified < $lastModified || (isset($cacheState['cacheUri']) && $cacheState['cacheUri'] !== $cacheUri) || !$this->container->isFresh($cacheModified) ) { $processingResult = $this->processTransformers($metadata); if ($processingResult === self::RESULT_TRANSFORMED) { $parentCacheDir = dirname($cacheUri); if (!is_dir($parentCacheDir)) { mkdir($parentCacheDir, $this->cacheFileMode, true); } file_put_contents($cacheUri, $metadata->source, LOCK_EX); // For cache files we don't want executable bits by default chmod($cacheUri, $this->cacheFileMode & (~0111)); } $this->cacheManager->setCacheState($originalUri, [ 'filemtime' => $_SERVER['REQUEST_TIME'] ?? time(), 'cacheUri' => ($processingResult === self::RESULT_TRANSFORMED) ? $cacheUri : null ]); return $processingResult; } if ($cacheState) { $processingResult = isset($cacheState['cacheUri']) ? self::RESULT_TRANSFORMED : self::RESULT_ABORTED; } if ($processingResult === self::RESULT_TRANSFORMED) { // Just replace all tokens in the stream $metadata->tokenStream = token_get_all(file_get_contents($cacheUri)); } return $processingResult; }
php
public function transform(StreamMetaData $metadata): string { $originalUri = $metadata->uri; $processingResult = self::RESULT_ABSTAIN; $cacheUri = $this->cacheManager->getCachePathForResource($originalUri); // Guard to disable overwriting of original files if ($cacheUri === $originalUri) { return self::RESULT_ABORTED; } $lastModified = filemtime($originalUri); $cacheState = $this->cacheManager->queryCacheState($originalUri); $cacheModified = $cacheState ? $cacheState['filemtime'] : 0; if ($cacheModified < $lastModified || (isset($cacheState['cacheUri']) && $cacheState['cacheUri'] !== $cacheUri) || !$this->container->isFresh($cacheModified) ) { $processingResult = $this->processTransformers($metadata); if ($processingResult === self::RESULT_TRANSFORMED) { $parentCacheDir = dirname($cacheUri); if (!is_dir($parentCacheDir)) { mkdir($parentCacheDir, $this->cacheFileMode, true); } file_put_contents($cacheUri, $metadata->source, LOCK_EX); // For cache files we don't want executable bits by default chmod($cacheUri, $this->cacheFileMode & (~0111)); } $this->cacheManager->setCacheState($originalUri, [ 'filemtime' => $_SERVER['REQUEST_TIME'] ?? time(), 'cacheUri' => ($processingResult === self::RESULT_TRANSFORMED) ? $cacheUri : null ]); return $processingResult; } if ($cacheState) { $processingResult = isset($cacheState['cacheUri']) ? self::RESULT_TRANSFORMED : self::RESULT_ABORTED; } if ($processingResult === self::RESULT_TRANSFORMED) { // Just replace all tokens in the stream $metadata->tokenStream = token_get_all(file_get_contents($cacheUri)); } return $processingResult; }
[ "public", "function", "transform", "(", "StreamMetaData", "$", "metadata", ")", ":", "string", "{", "$", "originalUri", "=", "$", "metadata", "->", "uri", ";", "$", "processingResult", "=", "self", "::", "RESULT_ABSTAIN", ";", "$", "cacheUri", "=", "$", "t...
This method may transform the supplied source and return a new replacement for it @return string See RESULT_XXX constants in the interface
[ "This", "method", "may", "transform", "the", "supplied", "source", "and", "return", "a", "new", "replacement", "for", "it" ]
train
https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Instrument/Transformer/CachingTransformer.php#L60-L105
goaop/framework
src/Instrument/Transformer/CachingTransformer.php
CachingTransformer.processTransformers
private function processTransformers(StreamMetaData $metadata): string { $overallResult = self::RESULT_ABSTAIN; if ($this->transformers instanceof Closure) { $delayedTransformers = $this->transformers; $this->transformers = $delayedTransformers(); } foreach ($this->transformers as $transformer) { $transformationResult = $transformer->transform($metadata); if ($overallResult === self::RESULT_ABSTAIN && $transformationResult === self::RESULT_TRANSFORMED) { $overallResult = self::RESULT_TRANSFORMED; } // transformer reported about termination, next transformers will be skipped if ($transformationResult === self::RESULT_ABORTED) { $overallResult = self::RESULT_ABORTED; break; } } return $overallResult; }
php
private function processTransformers(StreamMetaData $metadata): string { $overallResult = self::RESULT_ABSTAIN; if ($this->transformers instanceof Closure) { $delayedTransformers = $this->transformers; $this->transformers = $delayedTransformers(); } foreach ($this->transformers as $transformer) { $transformationResult = $transformer->transform($metadata); if ($overallResult === self::RESULT_ABSTAIN && $transformationResult === self::RESULT_TRANSFORMED) { $overallResult = self::RESULT_TRANSFORMED; } // transformer reported about termination, next transformers will be skipped if ($transformationResult === self::RESULT_ABORTED) { $overallResult = self::RESULT_ABORTED; break; } } return $overallResult; }
[ "private", "function", "processTransformers", "(", "StreamMetaData", "$", "metadata", ")", ":", "string", "{", "$", "overallResult", "=", "self", "::", "RESULT_ABSTAIN", ";", "if", "(", "$", "this", "->", "transformers", "instanceof", "Closure", ")", "{", "$",...
Iterates over transformers @return string See RESULT_XXX constants in the interface
[ "Iterates", "over", "transformers" ]
train
https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Instrument/Transformer/CachingTransformer.php#L112-L132
goaop/framework
src/Aop/Pointcut/OrPointcut.php
OrPointcut.matches
public function matches($point, $context = null, $instance = null, array $arguments = null): bool { return $this->matchPart($this->first, $point, $context, $instance, $arguments) || $this->matchPart($this->second, $point, $context, $instance, $arguments); }
php
public function matches($point, $context = null, $instance = null, array $arguments = null): bool { return $this->matchPart($this->first, $point, $context, $instance, $arguments) || $this->matchPart($this->second, $point, $context, $instance, $arguments); }
[ "public", "function", "matches", "(", "$", "point", ",", "$", "context", "=", "null", ",", "$", "instance", "=", "null", ",", "array", "$", "arguments", "=", "null", ")", ":", "bool", "{", "return", "$", "this", "->", "matchPart", "(", "$", "this", ...
Performs matching of point of code @param mixed $point Specific part of code, can be any Reflection class @param null|mixed $context Related context, can be class or namespace @param null|string|object $instance Invocation instance or string for static calls @param null|array $arguments Dynamic arguments for method
[ "Performs", "matching", "of", "point", "of", "code" ]
train
https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Aop/Pointcut/OrPointcut.php#L44-L48
goaop/framework
src/Core/AspectLoader.php
AspectLoader.registerLoaderExtension
public function registerLoaderExtension(AspectLoaderExtension $loader): void { $targets = $loader->getTargets(); foreach ($targets as $target) { $this->loaders[$target][] = $loader; } }
php
public function registerLoaderExtension(AspectLoaderExtension $loader): void { $targets = $loader->getTargets(); foreach ($targets as $target) { $this->loaders[$target][] = $loader; } }
[ "public", "function", "registerLoaderExtension", "(", "AspectLoaderExtension", "$", "loader", ")", ":", "void", "{", "$", "targets", "=", "$", "loader", "->", "getTargets", "(", ")", ";", "foreach", "(", "$", "targets", "as", "$", "target", ")", "{", "$", ...
Register an aspect loader extension This method allows to extend the logic of aspect loading by registering an extension for loader.
[ "Register", "an", "aspect", "loader", "extension" ]
train
https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Core/AspectLoader.php#L68-L74
goaop/framework
src/Core/AspectLoader.php
AspectLoader.load
public function load(Aspect $aspect): array { $loadedItems = []; $refAspect = new \ReflectionClass($aspect); if (!empty($this->loaders[AspectLoaderExtension::TARGET_CLASS])) { $loadedItems += $this->loadFrom($aspect, $refAspect, $this->loaders[AspectLoaderExtension::TARGET_CLASS]); } if (!empty($this->loaders[AspectLoaderExtension::TARGET_METHOD])) { $refMethods = $refAspect->getMethods(); foreach ($refMethods as $refMethod) { $loadedItems += $this->loadFrom($aspect, $refMethod, $this->loaders[AspectLoaderExtension::TARGET_METHOD]); } } if (!empty($this->loaders[AspectLoaderExtension::TARGET_PROPERTY])) { $refProperties = $refAspect->getProperties(); foreach ($refProperties as $refProperty) { $loadedItems += $this->loadFrom($aspect, $refProperty, $this->loaders[AspectLoaderExtension::TARGET_PROPERTY]); } } return $loadedItems; }
php
public function load(Aspect $aspect): array { $loadedItems = []; $refAspect = new \ReflectionClass($aspect); if (!empty($this->loaders[AspectLoaderExtension::TARGET_CLASS])) { $loadedItems += $this->loadFrom($aspect, $refAspect, $this->loaders[AspectLoaderExtension::TARGET_CLASS]); } if (!empty($this->loaders[AspectLoaderExtension::TARGET_METHOD])) { $refMethods = $refAspect->getMethods(); foreach ($refMethods as $refMethod) { $loadedItems += $this->loadFrom($aspect, $refMethod, $this->loaders[AspectLoaderExtension::TARGET_METHOD]); } } if (!empty($this->loaders[AspectLoaderExtension::TARGET_PROPERTY])) { $refProperties = $refAspect->getProperties(); foreach ($refProperties as $refProperty) { $loadedItems += $this->loadFrom($aspect, $refProperty, $this->loaders[AspectLoaderExtension::TARGET_PROPERTY]); } } return $loadedItems; }
[ "public", "function", "load", "(", "Aspect", "$", "aspect", ")", ":", "array", "{", "$", "loadedItems", "=", "[", "]", ";", "$", "refAspect", "=", "new", "\\", "ReflectionClass", "(", "$", "aspect", ")", ";", "if", "(", "!", "empty", "(", "$", "thi...
Loads an aspect with the help of aspect loaders, but don't register it in the container @see loadAndRegister() method for registration @return Pointcut[]|Advisor[]
[ "Loads", "an", "aspect", "with", "the", "help", "of", "aspect", "loaders", "but", "don", "t", "register", "it", "in", "the", "container" ]
train
https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Core/AspectLoader.php#L83-L107
goaop/framework
src/Core/AspectLoader.php
AspectLoader.loadAndRegister
public function loadAndRegister(Aspect $aspect): void { $loadedItems = $this->load($aspect); foreach ($loadedItems as $itemId => $item) { if ($item instanceof Pointcut) { $this->container->registerPointcut($item, $itemId); } if ($item instanceof Advisor) { $this->container->registerAdvisor($item, $itemId); } } $aspectClass = get_class($aspect); $this->loadedAspects[$aspectClass] = $aspectClass; }
php
public function loadAndRegister(Aspect $aspect): void { $loadedItems = $this->load($aspect); foreach ($loadedItems as $itemId => $item) { if ($item instanceof Pointcut) { $this->container->registerPointcut($item, $itemId); } if ($item instanceof Advisor) { $this->container->registerAdvisor($item, $itemId); } } $aspectClass = get_class($aspect); $this->loadedAspects[$aspectClass] = $aspectClass; }
[ "public", "function", "loadAndRegister", "(", "Aspect", "$", "aspect", ")", ":", "void", "{", "$", "loadedItems", "=", "$", "this", "->", "load", "(", "$", "aspect", ")", ";", "foreach", "(", "$", "loadedItems", "as", "$", "itemId", "=>", "$", "item", ...
Loads and register all items of aspect in the container
[ "Loads", "and", "register", "all", "items", "of", "aspect", "in", "the", "container" ]
train
https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Core/AspectLoader.php#L112-L126
goaop/framework
src/Core/AspectLoader.php
AspectLoader.getUnloadedAspects
public function getUnloadedAspects(): array { $unloadedAspects = []; foreach ($this->container->getByTag('aspect') as $aspect) { if (!isset($this->loadedAspects[get_class($aspect)])) { $unloadedAspects[] = $aspect; } } return $unloadedAspects; }
php
public function getUnloadedAspects(): array { $unloadedAspects = []; foreach ($this->container->getByTag('aspect') as $aspect) { if (!isset($this->loadedAspects[get_class($aspect)])) { $unloadedAspects[] = $aspect; } } return $unloadedAspects; }
[ "public", "function", "getUnloadedAspects", "(", ")", ":", "array", "{", "$", "unloadedAspects", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "container", "->", "getByTag", "(", "'aspect'", ")", "as", "$", "aspect", ")", "{", "if", "(", "!", ...
Returns list of unloaded aspects in the container @return Aspect[]
[ "Returns", "list", "of", "unloaded", "aspects", "in", "the", "container" ]
train
https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Core/AspectLoader.php#L133-L144
goaop/framework
src/Core/AspectLoader.php
AspectLoader.loadFrom
protected function loadFrom(Aspect $aspect, Reflector $reflector, array $loaders): array { $loadedItems = []; foreach ($loaders as $loader) { $loaderKind = $loader->getKind(); switch ($loaderKind) { case AspectLoaderExtension::KIND_REFLECTION: if ($loader->supports($aspect, $reflector)) { $loadedItems += $loader->load($aspect, $reflector); } break; case AspectLoaderExtension::KIND_ANNOTATION: $annotations = $this->getAnnotations($reflector); foreach ($annotations as $annotation) { if ($loader->supports($aspect, $reflector, $annotation)) { $loadedItems += $loader->load($aspect, $reflector, $annotation); } } break; default: throw new InvalidArgumentException("Unsupported loader kind {$loaderKind}"); } } return $loadedItems; }
php
protected function loadFrom(Aspect $aspect, Reflector $reflector, array $loaders): array { $loadedItems = []; foreach ($loaders as $loader) { $loaderKind = $loader->getKind(); switch ($loaderKind) { case AspectLoaderExtension::KIND_REFLECTION: if ($loader->supports($aspect, $reflector)) { $loadedItems += $loader->load($aspect, $reflector); } break; case AspectLoaderExtension::KIND_ANNOTATION: $annotations = $this->getAnnotations($reflector); foreach ($annotations as $annotation) { if ($loader->supports($aspect, $reflector, $annotation)) { $loadedItems += $loader->load($aspect, $reflector, $annotation); } } break; default: throw new InvalidArgumentException("Unsupported loader kind {$loaderKind}"); } } return $loadedItems; }
[ "protected", "function", "loadFrom", "(", "Aspect", "$", "aspect", ",", "Reflector", "$", "reflector", ",", "array", "$", "loaders", ")", ":", "array", "{", "$", "loadedItems", "=", "[", "]", ";", "foreach", "(", "$", "loaders", "as", "$", "loader", ")...
Load definitions from specific aspect part into the aspect container @param Aspect $aspect Aspect instance @param Reflector $reflector Reflection instance @param array|AspectLoaderExtension[] $loaders List of loaders that can produce advisors from aspect class @throws \InvalidArgumentException If kind of loader isn't supported @return array|Pointcut[]|Advisor[]
[ "Load", "definitions", "from", "specific", "aspect", "part", "into", "the", "aspect", "container" ]
train
https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Core/AspectLoader.php#L157-L185
goaop/framework
src/Core/AspectLoader.php
AspectLoader.getAnnotations
protected function getAnnotations(Reflector $reflector): array { switch (true) { case ($reflector instanceof ReflectionClass): return $this->annotationReader->getClassAnnotations($reflector); case ($reflector instanceof ReflectionMethod): return $this->annotationReader->getMethodAnnotations($reflector); case ($reflector instanceof ReflectionProperty): return $this->annotationReader->getPropertyAnnotations($reflector); default: throw new InvalidArgumentException('Unsupported reflection point ' . get_class($reflector)); } }
php
protected function getAnnotations(Reflector $reflector): array { switch (true) { case ($reflector instanceof ReflectionClass): return $this->annotationReader->getClassAnnotations($reflector); case ($reflector instanceof ReflectionMethod): return $this->annotationReader->getMethodAnnotations($reflector); case ($reflector instanceof ReflectionProperty): return $this->annotationReader->getPropertyAnnotations($reflector); default: throw new InvalidArgumentException('Unsupported reflection point ' . get_class($reflector)); } }
[ "protected", "function", "getAnnotations", "(", "Reflector", "$", "reflector", ")", ":", "array", "{", "switch", "(", "true", ")", "{", "case", "(", "$", "reflector", "instanceof", "ReflectionClass", ")", ":", "return", "$", "this", "->", "annotationReader", ...
Return list of annotations for reflection point @return array list of annotations @throws \InvalidArgumentException if $reflector is unsupported
[ "Return", "list", "of", "annotations", "for", "reflection", "point" ]
train
https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Core/AspectLoader.php#L193-L208
goaop/framework
src/Core/CachedAspectLoader.php
CachedAspectLoader.load
public function load(Aspect $aspect): array { $refAspect = new ReflectionClass($aspect); $fileName = $this->cacheDir . '/_aspect/' . sha1($refAspect->getName()); // If cache is present and actual, then use it if (file_exists($fileName) && filemtime($fileName) >= filemtime($refAspect->getFileName())) { $loadedItems = $this->loadFromCache($fileName); } else { $loadedItems = $this->loader->load($aspect); $this->saveToCache($loadedItems, $fileName); } return $loadedItems; }
php
public function load(Aspect $aspect): array { $refAspect = new ReflectionClass($aspect); $fileName = $this->cacheDir . '/_aspect/' . sha1($refAspect->getName()); // If cache is present and actual, then use it if (file_exists($fileName) && filemtime($fileName) >= filemtime($refAspect->getFileName())) { $loadedItems = $this->loadFromCache($fileName); } else { $loadedItems = $this->loader->load($aspect); $this->saveToCache($loadedItems, $fileName); } return $loadedItems; }
[ "public", "function", "load", "(", "Aspect", "$", "aspect", ")", ":", "array", "{", "$", "refAspect", "=", "new", "ReflectionClass", "(", "$", "aspect", ")", ";", "$", "fileName", "=", "$", "this", "->", "cacheDir", ".", "'/_aspect/'", ".", "sha1", "("...
{@inheritdoc}
[ "{" ]
train
https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Core/CachedAspectLoader.php#L61-L75
goaop/framework
src/Core/CachedAspectLoader.php
CachedAspectLoader.loadFromCache
protected function loadFromCache(string $fileName): array { $content = file_get_contents($fileName); $loadedItems = unserialize($content); return $loadedItems; }
php
protected function loadFromCache(string $fileName): array { $content = file_get_contents($fileName); $loadedItems = unserialize($content); return $loadedItems; }
[ "protected", "function", "loadFromCache", "(", "string", "$", "fileName", ")", ":", "array", "{", "$", "content", "=", "file_get_contents", "(", "$", "fileName", ")", ";", "$", "loadedItems", "=", "unserialize", "(", "$", "content", ")", ";", "return", "$"...
Loads pointcuts and advisors from the file @return Pointcut[]|Advisor[]
[ "Loads", "pointcuts", "and", "advisors", "from", "the", "file" ]
train
https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Core/CachedAspectLoader.php#L104-L110
goaop/framework
src/Core/CachedAspectLoader.php
CachedAspectLoader.saveToCache
protected function saveToCache(array $items, string $fileName): void { $content = serialize($items); $directoryName = dirname($fileName); if (!is_dir($directoryName)) { mkdir($directoryName, $this->cacheFileMode, true); } file_put_contents($fileName, $content, LOCK_EX); // For cache files we don't want executable bits by default chmod($fileName, $this->cacheFileMode & (~0111)); }
php
protected function saveToCache(array $items, string $fileName): void { $content = serialize($items); $directoryName = dirname($fileName); if (!is_dir($directoryName)) { mkdir($directoryName, $this->cacheFileMode, true); } file_put_contents($fileName, $content, LOCK_EX); // For cache files we don't want executable bits by default chmod($fileName, $this->cacheFileMode & (~0111)); }
[ "protected", "function", "saveToCache", "(", "array", "$", "items", ",", "string", "$", "fileName", ")", ":", "void", "{", "$", "content", "=", "serialize", "(", "$", "items", ")", ";", "$", "directoryName", "=", "dirname", "(", "$", "fileName", ")", "...
Save pointcuts and advisors to the file @param Pointcut[]|Advisor[] $items List of items to store
[ "Save", "pointcuts", "and", "advisors", "to", "the", "file" ]
train
https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Core/CachedAspectLoader.php#L117-L127
goaop/framework
src/Core/AbstractAspectLoaderExtension.php
AbstractAspectLoaderExtension.parsePointcut
final protected function parsePointcut(Aspect $aspect, $reflection, string $pointcutExpression): PointFilter { $stream = $this->makeLexicalAnalyze($aspect, $reflection, $pointcutExpression); return $this->parseTokenStream($reflection, $pointcutExpression, $stream); }
php
final protected function parsePointcut(Aspect $aspect, $reflection, string $pointcutExpression): PointFilter { $stream = $this->makeLexicalAnalyze($aspect, $reflection, $pointcutExpression); return $this->parseTokenStream($reflection, $pointcutExpression, $stream); }
[ "final", "protected", "function", "parsePointcut", "(", "Aspect", "$", "aspect", ",", "$", "reflection", ",", "string", "$", "pointcutExpression", ")", ":", "PointFilter", "{", "$", "stream", "=", "$", "this", "->", "makeLexicalAnalyze", "(", "$", "aspect", ...
General method for parsing pointcuts @param mixed|\ReflectionMethod|\ReflectionProperty $reflection Reflection of point @throws \UnexpectedValueException if there was an error during parsing @return Pointcut|PointFilter
[ "General", "method", "for", "parsing", "pointcuts" ]
train
https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Core/AbstractAspectLoaderExtension.php#L58-L63
goaop/framework
src/Core/AbstractAspectLoaderExtension.php
AbstractAspectLoaderExtension.makeLexicalAnalyze
private function makeLexicalAnalyze(Aspect $aspect, $reflection, string $pointcutExpression): TokenStream { try { $resolvedThisPointcut = str_replace('$this', \get_class($aspect), $pointcutExpression); $stream = $this->pointcutLexer->lex($resolvedThisPointcut); } catch (RecognitionException $e) { $message = 'Can not recognize the lexical structure `%s` before %s, defined in %s:%d'; $message = sprintf( $message, $pointcutExpression, (isset($reflection->class) ? $reflection->class . '->' : '') . $reflection->name, method_exists($reflection, 'getFileName') ? $reflection->getFileName() : $reflection->getDeclaringClass()->getFileName(), method_exists($reflection, 'getStartLine') ? $reflection->getStartLine() : 0 ); throw new UnexpectedValueException($message, 0, $e); } return $stream; }
php
private function makeLexicalAnalyze(Aspect $aspect, $reflection, string $pointcutExpression): TokenStream { try { $resolvedThisPointcut = str_replace('$this', \get_class($aspect), $pointcutExpression); $stream = $this->pointcutLexer->lex($resolvedThisPointcut); } catch (RecognitionException $e) { $message = 'Can not recognize the lexical structure `%s` before %s, defined in %s:%d'; $message = sprintf( $message, $pointcutExpression, (isset($reflection->class) ? $reflection->class . '->' : '') . $reflection->name, method_exists($reflection, 'getFileName') ? $reflection->getFileName() : $reflection->getDeclaringClass()->getFileName(), method_exists($reflection, 'getStartLine') ? $reflection->getStartLine() : 0 ); throw new UnexpectedValueException($message, 0, $e); } return $stream; }
[ "private", "function", "makeLexicalAnalyze", "(", "Aspect", "$", "aspect", ",", "$", "reflection", ",", "string", "$", "pointcutExpression", ")", ":", "TokenStream", "{", "try", "{", "$", "resolvedThisPointcut", "=", "str_replace", "(", "'$this'", ",", "\\", "...
Performs lexical analyze of pointcut @param ReflectionMethod|ReflectionProperty $reflection @throws UnexpectedValueException
[ "Performs", "lexical", "analyze", "of", "pointcut" ]
train
https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Core/AbstractAspectLoaderExtension.php#L72-L94
goaop/framework
src/Core/AbstractAspectLoaderExtension.php
AbstractAspectLoaderExtension.parseTokenStream
private function parseTokenStream($reflection, string $pointcutExpression, TokenStream $stream): PointFilter { try { $pointcut = $this->pointcutParser->parse($stream); } catch (UnexpectedTokenException $e) { $token = $e->getToken(); $message = 'Unexpected token %s in the `%s` before %s, defined in %s:%d.' . PHP_EOL; $message .= 'Expected one of: %s'; $message = sprintf( $message, $token->getValue(), $pointcutExpression, (isset($reflection->class) ? $reflection->class . '->' : '') . $reflection->name, method_exists($reflection, 'getFileName') ? $reflection->getFileName() : $reflection->getDeclaringClass()->getFileName(), method_exists($reflection, 'getStartLine') ? $reflection->getStartLine() : 0, implode(', ', $e->getExpected()) ); throw new UnexpectedValueException($message, 0, $e); } return $pointcut; }
php
private function parseTokenStream($reflection, string $pointcutExpression, TokenStream $stream): PointFilter { try { $pointcut = $this->pointcutParser->parse($stream); } catch (UnexpectedTokenException $e) { $token = $e->getToken(); $message = 'Unexpected token %s in the `%s` before %s, defined in %s:%d.' . PHP_EOL; $message .= 'Expected one of: %s'; $message = sprintf( $message, $token->getValue(), $pointcutExpression, (isset($reflection->class) ? $reflection->class . '->' : '') . $reflection->name, method_exists($reflection, 'getFileName') ? $reflection->getFileName() : $reflection->getDeclaringClass()->getFileName(), method_exists($reflection, 'getStartLine') ? $reflection->getStartLine() : 0, implode(', ', $e->getExpected()) ); throw new UnexpectedValueException($message, 0, $e); } return $pointcut; }
[ "private", "function", "parseTokenStream", "(", "$", "reflection", ",", "string", "$", "pointcutExpression", ",", "TokenStream", "$", "stream", ")", ":", "PointFilter", "{", "try", "{", "$", "pointcut", "=", "$", "this", "->", "pointcutParser", "->", "parse", ...
Performs parsing of pointcut @param ReflectionMethod|ReflectionProperty $reflection @throws UnexpectedValueException
[ "Performs", "parsing", "of", "pointcut" ]
train
https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Core/AbstractAspectLoaderExtension.php#L103-L128
goaop/framework
src/Aop/Pointcut/NotPointcut.php
NotPointcut.matches
public function matches($point, $context = null, $instance = null, array $arguments = null): bool { $isMatchesPre = $this->pointcut->getClassFilter()->matches($context); if (!$isMatchesPre) { return true; } $isMatchesPoint = $this->pointcut->matches($point, $context, $instance, $arguments); if (!$isMatchesPoint) { return true; } return false; }
php
public function matches($point, $context = null, $instance = null, array $arguments = null): bool { $isMatchesPre = $this->pointcut->getClassFilter()->matches($context); if (!$isMatchesPre) { return true; } $isMatchesPoint = $this->pointcut->matches($point, $context, $instance, $arguments); if (!$isMatchesPoint) { return true; } return false; }
[ "public", "function", "matches", "(", "$", "point", ",", "$", "context", "=", "null", ",", "$", "instance", "=", "null", ",", "array", "$", "arguments", "=", "null", ")", ":", "bool", "{", "$", "isMatchesPre", "=", "$", "this", "->", "pointcut", "->"...
Performs matching of point of code @param mixed $point Specific part of code, can be any Reflection class @param null|mixed $context Related context, can be class or namespace @param null|string|object $instance Invocation instance or string for static calls @param null|array $arguments Dynamic arguments for method
[ "Performs", "matching", "of", "point", "of", "code" ]
train
https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Aop/Pointcut/NotPointcut.php#L50-L62
goaop/framework
src/Aop/Framework/DeclareErrorInterceptor.php
DeclareErrorInterceptor.getDeclareErrorAdvice
private static function getDeclareErrorAdvice(): Closure { static $adviceMethod; if (!$adviceMethod) { $adviceMethod = function ($object, $reflectorName, $message, $level = E_USER_NOTICE) { $class = is_string($object) ? $object : get_class($object); $message = vsprintf('[AOP Declare Error]: %s has an error: "%s"', [ $class . '->' . $reflectorName, $message ]); trigger_error($message, $level); }; } return $adviceMethod; }
php
private static function getDeclareErrorAdvice(): Closure { static $adviceMethod; if (!$adviceMethod) { $adviceMethod = function ($object, $reflectorName, $message, $level = E_USER_NOTICE) { $class = is_string($object) ? $object : get_class($object); $message = vsprintf('[AOP Declare Error]: %s has an error: "%s"', [ $class . '->' . $reflectorName, $message ]); trigger_error($message, $level); }; } return $adviceMethod; }
[ "private", "static", "function", "getDeclareErrorAdvice", "(", ")", ":", "Closure", "{", "static", "$", "adviceMethod", ";", "if", "(", "!", "$", "adviceMethod", ")", "{", "$", "adviceMethod", "=", "function", "(", "$", "object", ",", "$", "reflectorName", ...
Returns an advice
[ "Returns", "an", "advice" ]
train
https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Aop/Framework/DeclareErrorInterceptor.php#L78-L93
goaop/framework
src/Console/Command/CacheWarmupCommand.php
CacheWarmupCommand.execute
protected function execute(InputInterface $input, OutputInterface $output) { $this->loadAspectKernel($input, $output); $warmer = new CacheWarmer($this->aspectKernel, $output); $warmer->warmUp(); }
php
protected function execute(InputInterface $input, OutputInterface $output) { $this->loadAspectKernel($input, $output); $warmer = new CacheWarmer($this->aspectKernel, $output); $warmer->warmUp(); }
[ "protected", "function", "execute", "(", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ")", "{", "$", "this", "->", "loadAspectKernel", "(", "$", "input", ",", "$", "output", ")", ";", "$", "warmer", "=", "new", "CacheWarmer", "(",...
{@inheritDoc}
[ "{" ]
train
https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Console/Command/CacheWarmupCommand.php#L47-L53
goaop/framework
src/Aop/Framework/AbstractJoinpoint.php
AbstractJoinpoint.sortAdvices
public static function sortAdvices(array $advices): array { $sortedAdvices = $advices; uasort($sortedAdvices, function (Advice $first, Advice $second) { switch (true) { case $first instanceof AdviceBefore && !($second instanceof AdviceBefore): return -1; case $first instanceof AdviceAround && !($second instanceof AdviceAround): return 1; case $first instanceof AdviceAfter && !($second instanceof AdviceAfter): return $second instanceof AdviceBefore ? 1 : -1; case ($first instanceof OrderedAdvice && $second instanceof OrderedAdvice): return $first->getAdviceOrder() - $second->getAdviceOrder(); default: return 0; } }); return $sortedAdvices; }
php
public static function sortAdvices(array $advices): array { $sortedAdvices = $advices; uasort($sortedAdvices, function (Advice $first, Advice $second) { switch (true) { case $first instanceof AdviceBefore && !($second instanceof AdviceBefore): return -1; case $first instanceof AdviceAround && !($second instanceof AdviceAround): return 1; case $first instanceof AdviceAfter && !($second instanceof AdviceAfter): return $second instanceof AdviceBefore ? 1 : -1; case ($first instanceof OrderedAdvice && $second instanceof OrderedAdvice): return $first->getAdviceOrder() - $second->getAdviceOrder(); default: return 0; } }); return $sortedAdvices; }
[ "public", "static", "function", "sortAdvices", "(", "array", "$", "advices", ")", ":", "array", "{", "$", "sortedAdvices", "=", "$", "advices", ";", "uasort", "(", "$", "sortedAdvices", ",", "function", "(", "Advice", "$", "first", ",", "Advice", "$", "s...
Sorts advices by priority @param array|Advice[] $advices @return array|Advice[] Sorted list of advices
[ "Sorts", "advices", "by", "priority" ]
train
https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Aop/Framework/AbstractJoinpoint.php#L78-L101
goaop/framework
src/Aop/Framework/AbstractJoinpoint.php
AbstractJoinpoint.flatAndSortAdvices
public static function flatAndSortAdvices(array $advices): array { $flattenAdvices = []; foreach ($advices as $type => $typedAdvices) { foreach ($typedAdvices as $name => $concreteAdvices) { if (is_array($concreteAdvices)) { $flattenAdvices[$type][$name] = array_keys(self::sortAdvices($concreteAdvices)); } else { $flattenAdvices[$type][$name] = $concreteAdvices; } } } return $flattenAdvices; }
php
public static function flatAndSortAdvices(array $advices): array { $flattenAdvices = []; foreach ($advices as $type => $typedAdvices) { foreach ($typedAdvices as $name => $concreteAdvices) { if (is_array($concreteAdvices)) { $flattenAdvices[$type][$name] = array_keys(self::sortAdvices($concreteAdvices)); } else { $flattenAdvices[$type][$name] = $concreteAdvices; } } } return $flattenAdvices; }
[ "public", "static", "function", "flatAndSortAdvices", "(", "array", "$", "advices", ")", ":", "array", "{", "$", "flattenAdvices", "=", "[", "]", ";", "foreach", "(", "$", "advices", "as", "$", "type", "=>", "$", "typedAdvices", ")", "{", "foreach", "(",...
Replace concrete advices with list of ids @param Advice[][][] $advices List of advices
[ "Replace", "concrete", "advices", "with", "list", "of", "ids" ]
train
https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Aop/Framework/AbstractJoinpoint.php#L108-L122
goaop/framework
src/Aop/Framework/ClassFieldAccess.php
ClassFieldAccess.ensureScopeRule
public function ensureScopeRule(int $stackLevel = 2): void { $property = $this->reflectionProperty; $isProtected = $property->isProtected(); $isPrivate = $property->isPrivate(); if ($isProtected || $isPrivate) { $backTrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, $stackLevel+1); $accessor = $backTrace[$stackLevel] ?? []; $propertyClass = $property->class; if (isset($accessor['class'])) { // For private and protected properties its ok to access from the same class if ($accessor['class'] === $propertyClass) { return; } // For protected properties its ok to access from any subclass if ($isProtected && is_subclass_of($accessor['class'], $propertyClass)) { return; } } throw new AspectException("Cannot access property {$propertyClass}::{$property->name}"); } }
php
public function ensureScopeRule(int $stackLevel = 2): void { $property = $this->reflectionProperty; $isProtected = $property->isProtected(); $isPrivate = $property->isPrivate(); if ($isProtected || $isPrivate) { $backTrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, $stackLevel+1); $accessor = $backTrace[$stackLevel] ?? []; $propertyClass = $property->class; if (isset($accessor['class'])) { // For private and protected properties its ok to access from the same class if ($accessor['class'] === $propertyClass) { return; } // For protected properties its ok to access from any subclass if ($isProtected && is_subclass_of($accessor['class'], $propertyClass)) { return; } } throw new AspectException("Cannot access property {$propertyClass}::{$property->name}"); } }
[ "public", "function", "ensureScopeRule", "(", "int", "$", "stackLevel", "=", "2", ")", ":", "void", "{", "$", "property", "=", "$", "this", "->", "reflectionProperty", ";", "$", "isProtected", "=", "$", "property", "->", "isProtected", "(", ")", ";", "$"...
Checks scope rules for accessing property
[ "Checks", "scope", "rules", "for", "accessing", "property" ]
train
https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Aop/Framework/ClassFieldAccess.php#L118-L139
goaop/framework
src/Aop/Framework/ClassFieldAccess.php
ClassFieldAccess.proceed
final public function proceed() { if (isset($this->advices[$this->current])) { $currentInterceptor = $this->advices[$this->current++]; $currentInterceptor->invoke($this); } }
php
final public function proceed() { if (isset($this->advices[$this->current])) { $currentInterceptor = $this->advices[$this->current++]; $currentInterceptor->invoke($this); } }
[ "final", "public", "function", "proceed", "(", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "advices", "[", "$", "this", "->", "current", "]", ")", ")", "{", "$", "currentInterceptor", "=", "$", "this", "->", "advices", "[", "$", "this", "...
Proceed to the next interceptor in the Chain @return void For field interceptor there is no return values
[ "Proceed", "to", "the", "next", "interceptor", "in", "the", "Chain" ]
train
https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Aop/Framework/ClassFieldAccess.php#L146-L153
goaop/framework
src/Aop/Framework/ClassFieldAccess.php
ClassFieldAccess.&
final public function &__invoke(object $instance, int $accessType, &$originalValue, $newValue = NAN) { if ($this->level > 0) { $this->stackFrames[] = [$this->instance, $this->accessType, &$this->value, &$this->newValue]; } try { ++$this->level; $this->current = 0; $this->instance = $instance; $this->accessType = $accessType; $this->value = &$originalValue; $this->newValue = $newValue; $this->proceed(); if ($accessType === self::READ) { $result = &$this->value; } else { $result = &$this->newValue; } return $result; } finally { --$this->level; if ($this->level > 0) { [$this->instance, $this->accessType, $this->value, $this->newValue] = array_pop($this->stackFrames); } } }
php
final public function &__invoke(object $instance, int $accessType, &$originalValue, $newValue = NAN) { if ($this->level > 0) { $this->stackFrames[] = [$this->instance, $this->accessType, &$this->value, &$this->newValue]; } try { ++$this->level; $this->current = 0; $this->instance = $instance; $this->accessType = $accessType; $this->value = &$originalValue; $this->newValue = $newValue; $this->proceed(); if ($accessType === self::READ) { $result = &$this->value; } else { $result = &$this->newValue; } return $result; } finally { --$this->level; if ($this->level > 0) { [$this->instance, $this->accessType, $this->value, $this->newValue] = array_pop($this->stackFrames); } } }
[ "final", "public", "function", "&", "__invoke", "(", "object", "$", "instance", ",", "int", "$", "accessType", ",", "&", "$", "originalValue", ",", "$", "newValue", "=", "NAN", ")", "{", "if", "(", "$", "this", "->", "level", ">", "0", ")", "{", "$...
Invokes current field access with all interceptors @param object $instance Instance of object @param integer $accessType Type of access: READ or WRITE @param mixed $originalValue Original value of property @param mixed $newValue New value to set @return mixed
[ "Invokes", "current", "field", "access", "with", "all", "interceptors" ]
train
https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Aop/Framework/ClassFieldAccess.php#L165-L196
goaop/framework
src/Instrument/Transformer/SelfValueTransformer.php
SelfValueTransformer.transform
public function transform(StreamMetaData $metadata): string { $selfValueVisitor = new SelfValueVisitor(); $traverser = new NodeTraverser(); $traverser->addVisitor($selfValueVisitor); $traverser->traverse($metadata->syntaxTree); $this->adjustSelfTokens($metadata, $selfValueVisitor->getReplacedNodes()); // We should always vote abstain, because if there are only changes for self we can drop them return self::RESULT_ABSTAIN; }
php
public function transform(StreamMetaData $metadata): string { $selfValueVisitor = new SelfValueVisitor(); $traverser = new NodeTraverser(); $traverser->addVisitor($selfValueVisitor); $traverser->traverse($metadata->syntaxTree); $this->adjustSelfTokens($metadata, $selfValueVisitor->getReplacedNodes()); // We should always vote abstain, because if there are only changes for self we can drop them return self::RESULT_ABSTAIN; }
[ "public", "function", "transform", "(", "StreamMetaData", "$", "metadata", ")", ":", "string", "{", "$", "selfValueVisitor", "=", "new", "SelfValueVisitor", "(", ")", ";", "$", "traverser", "=", "new", "NodeTraverser", "(", ")", ";", "$", "traverser", "->", ...
This method may transform the supplied source and return a new replacement for it @return string See RESULT_XXX constants in the interface
[ "This", "method", "may", "transform", "the", "supplied", "source", "and", "return", "a", "new", "replacement", "for", "it" ]
train
https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Instrument/Transformer/SelfValueTransformer.php#L27-L38
goaop/framework
src/Instrument/Transformer/SelfValueTransformer.php
SelfValueTransformer.adjustSelfTokens
private function adjustSelfTokens(StreamMetaData $metadata, array $replacedNodes): void { foreach ($replacedNodes as $replacedNode) { $position = $replacedNode->getAttribute('startTokenPos'); $metadata->tokenStream[$position][1] = $replacedNode->toString(); } }
php
private function adjustSelfTokens(StreamMetaData $metadata, array $replacedNodes): void { foreach ($replacedNodes as $replacedNode) { $position = $replacedNode->getAttribute('startTokenPos'); $metadata->tokenStream[$position][1] = $replacedNode->toString(); } }
[ "private", "function", "adjustSelfTokens", "(", "StreamMetaData", "$", "metadata", ",", "array", "$", "replacedNodes", ")", ":", "void", "{", "foreach", "(", "$", "replacedNodes", "as", "$", "replacedNode", ")", "{", "$", "position", "=", "$", "replacedNode", ...
Adjusts tokens in the source code @param FullyQualified[] $replacedNodes Replaced nodes in the source code
[ "Adjusts", "tokens", "in", "the", "source", "code" ]
train
https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Instrument/Transformer/SelfValueTransformer.php#L45-L52
goaop/framework
src/Aop/Framework/ReflectionConstructorInvocation.php
ReflectionConstructorInvocation.proceed
final public function proceed() { if (isset($this->advices[$this->current])) { $currentInterceptor = $this->advices[$this->current]; $this->current++; return $currentInterceptor->invoke($this); } $this->instance = $this->class->newInstance(...$this->arguments); return $this->instance; }
php
final public function proceed() { if (isset($this->advices[$this->current])) { $currentInterceptor = $this->advices[$this->current]; $this->current++; return $currentInterceptor->invoke($this); } $this->instance = $this->class->newInstance(...$this->arguments); return $this->instance; }
[ "final", "public", "function", "proceed", "(", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "advices", "[", "$", "this", "->", "current", "]", ")", ")", "{", "$", "currentInterceptor", "=", "$", "this", "->", "advices", "[", "$", "this", "...
Proceed to the next interceptor in the Chain Typically this method is called inside previous closure, as instance of Joinpoint is passed to callback Do not call this method directly, only inside callback closures. @return mixed
[ "Proceed", "to", "the", "next", "interceptor", "in", "the", "Chain" ]
train
https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Aop/Framework/ReflectionConstructorInvocation.php#L70-L82
goaop/framework
src/Aop/Support/PointcutBuilder.php
PointcutBuilder.before
public function before(string $pointcutExpression, Closure $adviceToInvoke): void { $interceptor = new BeforeInterceptor($adviceToInvoke, 0, $pointcutExpression); $this->registerAdviceInContainer($pointcutExpression, $interceptor); }
php
public function before(string $pointcutExpression, Closure $adviceToInvoke): void { $interceptor = new BeforeInterceptor($adviceToInvoke, 0, $pointcutExpression); $this->registerAdviceInContainer($pointcutExpression, $interceptor); }
[ "public", "function", "before", "(", "string", "$", "pointcutExpression", ",", "Closure", "$", "adviceToInvoke", ")", ":", "void", "{", "$", "interceptor", "=", "new", "BeforeInterceptor", "(", "$", "adviceToInvoke", ",", "0", ",", "$", "pointcutExpression", "...
Declares the "Before" hook for specific pointcut expression
[ "Declares", "the", "Before", "hook", "for", "specific", "pointcut", "expression" ]
train
https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Aop/Support/PointcutBuilder.php#L44-L48
goaop/framework
src/Aop/Support/PointcutBuilder.php
PointcutBuilder.after
public function after(string $pointcutExpression, Closure $adviceToInvoke): void { $interceptor = new AfterInterceptor($adviceToInvoke, 0, $pointcutExpression); $this->registerAdviceInContainer($pointcutExpression, $interceptor); }
php
public function after(string $pointcutExpression, Closure $adviceToInvoke): void { $interceptor = new AfterInterceptor($adviceToInvoke, 0, $pointcutExpression); $this->registerAdviceInContainer($pointcutExpression, $interceptor); }
[ "public", "function", "after", "(", "string", "$", "pointcutExpression", ",", "Closure", "$", "adviceToInvoke", ")", ":", "void", "{", "$", "interceptor", "=", "new", "AfterInterceptor", "(", "$", "adviceToInvoke", ",", "0", ",", "$", "pointcutExpression", ")"...
Declares the "After" hook for specific pointcut expression
[ "Declares", "the", "After", "hook", "for", "specific", "pointcut", "expression" ]
train
https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Aop/Support/PointcutBuilder.php#L53-L57
goaop/framework
src/Aop/Support/PointcutBuilder.php
PointcutBuilder.afterThrowing
public function afterThrowing(string $pointcutExpression, Closure $adviceToInvoke): void { $interceptor = new AfterThrowingInterceptor($adviceToInvoke, 0, $pointcutExpression); $this->registerAdviceInContainer($pointcutExpression, $interceptor); }
php
public function afterThrowing(string $pointcutExpression, Closure $adviceToInvoke): void { $interceptor = new AfterThrowingInterceptor($adviceToInvoke, 0, $pointcutExpression); $this->registerAdviceInContainer($pointcutExpression, $interceptor); }
[ "public", "function", "afterThrowing", "(", "string", "$", "pointcutExpression", ",", "Closure", "$", "adviceToInvoke", ")", ":", "void", "{", "$", "interceptor", "=", "new", "AfterThrowingInterceptor", "(", "$", "adviceToInvoke", ",", "0", ",", "$", "pointcutEx...
Declares the "AfterThrowing" hook for specific pointcut expression
[ "Declares", "the", "AfterThrowing", "hook", "for", "specific", "pointcut", "expression" ]
train
https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Aop/Support/PointcutBuilder.php#L62-L66
goaop/framework
src/Aop/Support/PointcutBuilder.php
PointcutBuilder.around
public function around(string $pointcutExpression, Closure $adviceToInvoke): void { $interceptor = new AroundInterceptor($adviceToInvoke, 0, $pointcutExpression); $this->registerAdviceInContainer($pointcutExpression, $interceptor); }
php
public function around(string $pointcutExpression, Closure $adviceToInvoke): void { $interceptor = new AroundInterceptor($adviceToInvoke, 0, $pointcutExpression); $this->registerAdviceInContainer($pointcutExpression, $interceptor); }
[ "public", "function", "around", "(", "string", "$", "pointcutExpression", ",", "Closure", "$", "adviceToInvoke", ")", ":", "void", "{", "$", "interceptor", "=", "new", "AroundInterceptor", "(", "$", "adviceToInvoke", ",", "0", ",", "$", "pointcutExpression", "...
Declares the "Around" hook for specific pointcut expression
[ "Declares", "the", "Around", "hook", "for", "specific", "pointcut", "expression" ]
train
https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Aop/Support/PointcutBuilder.php#L71-L75
goaop/framework
src/Aop/Support/PointcutBuilder.php
PointcutBuilder.declareError
public function declareError(string $pointcutExpression, string $message, int $errorLevel = E_USER_ERROR): void { $interceptor = new DeclareErrorInterceptor($message, $errorLevel, $pointcutExpression); $this->registerAdviceInContainer($pointcutExpression, $interceptor); }
php
public function declareError(string $pointcutExpression, string $message, int $errorLevel = E_USER_ERROR): void { $interceptor = new DeclareErrorInterceptor($message, $errorLevel, $pointcutExpression); $this->registerAdviceInContainer($pointcutExpression, $interceptor); }
[ "public", "function", "declareError", "(", "string", "$", "pointcutExpression", ",", "string", "$", "message", ",", "int", "$", "errorLevel", "=", "E_USER_ERROR", ")", ":", "void", "{", "$", "interceptor", "=", "new", "DeclareErrorInterceptor", "(", "$", "mess...
Declares the error message for specific pointcut expression with concrete error level
[ "Declares", "the", "error", "message", "for", "specific", "pointcut", "expression", "with", "concrete", "error", "level" ]
train
https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Aop/Support/PointcutBuilder.php#L80-L84
goaop/framework
src/Aop/Support/PointcutBuilder.php
PointcutBuilder.registerAdviceInContainer
private function registerAdviceInContainer(string $pointcutExpression, Advice $adviceToInvoke): void { $this->container->registerAdvisor( new LazyPointcutAdvisor($this->container, $pointcutExpression, $adviceToInvoke), $this->getPointcutId($pointcutExpression) ); }
php
private function registerAdviceInContainer(string $pointcutExpression, Advice $adviceToInvoke): void { $this->container->registerAdvisor( new LazyPointcutAdvisor($this->container, $pointcutExpression, $adviceToInvoke), $this->getPointcutId($pointcutExpression) ); }
[ "private", "function", "registerAdviceInContainer", "(", "string", "$", "pointcutExpression", ",", "Advice", "$", "adviceToInvoke", ")", ":", "void", "{", "$", "this", "->", "container", "->", "registerAdvisor", "(", "new", "LazyPointcutAdvisor", "(", "$", "this",...
General method to register advices
[ "General", "method", "to", "register", "advices" ]
train
https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Aop/Support/PointcutBuilder.php#L89-L95
goaop/framework
src/Instrument/Transformer/WeavingTransformer.php
WeavingTransformer.transform
public function transform(StreamMetaData $metadata): string { $totalTransformations = 0; $parsedSource = new ReflectionFile($metadata->uri, $metadata->syntaxTree); // Check if we have some new aspects that weren't loaded yet $unloadedAspects = $this->aspectLoader->getUnloadedAspects(); if (!empty($unloadedAspects)) { $this->loadAndRegisterAspects($unloadedAspects); } $advisors = $this->container->getByTag('advisor'); $namespaces = $parsedSource->getFileNamespaces(); foreach ($namespaces as $namespace) { $classes = $namespace->getClasses(); foreach ($classes as $class) { // Skip interfaces and aspects if ($class->isInterface() || in_array(Aspect::class, $class->getInterfaceNames(), true)) { continue; } $wasClassProcessed = $this->processSingleClass( $advisors, $metadata, $class, $parsedSource->isStrictMode() ); $totalTransformations += (integer) $wasClassProcessed; } $wasFunctionsProcessed = $this->processFunctions($advisors, $metadata, $namespace); $totalTransformations += (integer) $wasFunctionsProcessed; } $result = ($totalTransformations > 0) ? self::RESULT_TRANSFORMED : self::RESULT_ABSTAIN; return $result; }
php
public function transform(StreamMetaData $metadata): string { $totalTransformations = 0; $parsedSource = new ReflectionFile($metadata->uri, $metadata->syntaxTree); // Check if we have some new aspects that weren't loaded yet $unloadedAspects = $this->aspectLoader->getUnloadedAspects(); if (!empty($unloadedAspects)) { $this->loadAndRegisterAspects($unloadedAspects); } $advisors = $this->container->getByTag('advisor'); $namespaces = $parsedSource->getFileNamespaces(); foreach ($namespaces as $namespace) { $classes = $namespace->getClasses(); foreach ($classes as $class) { // Skip interfaces and aspects if ($class->isInterface() || in_array(Aspect::class, $class->getInterfaceNames(), true)) { continue; } $wasClassProcessed = $this->processSingleClass( $advisors, $metadata, $class, $parsedSource->isStrictMode() ); $totalTransformations += (integer) $wasClassProcessed; } $wasFunctionsProcessed = $this->processFunctions($advisors, $metadata, $namespace); $totalTransformations += (integer) $wasFunctionsProcessed; } $result = ($totalTransformations > 0) ? self::RESULT_TRANSFORMED : self::RESULT_ABSTAIN; return $result; }
[ "public", "function", "transform", "(", "StreamMetaData", "$", "metadata", ")", ":", "string", "{", "$", "totalTransformations", "=", "0", ";", "$", "parsedSource", "=", "new", "ReflectionFile", "(", "$", "metadata", "->", "uri", ",", "$", "metadata", "->", ...
This method may transform the supplied source and return a new replacement for it @param StreamMetaData $metadata @return string See RESULT_XXX constants in the interface
[ "This", "method", "may", "transform", "the", "supplied", "source", "and", "return", "a", "new", "replacement", "for", "it" ]
train
https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Instrument/Transformer/WeavingTransformer.php#L80-L116
goaop/framework
src/Instrument/Transformer/WeavingTransformer.php
WeavingTransformer.processSingleClass
private function processSingleClass( array $advisors, StreamMetaData $metadata, ReflectionClass $class, bool $useStrictMode ): bool { $advices = $this->adviceMatcher->getAdvicesForClass($class, $advisors); if (empty($advices)) { // Fast return if there aren't any advices for that class return false; } // Sort advices in advance to keep the correct order in cache, and leave only keys for the cache $advices = AbstractJoinpoint::flatAndSortAdvices($advices); // Prepare new class name $newClassName = $class->getShortName() . AspectContainer::AOP_PROXIED_SUFFIX; // Replace original class name with new $this->adjustOriginalClass($class, $advices, $metadata, $newClassName); $newParentName = $class->getNamespaceName() . '\\' . $newClassName; // Prepare child Aop proxy $childProxyGenerator = $class->isTrait() ? new TraitProxyGenerator($class, $newParentName, $advices, $this->useParameterWidening) : new ClassProxyGenerator($class, $newParentName, $advices, $this->useParameterWidening); $refNamespace = new ReflectionFileNamespace($class->getFileName(), $class->getNamespaceName()); foreach ($refNamespace->getNamespaceAliases() as $fqdn => $alias) { // Either we have a string or Identifier node if ($alias !== null) { $childProxyGenerator->addUse($fqdn, (string) $alias); } else { $childProxyGenerator->addUse($fqdn); } } $childCode = $childProxyGenerator->generate(); if ($useStrictMode) { $childCode = 'declare(strict_types=1);' . PHP_EOL . $childCode; } $contentToInclude = $this->saveProxyToCache($class, $childCode); // Get last token for this class $lastClassToken = $class->getNode()->getAttribute('endTokenPos'); $metadata->tokenStream[$lastClassToken][1] .= PHP_EOL . $contentToInclude; return true; }
php
private function processSingleClass( array $advisors, StreamMetaData $metadata, ReflectionClass $class, bool $useStrictMode ): bool { $advices = $this->adviceMatcher->getAdvicesForClass($class, $advisors); if (empty($advices)) { // Fast return if there aren't any advices for that class return false; } // Sort advices in advance to keep the correct order in cache, and leave only keys for the cache $advices = AbstractJoinpoint::flatAndSortAdvices($advices); // Prepare new class name $newClassName = $class->getShortName() . AspectContainer::AOP_PROXIED_SUFFIX; // Replace original class name with new $this->adjustOriginalClass($class, $advices, $metadata, $newClassName); $newParentName = $class->getNamespaceName() . '\\' . $newClassName; // Prepare child Aop proxy $childProxyGenerator = $class->isTrait() ? new TraitProxyGenerator($class, $newParentName, $advices, $this->useParameterWidening) : new ClassProxyGenerator($class, $newParentName, $advices, $this->useParameterWidening); $refNamespace = new ReflectionFileNamespace($class->getFileName(), $class->getNamespaceName()); foreach ($refNamespace->getNamespaceAliases() as $fqdn => $alias) { // Either we have a string or Identifier node if ($alias !== null) { $childProxyGenerator->addUse($fqdn, (string) $alias); } else { $childProxyGenerator->addUse($fqdn); } } $childCode = $childProxyGenerator->generate(); if ($useStrictMode) { $childCode = 'declare(strict_types=1);' . PHP_EOL . $childCode; } $contentToInclude = $this->saveProxyToCache($class, $childCode); // Get last token for this class $lastClassToken = $class->getNode()->getAttribute('endTokenPos'); $metadata->tokenStream[$lastClassToken][1] .= PHP_EOL . $contentToInclude; return true; }
[ "private", "function", "processSingleClass", "(", "array", "$", "advisors", ",", "StreamMetaData", "$", "metadata", ",", "ReflectionClass", "$", "class", ",", "bool", "$", "useStrictMode", ")", ":", "bool", "{", "$", "advices", "=", "$", "this", "->", "advic...
Performs weaving of single class if needed, returns true if the class was processed @param Advisor[] $advisors List of advisors @param StreamMetaData $metadata @param ReflectionClass $class @param bool $useStrictMode If the source file used strict mode, the proxy should too @return bool
[ "Performs", "weaving", "of", "single", "class", "if", "needed", "returns", "true", "if", "the", "class", "was", "processed" ]
train
https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Instrument/Transformer/WeavingTransformer.php#L127-L179
goaop/framework
src/Instrument/Transformer/WeavingTransformer.php
WeavingTransformer.adjustOriginalClass
private function adjustOriginalClass( ReflectionClass $class, array $advices, StreamMetaData $streamMetaData, string $newClassName ): void { $classNode = $class->getNode(); $position = $classNode->getAttribute('startTokenPos'); do { if (isset($streamMetaData->tokenStream[$position])) { $token = $streamMetaData->tokenStream[$position]; // Remove final and following whitespace from the class, child will be final instead if ($token[0] === T_FINAL) { unset($streamMetaData->tokenStream[$position], $streamMetaData->tokenStream[$position+1]); } // First string is class/trait name if ($token[0] === T_STRING) { $streamMetaData->tokenStream[$position][1] = $newClassName; // We have finished our job, can break this loop break; } } ++$position; } while (true); foreach ($class->getMethods(ReflectionMethod::IS_FINAL) as $finalMethod) { if (!$finalMethod instanceof ReflectionMethod || $finalMethod->getDeclaringClass()->name !== $class->name) { continue; } $hasDynamicAdvice = isset($advices[AspectContainer::METHOD_PREFIX][$finalMethod->name]); $hasStaticAdvice = isset($advices[AspectContainer::STATIC_METHOD_PREFIX][$finalMethod->name]); if (!$hasDynamicAdvice && !$hasStaticAdvice) { continue; } $methodNode = $finalMethod->getNode(); $position = $methodNode->getAttribute('startTokenPos'); do { if (isset($streamMetaData->tokenStream[$position])) { $token = $streamMetaData->tokenStream[$position]; // Remove final and following whitespace from the method, child will be final instead if ($token[0] === T_FINAL) { unset($streamMetaData->tokenStream[$position], $streamMetaData->tokenStream[$position+1]); break; } } ++$position; } while (true); } }
php
private function adjustOriginalClass( ReflectionClass $class, array $advices, StreamMetaData $streamMetaData, string $newClassName ): void { $classNode = $class->getNode(); $position = $classNode->getAttribute('startTokenPos'); do { if (isset($streamMetaData->tokenStream[$position])) { $token = $streamMetaData->tokenStream[$position]; // Remove final and following whitespace from the class, child will be final instead if ($token[0] === T_FINAL) { unset($streamMetaData->tokenStream[$position], $streamMetaData->tokenStream[$position+1]); } // First string is class/trait name if ($token[0] === T_STRING) { $streamMetaData->tokenStream[$position][1] = $newClassName; // We have finished our job, can break this loop break; } } ++$position; } while (true); foreach ($class->getMethods(ReflectionMethod::IS_FINAL) as $finalMethod) { if (!$finalMethod instanceof ReflectionMethod || $finalMethod->getDeclaringClass()->name !== $class->name) { continue; } $hasDynamicAdvice = isset($advices[AspectContainer::METHOD_PREFIX][$finalMethod->name]); $hasStaticAdvice = isset($advices[AspectContainer::STATIC_METHOD_PREFIX][$finalMethod->name]); if (!$hasDynamicAdvice && !$hasStaticAdvice) { continue; } $methodNode = $finalMethod->getNode(); $position = $methodNode->getAttribute('startTokenPos'); do { if (isset($streamMetaData->tokenStream[$position])) { $token = $streamMetaData->tokenStream[$position]; // Remove final and following whitespace from the method, child will be final instead if ($token[0] === T_FINAL) { unset($streamMetaData->tokenStream[$position], $streamMetaData->tokenStream[$position+1]); break; } } ++$position; } while (true); } }
[ "private", "function", "adjustOriginalClass", "(", "ReflectionClass", "$", "class", ",", "array", "$", "advices", ",", "StreamMetaData", "$", "streamMetaData", ",", "string", "$", "newClassName", ")", ":", "void", "{", "$", "classNode", "=", "$", "class", "->"...
Adjust definition of original class source to enable extending @param array $advices List of class advices (used to check for final methods and make them non-final)
[ "Adjust", "definition", "of", "original", "class", "source", "to", "enable", "extending" ]
train
https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Instrument/Transformer/WeavingTransformer.php#L186-L234
goaop/framework
src/Instrument/Transformer/WeavingTransformer.php
WeavingTransformer.processFunctions
private function processFunctions( array $advisors, StreamMetaData $metadata, ReflectionFileNamespace $namespace ): bool { static $cacheDirSuffix = '/_functions/'; $wasProcessedFunctions = false; $functionAdvices = $this->adviceMatcher->getAdvicesForFunctions($namespace, $advisors); $cacheDir = $this->cachePathManager->getCacheDir(); if (!empty($functionAdvices)) { $cacheDir .= $cacheDirSuffix; $fileName = str_replace('\\', '/', $namespace->getName()) . '.php'; $functionFileName = $cacheDir . $fileName; if (!file_exists($functionFileName) || !$this->container->isFresh(filemtime($functionFileName))) { $functionAdvices = AbstractJoinpoint::flatAndSortAdvices($functionAdvices); $dirname = dirname($functionFileName); if (!file_exists($dirname)) { mkdir($dirname, $this->options['cacheFileMode'], true); } $generator = new FunctionProxyGenerator($namespace, $functionAdvices, $this->useParameterWidening); file_put_contents($functionFileName, $generator->generate(), LOCK_EX); // For cache files we don't want executable bits by default chmod($functionFileName, $this->options['cacheFileMode'] & (~0111)); } $content = 'include_once AOP_CACHE_DIR . ' . var_export($cacheDirSuffix . $fileName, true) . ';'; $lastTokenPosition = $namespace->getLastTokenPosition(); $metadata->tokenStream[$lastTokenPosition][1] .= PHP_EOL . $content; $wasProcessedFunctions = true; } return $wasProcessedFunctions; }
php
private function processFunctions( array $advisors, StreamMetaData $metadata, ReflectionFileNamespace $namespace ): bool { static $cacheDirSuffix = '/_functions/'; $wasProcessedFunctions = false; $functionAdvices = $this->adviceMatcher->getAdvicesForFunctions($namespace, $advisors); $cacheDir = $this->cachePathManager->getCacheDir(); if (!empty($functionAdvices)) { $cacheDir .= $cacheDirSuffix; $fileName = str_replace('\\', '/', $namespace->getName()) . '.php'; $functionFileName = $cacheDir . $fileName; if (!file_exists($functionFileName) || !$this->container->isFresh(filemtime($functionFileName))) { $functionAdvices = AbstractJoinpoint::flatAndSortAdvices($functionAdvices); $dirname = dirname($functionFileName); if (!file_exists($dirname)) { mkdir($dirname, $this->options['cacheFileMode'], true); } $generator = new FunctionProxyGenerator($namespace, $functionAdvices, $this->useParameterWidening); file_put_contents($functionFileName, $generator->generate(), LOCK_EX); // For cache files we don't want executable bits by default chmod($functionFileName, $this->options['cacheFileMode'] & (~0111)); } $content = 'include_once AOP_CACHE_DIR . ' . var_export($cacheDirSuffix . $fileName, true) . ';'; $lastTokenPosition = $namespace->getLastTokenPosition(); $metadata->tokenStream[$lastTokenPosition][1] .= PHP_EOL . $content; $wasProcessedFunctions = true; } return $wasProcessedFunctions; }
[ "private", "function", "processFunctions", "(", "array", "$", "advisors", ",", "StreamMetaData", "$", "metadata", ",", "ReflectionFileNamespace", "$", "namespace", ")", ":", "bool", "{", "static", "$", "cacheDirSuffix", "=", "'/_functions/'", ";", "$", "wasProcess...
Performs weaving of functions in the current namespace, returns true if functions were processed, false otherwise @param Advisor[] $advisors List of advisors
[ "Performs", "weaving", "of", "functions", "in", "the", "current", "namespace", "returns", "true", "if", "functions", "were", "processed", "false", "otherwise" ]
train
https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Instrument/Transformer/WeavingTransformer.php#L241-L275
goaop/framework
src/Instrument/Transformer/WeavingTransformer.php
WeavingTransformer.saveProxyToCache
private function saveProxyToCache(ReflectionClass $class, string $childCode): string { static $cacheDirSuffix = '/_proxies/'; $cacheDir = $this->cachePathManager->getCacheDir() . $cacheDirSuffix; $relativePath = str_replace($this->options['appDir'] . DIRECTORY_SEPARATOR, '', $class->getFileName()); $proxyRelativePath = str_replace('\\', '/', $relativePath . '/' . $class->getName() . '.php'); $proxyFileName = $cacheDir . $proxyRelativePath; $dirname = dirname($proxyFileName); if (!file_exists($dirname)) { mkdir($dirname, $this->options['cacheFileMode'], true); } $body = '<?php' . PHP_EOL . $childCode; $isVirtualSystem = strpos($proxyFileName, 'vfs') === 0; file_put_contents($proxyFileName, $body, $isVirtualSystem ? 0 : LOCK_EX); // For cache files we don't want executable bits by default chmod($proxyFileName, $this->options['cacheFileMode'] & (~0111)); return 'include_once AOP_CACHE_DIR . ' . var_export($cacheDirSuffix . $proxyRelativePath, true) . ';'; }
php
private function saveProxyToCache(ReflectionClass $class, string $childCode): string { static $cacheDirSuffix = '/_proxies/'; $cacheDir = $this->cachePathManager->getCacheDir() . $cacheDirSuffix; $relativePath = str_replace($this->options['appDir'] . DIRECTORY_SEPARATOR, '', $class->getFileName()); $proxyRelativePath = str_replace('\\', '/', $relativePath . '/' . $class->getName() . '.php'); $proxyFileName = $cacheDir . $proxyRelativePath; $dirname = dirname($proxyFileName); if (!file_exists($dirname)) { mkdir($dirname, $this->options['cacheFileMode'], true); } $body = '<?php' . PHP_EOL . $childCode; $isVirtualSystem = strpos($proxyFileName, 'vfs') === 0; file_put_contents($proxyFileName, $body, $isVirtualSystem ? 0 : LOCK_EX); // For cache files we don't want executable bits by default chmod($proxyFileName, $this->options['cacheFileMode'] & (~0111)); return 'include_once AOP_CACHE_DIR . ' . var_export($cacheDirSuffix . $proxyRelativePath, true) . ';'; }
[ "private", "function", "saveProxyToCache", "(", "ReflectionClass", "$", "class", ",", "string", "$", "childCode", ")", ":", "string", "{", "static", "$", "cacheDirSuffix", "=", "'/_proxies/'", ";", "$", "cacheDir", "=", "$", "this", "->", "cachePathManager", "...
Save AOP proxy to the separate file anr returns the php source code for inclusion
[ "Save", "AOP", "proxy", "to", "the", "separate", "file", "anr", "returns", "the", "php", "source", "code", "for", "inclusion" ]
train
https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Instrument/Transformer/WeavingTransformer.php#L280-L301
goaop/framework
src/Instrument/Transformer/WeavingTransformer.php
WeavingTransformer.loadAndRegisterAspects
private function loadAndRegisterAspects(array $unloadedAspects): void { foreach ($unloadedAspects as $unloadedAspect) { $this->aspectLoader->loadAndRegister($unloadedAspect); } }
php
private function loadAndRegisterAspects(array $unloadedAspects): void { foreach ($unloadedAspects as $unloadedAspect) { $this->aspectLoader->loadAndRegister($unloadedAspect); } }
[ "private", "function", "loadAndRegisterAspects", "(", "array", "$", "unloadedAspects", ")", ":", "void", "{", "foreach", "(", "$", "unloadedAspects", "as", "$", "unloadedAspect", ")", "{", "$", "this", "->", "aspectLoader", "->", "loadAndRegister", "(", "$", "...
Utility method to load and register unloaded aspects @param array $unloadedAspects List of unloaded aspects
[ "Utility", "method", "to", "load", "and", "register", "unloaded", "aspects" ]
train
https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Instrument/Transformer/WeavingTransformer.php#L308-L313
goaop/framework
src/Core/IntroductionAspectExtension.php
IntroductionAspectExtension.supports
public function supports(Aspect $aspect, $reflection, $metaInformation = null): bool { return ($metaInformation instanceof Annotation\DeclareParents) || ($metaInformation instanceof Annotation\DeclareError); }
php
public function supports(Aspect $aspect, $reflection, $metaInformation = null): bool { return ($metaInformation instanceof Annotation\DeclareParents) || ($metaInformation instanceof Annotation\DeclareError); }
[ "public", "function", "supports", "(", "Aspect", "$", "aspect", ",", "$", "reflection", ",", "$", "metaInformation", "=", "null", ")", ":", "bool", "{", "return", "(", "$", "metaInformation", "instanceof", "Annotation", "\\", "DeclareParents", ")", "||", "("...
Checks if loader is able to handle specific point of aspect @param Aspect $aspect Instance of aspect @param mixed|\ReflectionClass|\ReflectionMethod|\ReflectionProperty $reflection Reflection of point @param mixed|null $metaInformation Additional meta-information, e.g. annotation for method @return boolean true if extension is able to create an advisor from reflection and metaInformation
[ "Checks", "if", "loader", "is", "able", "to", "handle", "specific", "point", "of", "aspect" ]
train
https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Core/IntroductionAspectExtension.php#L54-L59
goaop/framework
src/Core/IntroductionAspectExtension.php
IntroductionAspectExtension.load
public function load(Aspect $aspect, Reflector $reflection, $metaInformation = null): array { $loadedItems = []; $pointcut = $this->parsePointcut($aspect, $reflection, $metaInformation->value); $propertyId = $reflection->class . '->' . $reflection->name; switch (true) { case ($metaInformation instanceof Annotation\DeclareParents): $implement = $metaInformation->defaultImpl; $interface = $metaInformation->interface; $advice = new Framework\TraitIntroductionInfo($implement, $interface); $advisor = new Support\DeclareParentsAdvisor($pointcut->getClassFilter(), $advice); $loadedItems[$propertyId] = $advisor; break; case (($metaInformation instanceof Annotation\DeclareError) && ($pointcut instanceof Pointcut)): $reflection->setAccessible(true); $message = $reflection->getValue($aspect); $level = $metaInformation->level; $advice = new Framework\DeclareErrorInterceptor($message, $level, $metaInformation->value); $loadedItems[$propertyId] = new Support\DefaultPointcutAdvisor($pointcut, $advice); break; default: throw new UnexpectedValueException('Unsupported pointcut class: ' . get_class($pointcut)); } return $loadedItems; }
php
public function load(Aspect $aspect, Reflector $reflection, $metaInformation = null): array { $loadedItems = []; $pointcut = $this->parsePointcut($aspect, $reflection, $metaInformation->value); $propertyId = $reflection->class . '->' . $reflection->name; switch (true) { case ($metaInformation instanceof Annotation\DeclareParents): $implement = $metaInformation->defaultImpl; $interface = $metaInformation->interface; $advice = new Framework\TraitIntroductionInfo($implement, $interface); $advisor = new Support\DeclareParentsAdvisor($pointcut->getClassFilter(), $advice); $loadedItems[$propertyId] = $advisor; break; case (($metaInformation instanceof Annotation\DeclareError) && ($pointcut instanceof Pointcut)): $reflection->setAccessible(true); $message = $reflection->getValue($aspect); $level = $metaInformation->level; $advice = new Framework\DeclareErrorInterceptor($message, $level, $metaInformation->value); $loadedItems[$propertyId] = new Support\DefaultPointcutAdvisor($pointcut, $advice); break; default: throw new UnexpectedValueException('Unsupported pointcut class: ' . get_class($pointcut)); } return $loadedItems; }
[ "public", "function", "load", "(", "Aspect", "$", "aspect", ",", "Reflector", "$", "reflection", ",", "$", "metaInformation", "=", "null", ")", ":", "array", "{", "$", "loadedItems", "=", "[", "]", ";", "$", "pointcut", "=", "$", "this", "->", "parsePo...
Loads definition from specific point of aspect into the container @param Aspect $aspect Instance of aspect @param Reflector|ReflectionProperty $reflection Reflection of point @param mixed|null $metaInformation Additional meta-information @throws UnexpectedValueException @return Pointcut[]|Advisor[]
[ "Loads", "definition", "from", "specific", "point", "of", "aspect", "into", "the", "container" ]
train
https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Core/IntroductionAspectExtension.php#L72-L100
goaop/framework
src/Aop/Pointcut/PointcutClassFilterTrait.php
PointcutClassFilterTrait.getClassFilter
public function getClassFilter(): PointFilter { if ($this->classFilter === null) { $this->classFilter = TruePointFilter::getInstance(); } return $this->classFilter; }
php
public function getClassFilter(): PointFilter { if ($this->classFilter === null) { $this->classFilter = TruePointFilter::getInstance(); } return $this->classFilter; }
[ "public", "function", "getClassFilter", "(", ")", ":", "PointFilter", "{", "if", "(", "$", "this", "->", "classFilter", "===", "null", ")", "{", "$", "this", "->", "classFilter", "=", "TruePointFilter", "::", "getInstance", "(", ")", ";", "}", "return", ...
Return the class filter for this pointcut.
[ "Return", "the", "class", "filter", "for", "this", "pointcut", "." ]
train
https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Aop/Pointcut/PointcutClassFilterTrait.php#L42-L49
goaop/framework
src/Aop/Framework/ReflectionFunctionInvocation.php
ReflectionFunctionInvocation.proceed
public function proceed() { if (isset($this->advices[$this->current])) { $currentInterceptor = $this->advices[$this->current++]; return $currentInterceptor->invoke($this); } return $this->reflectionFunction->invokeArgs($this->arguments); }
php
public function proceed() { if (isset($this->advices[$this->current])) { $currentInterceptor = $this->advices[$this->current++]; return $currentInterceptor->invoke($this); } return $this->reflectionFunction->invokeArgs($this->arguments); }
[ "public", "function", "proceed", "(", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "advices", "[", "$", "this", "->", "current", "]", ")", ")", "{", "$", "currentInterceptor", "=", "$", "this", "->", "advices", "[", "$", "this", "->", "cur...
Invokes original function and return result from it @return mixed
[ "Invokes", "original", "function", "and", "return", "result", "from", "it" ]
train
https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Aop/Framework/ReflectionFunctionInvocation.php#L49-L58
goaop/framework
src/Instrument/Transformer/MagicConstantTransformer.php
MagicConstantTransformer.transform
public function transform(StreamMetaData $metadata): string { $this->replaceMagicDirFileConstants($metadata); $this->wrapReflectionGetFileName($metadata); // We should always vote abstain, because if there is only changes for magic constants, we can drop them return self::RESULT_ABSTAIN; }
php
public function transform(StreamMetaData $metadata): string { $this->replaceMagicDirFileConstants($metadata); $this->wrapReflectionGetFileName($metadata); // We should always vote abstain, because if there is only changes for magic constants, we can drop them return self::RESULT_ABSTAIN; }
[ "public", "function", "transform", "(", "StreamMetaData", "$", "metadata", ")", ":", "string", "{", "$", "this", "->", "replaceMagicDirFileConstants", "(", "$", "metadata", ")", ";", "$", "this", "->", "wrapReflectionGetFileName", "(", "$", "metadata", ")", ";...
This method may transform the supplied source and return a new replacement for it @return string See RESULT_XXX constants in the interface
[ "This", "method", "may", "transform", "the", "supplied", "source", "and", "return", "a", "new", "replacement", "for", "it" ]
train
https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Instrument/Transformer/MagicConstantTransformer.php#L58-L65
goaop/framework
src/Instrument/Transformer/MagicConstantTransformer.php
MagicConstantTransformer.resolveFileName
public static function resolveFileName(string $fileName): string { $suffix = '.php'; $pathParts = explode($suffix, str_replace( [self::$rewriteToPath, DIRECTORY_SEPARATOR . '_proxies'], [self::$rootPath, ''], $fileName )); // throw away namespaced path from actual filename return $pathParts[0] . $suffix; }
php
public static function resolveFileName(string $fileName): string { $suffix = '.php'; $pathParts = explode($suffix, str_replace( [self::$rewriteToPath, DIRECTORY_SEPARATOR . '_proxies'], [self::$rootPath, ''], $fileName )); // throw away namespaced path from actual filename return $pathParts[0] . $suffix; }
[ "public", "static", "function", "resolveFileName", "(", "string", "$", "fileName", ")", ":", "string", "{", "$", "suffix", "=", "'.php'", ";", "$", "pathParts", "=", "explode", "(", "$", "suffix", ",", "str_replace", "(", "[", "self", "::", "$", "rewrite...
Resolves file name from the cache directory to the real application root dir
[ "Resolves", "file", "name", "from", "the", "cache", "directory", "to", "the", "real", "application", "root", "dir" ]
train
https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Instrument/Transformer/MagicConstantTransformer.php#L70-L80
goaop/framework
src/Instrument/Transformer/MagicConstantTransformer.php
MagicConstantTransformer.wrapReflectionGetFileName
private function wrapReflectionGetFileName(StreamMetaData $metadata): void { $methodCallFinder = new NodeFinderVisitor([MethodCall::class]); $traverser = new NodeTraverser(); $traverser->addVisitor($methodCallFinder); $traverser->traverse($metadata->syntaxTree); /** @var MethodCall[] $methodCalls */ $methodCalls = $methodCallFinder->getFoundNodes(); foreach ($methodCalls as $methodCallNode) { if (($methodCallNode->name instanceof Identifier) && ($methodCallNode->name->toString() === 'getFileName')) { $startPosition = $methodCallNode->getAttribute('startTokenPos'); $endPosition = $methodCallNode->getAttribute('endTokenPos'); $expressionPrefix = '\\' . __CLASS__ . '::resolveFileName('; $metadata->tokenStream[$startPosition][1] = $expressionPrefix . $metadata->tokenStream[$startPosition][1]; $metadata->tokenStream[$endPosition][1] .= ')'; } } }
php
private function wrapReflectionGetFileName(StreamMetaData $metadata): void { $methodCallFinder = new NodeFinderVisitor([MethodCall::class]); $traverser = new NodeTraverser(); $traverser->addVisitor($methodCallFinder); $traverser->traverse($metadata->syntaxTree); /** @var MethodCall[] $methodCalls */ $methodCalls = $methodCallFinder->getFoundNodes(); foreach ($methodCalls as $methodCallNode) { if (($methodCallNode->name instanceof Identifier) && ($methodCallNode->name->toString() === 'getFileName')) { $startPosition = $methodCallNode->getAttribute('startTokenPos'); $endPosition = $methodCallNode->getAttribute('endTokenPos'); $expressionPrefix = '\\' . __CLASS__ . '::resolveFileName('; $metadata->tokenStream[$startPosition][1] = $expressionPrefix . $metadata->tokenStream[$startPosition][1]; $metadata->tokenStream[$endPosition][1] .= ')'; } } }
[ "private", "function", "wrapReflectionGetFileName", "(", "StreamMetaData", "$", "metadata", ")", ":", "void", "{", "$", "methodCallFinder", "=", "new", "NodeFinderVisitor", "(", "[", "MethodCall", "::", "class", "]", ")", ";", "$", "traverser", "=", "new", "No...
Wraps all possible getFileName() methods from ReflectionFile
[ "Wraps", "all", "possible", "getFileName", "()", "methods", "from", "ReflectionFile" ]
train
https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Instrument/Transformer/MagicConstantTransformer.php#L85-L105
goaop/framework
src/Instrument/Transformer/MagicConstantTransformer.php
MagicConstantTransformer.replaceMagicDirFileConstants
private function replaceMagicDirFileConstants(StreamMetaData $metadata): void { $magicConstFinder = new NodeFinderVisitor([Dir::class, File::class]); $traverser = new NodeTraverser(); $traverser->addVisitor($magicConstFinder); $traverser->traverse($metadata->syntaxTree); /** @var MagicConst[] $magicConstants */ $magicConstants = $magicConstFinder->getFoundNodes(); $magicFileValue = $metadata->uri; $magicDirValue = dirname($magicFileValue); foreach ($magicConstants as $magicConstantNode) { $tokenPosition = $magicConstantNode->getAttribute('startTokenPos'); $replacement = $magicConstantNode instanceof Dir ? $magicDirValue : $magicFileValue; $metadata->tokenStream[$tokenPosition][1] = "'{$replacement}'"; } }
php
private function replaceMagicDirFileConstants(StreamMetaData $metadata): void { $magicConstFinder = new NodeFinderVisitor([Dir::class, File::class]); $traverser = new NodeTraverser(); $traverser->addVisitor($magicConstFinder); $traverser->traverse($metadata->syntaxTree); /** @var MagicConst[] $magicConstants */ $magicConstants = $magicConstFinder->getFoundNodes(); $magicFileValue = $metadata->uri; $magicDirValue = dirname($magicFileValue); foreach ($magicConstants as $magicConstantNode) { $tokenPosition = $magicConstantNode->getAttribute('startTokenPos'); $replacement = $magicConstantNode instanceof Dir ? $magicDirValue : $magicFileValue; $metadata->tokenStream[$tokenPosition][1] = "'{$replacement}'"; } }
[ "private", "function", "replaceMagicDirFileConstants", "(", "StreamMetaData", "$", "metadata", ")", ":", "void", "{", "$", "magicConstFinder", "=", "new", "NodeFinderVisitor", "(", "[", "Dir", "::", "class", ",", "File", "::", "class", "]", ")", ";", "$", "t...
Replaces all magic __DIR__ and __FILE__ constants in the file with calculated value
[ "Replaces", "all", "magic", "__DIR__", "and", "__FILE__", "constants", "in", "the", "file", "with", "calculated", "value" ]
train
https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Instrument/Transformer/MagicConstantTransformer.php#L110-L127
goaop/framework
src/Aop/Support/ReturnTypeFilter.php
ReturnTypeFilter.matches
public function matches($functionLike, $context = null, $instance = null, array $arguments = null): bool { if (!$functionLike instanceof ReflectionFunctionAbstract) { return false; } if (!$functionLike->hasReturnType()) { return false; } $returnType = (string) $functionLike->getReturnType(); return ($returnType === $this->typeName) || (bool) preg_match("/^(?:{$this->regexp})$/", $returnType); }
php
public function matches($functionLike, $context = null, $instance = null, array $arguments = null): bool { if (!$functionLike instanceof ReflectionFunctionAbstract) { return false; } if (!$functionLike->hasReturnType()) { return false; } $returnType = (string) $functionLike->getReturnType(); return ($returnType === $this->typeName) || (bool) preg_match("/^(?:{$this->regexp})$/", $returnType); }
[ "public", "function", "matches", "(", "$", "functionLike", ",", "$", "context", "=", "null", ",", "$", "instance", "=", "null", ",", "array", "$", "arguments", "=", "null", ")", ":", "bool", "{", "if", "(", "!", "$", "functionLike", "instanceof", "Refl...
{@inheritdoc}
[ "{" ]
train
https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Aop/Support/ReturnTypeFilter.php#L52-L65
goaop/framework
src/Instrument/Transformer/NodeFinderVisitor.php
NodeFinderVisitor.enterNode
public function enterNode(Node $node) { foreach ($this->searchNodes as $nodeClassName) { if ($node instanceof $nodeClassName) { $this->foundNodes[] = $node; } } return null; }
php
public function enterNode(Node $node) { foreach ($this->searchNodes as $nodeClassName) { if ($node instanceof $nodeClassName) { $this->foundNodes[] = $node; } } return null; }
[ "public", "function", "enterNode", "(", "Node", "$", "node", ")", "{", "foreach", "(", "$", "this", "->", "searchNodes", "as", "$", "nodeClassName", ")", "{", "if", "(", "$", "node", "instanceof", "$", "nodeClassName", ")", "{", "$", "this", "->", "fou...
Called when entering a node. Return value semantics: * null => $node stays as-is * NodeTraverser::DONT_TRAVERSE_CHILDREN => Children of $node are not traversed. $node stays as-is * NodeTraverser::STOP_TRAVERSAL => Traversal is aborted. $node stays as-is * otherwise => $node is set to the return value @param Node $node Node @return null|int|Node Node
[ "Called", "when", "entering", "a", "node", "." ]
train
https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Instrument/Transformer/NodeFinderVisitor.php#L93-L102
spatie/once
src/Cache.php
Cache.has
public static function has($object, string $backtraceHash): bool { $objectHash = static::objectHash($object); if (! isset(static::$values[$objectHash])) { return false; } return array_key_exists($backtraceHash, static::$values[$objectHash]); }
php
public static function has($object, string $backtraceHash): bool { $objectHash = static::objectHash($object); if (! isset(static::$values[$objectHash])) { return false; } return array_key_exists($backtraceHash, static::$values[$objectHash]); }
[ "public", "static", "function", "has", "(", "$", "object", ",", "string", "$", "backtraceHash", ")", ":", "bool", "{", "$", "objectHash", "=", "static", "::", "objectHash", "(", "$", "object", ")", ";", "if", "(", "!", "isset", "(", "static", "::", "...
Determine if a value exists for a given object / hash. @param mixed $object @param string $backtraceHash @return bool
[ "Determine", "if", "a", "value", "exists", "for", "a", "given", "object", "/", "hash", "." ]
train
https://github.com/spatie/once/blob/05ce42ec46a2039a952e761588d5eab5662b4e11/src/Cache.php#L18-L27
spatie/once
src/Cache.php
Cache.set
public static function set($object, string $backtraceHash, $value) { static::addDestroyListener($object, $backtraceHash); static::$values[static::objectHash($object)][$backtraceHash] = $value; }
php
public static function set($object, string $backtraceHash, $value) { static::addDestroyListener($object, $backtraceHash); static::$values[static::objectHash($object)][$backtraceHash] = $value; }
[ "public", "static", "function", "set", "(", "$", "object", ",", "string", "$", "backtraceHash", ",", "$", "value", ")", "{", "static", "::", "addDestroyListener", "(", "$", "object", ",", "$", "backtraceHash", ")", ";", "static", "::", "$", "values", "["...
Set a cached value for an object / hash. @param mixed $object @param string $backtraceHash @param mixed $value
[ "Set", "a", "cached", "value", "for", "an", "object", "/", "hash", "." ]
train
https://github.com/spatie/once/blob/05ce42ec46a2039a952e761588d5eab5662b4e11/src/Cache.php#L49-L54
schmittjoh/parser-lib
src/JMS/Parser/AbstractParser.php
AbstractParser.parse
public function parse($str, $context = null) { $this->lexer->setInput($str); $this->context = $context; $rs = $this->parseInternal(); if (null !== $this->lexer->next) { $this->syntaxError('end of input'); } return $rs; }
php
public function parse($str, $context = null) { $this->lexer->setInput($str); $this->context = $context; $rs = $this->parseInternal(); if (null !== $this->lexer->next) { $this->syntaxError('end of input'); } return $rs; }
[ "public", "function", "parse", "(", "$", "str", ",", "$", "context", "=", "null", ")", "{", "$", "this", "->", "lexer", "->", "setInput", "(", "$", "str", ")", ";", "$", "this", "->", "context", "=", "$", "context", ";", "$", "rs", "=", "$", "t...
Parses the given input. @param string $str @param string $context parsing context (allows to produce better error messages) @return mixed
[ "Parses", "the", "given", "input", "." ]
train
https://github.com/schmittjoh/parser-lib/blob/6067cc609074ae215b96dc51047affee65f77b0f/src/JMS/Parser/AbstractParser.php#L44-L56
schmittjoh/parser-lib
src/JMS/Parser/AbstractParser.php
AbstractParser.match
protected function match($type) { if ( ! $this->lexer->isNext($type)) { $this->syntaxError($this->lexer->getName($type)); } $this->lexer->moveNext(); return $this->lexer->token[0]; }
php
protected function match($type) { if ( ! $this->lexer->isNext($type)) { $this->syntaxError($this->lexer->getName($type)); } $this->lexer->moveNext(); return $this->lexer->token[0]; }
[ "protected", "function", "match", "(", "$", "type", ")", "{", "if", "(", "!", "$", "this", "->", "lexer", "->", "isNext", "(", "$", "type", ")", ")", "{", "$", "this", "->", "syntaxError", "(", "$", "this", "->", "lexer", "->", "getName", "(", "$...
Matches a token, and returns its value. @param integer $type @return mixed the value of the matched token
[ "Matches", "a", "token", "and", "returns", "its", "value", "." ]
train
https://github.com/schmittjoh/parser-lib/blob/6067cc609074ae215b96dc51047affee65f77b0f/src/JMS/Parser/AbstractParser.php#L70-L79
schmittjoh/parser-lib
src/JMS/Parser/AbstractParser.php
AbstractParser.matchAny
protected function matchAny(array $types) { if ( ! $this->lexer->isNextAny($types)) { $this->syntaxError('any of '.implode(' or ', array_map(array($this->lexer, 'getName'), $types))); } $this->lexer->moveNext(); return $this->lexer->token[0]; }
php
protected function matchAny(array $types) { if ( ! $this->lexer->isNextAny($types)) { $this->syntaxError('any of '.implode(' or ', array_map(array($this->lexer, 'getName'), $types))); } $this->lexer->moveNext(); return $this->lexer->token[0]; }
[ "protected", "function", "matchAny", "(", "array", "$", "types", ")", "{", "if", "(", "!", "$", "this", "->", "lexer", "->", "isNextAny", "(", "$", "types", ")", ")", "{", "$", "this", "->", "syntaxError", "(", "'any of '", ".", "implode", "(", "' or...
Matches any of the passed tokens, and returns the matched token's value. @param array<integer> $types @return mixed
[ "Matches", "any", "of", "the", "passed", "tokens", "and", "returns", "the", "matched", "token", "s", "value", "." ]
train
https://github.com/schmittjoh/parser-lib/blob/6067cc609074ae215b96dc51047affee65f77b0f/src/JMS/Parser/AbstractParser.php#L88-L97
schmittjoh/parser-lib
src/JMS/Parser/AbstractParser.php
AbstractParser.syntaxError
protected function syntaxError($expectedDesc, $actualToken = null) { if (null === $actualToken) { $actualToken = $this->lexer->next; } if (null === $actualToken) { $actualDesc = 'end of input'; } else if ($actualToken[1] === 0) { $actualDesc = sprintf('"%s" of type %s at beginning of input', $actualToken[0], $this->lexer->getName($actualToken[2])); } else { $actualDesc = sprintf('"%s" of type %s at position %d (0-based)', $actualToken[0], $this->lexer->getName($actualToken[2]), $actualToken[1]); } $ex = new SyntaxErrorException(sprintf('Expected %s, but got %s%s.', $expectedDesc, $actualDesc, $this->context ? ' '.$this->context : '')); if (null !== $actualToken) { $ex->setActualToken($actualToken); } if (null !== $this->context) { $ex->setContext($this->context); } throw $ex; }
php
protected function syntaxError($expectedDesc, $actualToken = null) { if (null === $actualToken) { $actualToken = $this->lexer->next; } if (null === $actualToken) { $actualDesc = 'end of input'; } else if ($actualToken[1] === 0) { $actualDesc = sprintf('"%s" of type %s at beginning of input', $actualToken[0], $this->lexer->getName($actualToken[2])); } else { $actualDesc = sprintf('"%s" of type %s at position %d (0-based)', $actualToken[0], $this->lexer->getName($actualToken[2]), $actualToken[1]); } $ex = new SyntaxErrorException(sprintf('Expected %s, but got %s%s.', $expectedDesc, $actualDesc, $this->context ? ' '.$this->context : '')); if (null !== $actualToken) { $ex->setActualToken($actualToken); } if (null !== $this->context) { $ex->setContext($this->context); } throw $ex; }
[ "protected", "function", "syntaxError", "(", "$", "expectedDesc", ",", "$", "actualToken", "=", "null", ")", "{", "if", "(", "null", "===", "$", "actualToken", ")", "{", "$", "actualToken", "=", "$", "this", "->", "lexer", "->", "next", ";", "}", "if",...
Raises a syntax error exception. @param string $expectedDesc A human understandable explanation what was expected @param array $actualToken The token that was found. If not given, next token will be assumed.
[ "Raises", "a", "syntax", "error", "exception", "." ]
train
https://github.com/schmittjoh/parser-lib/blob/6067cc609074ae215b96dc51047affee65f77b0f/src/JMS/Parser/AbstractParser.php#L105-L127
schmittjoh/parser-lib
src/JMS/Parser/AbstractLexer.php
AbstractLexer.getName
public function getName($type) { $ref = new \ReflectionClass($this); foreach ($ref->getConstants() as $name => $value) { if ($value === $type) { return $name; } } throw new \InvalidArgumentException(sprintf('There is no token with value %s.', json_encode($type))); }
php
public function getName($type) { $ref = new \ReflectionClass($this); foreach ($ref->getConstants() as $name => $value) { if ($value === $type) { return $name; } } throw new \InvalidArgumentException(sprintf('There is no token with value %s.', json_encode($type))); }
[ "public", "function", "getName", "(", "$", "type", ")", "{", "$", "ref", "=", "new", "\\", "ReflectionClass", "(", "$", "this", ")", ";", "foreach", "(", "$", "ref", "->", "getConstants", "(", ")", "as", "$", "name", "=>", "$", "value", ")", "{", ...
Returns the name of the given token. @param integer $type @return string
[ "Returns", "the", "name", "of", "the", "given", "token", "." ]
train
https://github.com/schmittjoh/parser-lib/blob/6067cc609074ae215b96dc51047affee65f77b0f/src/JMS/Parser/AbstractLexer.php#L42-L52
schmittjoh/parser-lib
src/JMS/Parser/AbstractLexer.php
AbstractLexer.moveNext
public function moveNext() { $this->peek = 0; $this->token = $this->next; $this->next = isset($this->tokens[++$this->i]) ? $this->tokens[$this->i] : null; return null !== $this->next; }
php
public function moveNext() { $this->peek = 0; $this->token = $this->next; $this->next = isset($this->tokens[++$this->i]) ? $this->tokens[$this->i] : null; return null !== $this->next; }
[ "public", "function", "moveNext", "(", ")", "{", "$", "this", "->", "peek", "=", "0", ";", "$", "this", "->", "token", "=", "$", "this", "->", "next", ";", "$", "this", "->", "next", "=", "isset", "(", "$", "this", "->", "tokens", "[", "++", "$...
Moves the pointer one token forward. @return boolean if we have not yet reached the end of the input
[ "Moves", "the", "pointer", "one", "token", "forward", "." ]
train
https://github.com/schmittjoh/parser-lib/blob/6067cc609074ae215b96dc51047affee65f77b0f/src/JMS/Parser/AbstractLexer.php#L80-L87
schmittjoh/parser-lib
src/JMS/Parser/AbstractLexer.php
AbstractLexer.skipUntil
public function skipUntil($type) { while ( ! $this->isNext($type) && $this->moveNext()); if ( ! $this->isNext($type)) { throw new \RuntimeException(sprintf('Could not find the token %s.', $this->getName($type))); } }
php
public function skipUntil($type) { while ( ! $this->isNext($type) && $this->moveNext()); if ( ! $this->isNext($type)) { throw new \RuntimeException(sprintf('Could not find the token %s.', $this->getName($type))); } }
[ "public", "function", "skipUntil", "(", "$", "type", ")", "{", "while", "(", "!", "$", "this", "->", "isNext", "(", "$", "type", ")", "&&", "$", "this", "->", "moveNext", "(", ")", ")", ";", "if", "(", "!", "$", "this", "->", "isNext", "(", "$"...
Skips the token stream until a token of the given type. @param integer $type @throws \RuntimeException When the token is not found
[ "Skips", "the", "token", "stream", "until", "a", "token", "of", "the", "given", "type", "." ]
train
https://github.com/schmittjoh/parser-lib/blob/6067cc609074ae215b96dc51047affee65f77b0f/src/JMS/Parser/AbstractLexer.php#L96-L103
schmittjoh/parser-lib
src/JMS/Parser/AbstractLexer.php
AbstractLexer.isNextAny
public function isNextAny(array $types) { if (null === $this->next) { return false; } foreach ($types as $type) { if ($type === $this->next[2]) { return true; } } return false; }
php
public function isNextAny(array $types) { if (null === $this->next) { return false; } foreach ($types as $type) { if ($type === $this->next[2]) { return true; } } return false; }
[ "public", "function", "isNextAny", "(", "array", "$", "types", ")", "{", "if", "(", "null", "===", "$", "this", "->", "next", ")", "{", "return", "false", ";", "}", "foreach", "(", "$", "types", "as", "$", "type", ")", "{", "if", "(", "$", "type"...
@param array<integer> $types @return boolean
[ "@param", "array<integer", ">", "$types" ]
train
https://github.com/schmittjoh/parser-lib/blob/6067cc609074ae215b96dc51047affee65f77b0f/src/JMS/Parser/AbstractLexer.php#L120-L133
alterphp/EasyAdminExtensionBundle
src/EventListener/PostQueryBuilderSubscriber.php
PostQueryBuilderSubscriber.onPostListQueryBuilder
public function onPostListQueryBuilder(GenericEvent $event) { $queryBuilder = $event->getArgument('query_builder'); // Request filters if ($event->hasArgument('request')) { $this->applyRequestFilters($queryBuilder, $event->getArgument('request')->get('filters', [])); } // List form filters if ($event->hasArgument('entity')) { $entityConfig = $event->getArgument('entity'); if (isset($entityConfig['list']['form_filters'])) { $listFormFiltersForm = $this->listFormFiltersHelper->getListFormFilters($entityConfig['list']['form_filters']); if ($listFormFiltersForm->isSubmitted() && $listFormFiltersForm->isValid()) { $this->applyFormFilters($queryBuilder, $listFormFiltersForm->getData()); } } } }
php
public function onPostListQueryBuilder(GenericEvent $event) { $queryBuilder = $event->getArgument('query_builder'); // Request filters if ($event->hasArgument('request')) { $this->applyRequestFilters($queryBuilder, $event->getArgument('request')->get('filters', [])); } // List form filters if ($event->hasArgument('entity')) { $entityConfig = $event->getArgument('entity'); if (isset($entityConfig['list']['form_filters'])) { $listFormFiltersForm = $this->listFormFiltersHelper->getListFormFilters($entityConfig['list']['form_filters']); if ($listFormFiltersForm->isSubmitted() && $listFormFiltersForm->isValid()) { $this->applyFormFilters($queryBuilder, $listFormFiltersForm->getData()); } } } }
[ "public", "function", "onPostListQueryBuilder", "(", "GenericEvent", "$", "event", ")", "{", "$", "queryBuilder", "=", "$", "event", "->", "getArgument", "(", "'query_builder'", ")", ";", "// Request filters", "if", "(", "$", "event", "->", "hasArgument", "(", ...
Called on POST_LIST_QUERY_BUILDER event. @param GenericEvent $event
[ "Called", "on", "POST_LIST_QUERY_BUILDER", "event", "." ]
train
https://github.com/alterphp/EasyAdminExtensionBundle/blob/c9e8cc3530ba053ae22edde8ca3d14d1984936b3/src/EventListener/PostQueryBuilderSubscriber.php#L48-L67
alterphp/EasyAdminExtensionBundle
src/EventListener/PostQueryBuilderSubscriber.php
PostQueryBuilderSubscriber.onPostSearchQueryBuilder
public function onPostSearchQueryBuilder(GenericEvent $event) { $queryBuilder = $event->getArgument('query_builder'); if ($event->hasArgument('request')) { $this->applyRequestFilters($queryBuilder, $event->getArgument('request')->get('filters', [])); } }
php
public function onPostSearchQueryBuilder(GenericEvent $event) { $queryBuilder = $event->getArgument('query_builder'); if ($event->hasArgument('request')) { $this->applyRequestFilters($queryBuilder, $event->getArgument('request')->get('filters', [])); } }
[ "public", "function", "onPostSearchQueryBuilder", "(", "GenericEvent", "$", "event", ")", "{", "$", "queryBuilder", "=", "$", "event", "->", "getArgument", "(", "'query_builder'", ")", ";", "if", "(", "$", "event", "->", "hasArgument", "(", "'request'", ")", ...
Called on POST_SEARCH_QUERY_BUILDER event. @param GenericEvent $event
[ "Called", "on", "POST_SEARCH_QUERY_BUILDER", "event", "." ]
train
https://github.com/alterphp/EasyAdminExtensionBundle/blob/c9e8cc3530ba053ae22edde8ca3d14d1984936b3/src/EventListener/PostQueryBuilderSubscriber.php#L74-L81
alterphp/EasyAdminExtensionBundle
src/EventListener/PostQueryBuilderSubscriber.php
PostQueryBuilderSubscriber.applyRequestFilters
protected function applyRequestFilters(QueryBuilder $queryBuilder, array $filters = []) { foreach ($filters as $field => $value) { // Empty string and numeric keys is considered as "not applied filter" if ('' === $value || \is_int($field)) { continue; } $operator = \is_array($value) ? ListFilter::OPERATOR_IN : ListFilter::OPERATOR_EQUALS; $listFilter = ListFilter::createFromRequest($field, $operator, $value); $this->filterQueryBuilder($queryBuilder, $field, $listFilter); } }
php
protected function applyRequestFilters(QueryBuilder $queryBuilder, array $filters = []) { foreach ($filters as $field => $value) { // Empty string and numeric keys is considered as "not applied filter" if ('' === $value || \is_int($field)) { continue; } $operator = \is_array($value) ? ListFilter::OPERATOR_IN : ListFilter::OPERATOR_EQUALS; $listFilter = ListFilter::createFromRequest($field, $operator, $value); $this->filterQueryBuilder($queryBuilder, $field, $listFilter); } }
[ "protected", "function", "applyRequestFilters", "(", "QueryBuilder", "$", "queryBuilder", ",", "array", "$", "filters", "=", "[", "]", ")", "{", "foreach", "(", "$", "filters", "as", "$", "field", "=>", "$", "value", ")", "{", "// Empty string and numeric keys...
Applies request filters on queryBuilder. @param QueryBuilder $queryBuilder @param array $filters
[ "Applies", "request", "filters", "on", "queryBuilder", "." ]
train
https://github.com/alterphp/EasyAdminExtensionBundle/blob/c9e8cc3530ba053ae22edde8ca3d14d1984936b3/src/EventListener/PostQueryBuilderSubscriber.php#L89-L102
alterphp/EasyAdminExtensionBundle
src/EventListener/PostQueryBuilderSubscriber.php
PostQueryBuilderSubscriber.applyFormFilters
protected function applyFormFilters(QueryBuilder $queryBuilder, array $filters = []) { foreach ($filters as $field => $listFilter) { if (null === $listFilter) { continue; } $this->filterQueryBuilder($queryBuilder, $field, $listFilter); } }
php
protected function applyFormFilters(QueryBuilder $queryBuilder, array $filters = []) { foreach ($filters as $field => $listFilter) { if (null === $listFilter) { continue; } $this->filterQueryBuilder($queryBuilder, $field, $listFilter); } }
[ "protected", "function", "applyFormFilters", "(", "QueryBuilder", "$", "queryBuilder", ",", "array", "$", "filters", "=", "[", "]", ")", "{", "foreach", "(", "$", "filters", "as", "$", "field", "=>", "$", "listFilter", ")", "{", "if", "(", "null", "===",...
Applies form filters on queryBuilder. @param QueryBuilder $queryBuilder @param array $filters
[ "Applies", "form", "filters", "on", "queryBuilder", "." ]
train
https://github.com/alterphp/EasyAdminExtensionBundle/blob/c9e8cc3530ba053ae22edde8ca3d14d1984936b3/src/EventListener/PostQueryBuilderSubscriber.php#L110-L119
alterphp/EasyAdminExtensionBundle
src/EventListener/PostQueryBuilderSubscriber.php
PostQueryBuilderSubscriber.filterQueryBuilder
protected function filterQueryBuilder(QueryBuilder $queryBuilder, string $field, ListFilter $listFilter) { $value = $this->filterEasyadminAutocompleteValue($listFilter->getValue()); // Empty string and numeric keys is considered as "not applied filter" if (null === $value || '' === $value || \is_int($field)) { return; } // Add root entity alias if none provided $queryField = $listFilter->getProperty(); if (false === \strpos($queryField, '.')) { $queryField = $queryBuilder->getRootAlias().'.'.$queryField; } // Checks if filter is directly appliable on queryBuilder if (!$this->isFilterAppliable($queryBuilder, $queryField)) { return; } $operator = $listFilter->getOperator(); // Sanitize parameter name $parameter = 'form_filter_'.\str_replace('.', '_', $field); switch ($operator) { case ListFilter::OPERATOR_EQUALS: if ('_NULL' === $value) { $queryBuilder->andWhere(\sprintf('%s IS NULL', $queryField)); } elseif ('_NOT_NULL' === $value) { $queryBuilder->andWhere(\sprintf('%s IS NOT NULL', $queryField)); } else { $queryBuilder ->andWhere(\sprintf('%s %s :%s', $queryField, '=', $parameter)) ->setParameter($parameter, $value) ; } break; case ListFilter::OPERATOR_NOT: $queryBuilder ->andWhere(\sprintf('%s %s :%s', $queryField, '!=', $parameter)) ->setParameter($parameter, $value) ; break; case ListFilter::OPERATOR_IN: // Checks that $value is not an empty Traversable if (0 < \count($value)) { $queryBuilder ->andWhere(\sprintf('%s %s (:%s)', $queryField, 'IN', $parameter)) ->setParameter($parameter, $value) ; } break; case ListFilter::OPERATOR_NOTIN: // Checks that $value is not an empty Traversable if (0 < \count($value)) { $queryBuilder ->andWhere(\sprintf('%s %s (:%s)', $queryField, 'NOT IN', $parameter)) ->setParameter($parameter, $value) ; } break; case ListFilter::OPERATOR_GT: $queryBuilder ->andWhere(\sprintf('%s %s :%s', $queryField, '>', $parameter)) ->setParameter($parameter, $value) ; break; case ListFilter::OPERATOR_GTE: $queryBuilder ->andWhere(\sprintf('%s %s :%s', $queryField, '>=', $parameter)) ->setParameter($parameter, $value) ; break; case ListFilter::OPERATOR_LT: $queryBuilder ->andWhere(\sprintf('%s %s :%s', $queryField, '<', $parameter)) ->setParameter($parameter, $value) ; break; case ListFilter::OPERATOR_LTE: $queryBuilder ->andWhere(\sprintf('%s %s :%s', $queryField, '<=', $parameter)) ->setParameter($parameter, $value) ; break; case ListFilter::OPERATOR_LIKE: $queryBuilder ->andWhere(\sprintf('%s %s :%s', $queryField, 'LIKE', $parameter)) ->setParameter($parameter, '%'.$value.'%') ; break; default: throw new \RuntimeException(\sprintf('Operator "%s" is not supported !', $operator)); } }
php
protected function filterQueryBuilder(QueryBuilder $queryBuilder, string $field, ListFilter $listFilter) { $value = $this->filterEasyadminAutocompleteValue($listFilter->getValue()); // Empty string and numeric keys is considered as "not applied filter" if (null === $value || '' === $value || \is_int($field)) { return; } // Add root entity alias if none provided $queryField = $listFilter->getProperty(); if (false === \strpos($queryField, '.')) { $queryField = $queryBuilder->getRootAlias().'.'.$queryField; } // Checks if filter is directly appliable on queryBuilder if (!$this->isFilterAppliable($queryBuilder, $queryField)) { return; } $operator = $listFilter->getOperator(); // Sanitize parameter name $parameter = 'form_filter_'.\str_replace('.', '_', $field); switch ($operator) { case ListFilter::OPERATOR_EQUALS: if ('_NULL' === $value) { $queryBuilder->andWhere(\sprintf('%s IS NULL', $queryField)); } elseif ('_NOT_NULL' === $value) { $queryBuilder->andWhere(\sprintf('%s IS NOT NULL', $queryField)); } else { $queryBuilder ->andWhere(\sprintf('%s %s :%s', $queryField, '=', $parameter)) ->setParameter($parameter, $value) ; } break; case ListFilter::OPERATOR_NOT: $queryBuilder ->andWhere(\sprintf('%s %s :%s', $queryField, '!=', $parameter)) ->setParameter($parameter, $value) ; break; case ListFilter::OPERATOR_IN: // Checks that $value is not an empty Traversable if (0 < \count($value)) { $queryBuilder ->andWhere(\sprintf('%s %s (:%s)', $queryField, 'IN', $parameter)) ->setParameter($parameter, $value) ; } break; case ListFilter::OPERATOR_NOTIN: // Checks that $value is not an empty Traversable if (0 < \count($value)) { $queryBuilder ->andWhere(\sprintf('%s %s (:%s)', $queryField, 'NOT IN', $parameter)) ->setParameter($parameter, $value) ; } break; case ListFilter::OPERATOR_GT: $queryBuilder ->andWhere(\sprintf('%s %s :%s', $queryField, '>', $parameter)) ->setParameter($parameter, $value) ; break; case ListFilter::OPERATOR_GTE: $queryBuilder ->andWhere(\sprintf('%s %s :%s', $queryField, '>=', $parameter)) ->setParameter($parameter, $value) ; break; case ListFilter::OPERATOR_LT: $queryBuilder ->andWhere(\sprintf('%s %s :%s', $queryField, '<', $parameter)) ->setParameter($parameter, $value) ; break; case ListFilter::OPERATOR_LTE: $queryBuilder ->andWhere(\sprintf('%s %s :%s', $queryField, '<=', $parameter)) ->setParameter($parameter, $value) ; break; case ListFilter::OPERATOR_LIKE: $queryBuilder ->andWhere(\sprintf('%s %s :%s', $queryField, 'LIKE', $parameter)) ->setParameter($parameter, '%'.$value.'%') ; break; default: throw new \RuntimeException(\sprintf('Operator "%s" is not supported !', $operator)); } }
[ "protected", "function", "filterQueryBuilder", "(", "QueryBuilder", "$", "queryBuilder", ",", "string", "$", "field", ",", "ListFilter", "$", "listFilter", ")", "{", "$", "value", "=", "$", "this", "->", "filterEasyadminAutocompleteValue", "(", "$", "listFilter", ...
Filters queryBuilder. @param QueryBuilder $queryBuilder @param string $field @param ListFilter $listFilter
[ "Filters", "queryBuilder", "." ]
train
https://github.com/alterphp/EasyAdminExtensionBundle/blob/c9e8cc3530ba053ae22edde8ca3d14d1984936b3/src/EventListener/PostQueryBuilderSubscriber.php#L128-L221
alterphp/EasyAdminExtensionBundle
src/EventListener/PostQueryBuilderSubscriber.php
PostQueryBuilderSubscriber.isFilterAppliable
protected function isFilterAppliable(QueryBuilder $queryBuilder, string $field): bool { $qbClone = clone $queryBuilder; try { $qbClone->andWhere($field.' IS NULL'); // Generating SQL throws a QueryException if using wrong field/association $qbClone->getQuery()->getSQL(); } catch (QueryException $e) { return false; } return true; }
php
protected function isFilterAppliable(QueryBuilder $queryBuilder, string $field): bool { $qbClone = clone $queryBuilder; try { $qbClone->andWhere($field.' IS NULL'); // Generating SQL throws a QueryException if using wrong field/association $qbClone->getQuery()->getSQL(); } catch (QueryException $e) { return false; } return true; }
[ "protected", "function", "isFilterAppliable", "(", "QueryBuilder", "$", "queryBuilder", ",", "string", "$", "field", ")", ":", "bool", "{", "$", "qbClone", "=", "clone", "$", "queryBuilder", ";", "try", "{", "$", "qbClone", "->", "andWhere", "(", "$", "fie...
Checks if filter is directly appliable on queryBuilder. @param QueryBuilder $queryBuilder @param string $field @return bool
[ "Checks", "if", "filter", "is", "directly", "appliable", "on", "queryBuilder", "." ]
train
https://github.com/alterphp/EasyAdminExtensionBundle/blob/c9e8cc3530ba053ae22edde8ca3d14d1984936b3/src/EventListener/PostQueryBuilderSubscriber.php#L240-L254
alterphp/EasyAdminExtensionBundle
src/Security/AdminAuthorizationChecker.php
AdminAuthorizationChecker.checksUserAccess
public function checksUserAccess(array $entityConfig, string $actionName, $subject = null) { if ($this->adminMinimumRole && !$this->authorizationChecker->isGranted($this->adminMinimumRole)) { throw new AccessDeniedException( \sprintf('You must be granted %s role to access admin !', $this->adminMinimumRole) ); } $requiredRole = $this->getRequiredRole($entityConfig, $actionName); if ($requiredRole && !$this->authorizationChecker->isGranted($requiredRole, $subject)) { throw new AccessDeniedException( \sprintf('You must be granted %s role to perform this entity action !', $requiredRole) ); } }
php
public function checksUserAccess(array $entityConfig, string $actionName, $subject = null) { if ($this->adminMinimumRole && !$this->authorizationChecker->isGranted($this->adminMinimumRole)) { throw new AccessDeniedException( \sprintf('You must be granted %s role to access admin !', $this->adminMinimumRole) ); } $requiredRole = $this->getRequiredRole($entityConfig, $actionName); if ($requiredRole && !$this->authorizationChecker->isGranted($requiredRole, $subject)) { throw new AccessDeniedException( \sprintf('You must be granted %s role to perform this entity action !', $requiredRole) ); } }
[ "public", "function", "checksUserAccess", "(", "array", "$", "entityConfig", ",", "string", "$", "actionName", ",", "$", "subject", "=", "null", ")", "{", "if", "(", "$", "this", "->", "adminMinimumRole", "&&", "!", "$", "this", "->", "authorizationChecker",...
Throws an error if user has no access to the entity action. @param array $entityConfig @param string $actionName @param mixed $subject
[ "Throws", "an", "error", "if", "user", "has", "no", "access", "to", "the", "entity", "action", "." ]
train
https://github.com/alterphp/EasyAdminExtensionBundle/blob/c9e8cc3530ba053ae22edde8ca3d14d1984936b3/src/Security/AdminAuthorizationChecker.php#L26-L41
alterphp/EasyAdminExtensionBundle
src/Security/AdminAuthorizationChecker.php
AdminAuthorizationChecker.isEasyAdminGranted
public function isEasyAdminGranted(array $entityConfig, string $actionName, $subject = null) { try { $this->checksUserAccess($entityConfig, $actionName, $subject); } catch (AccessDeniedException $e) { return false; } return true; }
php
public function isEasyAdminGranted(array $entityConfig, string $actionName, $subject = null) { try { $this->checksUserAccess($entityConfig, $actionName, $subject); } catch (AccessDeniedException $e) { return false; } return true; }
[ "public", "function", "isEasyAdminGranted", "(", "array", "$", "entityConfig", ",", "string", "$", "actionName", ",", "$", "subject", "=", "null", ")", "{", "try", "{", "$", "this", "->", "checksUserAccess", "(", "$", "entityConfig", ",", "$", "actionName", ...
Returns user access as boolean, no exception thrown. @param array $entityConfig @param string $actionName @param mixed $subject @return bool
[ "Returns", "user", "access", "as", "boolean", "no", "exception", "thrown", "." ]
train
https://github.com/alterphp/EasyAdminExtensionBundle/blob/c9e8cc3530ba053ae22edde8ca3d14d1984936b3/src/Security/AdminAuthorizationChecker.php#L52-L61
alterphp/EasyAdminExtensionBundle
src/Form/Type/Security/AdminRolesType.php
AdminRolesType.configureOptions
public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ // make expanded default value 'expanded' => true, 'choices' => function (Options $options, $parentChoices) { if (!empty($parentChoices)) { return []; } return $this->rolesBuilder->getRoles(); }, 'multiple' => true, 'data_class' => null, ]); }
php
public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ // make expanded default value 'expanded' => true, 'choices' => function (Options $options, $parentChoices) { if (!empty($parentChoices)) { return []; } return $this->rolesBuilder->getRoles(); }, 'multiple' => true, 'data_class' => null, ]); }
[ "public", "function", "configureOptions", "(", "OptionsResolver", "$", "resolver", ")", "{", "$", "resolver", "->", "setDefaults", "(", "[", "// make expanded default value", "'expanded'", "=>", "true", ",", "'choices'", "=>", "function", "(", "Options", "$", "opt...
{@inheritdoc}
[ "{" ]
train
https://github.com/alterphp/EasyAdminExtensionBundle/blob/c9e8cc3530ba053ae22edde8ca3d14d1984936b3/src/Form/Type/Security/AdminRolesType.php#L77-L92
alterphp/EasyAdminExtensionBundle
src/Configuration/EmbeddedListViewConfigPass.php
EmbeddedListViewConfigPass.processOpenNewTabConfig
private function processOpenNewTabConfig(array $backendConfig) { foreach ($backendConfig['entities'] as $entityName => $entityConfig) { if (!isset($entityConfig['embeddedList']['open_new_tab'])) { $backendConfig['entities'][$entityName]['embeddedList']['open_new_tab'] = $this->defaultOpenNewTab; } } return $backendConfig; }
php
private function processOpenNewTabConfig(array $backendConfig) { foreach ($backendConfig['entities'] as $entityName => $entityConfig) { if (!isset($entityConfig['embeddedList']['open_new_tab'])) { $backendConfig['entities'][$entityName]['embeddedList']['open_new_tab'] = $this->defaultOpenNewTab; } } return $backendConfig; }
[ "private", "function", "processOpenNewTabConfig", "(", "array", "$", "backendConfig", ")", "{", "foreach", "(", "$", "backendConfig", "[", "'entities'", "]", "as", "$", "entityName", "=>", "$", "entityConfig", ")", "{", "if", "(", "!", "isset", "(", "$", "...
@param array $backendConfig @return array
[ "@param", "array", "$backendConfig" ]
train
https://github.com/alterphp/EasyAdminExtensionBundle/blob/c9e8cc3530ba053ae22edde8ca3d14d1984936b3/src/Configuration/EmbeddedListViewConfigPass.php#L33-L42