A method invocation is a joinpoint and can be intercepted by a method interceptor.
Inheritance: extends Go\Aop\Intercept\Invocation
Exemple #1
0
 /**
  * Checks if this method invocation is mockable.
  *
  * @param MethodInvocation $invocation        	
  * @return object The mock return value if this invocation is happening in test
  *         environment and it is listed in the mockable_methods array null otherwise.
  */
 private static function isMockable(MethodInvocation $invocation)
 {
     // Check for testing config, nothing is mockable if we are not testing
     if (Config::get('aopmock.testing') === false) {
         return null;
     }
     // Get the object
     $obj = $invocation->getThis();
     // Get the method name
     $methodName = $invocation->getMethod()->name;
     // Get class name
     if ($invocation->getMethod()->isStatic()) {
         $class = $obj;
         $obj = new $class();
     } else {
         $class = get_class($obj);
     }
     $types = Config::get('aopmock.mockable_methods');
     foreach ($types as $type => $val) {
         if ($obj instanceof $type) {
             if (isset($types[$type][$methodName])) {
                 return $types[$type][$methodName];
             }
         }
     }
     return null;
 }
 /**
  * Converts the given text area into a WYSIWYG editor.
  *
  * @param \Go\Aop\Intercept\MethodInvocation $invocation Invocation
  * @Around("execution(public CMS\View\Helper\FormHelper->textarea(*))")
  * @return bool Whether object invocation should proceed or not
  */
 public function alterTextarea(MethodInvocation $invocation)
 {
     $helper = $invocation->getThis();
     list($fieldName, $options) = array_pad($invocation->getArguments(), 2, null);
     if (!empty($options['class']) && strpos($options['class'], 'ckeditor') !== false && $helper instanceof FormHelper) {
         static::$_counter++;
         $editorId = 'ck-editor-' . static::$_counter;
         $options['class'] .= ' ' . $editorId;
         $view = $this->getProperty($helper, '_View');
         if (!static::$_scriptsLoaded) {
             static::$_scriptsLoaded = true;
             $filebrowserBrowseUrl = $view->Url->build(['plugin' => 'Wysiwyg', 'controller' => 'finder']);
             $view->Html->script('Wysiwyg./ckeditor/ckeditor.js', ['block' => true]);
             $view->Html->script('Wysiwyg./ckeditor/adapters/jquery.js', ['block' => true]);
             $view->Html->scriptBlock('$(document).ready(function () {
                 CKEDITOR.editorConfig = function(config) {
                     config.filebrowserBrowseUrl = "' . $filebrowserBrowseUrl . '";
                 };
             });', ['block' => true]);
             $this->_includeLinksToContents($view);
         }
     }
     $this->setProperty($invocation, 'arguments', [$fieldName, $options]);
     return $invocation->proceed();
 }
 /**
  * Method invoker
  *
  * @param $invocation MethodInvocation the method invocation joinpoint
  * @return mixed the result of the call to {@see Joinpoint->proceed()}
  */
 public final function invoke(MethodInvocation $invocation)
 {
     if ($this->pointcut->matches($invocation->getMethod(), $invocation->getThis(), $invocation->getArguments())) {
         return $this->adviceMethod->invoke($invocation);
     }
     return $invocation->proceed();
 }
 /**
  * Adds custom templates to PaginatorHelper::$_defaultConfig['templates'].
  *
  * @param \Go\Aop\Intercept\MethodInvocation $invocation Joinpoint
  * @Before("execution(public Cake\View\Helper\PaginatorHelper->prev|numbers|next(*))")
  * @return bool Whether object invocation should proceed or not
  */
 public function defaultTemplates(MethodInvocation $invocation)
 {
     if (!static::cache('bootstrapTemplates')) {
         $helper = $invocation->getThis();
         $helper->templates($this->_templates);
         static::cache('bootstrapTemplates', true);
     }
 }
 /**
  * @param MethodInvocation $methodInvocation
  *
  * @return void
  *
  * @throws \ErrorException
  */
 public function __invoke(MethodInvocation $methodInvocation)
 {
     $reflectionParameters = $methodInvocation->getMethod()->getParameters();
     $applyTypeChecks = $this->applyTypeChecks;
     foreach ($methodInvocation->getArguments() as $argumentIndex => $argument) {
         $applyTypeChecks($this->getParameterDocblockType(get_class($methodInvocation->getThis()), $reflectionParameters, $argumentIndex), $argument);
     }
 }
 /**
  * Returns an associative list of arguments for the method invocation
  *
  * @param MethodInvocation $invocation
  * @return array
  */
 protected function fetchMethodArguments(MethodInvocation $invocation)
 {
     $parameters = $invocation->getMethod()->getParameters();
     $argumentNames = array_map(function (\ReflectionParameter $parameter) {
         return $parameter->name;
     }, $parameters);
     $parameters = array_combine($argumentNames, $invocation->getArguments());
     return $parameters;
 }
 /**
  * @Go\After("execution(public **->__construct(*))")
  *
  * @param MethodInvocation $constructorInvocation
  *
  * @return mixed
  *
  * @throws \ErrorException|\Exception
  */
 public function postConstruct(MethodInvocation $constructorInvocation)
 {
     $that = $constructorInvocation->getThis();
     $scope = $constructorInvocation->getMethod()->getDeclaringClass()->getName();
     array_map(function (callable $checker) use($that, $scope) {
         $checker($that, $scope);
     }, $this->stateCheckers);
     return $constructorInvocation->proceed();
 }
 /**
  * Cacheable methods
  *
  * @param MethodInvocation $invocation Invocation
  *
  * @Go\Lang\Annotation\Around("execution(public Nucleus\Cache\BaseCacheService->set(*))")
  */
 public function arroundSet(MethodInvocation $invocation)
 {
     $arguments = $invocation->getArguments();
     $call = array('method' => 'set', 'name' => $arguments[0], 'namespace' => $arguments[3]);
     $this->getDebugBar()->getCollector('messages')->addMessage('Cache set [' . $arguments[3] . '] / [' . $arguments[0] . ']');
     $result = $invocation->proceed();
     $this->data['calls'][] = $call;
     return $result;
 }
 /**
  * Adds prefix to every input element that may have a "name" attribute.
  *
  * @param \Go\Aop\Intercept\MethodInvocation $invocation Invocation
  * @Around("execution(public Cake\View\Helper\FormHelper->label|input|checkbox|radio|textarea|hidden|file|select|multiCheckbox|day|year|month|hour|minute|meridian|dateTime|time|date(*))")
  * @return bool Whether object invocation should proceed or not
  */
 public function addInputPrefix(MethodInvocation $invocation)
 {
     $helper = $invocation->getThis();
     $args = $invocation->getArguments();
     if (!empty($args[0]) && is_string($args[0]) && $helper instanceof FormHelper) {
         $args[0] = $this->_fieldName($helper, $args[0]);
     }
     $this->setProperty($invocation, 'arguments', $args);
     return $invocation->proceed();
 }
 /**
  *
  * Adds a shortcut button to Comment's management submenu.
  *
  * @param \Go\Aop\Intercept\MethodInvocation $invocation Invocation
  * @Before("execution(public Menu\View\Helper\MenuHelper->render(*))")
  */
 public function commentsNav(MethodInvocation $invocation)
 {
     $helper = $invocation->getThis();
     $settings = plugin('Disqus')->settings;
     list($items, $options) = $invocation->getArguments();
     if (!empty($settings['disqus_shortname']) && count($items) == 5 && $items[0]['title'] == __d('comment', 'All')) {
         $items[] = ['title' => __d('disqus', 'Go to Disqus Moderation'), 'url' => 'https://' . $settings['disqus_shortname'] . '.disqus.com/admin/moderate/', 'target' => '_blank'];
         $this->setProperty($invocation, 'arguments', [$items, $options]);
     }
 }
 /**
  * After throwing exception invoker
  *
  * @param $invocation MethodInvocation the method invocation joinpoint
  * @return mixed the result of the call to {@link Joinpoint::proceed()}
  * @throws Exception
  */
 public final function invoke(MethodInvocation $invocation)
 {
     $result = null;
     try {
         $result = $invocation->proceed();
     } catch (Exception $invocationException) {
         $adviceMethod = $this->adviceMethod;
         $adviceMethod($invocation);
         throw $invocationException;
     }
     return $result;
 }
Exemple #12
0
 /**
  * Intercept any public method and store them on the object.
  *
  * @param MethodInvocation $invocation Invocation
  * @Before("execution(public Mage_Cms_Block_Page->*(*))")
  */
 public function storeInterceptedPublicMethods(MethodInvocation $invocation)
 {
     $obj = $invocation->getThis();
     $method = $invocation->getMethod()->getName();
     $interceptedMethods = $obj->getInterceptedMethods();
     if ($interceptedMethods === null) {
         $interceptedMethods = array();
     }
     if (!in_array($method, $interceptedMethods)) {
         $interceptedMethods[] = $method;
     }
     $obj->setInterceptedMethods($interceptedMethods);
 }
 public function testWillNotProceedExecuteOnWriteAndCrash()
 {
     $object = new \stdClass();
     $this->methodInvocation->expects($this->never())->method('proceed')->will($this->returnValue('done'));
     $this->methodInvocation->expects($this->any())->method('getThis')->will($this->returnValue($object));
     $this->methodInvocation->expects($this->any())->method('getMethod')->will($this->returnValue(new ReflectionMethod(__CLASS__, __FUNCTION__)));
     foreach ($this->callables as $callable) {
         $callable->expects($this->any())->method('__invoke')->with($object, __CLASS__)->will($this->throwException(new \Exception()));
     }
     $aspect = new PostConstructAspect(...$this->callables);
     $this->setExpectedException(\Exception::class);
     $aspect->postConstruct($this->methodInvocation);
 }
 /**
  * Cacheable methods
  *
  * @param MethodInvocation $invocation Invocation
  *
  * @Go\Lang\Annotation\Around("execution(public Twig_Template->display(*))")
  */
 public function aroundDisplay(MethodInvocation $invocation)
 {
     $this->deepness++;
     $start = microtime(true);
     $result = $invocation->proceed();
     $end = microtime(true);
     if (!is_null($timeDataCollector = $this->getTimeDataCollector())) {
         $name = sprintf("twig.render(%s)", $invocation->getThis()->getTemplateName());
         $timeDataCollector->addMeasure($name, $start, $end);
     }
     $this->renderedTemplates[] = array('name' => str_repeat('-', $this->deepness) . '> ' . $invocation->getThis()->getTemplateName(), 'render_time' => $end - $start);
     $this->deepness--;
     return $result;
 }
 /**
  * Verifies invariants for contract class
  *
  * @Around("@within(PhpDeal\Annotation\Invariant) && execution(public **->*(*))")
  * @param MethodInvocation $invocation
  *
  * @throws ContractViolation
  * @return mixed
  */
 public function invariantContract(MethodInvocation $invocation)
 {
     $object = $invocation->getThis();
     $args = $this->fetchMethodArguments($invocation);
     $class = $invocation->getMethod()->getDeclaringClass();
     if ($class->isCloneable()) {
         $args['__old'] = clone $object;
     }
     $result = $invocation->proceed();
     $args['__result'] = $result;
     $allContracts = $this->fetchAllContracts($class);
     $this->ensureContracts($invocation, $allContracts, $object, $class->name, $args);
     return $result;
 }
 /**
  * After invoker
  *
  * @param $invocation MethodInvocation the method invocation joinpoint
  * @return mixed the result of the call to {@link Joinpoint::proceed()}
  * @throws Exception
  */
 public final function invoke(MethodInvocation $invocation)
 {
     $result = null;
     try {
         $result = $invocation->proceed();
     } catch (Exception $invocationException) {
         // this is need for finally emulation in PHP
     }
     $adviceMethod = $this->adviceMethod;
     $adviceMethod($invocation);
     if (isset($invocationException)) {
         throw $invocationException;
     }
     return $result;
 }
 /**
  * Logic to notify all observers on subject
  *
  * @After("$this->subjectChange")
  *
  * @param MethodInvocation $invocation
  */
 protected function afterSubjectChange(MethodInvocation $invocation)
 {
     $subject = $invocation->getThis();
     $observers = $this->getObservers($subject);
     foreach ($observers as $observer) {
         $this->updateObserver($subject, $observer);
     }
 }
 /**
  * This advice intercepts an execution of cacheable methods
  *
  * Logic is pretty simple: we look for the value in the cache and if it's not present here
  * then invoke original method and store it's result in the cache.
  *
  * Real-life examples will use APC or Memcache to store value in the cache
  *
  * @param MethodInvocation $invocation Invocation
  *
  * @Around("@execution(Demo\Annotation\Cacheable)")
  */
 public function aroundCacheable(MethodInvocation $invocation)
 {
     static $memoryCache = array();
     $time = microtime(true);
     $obj = $invocation->getThis();
     $class = is_object($obj) ? get_class($obj) : $obj;
     $key = $class . ':' . $invocation->getMethod()->name;
     if (!isset($memoryCache[$key])) {
         // We can use ttl value from annotation, but Doctrine annotations doesn't work under GAE
         if (!isset($_SERVER['APPENGINE_RUNTIME'])) {
             echo "Ttl is: ", $invocation->getMethod()->getAnnotation('Demo\\Annotation\\Cacheable')->time, PHP_EOL;
         }
         $memoryCache[$key] = $invocation->proceed();
     }
     echo "Take ", sprintf("%0.3f", (microtime(true) - $time) * 1000.0), "ms to call method {$key}", PHP_EOL;
     return $memoryCache[$key];
 }
Exemple #19
0
 /**
  * @param MethodInvocation $invocation Invocation
  * @Before("execution(public Endpoint->call(*))") // This is our PointCut
  */
 public function beforeServiceCall(MethodInvocation $invocation)
 {
     $methodThis = $invocation->getThis();
     $service = $methodThis->service()->first();
     $serviceName = $service->name;
     $serviceLimit = \DB::table('limits')->where('service_id', '=', $service->id)->first();
     \DB::table('limits')->where('service_id', '=', $service->id)->update(array('current_hits' => 0));
     $serviceLimit->current_hits = 0;
     $hasLimitBeenReached = $serviceLimit->current_hits >= $serviceLimit->max_hits;
     if ($hasLimitBeenReached) {
         echo "The limit number of calls for service \"" . $serviceName . "\" have been reached \n";
         echo "Method execution stoped";
         die;
     }
     \DB::table('limits')->where('service_id', '=', $service->id)->update(array('current_hits' => $serviceLimit->current_hits + 1));
     $methodName = $invocation->getMethod()->getName();
     $methodParams = implode(', ', $invocation->getArguments());
     // echo "Calling method " . $methodName . " with params : " . $methodParams . "\n";
     // echo "Method execution continues \n";
     // echo "Method result \n";
 }
 /**
  * @param MethodInvocation $invocation Invocation
  * @Around("@annotation(Reynholm\Aop\Annotation\Transactional)")
  *
  * @return mixed
  */
 public function aroundTransactional(MethodInvocation $invocation)
 {
     /** @var Transactional $transactionalAnnotation */
     $transactionalAnnotation = $invocation->getMethod()->getAnnotation('Reynholm\\LaravelAop\\Annotation\\Transactional');
     if (empty($transactionalAnnotation->databaseConnection)) {
         $transactionalAnnotation->databaseConnection = \Config::get('database.default');
     }
     /** @var \PDO $pdoConnection */
     $pdoConnection = \DB::connection($transactionalAnnotation->databaseConnection)->getPdo();
     try {
         $pdoConnection->beginTransaction();
         $result = $invocation->proceed();
         $pdoConnection->commit();
         return $result;
     } catch (\Exception $e) {
         $pdoConnection->rollBack();
         if ($transactionalAnnotation->throwExceptions === true) {
             throw $e;
         }
     }
 }
 /**
  * This method will check, if user is authorized
  *
  * @param MethodInvocation $invocation
  * @Around("$this->authorizePointcut")
  */
 public function authorize(MethodInvocation $invocation)
 {
     $rflMethod = $invocation->getMethod();
     $type = null;
     $userFactory = null;
     $expression = null;
     $resourceFactory = null;
     $resourceFactoryAdditionalParameters = null;
     $policies = array();
     foreach ($rflMethod->getAnnotations() as $annotation) {
         switch ($annotation) {
             case $annotation instanceof AuthorizationSecurity:
                 $type = $annotation->securityTypeName();
                 $userFactory = $annotation->userFactoryName();
                 break;
             case $annotation instanceof AuthorizationExpression:
                 $expression = $annotation->expression();
                 break;
             case $annotation instanceof AuthorizationResourceFactory:
                 $resourceFactory = $annotation->resourceFactoryName();
                 $resourceFactoryAdditionalParameters = $annotation->additionalParameters();
                 break;
             case $annotation instanceof AuthorizationPolicy:
                 $policies[] = $annotation->policyName();
                 break;
         }
     }
     /** @var Security $securityAPI */
     $securityAPI = DIContainer::getInstance()->get('security');
     if (!is_null($resourceFactory)) {
         /** @var ResourceFactory $userFactory */
         $resourceFactoryForArguments = DIContainer::getInstance()->getResourceFactory($resourceFactory);
         $resourceFactoryForArguments->setArguments($invocation->getArguments());
         $resourceFactoryForArguments->setAdditionalParameters($resourceFactoryAdditionalParameters);
     }
     $securityCommand = new SecurityCommand($type, $userFactory, $expression, $resourceFactory, $policies);
     $securityAPI->authorize($securityCommand);
     $invocation->proceed();
 }
 /**
  * @param MethodInvocation $methodInvocation
  *
  * @return void
  *
  * @throws \ErrorException
  */
 public function __invoke(MethodInvocation $methodInvocation)
 {
     $reflectionMethod = $methodInvocation->getMethod();
     $applyTypeChecks = $this->applyTypeChecks;
     $applyTypeChecks($this->getReturnDocblockType($methodInvocation->getMethod()->getDeclaringClass()->getName(), $reflectionMethod), $methodInvocation->proceed());
 }
 /**
  * This advice intercepts an execution of methods via __callStatic
  *
  * @param MethodInvocation $invocation
  * @Before("dynamic(public Demo\Example\DynamicMethodsDemo::find*(*))")
  */
 public function beforeMagicStaticMethodExecution(MethodInvocation $invocation)
 {
     // we need to unpack args from invocation args
     list($methodName) = $invocation->getArguments();
     echo "Calling Magic Static Interceptor for method: ", $methodName, PHP_EOL;
 }
 /**
  * Method that advice to clean the teeth before going to sleep
  *
  * @param MethodInvocation $invocation Invocation
  * @Before("execution(public Demo\Example\HumanDemo->sleep(*))")
  */
 protected function cleanTeethBeforeSleep(MethodInvocation $invocation)
 {
     /** @var $person \Demo\Example\HumanDemo */
     $person = $invocation->getThis();
     $person->cleanTeeth();
 }
Exemple #25
0
 protected function getAnnotation(MethodInvocation $invocation, $annotationName)
 {
     return $this->getServiceContainer()->getServiceByName('aspectKernel')->getContainer()->get('aspect.annotation.reader')->getMethodAnnotation($invocation->getMethod(), $annotationName);
 }
 /**
  * Fluent interface advice
  *
  * @Around("within(Demo\Aspect\FluentInterface+) && execution(public **->set*(*))")
  *
  * @param MethodInvocation $invocation
  * @return mixed|null|object
  */
 protected function aroundMethodExecution(MethodInvocation $invocation)
 {
     $result = $invocation->proceed();
     return $result !== null ? $result : $invocation->getThis();
 }
 /**
  * @param MethodInvocation $invocation
  * @return array
  */
 private function fetchParentsContracts(MethodInvocation $invocation)
 {
     return $this->methodConditionFetcher->getConditions($invocation->getMethod()->getDeclaringClass(), $invocation->getMethod()->name);
 }
Exemple #28
0
 /**
  * Method that should be called before real method
  *
  * @param MethodInvocation $invocation Invocation
  * @Before("within(**)")
  */
 public function beforeMethodExecution(MethodInvocation $invocation)
 {
     $obj = $invocation->getThis();
     echo 'Calling Before Interceptor for method: ', is_object($obj) ? get_class($obj) : $obj, $invocation->getMethod()->isStatic() ? '::' : '->', $invocation->getMethod()->getName(), '()', ' with arguments: ', json_encode($invocation->getArguments()), "<br>\n";
 }
 /**
  * @param MethodInvocation $invocation Invocation
  *
  * @Go\Lang\Annotation\Around("execution(public Kohana_Request_Client_Internal->execute_request(*))")
  */
 public function aroundKohanaRequestClientInternalExecuteRequest(MethodInvocation $invocation)
 {
     $arguments = $invocation->getArguments();
     $kohanaRequest = $arguments[0];
     /* @var $kohanaRequest \Request */
     $kohanaParameters = $kohanaRequest->param();
     $request = $this->createNucleusRequest($kohanaRequest, $kohanaParameters);
     //We do this now so a controller in kohana can generate route properly from nucleus
     $this->getRouter()->setCurrentRequest($request);
     if (!isset($kohanaParameters['_nucleus'])) {
         return $invocation->proceed();
     }
     $previousKohanaRequest = KohanaRequest::$current;
     KohanaRequest::$current = $kohanaRequest;
     $request->request->add($kohanaParameters['_nucleus']);
     $service = $request->request->get('_service');
     $response = $this->getFrontController()->execute($service['name'], $service['method'], $request);
     $kohanaResponse = $kohanaRequest->create_response();
     $this->mergeResponse($kohanaResponse, $response);
     KohanaRequest::$current = $previousKohanaRequest;
     return $kohanaResponse;
 }
 /**
  * This advice intercepts an execution of loggable methods
  *
  * We use "Before" type of advice to log only class name, method name and arguments before
  * method execution.
  * You can choose your own logger, for example, monolog or log4php.
  * Also you can choose "After" or "Around" advice to access an return value from method.
  *
  * To inject logger into this aspect you can look at Warlock framework with DI+AOP
  *
  * @param MethodInvocation $invocation Invocation
  *
  * @Before("@execution(Demo\Annotation\Loggable)")
  */
 public function beforeMethodExecution(MethodInvocation $invocation)
 {
     echo 'Calling Before Interceptor for ', $invocation, ' with arguments: ', json_encode($invocation->getArguments()), PHP_EOL;
 }