public function intercept(MethodInvocation $invocation)
 {
     /*
      * First let's make sure we can even bother caching this
      * if we can't then just return the controller response
      */
     if (!$this->decider->decide()) {
         return $invocation->proceed();
     }
     /* @var $controller ResourceController */
     $controller = $invocation->object;
     /* @var $request Request */
     $request = $invocation->arguments[0];
     // Current Resource
     $resource = $controller->findOr404($request);
     // Cache Options
     $options = $request->attributes->get('_sylius', []);
     $cacheOptions = array_key_exists('cache', $options) ? $options['cache'] : [];
     // Build the actual cache options since we'll need to use it twice
     $this->parser->process($cacheOptions, $resource);
     // Create a preliminary response to see if it is already cached
     $cachedResponse = new Response();
     $cachedResponse->setCache($cacheOptions);
     if ($cachedResponse->isNotModified($request)) {
         return $cachedResponse;
     }
     // If not we take the response back from the controller and modify it again
     $controllerResponse = $invocation->proceed();
     $controllerResponse->setCache($cacheOptions);
     return $controllerResponse;
 }
示例#2
0
 /**
  * {@inheritdoc}
  */
 public function intercept(MethodInvocation $invocation)
 {
     $metadata = $this->findMethodMetadata(get_class($invocation->object), $invocation->reflection->name);
     $object = $invocation->object;
     /** @var LoggerAwareInterface $object */
     $targetObject = null;
     foreach ($invocation->reflection->getParameters() as $parameter) {
         if ($parameter->name === $metadata->getArgument()) {
             $targetObject = $invocation->arguments[$parameter->getPosition()];
             break;
         }
     }
     if ($targetObject) {
         $this->logger->pushProcessor(function ($record) use(&$targetObject) {
             $record['extra'][DoctrineHandler::OBJECT_KEY] = $targetObject;
             return $record;
         });
     }
     // TODO: logger ставить при создании сервиса
     $object->setLogger($this->logger);
     try {
         $ret = $invocation->proceed();
     } catch (\Exception $e) {
     }
     if ($targetObject) {
         $this->logger->popProcessor();
     }
     if (isset($e)) {
         throw $e;
     }
     return $ret;
 }
 function it_calls_the_method_without_any_runner(RunnerRepository $runnerRepository, \ReflectionMethod $method, MethodInvocation $invocation)
 {
     $invocation->proceed()->shouldBeCalled();
     $invocation->reflection = $method;
     $runnerRepository->getRunnerByMethod($method)->willReturn(null);
     $this->intercept($invocation);
 }
 public function intercept(MethodInvocation $method)
 {
     $message = sprintf('%s::%s(', $method->reflection->class, $method->reflection->name);
     $logArgs = array();
     foreach ($method->arguments as $arg) {
         $logArgs[] = var_export($arg, true);
     }
     $this->log[] = $message . implode(', ', $logArgs) . ')';
     return $method->proceed();
 }
示例#5
0
 /**
  * {@inheritdoc}
  */
 public function intercept(MethodInvocation $invocation)
 {
     $operation = new Callback(function () use($invocation) {
         return $invocation->proceed();
     });
     if (null === ($runner = $this->runnerRepository->getRunnerByMethod($invocation->reflection))) {
         return $operation->call();
     }
     return $runner->run($operation);
 }
 /**
  * @inheritdoc
  */
 public function intercept(MethodInvocation $invocation)
 {
     $metadata = $this->findMethodMetadata(get_class($invocation->object), $invocation->reflection->name);
     $em = $this->doctrine->getManager($metadata->getEm());
     if (!$em instanceof EntityManagerInterface) {
         throw new \Exception('Wrong object manager class');
     }
     $context = new TransactionalInvocationContext($em);
     $arguments = [];
     foreach ($invocation->reflection->getParameters() as $i => $param) {
         $arguments[$param->name] = $invocation->arguments[$i];
     }
     try {
         $em->beginTransaction();
         /** @see https://www.percona.com/blog/2012/08/28/differences-between-read-committed-and-repeatable-read-transaction-isolation-levels/ */
         /** @see http://www.ovaistariq.net/597/understanding-innodb-transaction-isolation-levels/ */
         $em->getConnection()->setTransactionIsolation(Connection::TRANSACTION_READ_COMMITTED);
         array_push($invocation->arguments, $context);
         $ret = $invocation->proceed();
         $em->flush();
         if (!$em->isOpen() || $em->getConnection()->isRollbackOnly()) {
             throw new \Exception('Rollback invoked');
         }
         $em->commit();
         if ($metadata->getOnSuccess() && !$context->isPreventSuccess()) {
             $this->invokeEvent($invocation->object, $metadata->getOnSuccess(), new TransactionalSuccessEvent($arguments, $context, $ret));
         }
         return $ret;
     } catch (\Exception $e) {
         if ($em->getConnection()->isTransactionActive()) {
             // TODO: postgresql, savepoints
             if (!$e instanceof DBALException && !$e instanceof \PDOException && $em->isOpen() && !$em->getConnection()->isRollbackOnly()) {
                 try {
                     $em->flush();
                 } catch (\Exception $e) {
                     // TODO: log? stop catching?
                 }
             }
             $em->rollback();
         }
         if (!$em->isOpen()) {
             $this->doctrine->resetManager($metadata->getEm());
             $contextOld = $context;
             /** @var EntityManagerInterface $em */
             $em = $this->doctrine->getManager($metadata->getEm());
             $context = new TransactionalInvocationContext($em);
             $context->setData($contextOld->getData());
         }
         if ($metadata->getOnError()) {
             return $this->invokeEvent($invocation->object, $metadata->getOnError(), new TransactionalErrorEvent($arguments, $context, $e));
         }
         throw $e;
     }
 }
 public function intercept(MethodInvocation $invocation)
 {
     $variables = $invocation->proceed();
     if (!is_array($variables)) {
         return $variables;
     }
     /** @var FillLayout $annotation */
     $annotation = $this->annotationReader->getMethodAnnotation($invocation->reflection, FillLayout::class);
     /** @var ILayoutFiller $layoutFiller */
     $layoutFiller = $this->container->get($annotation->getServiceId());
     return $layoutFiller->setDefaultVariables($variables);
 }
 public function intercept(MethodInvocation $method)
 {
     $metadata = $this->metadataFactory->getMetadataForClass($method->reflection->class);
     // no security metadata, proceed
     if (empty($metadata) || !isset($metadata->methodMetadata[$method->reflection->name])) {
         return $method->proceed();
     }
     $metadata = $metadata->methodMetadata[$method->reflection->name];
     if (null === ($token = $this->tokenStorage->getToken())) {
         throw new AuthenticationCredentialsNotFoundException('The security context was not populated with a Token.');
     }
     if ($this->alwaysAuthenticate || !$token->isAuthenticated()) {
         $token = $this->authenticationManager->authenticate($token);
         $this->tokenStorage->setToken($token);
     }
     if (!empty($metadata->roles) && false === $this->accessDecisionManager->decide($token, $metadata->roles, $method)) {
         throw new AccessDeniedException('Token does not have the required roles.');
     }
     if (!empty($metadata->paramPermissions)) {
         foreach ($method->arguments as $index => $argument) {
             if (null !== $argument && isset($metadata->paramPermissions[$index]) && false === $this->accessDecisionManager->decide($token, $metadata->paramPermissions[$index], $argument)) {
                 throw new AccessDeniedException(sprintf('Token does not have the required permissions for method "%s::%s".', $method->reflection->class, $method->reflection->name));
             }
         }
     }
     $runAsToken = null;
     if (!empty($metadata->runAsRoles)) {
         $runAsToken = $this->runAsManager->buildRunAs($token, $method, $metadata->runAsRoles);
         if (null !== $this->logger) {
             $this->logger->debug('Populating security context with RunAsToken');
         }
         if (null === $runAsToken) {
             throw new RuntimeException('RunAsManager must not return null from buildRunAs().');
         }
         $this->tokenStorage->setToken($runAsToken);
     }
     try {
         $returnValue = $method->proceed();
         if (null !== $runAsToken) {
             $this->restoreOriginalToken($runAsToken);
         }
         if (empty($metadata->returnPermissions)) {
             return $returnValue;
         }
         return $this->afterInvocationManager->decide($this->tokenStorage->getToken(), $method, $metadata->returnPermissions, $returnValue);
     } catch (\Exception $failed) {
         if (null !== $runAsToken) {
             $this->restoreOriginalToken($runAsToken);
         }
         throw $failed;
     }
 }
 public function intercept(MethodInvocation $invocation)
 {
     $connection = $this->em->getConnection();
     $connection->beginTransaction();
     try {
         $result = $invocation->proceed();
         $connection->commit();
         return $result;
     } catch (Exception $ex) {
         $connection->rollBack();
         throw $ex;
     }
 }
 public function intercept(MethodInvocation $invocation)
 {
     $this->em->getConnection()->beginTransaction();
     try {
         $rs = $invocation->proceed();
         $this->em->flush();
         $this->em->getConnection()->commit();
         return $rs;
     } catch (\Exception $ex) {
         $this->em->close();
         $this->em->getConnection()->rollBack();
         throw $ex;
     }
 }
示例#11
0
 public function intercept(MethodInvocation $invocation)
 {
     /** @var Doorkeeper $annotation */
     $annotation = $this->annotationReader->getMethodAnnotation($invocation->reflection, Doorkeeper::class);
     /** @var IDoorkeeper $doorKeeper */
     $doorKeeper = $this->container->get($annotation->getServiceId());
     $checkResult = $doorKeeper->checkAccess($this->request);
     if ($checkResult === true) {
         return $invocation->proceed();
     } else {
         if ($checkResult instanceof Response) {
             return $checkResult;
         } else {
             throw new Exception('Unexpected Doorkeeper check result: ' . var_export($checkResult, true));
         }
     }
 }
示例#12
0
 /**
  * {@inheritdoc}
  */
 public function intercept(MethodInvocation $invocation)
 {
     $metadata = $this->findMethodMetadata(get_class($invocation->object), $invocation->reflection->name);
     $key = $metadata->getKey();
     if ($key[0] === '=') {
         $lang = new ExpressionLanguage();
         $attrs = [];
         foreach ($invocation->reflection->getParameters() as $i => $param) {
             $attrs[$param->name] = $invocation->arguments[$i];
         }
         $key = $lang->evaluate(substr($key, 1), $attrs);
     }
     try {
         $this->mutexManager->lock($key, $metadata->getWaitTimeout());
         $ret = $invocation->proceed();
         $this->mutexManager->unlock($key);
     } catch (\Exception $e) {
         $this->mutexManager->unlock($key);
         throw $e;
     }
     return $ret;
 }
 /**
  * {@inheritDoc}
  *
  * @param MethodInvocation $method Current method invocation.
  */
 public function intercept(MethodInvocation $method)
 {
     $methodDefinition = $method->reflection;
     // Gets the Transactional annotation, if existing.
     $annotation = $this->getTransactionalAnnotation($methodDefinition);
     // The transactional policy is determined by the annotation, if found.
     // If missing, default behaviour is to do nothing (no transaction started).
     if ($annotation === null) {
         $policy = Transactional::NOT_REQUIRED;
     } elseif ($annotation->getPolicy() === null) {
         $policy = $this->container->getParameter(Configuration::ROOT_NODE_NAME . '.' . Configuration::DEFAULT_POLICY);
     } else {
         $policy = $annotation->getPolicy();
     }
     if ($policy === Transactional::NOT_REQUIRED && $annotation === null) {
         // No annotation found: there is probably a bug in the pointcut class, because the interceptor should not
         // have been invoked.
         $this->logger->warning('Transactional interceptor was invoked, but no annotation was found for method \'' . $methodDefinition->getDeclaringClass()->getName() . '::' . $methodDefinition->getName() . '\'');
     }
     $transactionRequired = false;
     if ($annotation !== null) {
         // Determine if a transaction must be started.
         $transactionRequired = $this->isTransactionRequired($policy, $this->getEntityManager()->getConnection()->isTransactionActive());
     }
     $this->beforeMethodInvocation($transactionRequired);
     try {
         // Invokes the method.
         $this->logger->debug($methodDefinition->getDeclaringClass()->getName() . '::' . $methodDefinition->getName());
         $result = $method->proceed();
         $this->afterMethodInvocationSuccess($transactionRequired);
     } catch (Exception $e) {
         // Manage special exceptions (commit or rollback strategy).
         if ($annotation === null) {
             // At this point, it means there is no inner transaction context for the method.
             $noRollbackExceptions = null;
         } elseif ($annotation->getNoRollbackExceptions() === null) {
             // No exceptions set in the annotation (even if the parameter was found), use the default configuration.
             $noRollbackExceptions = $this->container->getParameter(Configuration::ROOT_NODE_NAME . '.' . Configuration::NO_ROLLBACK_EXCEPTIONS);
         } else {
             // Use the annotation parameter.
             $noRollbackExceptions = $annotation->getNoRollbackExceptions();
         }
         $this->afterMethodInvocationFailure($transactionRequired, $e, $noRollbackExceptions);
     }
     return $result;
 }
 public function intercept(MethodInvocation $invocation)
 {
     $this->log[] = $invocation->reflection->name;
     return $invocation->proceed();
 }
 /**
  * {@inheritDoc}
  */
 public function intercept(MethodInvocation $invocation)
 {
     $this->entries[] = new AmqpPublicationEntry($invocation->arguments[0], $invocation->arguments[1], $invocation->arguments[2]);
     return $invocation->proceed();
 }