Ejemplo n.º 1
0
 /**
  * @param Request        $request
  * @param ParamConverter $configuration
  * @param string         $mapToField
  *
  * @return array
  */
 private function getMappingOptions(Request $request, ParamConverter $configuration, $mapToField)
 {
     $routeParams = $request->attributes->get('_route_params');
     if (isset($routeParams[$configuration->getName()])) {
         return ['mapping' => [$configuration->getName() => $mapToField]];
     }
     return [];
 }
 /**
  * @param Request                $request
  * @param ParamConverter $configuration
  *
  * @return bool
  *
  * @throws \LogicException
  * @throws NotFoundHttpException
  * @throws \Exception
  */
 public function apply(Request $request, ParamConverter $configuration)
 {
     $classQuery = $configuration->getClass() . 'Query';
     $classPeer = $configuration->getClass() . 'Peer';
     $this->filters = array();
     $this->exclude = array();
     if (!class_exists($classQuery)) {
         throw new \Exception(sprintf('The %s Query class does not exist', $classQuery));
     }
     $tableMap = $classPeer::getTableMap();
     $pkColumns = $tableMap->getPrimaryKeyColumns();
     if (count($pkColumns) == 1) {
         $this->pk = strtolower($pkColumns[0]->getName());
     }
     $options = $configuration->getOptions();
     // Check route options for converter options, if there are non provided.
     if (empty($options) && $request->attributes->has('_route') && $this->router && $configuration instanceof ParamConverter) {
         $converterOption = $this->router->getRouteCollection()->get($request->attributes->get('_route'))->getOption('propel_converter');
         if (!empty($converterOption[$configuration->getName()])) {
             $options = $converterOption[$configuration->getName()];
         }
     }
     if (isset($options['mapping'])) {
         // We use the mapping for calling findPk or filterBy
         foreach ($options['mapping'] as $routeParam => $column) {
             if ($request->attributes->has($routeParam)) {
                 if ($this->pk === $column) {
                     $this->pk = $routeParam;
                 } else {
                     $this->filters[$column] = $request->attributes->get($routeParam);
                 }
             }
         }
     } else {
         $this->exclude = isset($options['exclude']) ? $options['exclude'] : array();
         $this->filters = $request->attributes->all();
     }
     $this->withs = isset($options['with']) ? is_array($options['with']) ? $options['with'] : array($options['with']) : array();
     // find by Pk
     if (false === ($object = $this->findPk($classQuery, $request))) {
         // find by criteria
         if (false === ($object = $this->findOneBy($classQuery, $request))) {
             if ($configuration->isOptional()) {
                 //we find nothing but the object is optional
                 $object = null;
             } else {
                 throw new \LogicException('Unable to guess how to get a Propel object from the request information.');
             }
         }
     }
     if (null === $object && false === $configuration->isOptional()) {
         throw new NotFoundHttpException(sprintf('%s object not found.', $configuration->getClass()));
     }
     $request->attributes->set($configuration->getName(), $object);
     return true;
 }
Ejemplo n.º 3
0
 public function apply(Request $request, ParamConverter $configuration)
 {
     $result = null;
     if ($configuration->getClass() == 'Symfony\\Component\\HttpFoundation\\File\\UploadedFile') {
         $result = $this->parseFile($configuration->getName(), $request);
     } else {
         $result = $this->parser->parseClass($configuration->getClass(), $request->getContent());
     }
     $request->attributes->set($configuration->getName(), $result);
     return true;
 }
 /**
  * Stores the object in the request.
  *
  * @param Request $request The request
  * @param ParamConverter $configuration Contains the name, class and options of the object
  *
  * @return bool True if the object has been successfully set, else false
  */
 public function apply(Request $request, ParamConverter $configuration)
 {
     if (!$request->attributes->has($configuration->getName())) {
         return false;
     }
     $id = $request->attributes->get($configuration->getName());
     $conversation = $this->repository->getConversation($id);
     if (!$conversation) {
         throw new NotFoundHttpException();
     }
     $request->attributes->set($configuration->getName(), $conversation);
     return true;
 }
 /**
  * Stores the object in the request.
  *
  * @param Request        $request       The request
  * @param ParamConverter $configuration Contains the name, class and options of the object
  *
  * @return bool    True if the object has been successfully set, else false
  */
 public function apply(Request $request, ParamConverter $configuration)
 {
     $name = $configuration->getName();
     $class = $configuration->getClass();
     $site = $this->siteManager->getSite();
     if (!$site) {
         throw new NotFoundHttpException(sprintf('%s object not found.', $class));
     }
     if ($request->attributes->get($name, false) === null) {
         return false;
     }
     if ($name !== 'site') {
         $request->attributes->set('site', $site->getId());
     }
     if (parent::apply($request, $configuration) === false) {
         return false;
     }
     $object = $request->attributes->get($name);
     if (!$object) {
         throw new NotFoundHttpException(sprintf('%s object not found.', $class));
     }
     if (!$object instanceof SiteBoundInterface) {
         return false;
     }
     if ($object instanceof SiteBoundInterface && !$object->checkSite($site)) {
         throw new NotFoundHttpException(sprintf('%s object not found.', $class));
     }
     return true;
 }
Ejemplo n.º 6
0
 public function apply(Request $request, ParamConverter $configuration)
 {
     //$options = $this->getOptions($configuration);
     //echo $options['test'];
     $ownerNameCanonical = $request->attributes->get('owner');
     $modId = $request->attributes->get('mod');
     $branchId = $request->attributes->get('branch');
     if ($branchId == 'default') {
         $branchId = null;
     }
     $version = $request->attributes->get('build');
     if (!($version == 'current')) {
         list($versionRest, $versionMetadata) = array_pad(explode('+', $version, 2), 2, null);
         list($versionMain, $versionPreRelease) = array_pad(explode('-', $versionRest, 2), 2, null);
         list($versionMajor, $versionMinor, $versionPatch) = explode('.', $versionMain);
     } else {
         $versionMajor = null;
         $versionMinor = null;
         $versionPatch = null;
         $versionPreRelease = null;
         $versionMetadata = null;
     }
     $build = $this->repository->findSingleBuild($ownerNameCanonical, $modId, $branchId, $versionMajor, $versionMinor, $versionPatch, $versionPreRelease, $versionMetadata);
     if (null === $build) {
         throw new NotFoundHttpException("Build not found.");
     }
     $request->attributes->set($configuration->getName(), $build);
     return true;
 }
Ejemplo n.º 7
0
 /**
  * Stores the object in the request.
  *
  * @param Request $request The request
  * @param ParamConverter $configuration Contains the name, class and options of the object
  *
  * @return bool True if the object has been successfully set, else false
  */
 public function apply(Request $request, ParamConverter $configuration)
 {
     $slug = $request->get('slug', null);
     $username = $request->get('username', null);
     $id = $request->get('id', null);
     $name = $request->get('name', null);
     if ($slug) {
         $searchArray = array('slug' => $slug);
     } elseif ($username) {
         $searchArray = array('username' => $username);
     } elseif ($id) {
         $searchArray = array('id' => $id);
     } elseif ($id) {
         $searchArray = array('name' => $name);
     } else {
         throw new \InvalidArgumentException('Route attribute is missing');
     }
     $class = $this->targetEntitiesArray[$configuration->getClass()];
     $repository = $this->doctrine->getRepository($class);
     $object = $repository->findOneBy($searchArray);
     if (!$object) {
         throw new NotFoundHttpException($name);
     }
     $request->attributes->set($configuration->getName(), $object);
 }
Ejemplo n.º 8
0
 function supports(ParamConverter $configuration)
 {
     if ('json' !== $configuration->getName()) {
         return false;
     }
     return true;
 }
Ejemplo n.º 9
0
 /**
  * @{inheritDoc}
  *
  * @throws InvalidConfigurationException if the parameter name, class or id option are missing
  * @throws NotFoundHttpException         if the id doesn't matche an existing entity
  */
 public function apply(Request $request, ParamConverter $configuration)
 {
     if (null === ($parameter = $configuration->getName())) {
         throw new InvalidConfigurationException(InvalidConfigurationException::MISSING_NAME);
     }
     if (null === ($entityClass = $configuration->getClass())) {
         throw new InvalidConfigurationException(InvalidConfigurationException::MISSING_CLASS);
     }
     $options = $configuration->getOptions();
     if (!isset($options['id'])) {
         throw new InvalidConfigurationException(InvalidConfigurationException::MISSING_ID);
     }
     if ($request->attributes->has($options['id'])) {
         if (null !== ($id = $request->attributes->get($options['id']))) {
             if (null !== ($entity = $this->em->getRepository($entityClass)->find($id))) {
                 $request->attributes->set($parameter, $entity);
                 return true;
             }
         }
         if (!$configuration->isOptional()) {
             throw new NotFoundHttpException();
         }
     }
     return false;
 }
Ejemplo n.º 10
0
 /**
  * {@inheritdoc}
  *
  * @throws InvalidConfigurationException if the name or class parameters are missing
  * @throws NotFoundHttpException         if one or more entities cannot be retreived
  * @throws BadRequestHttpException       if there is no "ids" array parameter in the query string
  */
 public function apply(Request $request, ParamConverter $configuration)
 {
     if (null === ($parameter = $configuration->getName())) {
         throw new InvalidConfigurationException(InvalidConfigurationException::MISSING_NAME);
     }
     if (null === ($entityClass = $configuration->getClass())) {
         throw new InvalidConfigurationException(InvalidConfigurationException::MISSING_CLASS);
     }
     $options = $configuration->getOptions();
     $paramName = isset($options['name']) ? $options['name'] : 'ids';
     if ($request->query->has($paramName)) {
         if (is_array($ids = $request->query->get($paramName))) {
             try {
                 $entities = $this->om->findByIds($entityClass, $ids);
                 $request->attributes->set($parameter, $entities);
                 return true;
             } catch (MissingObjectException $ex) {
                 throw new NotFoundHttpException($ex->getMessage());
             }
         }
         throw new BadRequestHttpException();
     }
     $request->attributes->set($parameter, []);
     return true;
 }
 /**
  * {@inheritdoc}
  *
  * @throws InvalidConfigurationException if the parameter name is missing
  * @throws AccessDeniedException         if the current request is anonymous
  */
 public function apply(Request $request, ParamConverter $configuration)
 {
     if (null === ($parameter = $configuration->getName())) {
         throw new InvalidConfigurationException(InvalidConfigurationException::MISSING_NAME);
     }
     $options = $configuration->getOptions();
     if ($options['authenticatedUser'] === true) {
         if (($user = $this->tokenStorage->getToken()->getUser()) instanceof User) {
             $request->attributes->set($parameter, $user);
             return true;
         } else {
             if (array_key_exists('messageEnabled', $options) && $options['messageEnabled'] === true) {
                 $messageType = 'warning';
                 if (array_key_exists('messageType', $options)) {
                     $messageType = $options['messageType'];
                 }
                 $messageTranslationKey = 'this_page_requires_authentication';
                 $messageTranslationDomain = 'platform';
                 if (array_key_exists('messageTranslationKey', $options)) {
                     $messageTranslationKey = $options['messageTranslationKey'];
                     if (array_key_exists('messageTranslationDomain', $options)) {
                         $messageTranslationDomain = $options['messageTranslationDomain'];
                     }
                 }
                 $request->getSession()->getFlashBag()->add($messageType, $this->translator->trans($messageTranslationKey, [], $messageTranslationDomain));
             }
             throw new AccessDeniedException();
         }
     } else {
         $request->attributes->set($parameter, $user = $this->tokenStorage->getToken()->getUser());
     }
 }
Ejemplo n.º 12
0
 /**
  * {@inheritdoc}
  *
  * @throws NotFoundHttpException When invalid date given
  */
 public function apply(Request $request, ParamConverter $configuration)
 {
     $param = $configuration->getName();
     if (!$request->attributes->has($param)) {
         return false;
     }
     $options = $configuration->getOptions();
     $value = $request->attributes->get($param);
     if (!$value && $configuration->isOptional()) {
         return false;
     }
     if (isset($options['format'])) {
         $date = DateTime::createFromFormat($options['format'], $value);
         if (!$date) {
             throw new NotFoundHttpException('Invalid date given.');
         }
     } else {
         if (false === strtotime($value)) {
             throw new NotFoundHttpException('Invalid date given.');
         }
         $date = new DateTime($value);
     }
     $request->attributes->set($param, $date);
     return true;
 }
 /**
  * {@inheritdoc}
  */
 public function apply(Request $request, ParamConverter $configuration)
 {
     $options = (array) $configuration->getOptions();
     if (isset($options['deserializationContext']) && is_array($options['deserializationContext'])) {
         $arrayContext = array_merge($this->context, $options['deserializationContext']);
     } else {
         $arrayContext = $this->context;
     }
     $this->configureContext($context = new Context(), $arrayContext);
     try {
         $object = $this->serializer->deserialize($request->getContent(), $configuration->getClass(), $request->getContentType(), $context);
     } catch (UnsupportedFormatException $e) {
         throw new UnsupportedMediaTypeHttpException($e->getMessage(), $e);
     } catch (JMSSerializerException $e) {
         throw new BadRequestHttpException($e->getMessage(), $e);
     } catch (SymfonySerializerException $e) {
         throw new BadRequestHttpException($e->getMessage(), $e);
     }
     $request->attributes->set($configuration->getName(), $object);
     if (null !== $this->validator) {
         $validatorOptions = $this->getValidatorOptions($options);
         $errors = $this->validator->validate($object, null, $validatorOptions['groups']);
         $request->attributes->set($this->validationErrorsArgument, $errors);
     }
     return true;
 }
Ejemplo n.º 14
0
 /**
  * {@inheritdoc}
  */
 public function apply(Request $request, ParamConverter $configuration) : bool
 {
     $class = $configuration->getClass();
     $constant = sprintf('%s::EMPTY_PROPERTIES', $class);
     $propertiesToBeSkipped = [];
     $instance = new $class();
     $declaredProperties = array_filter((new \ReflectionClass($class))->getProperties(), function (ReflectionProperty $property) use($class) {
         return $property->getDeclaringClass()->name === $class;
     });
     // fetch result properties that are optional and to be skipped as those must not be processed
     if (defined($constant)) {
         $propertiesToBeSkipped = constant($constant);
     }
     /** @var ReflectionProperty $property */
     foreach ($declaredProperties as $property) {
         $propertyName = $property->getName();
         if (in_array($propertyName, $propertiesToBeSkipped, true)) {
             continue;
         }
         // non-writable properties cause issues with the DTO creation
         if (!$this->propertyAccess->isWritable($instance, $propertyName)) {
             throw new \RuntimeException($this->getInvalidPropertyExceptionMessage($class, $propertyName));
         }
         $this->propertyAccess->setValue($instance, $propertyName, $this->findAttributeInRequest($request, $property, $this->propertyAccess->getValue($instance, $propertyName)));
     }
     $request->attributes->set($configuration->getName(), $instance);
     return true;
 }
 /**
  * {@inheritdoc}
  *
  * @throws \LogicException       When unable to guess how to get a Doctrine instance from the request information
  * @throws NotFoundHttpException When object not found
  */
 public function apply(Request $request, ParamConverter $configuration)
 {
     $name = $configuration->getName();
     $class = $configuration->getClass();
     $options = $this->getOptions($configuration);
     if (null === $request->attributes->get($name, false)) {
         $configuration->setIsOptional(true);
     }
     // find by identifier?
     if (false === ($object = $this->find($class, $request, $options, $name))) {
         // find by criteria
         if (false === ($object = $this->findOneBy($class, $request, $options))) {
             if ($configuration->isOptional()) {
                 $object = null;
             } else {
                 throw new \LogicException('Unable to guess how to get a Doctrine instance from the request information.');
             }
         }
     }
     if (null === $object && false === $configuration->isOptional()) {
         throw new NotFoundHttpException(sprintf('%s object not found.', $class));
     }
     $request->attributes->set($name, $object);
     return true;
 }
 /**
  * map specified attribute to configured variable
  * @param $attribute
  * @param ParamConverter $configuration
  * @param Request $request
  */
 protected function mapAttribute($attribute, ParamConverter $configuration, Request $request)
 {
     if ($request->attributes->has($attribute)) {
         $name = $configuration->getName();
         $request->attributes->set($name, $request->attributes->get($attribute));
     }
 }
Ejemplo n.º 17
0
 /**
  * @inheritdoc
  */
 public function apply(Request $request, ParamConverter $configuration)
 {
     $context = DeserializationContext::create();
     $context->setGroups(['query']);
     try {
         $object = $this->serializer->deserialize($request->attributes->get($configuration->getName()), $configuration->getClass(), 'json', $context);
     } catch (UnsupportedFormatException $e) {
         throw new UnsupportedMediaTypeHttpException($e->getMessage(), $e);
     } catch (JMSSerializerException $e) {
         throw new BadRequestHttpException($e->getMessage(), $e);
     } catch (SymfonySerializerException $e) {
         throw new BadRequestHttpException($e->getMessage(), $e);
     }
     $request->attributes->set($configuration->getName(), $object);
     return true;
 }
 public function apply(Request $request, ParamConverter $configuration)
 {
     $name = $configuration->getName();
     $snakeCasedName = $this->camelCaseToSnakeCase($name);
     $class = $configuration->getClass();
     $json = $request->getContent();
     $object = json_decode($json, true);
     if (!isset($object[$snakeCasedName]) || !is_array($object[$snakeCasedName])) {
         throw new BadJsonRequestException([sprintf("Missing parameter '%s'", $name)]);
     }
     $object = $object[$snakeCasedName];
     $convertedObject = new $class();
     $errors = [];
     foreach ($object as $key => $value) {
         $properlyCasedKey = lcfirst(str_replace(' ', '', ucwords(str_replace('_', ' ', $key))));
         if (!property_exists($convertedObject, $properlyCasedKey)) {
             $errors[] = sprintf("Unknown property '%s.%s'", $snakeCasedName, $key);
             continue;
         }
         $convertedObject->{$properlyCasedKey} = $value;
     }
     $violations = $this->validator->validate($convertedObject);
     if (count($errors) + count($violations) > 0) {
         throw BadJsonRequestException::createForViolationsAndErrors($violations, $name, $errors);
     }
     $request->attributes->set($name, $convertedObject);
 }
Ejemplo n.º 19
0
 /**
  * execute
  *
  * @param Request              $request
  * @param SensioParamConverter $configuration
  *
  * @return bool|mixed
  */
 public function execute(Request $request, SensioParamConverter $configuration)
 {
     $id = $request->attributes->get('id');
     $locale = $request->attributes->get('locale');
     $url = $request->attributes->get('url');
     $name = $configuration->getName();
     $options = $configuration->getOptions();
     $resolvedClass = $configuration->getClass();
     $method = $request->getMethod();
     $rawPayload = $request->getContent();
     switch (true) {
         case 'GET' === $method:
             $convertedValue = $this->loadEntity($resolvedClass, $id, $locale, $url);
             break;
         case 'DELETE' === $method:
             $convertedValue = $this->loadEntity($resolvedClass, $id, $locale, $url);
             break;
         case 'PUT' === $method:
             $payload = array_merge(array('id' => $id), json_decode($rawPayload, true));
             $convertedValue = $this->updateEntity($resolvedClass, json_encode($payload));
             break;
         case 'POST' === $method:
             $convertedValue = $this->updateEntity($resolvedClass, $rawPayload);
             break;
     }
     return $convertedValue;
 }
Ejemplo n.º 20
0
 /**
  * {@inheritdoc}
  */
 public function apply(Request $request, ParamConverter $configuration)
 {
     $comment = new Comment();
     $comment->setSubject('old subject');
     $request->attributes->set($configuration->getName(), $comment);
     return true;
 }
Ejemplo n.º 21
0
 function supports(ParamConverter $configuration)
 {
     // Si le nom de l'argument du contrôleur n'est pas "json", on n'applique pas le convertisseur
     if ('json' !== $configuration->getName()) {
         return false;
     }
     return true;
 }
 /**
  * @param Request        $request
  * @param ParamConverter $configuration
  * @return string
  */
 protected function getRequestAttributeName(Request $request, ParamConverter $configuration)
 {
     $param = $configuration->getName();
     if (array_key_exists('id', $configuration->getOptions())) {
         $param = $configuration->getOptions()['id'];
     }
     return $param;
 }
 /**
  * @param ParamConverter $configuration
  * @return string
  */
 private function getServiceIdForClassName(ParamConverter $configuration)
 {
     $service_ids = [];
     $class = $configuration->getClass();
     foreach ($this->handlers as $service_id => $service_class) {
         if ($class === $service_class) {
             $service_ids[] = $service_id;
         }
     }
     if (count($service_ids) === 0) {
         throw new \InvalidArgumentException(sprintf("No service_id found for parameter converter %s.", $configuration->getName()));
     }
     if (count($service_ids) > 1) {
         throw new \InvalidArgumentException(sprintf("More than one service_id found for parameter converter %s.", $configuration->getName()));
     }
     return $service_ids[0];
 }
 /**
  * {@inheritdoc}
  */
 function apply(Request $request, ParamConverter $configuration)
 {
     if (!is_null($route = $this->manager->getRepository($this->repositoryClass)->findOneBy(array('route' => '/' . $request->attributes->get('route'))))) {
         $request->attributes->add(array($configuration->getName() => $route));
         return true;
     }
     return false;
 }
Ejemplo n.º 25
0
 /**
  * {@inheritdoc}
  */
 public function apply(Request $request, ParamConverter $configuration)
 {
     $name = $configuration->getName();
     $slug = $request->get($name);
     $elect = $this->electsService->getElectFromSlug($slug);
     $request->attributes->set('elect', $elect);
     return true;
 }
Ejemplo n.º 26
0
 public function apply(Request $request, ParamConverter $configuration)
 {
     $name = $configuration->getName();
     $attribute = $request->attributes->get($name);
     $wiki = $this->container->get('app.wikis')->getWiki($attribute);
     $request->attributes->set($name, $wiki);
     return true;
 }
 /**
  * {@inheritdoc}
  */
 public function apply(Request $request, ParamConverter $configuration)
 {
     $events = GripControl::decode_websocket_events($request->getContent());
     $dto = new WebSocketEventsDTO();
     $dto->webSocketEvents = $events;
     $dto->connectionId = $request->headers->get('connection-id');
     $format = $configuration->getOptions()['format'];
     $request->attributes->set($configuration->getName(), $dto = $this->resolveEvents($dto, $format));
 }
Ejemplo n.º 28
0
 /**
  * {@inheritdoc}
  */
 public function apply(Request $request, ParamConverter $configuration)
 {
     if (null === ($rawMessageIdentifier = $request->query->get('message_identifier'))) {
         throw new BadRequestHttpException('The `message_identifier` parameter is required');
     }
     $messageIdentifier = StringMessageIdentifier::fromString($rawMessageIdentifier);
     $inspectionRequest = InspectionRequest::fromMessageIdentifier($messageIdentifier);
     $request->attributes->set($configuration->getName(), $inspectionRequest);
 }
 /**
  * {@inheritdoc}
  */
 function apply(Request $request, ParamConverter $configuration)
 {
     $route = $this->manager->getRepository($this->repositoryClass)->findOneBy(array('route' => $request->getPathInfo()));
     if ($route) {
         $request->attributes->add(array($configuration->getName() => $route->getNode()));
         return true;
     }
     return false;
 }
Ejemplo n.º 30
0
 /**
  * @param Request $request
  * @param ParamConverter $configuration
  * @return bool
  */
 public function apply(Request $request, ParamConverter $configuration)
 {
     $value = $request->attributes->get($configuration->getName());
     if ($value === null) {
         throw new NotFoundHttpException('Invalid date given.');
     }
     $request->attributes->set('file', new \SplFileObject($value));
     return true;
 }