Ejemplo n.º 1
0
 /**
  * {@inheritDoc}
  */
 protected function traverseInputs(InputFilterInterface $inputFilter, $values, $callback)
 {
     $returnValues = null;
     foreach ($values as $name => $value) {
         if (!$inputFilter->has($name)) {
             continue;
         }
         $input = $inputFilter->get($name);
         if ($input instanceof InputFilterInterface && is_array($value)) {
             if ($input instanceof CollectionInputFilter) {
                 $filter = $input->getInputFilter();
                 foreach ($value as $key => $subValue) {
                     $filter->setData($subValue);
                     $returnValues[$name][$key] = (array) $this->traverseInputs($filter, $subValue, $callback);
                 }
                 $filter->setData([]);
                 continue;
             }
             $retVal = $this->traverseInputs($input, $value, $callback);
             if (null !== $retVal) {
                 $returnValues[$name] = $retVal;
             }
             continue;
         }
         $retVal = $callback($input, $value);
         if (null !== $retVal) {
             $returnValues[$name] = $retVal;
         }
     }
     return $returnValues;
 }
 /**
  * Validates the attributes according to the configuration and throws an exception in case of invalid input.
  * 
  * @param array $attributes
  * @throws Exception\InvalidInputException
  */
 public function filterValues(array $attributes)
 {
     $this->inputFilter->setData($attributes);
     if (!$this->inputFilter->isValid()) {
         throw new Exception\InvalidInputException($this->inputFilter->getMessages());
     }
     return $this->inputFilter->getValues();
 }
Ejemplo n.º 3
0
 /**
  * build
  *
  * @param InputFilterInterface $inputFilter
  * @param array                $params
  *
  * @return void
  */
 public function build(InputFilterInterface $inputFilter, $params = [])
 {
     if ($inputFilter instanceof MessageParamInterface) {
         $params = array_merge($inputFilter->getMessageParams(), $params);
     }
     $primaryApiMessage = new ApiMessage($this->primaryType, $this->primaryMessage, $this->primarySource, $this->primaryCode, true, $params);
     $this->add($primaryApiMessage);
     $this->parseInputs($inputFilter);
 }
Ejemplo n.º 4
0
 public function login(InputFilterInterface $filter)
 {
     if (!$filter->isValid()) {
         throw new \LogicException('Form is not valid');
     }
     $this->authAdapter->setIdentity($filter->getValue('login'));
     $this->authAdapter->setCredential($filter->getValue('password'));
     $result = $this->authenticationService->authenticate($this->authAdapter);
     return $result->isValid();
 }
Ejemplo n.º 5
0
 /**
  * @param BookEntity           $bookEntity
  * @param InputFilterInterface $filter
  *
  * @throws \LogicException
  * @return BookEntity
  */
 public function update(BookEntity $bookEntity, InputFilterInterface $filter)
 {
     if (!$filter->isValid()) {
         throw new \LogicException('Form is not valid!');
     }
     $data = $filter->getValues();
     $bookEntity = $this->bookRepository->hydrate($bookEntity, $data);
     $this->bookRepository->save($bookEntity);
     return $bookEntity;
 }
Ejemplo n.º 6
0
 /**
  * Initialize instance
  * 
  * @param InputFilterInterface $inputFilter
  * @param string $variables
  * @param string $options
  */
 public function __construct(InputFilterInterface $inputFilter, $variables = null, $options = null)
 {
     parent::__construct($variables, $options);
     $this->setVariable('isValid', $inputFilter->isValid());
     $messages = $inputFilter->getMessages();
     $inputs = array();
     foreach ($inputFilter->getValues() as $name => $value) {
         $inputs[$name] = array('value' => $value, 'messages' => array_key_exists($name, $messages) ? $messages[$name] : array());
     }
     $this->setVariable('inputs', $inputs);
 }
Ejemplo n.º 7
0
 /**
  * @param  InputFilterInterface $inputFilter
  * @return array
  */
 private function extractErrorMessages(InputFilterInterface $inputFilter)
 {
     $errorMessages = $inputFilter->getMessages();
     array_walk($errorMessages, function (&$value, $key) use($inputFilter) {
         if ($inputFilter->has($key) && $inputFilter->get($key) instanceof InputFilterInterface) {
             $value = $this->extractErrorMessages($inputFilter->get($key));
         } else {
             $value = array_values($value);
         }
     });
     return $errorMessages;
 }
Ejemplo n.º 8
0
 /**
  * Get all validators for a given element
  *
  * @param InputFilterInterface $inputFilter
  * @param ElementInterface     $element
  * @return mixed
  */
 static function getValidatorsForElement(InputFilterInterface $inputFilter, ElementInterface $element)
 {
     // Check if we are dealing with a fieldset element
     if (preg_match('/^.*\\[(.*)\\]$/', $element->getName(), $matches)) {
         $elementName = $matches[1];
     } else {
         $elementName = $element->getName();
     }
     if (!$inputFilter->has($elementName)) {
         return;
     }
     $input = $inputFilter->get($elementName);
     // Make sure NotEmpty validator is added when input is required
     // $input->isValid();
     $chain = $input->getValidatorChain();
     return $chain->getValidators();
 }
Ejemplo n.º 9
0
 public function __invoke(Request $req, Response $res)
 {
     $school = $req->getAttribute('school');
     if ($req->isPost()) {
         $this->appFormInputFilter->setData(array_merge($req->getParams(), ['school_id' => $school->id, 'submitted_by' => $this->authService->getIdentity()->mail]));
         $isValid = $this->appFormInputFilter->isValid();
         if ($isValid) {
             $data = $this->appFormInputFilter->getValues();
             $appForm = $this->appFormService->submit($data);
             $_SESSION['applicationForm']['appForm'] = $appForm;
             $res = $res->withRedirect($this->successUrl);
             return $res;
         }
         $this->view['form'] = ['is_valid' => $isValid, 'values' => $this->appFormInputFilter->getValues(), 'raw_values' => $this->appFormInputFilter->getRawValues(), 'messages' => $this->appFormInputFilter->getMessages()];
     }
     $loadForm = (bool) $req->getParam('load', false);
     $this->view['choose'] = !$loadForm && !$req->isPost();
     if (!$req->isPost() && $loadForm) {
         if (null !== ($appForm = $this->appFormService->findSchoolApplicationForm($school->id))) {
             $this->view['form'] = ['values' => $appForm];
         }
     }
     $labs = $this->labService->getLabsBySchoolId($school->id);
     $res = $this->view->render($res, 'application_form/form.twig', ['lab_choices' => array_map(function ($lab) {
         return ['value' => $lab['id'], 'label' => $lab['name']];
     }, $labs), 'type_choices' => array_map(function ($category) {
         return ['value' => $category['id'], 'label' => $category['name']];
     }, $this->assetsService->getAllItemCategories())]);
     return $res;
 }
 /**
  * {@inheritdoc}
  */
 public function isValid($values, $context = null)
 {
     if (!is_array($values)) {
         $this->error(static::ERROR_NOT_ARRAY);
         return false;
     }
     $this->inputFilter->setData($values);
     if (!$this->inputFilter->isValid()) {
         $i = 0;
         foreach ($this->inputFilter->getMessages() as $field => $errors) {
             foreach ($errors as $key => $string) {
                 $this->messages[$i][$field][$key] = $string;
                 $i++;
             }
         }
         return false;
     }
     return true;
 }
Ejemplo n.º 11
0
 /**
  * Add an input to the input filter
  *
  * @param  array|Traversable|InputInterface|InputFilterInterface $input
  * @param  null|string $name
  * @param $disablePurifier
  * @return InputFilter
  */
 public function add($input, $name = null, $disablePurifier = false)
 {
     /**
      * By Default all Inputs will filter against XSS and invalid HTML, attributes and scripts
      */
     $purifier = $this->getHtmlPurifier();
     $input->getFilterChain()->attach(function ($value) use($purifier, $disablePurifier) {
         if ($purifier instanceof HTMLPurifier && !$disablePurifier) {
             if (is_array($value)) {
                 foreach ($value as $key => $v) {
                     $value[$key] = $purifier->purify($v);
                 }
                 return $value;
             } else {
                 return $purifier->purify($value);
             }
         }
         return $value;
     });
     return parent::add($input, $name);
 }
Ejemplo n.º 12
0
 /**
  * @return $this
  * @throws \LogicException
  * @throws \InvalidArgumentException
  */
 protected function extractUserMailFromFormular()
 {
     if (!isset($this->filter)) {
         throw new \InvalidArgumentException('No Form set');
     }
     if (!$this->filter->isValid()) {
         throw new \LogicException('Form is not valid');
     }
     $registerFilter = $this->filter->get('register');
     $this->setName($registerFilter->getValue('name'));
     $this->setEmail($registerFilter->getValue('email'));
     return $this;
 }
Ejemplo n.º 13
0
 /**
  * Execute the request
  *
  * @param  MvcEvent $e
  * @return ListViewModelInterface
  */
 public function onDispatch(MvcEvent $e)
 {
     if ($this->inputFilter) {
         $this->inputFilter->setData($this->query);
         if ($this->inputFilter->isValid()) {
             $validData = $this->inputFilter->getValues();
             $criteria = $this->repository->createCriteria($validData);
             $collection = $this->repository->findMany($criteria);
             $this->viewModel->setCollection($collection);
             $this->viewModel->setInputData($validData);
         } else {
             $this->viewModel->setErrors($this->inputFilter->getMessages());
             $this->viewModel->setInputData($this->query);
         }
     } else {
         $criteria = $this->repository->createCriteria($this->query);
         $collection = $this->repository->findMany($criteria);
         $this->viewModel->setCollection($collection);
         $this->viewModel->setInputData($this->query);
     }
     $e->setResult($this->viewModel);
     return $this->viewModel;
 }
Ejemplo n.º 14
0
 /**
  * Attach defaults provided by the elements to the input filter
  *
  * @param  InputFilterInterface $inputFilter
  * @param  FieldsetInterface $fieldset Fieldset to traverse when looking for default inputs
  * @return void
  */
 public function attachInputFilterDefaults(InputFilterInterface $inputFilter, FieldsetInterface $fieldset)
 {
     $formFactory = $this->getFormFactory();
     $inputFactory = $formFactory->getInputFilterFactory();
     if ($fieldset instanceof Collection && $fieldset->getTargetElement() instanceof FieldsetInterface) {
         $elements = $fieldset->getTargetElement()->getElements();
     } else {
         $elements = $fieldset->getElements();
     }
     if (!$fieldset instanceof Collection || !$fieldset->getTargetElement() instanceof FieldsetInterface || $inputFilter instanceof CollectionInputFilter) {
         foreach ($elements as $name => $element) {
             if ($this->preferFormInputFilter && $inputFilter->has($name)) {
                 continue;
             }
             if (!$element instanceof InputProviderInterface) {
                 if ($inputFilter->has($name)) {
                     continue;
                 }
                 // Create a new empty default input for this element
                 $spec = array('name' => $name, 'required' => false);
                 $input = $inputFactory->createInput($spec);
             } else {
                 // Create an input based on the specification returned from the element
                 $spec = $element->getInputSpecification();
                 $input = $inputFactory->createInput($spec);
                 if ($inputFilter->has($name) && $inputFilter instanceof ReplaceableInputInterface) {
                     $input->merge($inputFilter->get($name));
                     $inputFilter->replace($input, $name);
                     continue;
                 }
             }
             // Add element input filter to CollectionInputFilter
             if ($inputFilter instanceof CollectionInputFilter && !$inputFilter->getInputFilter()->has($name)) {
                 $inputFilter->getInputFilter()->add($input, $name);
             } else {
                 $inputFilter->add($input, $name);
             }
         }
         if ($fieldset === $this && $fieldset instanceof InputFilterProviderInterface) {
             foreach ($fieldset->getInputFilterSpecification() as $name => $spec) {
                 $input = $inputFactory->createInput($spec);
                 $inputFilter->add($input, $name);
             }
         }
     }
     foreach ($fieldset->getFieldsets() as $name => $childFieldset) {
         if (!$childFieldset instanceof InputFilterProviderInterface) {
             if (!$inputFilter->has($name)) {
                 // Add a new empty input filter if it does not exist (or the fieldset's object input filter),
                 // so that elements of nested fieldsets can be recursively added
                 if ($childFieldset->getObject() instanceof InputFilterAwareInterface) {
                     $inputFilter->add($childFieldset->getObject()->getInputFilter(), $name);
                 } else {
                     // Add input filter for collections via getInputFilterSpecification()
                     if ($childFieldset instanceof Collection && $childFieldset->getTargetElement() instanceof InputFilterProviderInterface && $childFieldset->getTargetElement()->getInputFilterSpecification()) {
                         $collectionContainerFilter = new CollectionInputFilter();
                         $spec = $childFieldset->getTargetElement()->getInputFilterSpecification();
                         $filter = $inputFactory->createInputFilter($spec);
                         $collectionContainerFilter->setInputFilter($filter);
                         $inputFilter->add($collectionContainerFilter, $name);
                         // We need to copy the inputs to the collection input filter
                         if ($inputFilter instanceof CollectionInputFilter) {
                             $inputFilter = $this->addInputsToCollectionInputFilter($inputFilter);
                         }
                         // Add child elements from target element
                         $childFieldset = $childFieldset->getTargetElement();
                     } else {
                         $inputFilter->add(new InputFilter(), $name);
                     }
                 }
             }
             $fieldsetFilter = $inputFilter->get($name);
             if (!$fieldsetFilter instanceof InputFilterInterface) {
                 // Input attached for fieldset, not input filter; nothing more to do.
                 continue;
             }
             // Traverse the elements of the fieldset, and attach any
             // defaults to the fieldset's input filter
             $this->attachInputFilterDefaults($fieldsetFilter, $childFieldset);
             continue;
         }
         if ($inputFilter->has($name)) {
             // if we already have an input/filter by this name, use it
             continue;
         }
         // Create an input filter based on the specification returned from the fieldset
         $spec = $childFieldset->getInputFilterSpecification();
         $filter = $inputFactory->createInputFilter($spec);
         $inputFilter->add($filter, $name);
         // Recursively attach sub filters
         $this->attachInputFilterDefaults($filter, $childFieldset);
         // We need to copy the inputs to the collection input filter to ensure that all sub filters are added
         if ($inputFilter instanceof CollectionInputFilter) {
             $inputFilter = $this->addInputsToCollectionInputFilter($inputFilter);
         }
     }
 }
Ejemplo n.º 15
0
 public function getValues()
 {
     return $this->inputFilter->getValues();
 }
Ejemplo n.º 16
0
    /**
     * Attach defaults provided by the elements to the input filter
     * 
     * @param  InputFilterInterface $inputFilter 
     * @param  FieldsetInterface $fieldset Fieldset to traverse when looking for default inputs 
     * @return void
     */
    public function attachInputFilterDefaults(InputFilterInterface $inputFilter, FieldsetInterface $fieldset)
    {
        $formFactory  = $this->getFormFactory();
        $inputFactory = $formFactory->getInputFilterFactory();
        foreach ($fieldset->getElements() as $element) {
            if (!$element instanceof InputProviderInterface) {
                // only interested in the element if it provides input information
                continue;
            }

            $name = $element->getName();
            if ($inputFilter->has($name)) {
                // if we already have an input by this name, use it
                continue;
            }

            // Create an input based on the specification returned from the element
            $spec  = $element->getInputSpecification();
            $input = $inputFactory->createInput($spec);
            $inputFilter->add($input, $name);
        }

        foreach ($fieldset->getFieldsets() as $fieldset) {
            $name = $fieldset->getName();
            if (!$fieldset instanceof InputFilterProviderInterface) {
                if (!$inputFilter->has($name)) {
                    // Not an input filter provider, and no matching input for this fieldset.
                    // Nothing more to do for this one.
                    continue;
                }

                $fieldsetFilter = $inputFilter->get($name);
                if (!$fieldsetFilter instanceof InputFilterInterface) {
                    // Input attached for fieldset, not input filter; nothing more to do.
                    continue;
                }

                // Traverse the elements of the fieldset, and attach any 
                // defaults to the fieldset's input filter
                $this->attachInputFilterDefaults($fieldsetFilter, $fieldset);
                continue;
            }

            if ($inputFilter->has($name)) {
                // if we already have an input/filter by this name, use it
                continue;
            }

            // Create an inputfilter based on the specification returned from the fieldset
            $spec   = $fieldset->getInputFilterSpecification();
            $filter = $inputFactory->createInputFilter($spec);
            $inputFilter->add($filter, $name);
        }
    }
Ejemplo n.º 17
0
 /**
  * Build the InputFilter, validators and filters from form fields
  *
  * @param InputFilterInterface $inputFilter
  */
 private function buildInputFilterFromForm(InputFilterInterface $inputFilter)
 {
     foreach ($this->getNodeList() as $name => $node) {
         if ($inputFilter->has($name)) {
             continue;
         }
         // Detect element type
         $type = $node->getAttribute('type');
         if ($node->tagName === 'textarea') {
             $type = 'textarea';
         } elseif ($node->tagName === 'select') {
             $type = 'select';
         }
         // Add validation
         if (array_key_exists($type, $this->formElements)) {
             $elementClass = $this->formElements[$type];
         } else {
             // Create a default validator
             $elementClass = $this->formElements['text'];
         }
         /** @var \Zend\InputFilter\InputProviderInterface $element */
         $element = new $elementClass($node, $this->document);
         $input = $this->factory->createInput($element);
         $inputFilter->add($input, $name);
     }
 }
Ejemplo n.º 18
0
 /**
  * Attach defaults provided by the elements to the input filter
  *
  * @param  InputFilterInterface $inputFilter
  * @param  FieldsetInterface $fieldset Fieldset to traverse when looking for default inputs
  * @return void
  */
 public function attachInputFilterDefaults(InputFilterInterface $inputFilter, FieldsetInterface $fieldset)
 {
     $formFactory = $this->getFormFactory();
     $inputFactory = $formFactory->getInputFilterFactory();
     foreach ($fieldset->getElements() as $element) {
         if (!$element instanceof InputProviderInterface) {
             // only interested in the element if it provides input information
             continue;
         }
         $name = $element->getName();
         // Create an input based on the specification returned from the element
         $spec = $element->getInputSpecification();
         $input = $inputFactory->createInput($spec);
         $inputFilter->add($input, $name);
     }
     foreach ($fieldset->getFieldsets() as $fieldset) {
         $name = $fieldset->getName();
         if (!$fieldset instanceof InputFilterProviderInterface) {
             if (!$inputFilter->has($name)) {
                 // Add a new empty input filter if it does not exist, so that elements of nested fieldsets can be
                 // recursively added
                 $inputFilter->add(new InputFilter(), $name);
             }
             $fieldsetFilter = $inputFilter->get($name);
             if (!$fieldsetFilter instanceof InputFilterInterface) {
                 // Input attached for fieldset, not input filter; nothing more to do.
                 continue;
             }
             // Traverse the elements of the fieldset, and attach any
             // defaults to the fieldset's input filter
             $this->attachInputFilterDefaults($fieldsetFilter, $fieldset);
             continue;
         }
         if ($inputFilter->has($name)) {
             // if we already have an input/filter by this name, use it
             continue;
         }
         // Create an input filter based on the specification returned from the fieldset
         $spec = $fieldset->getInputFilterSpecification();
         $filter = $inputFactory->createInputFilter($spec);
         $inputFilter->add($filter, $name);
         // Recursively attach sub filters
         $this->attachInputFilterDefaults($filter, $fieldset);
     }
 }
Ejemplo n.º 19
0
 /**
  *
  */
 protected function addMessageFilter()
 {
     $this->inputFilter->add($this->getFactory()->createInput(array('name' => 'message', 'required' => true, 'filters' => array(array('name' => 'StripTags'), array('name' => 'StringTrim')), 'validators' => array(array('name' => 'StringLength', 'options' => array('encoding' => 'UTF-8', 'min' => 1))))));
 }
Ejemplo n.º 20
0
 public function updateInputFilter(InputFilterInterface $addInputFilter, $fieldsetName)
 {
     $inputFilter = $this->getInputFilter();
     if (!in_array($fieldsetName, array_keys($inputFilter->getInputs()))) {
         throw new \Exception("Sorry, {$fieldsetName} is invalid fieldset name", null, null);
     }
     foreach ($addInputFilter->getValues() as $key => $value) {
         $this->addInput($addInputFilter->get($key), $fieldsetName);
     }
 }
Ejemplo n.º 21
0
 public function testGetValue()
 {
     $name = uniqid('name');
     $this->adapterMock->expects($this->once())->method('getValue')->with($name);
     $this->testedObject->getValue($name);
 }
Ejemplo n.º 22
0
 /**
  * @param string $name
  * @return mixed
  */
 public function getValue($name)
 {
     return $this->inputFilter->getValue($name);
 }
Ejemplo n.º 23
0
 /**
  * Attach defaults provided by the elements to the input filter
  *
  * @param  InputFilterInterface $inputFilter
  * @param  FieldsetInterface $fieldset Fieldset to traverse when looking for default inputs
  * @return void
  */
 public function attachInputFilterDefaults(InputFilterInterface $inputFilter, FieldsetInterface $fieldset)
 {
     $formFactory = $this->getFormFactory();
     $inputFactory = $formFactory->getInputFilterFactory();
     if ($this instanceof InputFilterProviderInterface) {
         foreach ($this->getInputFilterSpecification() as $name => $spec) {
             $input = $inputFactory->createInput($spec);
             $inputFilter->add($input, $name);
         }
     }
     foreach ($fieldset->getElements() as $element) {
         $name = $element->getName();
         if ($this->preferFormInputFilter && $inputFilter->has($name)) {
             continue;
         }
         if (!$element instanceof InputProviderInterface) {
             if ($inputFilter->has($name)) {
                 continue;
             }
             // Create a new empty default input for this element
             $spec = array('name' => $name, 'required' => false);
         } else {
             // Create an input based on the specification returned from the element
             $spec = $element->getInputSpecification();
         }
         $input = $inputFactory->createInput($spec);
         $inputFilter->add($input, $name);
     }
     foreach ($fieldset->getFieldsets() as $fieldset) {
         $name = $fieldset->getName();
         if (!$fieldset instanceof InputFilterProviderInterface) {
             if (!$inputFilter->has($name)) {
                 // Add a new empty input filter if it does not exist (or the fieldset's object input filter),
                 // so that elements of nested fieldsets can be recursively added
                 if ($fieldset->getObject() instanceof InputFilterAwareInterface) {
                     $inputFilter->add($fieldset->getObject()->getInputFilter(), $name);
                 } else {
                     $inputFilter->add(new InputFilter(), $name);
                 }
             }
             $fieldsetFilter = $inputFilter->get($name);
             if (!$fieldsetFilter instanceof InputFilterInterface) {
                 // Input attached for fieldset, not input filter; nothing more to do.
                 continue;
             }
             // Traverse the elements of the fieldset, and attach any
             // defaults to the fieldset's input filter
             $this->attachInputFilterDefaults($fieldsetFilter, $fieldset);
             continue;
         }
         if ($inputFilter->has($name)) {
             // if we already have an input/filter by this name, use it
             continue;
         }
         // Create an input filter based on the specification returned from the fieldset
         $spec = $fieldset->getInputFilterSpecification();
         $filter = $inputFactory->createInputFilter($spec);
         $inputFilter->add($filter, $name);
         // Recursively attach sub filters
         $this->attachInputFilterDefaults($filter, $fieldset);
     }
 }
Ejemplo n.º 24
0
 /**
  * @todo remove unused $mailer parameter an fix tests
  *
  * @param InputFilterInterface $filter
  * @param Plugin\Mailer $mailer
  * @param Url $url
  * @throws \LogicException
  * @throws UserDoesNotHaveAnEmailException
  * @throws UserNotFoundException
  */
 public function proceed(InputFilterInterface $filter, Plugin\Mailer $mailer, Url $url)
 {
     if (!$filter->isValid()) {
         throw new \LogicException('Form is not valid');
     }
     $identity = $filter->getValue('identity');
     $suffix = $this->loginFilter->filter();
     if (!($user = $this->userRepository->findByLoginOrEmail($identity, $suffix))) {
         throw new UserNotFoundException('User is not found');
     }
     if (!($email = $user->getInfo()->getEmail())) {
         throw new UserDoesNotHaveAnEmailException('User does not have an email');
     }
     $tokenHash = $this->tokenGenerator->generate($user);
     $resetLink = $url->fromRoute('lang/goto-reset-password', array('token' => $tokenHash, 'userId' => $user->getId()), array('force_canonical' => true));
     $e = new AuthEvent();
     $e->setResetLink($resetLink);
     $e->setUser($user);
     $this->eventManager->trigger(AuthEvent::EVENT_AUTH_NEWPASSWORD, $e);
 }
Ejemplo n.º 25
0
 /**
  * @param InputFilterInterface $inputFilter
  * @return string
  */
 protected function getInputFilterMessage(InputFilterInterface $inputFilter)
 {
     $message = 'Invalid parameters. ';
     foreach ($inputFilter->getMessages() as $element => $error) {
         $message .= $element . ' ';
         foreach ($error as $k => $v) {
             $message .= $v . '. ';
         }
     }
     return $message;
 }
 /**
  * @param $association
  * @param $inputFilter
  *
  * @return InputFilterInterface
  */
 protected function getAssociatedEntityInputFilter($association, InputFilterInterface $inputFilter)
 {
     // Skip handling associations that aren't in the data
     // Ensure the collection value has an input filter
     if (!$inputFilter->has($association)) {
         /*
          * Value must not have been in the inputFilter and wasn't stripped out.
          * Treat as hostile and stop execution.
          */
         throw new InvalidArgumentException('Non-validated input detected: ' . $association);
     }
     $childInputFilter = $inputFilter->get($association);
     if ($childInputFilter instanceof CollectionInputFilter) {
         return $childInputFilter->getInputFilter();
     } else {
         return $childInputFilter;
     }
 }
Ejemplo n.º 27
0
 /**
  * validateUser
  *
  * @param User                 $requestUser requestUser
  * @param InputFilterInterface $inputFilter inputFilter
  *
  * @return Result
  */
 public function validateUser(User $requestUser, InputFilterInterface $inputFilter)
 {
     $validUser = new User();
     $validUser->populate($requestUser);
     $inputFilter->setData($validUser);
     if ($inputFilter->isValid()) {
         $validUser->populate($inputFilter->getValues());
         return new Result($validUser);
     } else {
         $result = new Result($validUser, Result::CODE_FAIL, 'User input not valid');
         foreach ($inputFilter->getInvalidInput() as $error) {
             $msg = $error->getName() . ': ';
             $errs = $error->getMessages();
             foreach ($errs as $key => $val) {
                 $result->setMessage($msg .= "{$val} ({$key})");
             }
         }
         return $result;
     }
 }
Ejemplo n.º 28
0
    /**
     * Validate a PATCH request
     *
     * @param InputFilterInterface $inputFilter
     * @param array|object $data
     * @param bool $isCollection
     * @return bool|ApiProblemResponse
     */
    protected function validatePatch(InputFilterInterface $inputFilter, $data, $isCollection)
    {
        if ($isCollection) {
            $validationGroup = $data;
            foreach ($validationGroup as &$subData) {
                $subData = array_keys($subData);
            }
        } else {
            $validationGroup = array_keys($data);
        }

        try {
            $inputFilter->setValidationGroup($validationGroup);
            return $inputFilter->isValid();
        } catch (InputFilterInvalidArgumentException $ex) {
            $pattern = '/expects a list of valid input names; "(?P<field>[^"]+)" was not found/';
            $matched = preg_match($pattern, $ex->getMessage(), $matches);
            if (! $matched) {
                return new ApiProblemResponse(
                    new ApiProblem(400, $ex)
                );
            }

            return new ApiProblemResponse(
                new ApiProblem(400, 'Unrecognized field "' . $matches['field'] . '"')
            );
        }
    }
Ejemplo n.º 29
0
 /**
  * Traverse the InputFilter and run a callback against each Input and associated value
  *
  * @param  InputFilterInterface $inputFilter
  * @param  array                $values
  * @param  callable             $callback
  * @return array|null
  */
 protected function traverseInputs(InputFilterInterface $inputFilter, $values, $callback)
 {
     $returnValues = null;
     foreach ($values as $name => $value) {
         if (!$inputFilter->has($name)) {
             continue;
         }
         $input = $inputFilter->get($name);
         if ($input instanceof InputFilterInterface && is_array($value)) {
             $retVal = $this->traverseInputs($input, $value, $callback);
             if (null !== $retVal) {
                 $returnValues[$name] = $retVal;
             }
             continue;
         }
         $retVal = $callback($input, $value);
         if (null !== $retVal) {
             $returnValues[$name] = $retVal;
         }
     }
     return $returnValues;
 }
Ejemplo n.º 30
0
 public function __invoke(Request $req, Response $res)
 {
     $school = $req->getAttribute('school');
     if ($req->isPost()) {
         $reqParams = $req->getParams();
         array_splice($reqParams['items'], 0, 0);
         $this->appFormInputFilter->setData(array_merge($reqParams, ['school_id' => $school->id, 'submitted_by' => $this->authService->getIdentity()->mail]));
         $isValid = $this->appFormInputFilter->isValid();
         if ($isValid) {
             $data = $this->appFormInputFilter->getValues();
             $appForm = $this->appFormService->submit($data);
             $_SESSION['applicationForm']['appForm'] = $appForm;
             $res = $res->withRedirect($this->successUrl);
             return $res;
         }
         $this->view['form'] = ['is_valid' => $isValid, 'values' => $this->appFormInputFilter->getValues(), 'raw_values' => $this->appFormInputFilter->getRawValues(), 'messages' => $this->appFormInputFilter->getMessages()];
     }
     $loadForm = (bool) $req->getParam('load', false);
     $this->view['choose'] = !$loadForm && !$req->isPost();
     if (!$req->isPost() && $loadForm) {
         // take care of new options in applications and migrate existing ones
         if (null !== ($appForm = $this->appFormService->findSchoolApplicationForm($school->id))) {
             /**
              * Do mapping of old items to new only if items do exist (old form) 
              * and the map is available at the app settings.
              * TODO: Only one version migrations are supported. If the old items are
              * two or more versions older, they will not be handled.
              */
             // get the existing (db) application form version
             $items_version = $this->version;
             if (isset($appForm['items']) && \count($appForm['items']) > 0) {
                 $items_version = array_values($appForm['items'])[0]['version'];
             }
             if ($this->version != $items_version && isset($appForm['items']) && isset($this->container['settings']['application_form']['itemcategory']['map']) && $this->container['settings']['application_form']['itemcategory']['map']['fromversion'] == $items_version && $this->container['settings']['application_form']['itemcategory']['map']['toversion'] == $this->version && isset($this->container['settings']['application_form']['itemcategory']['map']['items'])) {
                 // if map exists for this version, use it
                 $items_map = $this->container['settings']['application_form']['itemcategory']['map']['items'];
                 $appForm['items'] = array_map(function ($item) use($items_map) {
                     $migrate_values = [];
                     if (isset($items_map[$item['itemcategory_id']]) && intval($items_map[$item['itemcategory_id']]) > 0) {
                         $migrate_values = ['itemcategory_prev' => $item['itemcategory_id'], 'itemcategory_id_prev' => $item['itemcategory_id'], 'itemcategory_id' => intval($items_map[$item['itemcategory_id']])];
                     } else {
                         $migrate_values = ['itemcategory_prev' => '', 'itemcategory_id_prev' => -1];
                     }
                     $migrate_values['prev_form_load'] = true;
                     return array_merge($item, $migrate_values);
                 }, $appForm['items']);
             } elseif ($this->version != $items_version && isset($appForm['items']) && isset($this->container['settings']['application_form']['itemcategory']['map']) && ($this->container['settings']['application_form']['itemcategory']['map']['fromversion'] != $items_version || $this->container['settings']['application_form']['itemcategory']['map']['toversion'] != $this->version)) {
                 // if map does not exist for this version, notify user
                 $items_map = $this->container['settings']['application_form']['itemcategory']['map']['items'];
                 $appForm['items'] = array_map(function ($item) use($items_map) {
                     $migrate_values = ['itemcategory_prev' => '', 'itemcategory_id_prev' => -2, 'prev_form_load' => true];
                     return array_merge($item, $migrate_values);
                 }, $appForm['items']);
             }
             $this->view['form'] = ['values' => $appForm];
         }
     }
     $labs = $this->labService->getLabsBySchoolId($school->id);
     $res = $this->view->render($res, 'application_form/form.twig', ['lab_choices' => array_map(function ($lab) {
         return ['value' => $lab['id'], 'label' => $lab['name']];
     }, $labs), 'type_choices' => array_map(function ($category) {
         return ['value' => $category['id'], 'label' => $category['name']];
     }, $this->assetsService->getAllItemCategories($this->version))]);
     return $res;
 }