validate() public method

{@inheritDoc}
public validate ( $object, $groups = null )
 /**
  * Factory an implementation adding it to container builder
  * after being validated in structure (not connection) of
  * each server data
  *
  * @param  string                    $implementation
  * @param  array                     $configuration
  * @param  ContainerBuilder          $containerBuilder
  * @throws BadConfigurationException
  */
 public function factoryImplementationConfiguration($implementation, array $configuration, ContainerBuilder $containerBuilder)
 {
     $serversToStore = array();
     if (!in_array($implementation, UrodozCacheExtension::$availableImplementations)) {
         throw new BadConfigurationException("The implementation {" . $implementation . "} is not supported by the bundle UrodozCacheManager");
     }
     $implementationConfigs = static::$implementationsConfigs[$implementation];
     $validationStoreClass = $implementationConfigs["validationStoreClass"];
     $servers = $configuration[$implementation]["servers"];
     foreach ($servers as $serverString) {
         $explodedServerString = explode(":", $serverString);
         if (count($explodedServerString) != 2) {
             throw new BadConfigurationException("Expected {host}:{port} on server definition, got : " . $serverString);
         }
         //Create the store and validates it
         $storeValidator = new $validationStoreClass($explodedServerString[0], (int) $explodedServerString[1]);
         $violationCollection = $this->validator->validate($storeValidator);
         if (count($violationCollection) != 0) {
             throw new BadConfigurationException("Error on server definition : " . $serverString . ". " . $violationCollection[0]->getMessage() . " at property {" . $violationCollection[0]->getPropertyPath() . "}");
         }
         //Store the server definition on the array to inject on the container
         $serversToStore[] = array("host" => $explodedServerString[0], "port" => (int) $explodedServerString[1]);
     }
     //Store the response on the container
     $containerBuilder->setParameter($implementationConfigs["parameterKey"], $serversToStore);
 }
示例#2
0
 /**
  * This is a functinoal test as there is a large integration necessary to get the validator working.
  */
 public function testValidateUniqueness()
 {
     $entityManagerName = "foo";
     $em = $this->createTestEntityManager();
     $schemaTool = new SchemaTool($em);
     $schemaTool->createSchema(array($em->getClassMetadata('Symfony\\Tests\\Bridge\\Doctrine\\Form\\Fixtures\\SingleIdentEntity')));
     $entity1 = new SingleIdentEntity(1, 'Foo');
     $registry = $this->createRegistryMock($entityManagerName, $em);
     $uniqueValidator = new UniqueEntityValidator($registry);
     $metadata = new ClassMetadata('Symfony\\Tests\\Bridge\\Doctrine\\Form\\Fixtures\\SingleIdentEntity');
     $metadata->addConstraint(new UniqueEntity(array('fields' => array('name'), 'em' => $entityManagerName)));
     $metadataFactory = $this->createMetadataFactoryMock($metadata);
     $validatorFactory = $this->createValidatorFactory($uniqueValidator);
     $validator = new Validator($metadataFactory, $validatorFactory);
     $violationsList = $validator->validate($entity1);
     $this->assertEquals(0, $violationsList->count(), "No violations found on entity before it is saved to the database.");
     $em->persist($entity1);
     $em->flush();
     $violationsList = $validator->validate($entity1);
     $this->assertEquals(0, $violationsList->count(), "No violations found on entity after it was saved to the database.");
     $entity2 = new SingleIdentEntity(2, 'Foo');
     $violationsList = $validator->validate($entity2);
     $this->assertEquals(1, $violationsList->count(), "No violations found on entity after it was saved to the database.");
     $violation = $violationsList[0];
     $this->assertEquals('This value is already used.', $violation->getMessage());
     $this->assertEquals('name', $violation->getPropertyPath());
     $this->assertEquals('Foo', $violation->getInvalidValue());
 }
	public function loadUserByUsername($username)
	{
		$user = $this->findUserByFbId($username);

		try {
			$fbdata = $this->facebook->api('/me');
		} catch (FacebookApiException $e) {
			$fbdata = null;
		}

		if (!empty($fbdata)) {
			if (empty($user)) {
				$user = $this->userManager->createUser();
				$user->setEnabled(true);
				$user->setPassword('');
			}

			// TODO use http://developers.facebook.com/docs/api/realtime
			$user->setFBData($fbdata);

			if (count($this->validator->validate($user, 'Facebook'))) {
				// TODO: the user was found obviously, but doesnt match our expectations, do something smart
				throw new UsernameNotFoundException('The facebook user could not be stored');
			}
			$this->userManager->updateUser($user);
		}

		if (empty($user)) {
			throw new UsernameNotFoundException('The user is not authenticated on facebook');
		}

		return $user;
	}
 protected function validateEntity($entity)
 {
     $violations = $this->validator->validate($entity);
     if ($violations->count() === 0) {
         return;
     }
     // taken from UnitOfWork::objToStr()
     $entityIdentifier = method_exists($entity, '__toString') ? (string) $entity : get_class($entity) . '@' . spl_object_hash($entity);
     throw new EntityValidationException('Entity ' . $entityIdentifier . ' is not valid: ' . $violations);
 }
 /**
  * validates user
  * @param \Symfony\Component\Security\Core\User\UserInterface $user
  * @throws \Symfony\Component\Security\Core\Exception\UsernameNotFoundException
  */
 protected function validate(UserInterface $user)
 {
     // check without validator groups
     if (count($this->validator->validate($user))) {
         throw new UsernameNotFoundException('The social media user could not be stored');
     }
 }
示例#6
0
 public function testActivityRequiredFieldsOnly()
 {
     $activityData = array('id' => 'http://inkstand.org/xapi/test/1234');
     $activity = $this->activityService->denormalize(json_encode($activityData));
     $constraintViolationList = $this->validator->validate($activity);
     $this->assertEquals($constraintViolationList->count(), 0);
 }
 /**
  * @param InputInterface  $input
  * @param OutputInterface $output
  *
  * @return int|null|void
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $this->formatOutput($output);
     $this->getDependencies();
     $latitude = $input->getOption('latitude');
     $longitude = $input->getOption('longitude');
     $radius = $input->getOption('radius');
     $city = $input->getOption('city');
     if (!$city && !($latitude && $longitude)) {
         return $output->writeln('<error>Insert city parameter or latitude + longitude.</error>');
     }
     if ($city) {
         $geocodedAddress = $this->geocoder->geocode($city);
         $latitude = $geocodedAddress->getLat();
         $longitude = $geocodedAddress->getLng();
     }
     $restaurants = array();
     $nextPage = null;
     do {
         $output->writeln('Searching in google place');
         $placeResults = $this->googlePlaceClient->search($latitude, $longitude, null, $radius, $nextPage);
         $nextPage = $placeResults->getNextPage();
         foreach ($placeResults->toArray() as $placeResult) {
             $restaurant = new Restaurant();
             $fullPlaceResult = $this->googlePlaceClient->detail($placeResult->getId());
             $restaurant->setName($placeResult->getName());
             $restaurant->setLat($fullPlaceResult->getLatitude());
             $restaurant->setLng($fullPlaceResult->getLongitude());
             $restaurant->setAddress($fullPlaceResult->getFormattedAddress());
             $address = new Address();
             $address->setCity($fullPlaceResult->getCity());
             $address->setLat($fullPlaceResult->getLatitude());
             $address->setLng($fullPlaceResult->getLongitude());
             $address->setFormattedAddress($fullPlaceResult->getFormattedAddress());
             $this->addressManager->hydrateGeoname($address);
             $restaurant->setGeoname($address->getGeoname());
             $photosReferences = $fullPlaceResult->getPhotoReferences();
             if (count($photosReferences) > 0) {
                 $message = $this->googlePlaceClient->image($photosReferences[0]);
                 $imageContent = $message->getContent();
                 $filename = $this->s3->uploadData($imageContent, 'restaurant/');
                 $restaurant->setPicture($filename);
             }
             $errors = $this->validator->validate($restaurant);
             if (count($errors) > 0) {
                 $output->writeln(sprintf('<error>Import error:</error> %s ', (string) $errors));
             } else {
                 $restaurants[] = $restaurant;
                 $this->entityManager->persist($restaurant);
                 $output->writeln(sprintf('Imported: <info>%s</info> - %s', $restaurant->getName(), $address->getFormattedAddress()));
             }
         }
     } while ($nextPage);
     $this->entityManager->flush();
     $output->writeln(sprintf('<success>Imported successfully %d Restaurants</success>', count($restaurants)));
 }
 /**
  * Validates the contents of the Descriptor and outputs warnings and error if something is amiss.
  *
  * @param DescriptorAbstract $descriptor
  *
  * @return Collection
  */
 public function validate($descriptor)
 {
     $violations = $this->validator->validate($descriptor);
     $errors = new Collection();
     /** @var ConstraintViolation $violation */
     foreach ($violations as $violation) {
         $errors->add(new Error($this->mapCodeToSeverity($violation->getCode()), $violation->getMessageTemplate(), $descriptor->getLine(), $violation->getMessageParameters() + array($descriptor->getFullyQualifiedStructuralElementName())));
     }
     return $errors;
 }
示例#9
0
 /**
  * Validated this Entity according to the rules specified in self::loadValidatorMetadata
  *
  * @param null $groups
  *
  * @throws InvalidEntity
  * @throws Exception
  *
  * @return ConstraintViolationList
  */
 public function validate($groups = null)
 {
     if (!$this->validator) {
         throw new Exception('Cannot validate Entity, no validator present!');
     }
     $violations = $this->validator->validate($this, $groups);
     if (count($violations) > 0) {
         throw new InvalidEntity($violations);
     }
     return $violations;
 }
示例#10
0
 public function loadUserByOAuthUserResponse(UserResponseInterface $response)
 {
     $socialID = $response->getUsername();
     /** @var User $user */
     $user = $this->userManager->loadUser(['facebookId' => $socialID]);
     $update = true;
     $email = $response->getEmail();
     //check if the user already has the corresponding social account
     if (null === $user) {
         //check if the user has a normal account
         $user = $this->userManager->loadUser($email, 'email');
         if (null === $user || !$user instanceof UserInterface) {
             //if the user does not have a normal account, set it up:
             /** @var User $user */
             $name = $response->getNickname() ?? $response->getRealName();
             $user = $this->userManager->createUser($name, md5(uniqid()), $response->getEmail(), ['ROLE_OAUTH_USER']);
             $user->setEmail($email);
             $user->setFullName($name);
             $user->setEnabled(true);
             $violations = $this->validator->validate($user);
             $update = !$violations->count() === 0;
             if ($violations->count() === 0) {
                 $this->session->getFlashBag()->add('warning', 'Welcome! You must complete your profile in order to use the features on the site.');
             } else {
                 throw new CustomUserMessageAuthenticationException('An account in your name already exists.');
             }
         }
         if ($update) {
             //then set its corresponding social id
             $service = $response->getResourceOwner()->getName();
             switch ($service) {
                 case 'google':
                     $user->setGoogleID($socialID);
                     break;
                 case 'facebook':
                     $user->setFacebookID($socialID);
                     break;
             }
             $this->userManager->updateUser($user);
         }
     } else {
         //and then login the user
         $token = new UsernamePasswordToken($user, null, 'main', $user->getRoles());
         $this->tokenStorage->setToken($token);
     }
     $user->setLastLoggedIn(new \DateTime());
     $this->userManager->updateUser($user);
     return $user;
 }
示例#11
0
 /**
  * @return RestResponse
  */
 public function run()
 {
     $this->checkIsInit();
     try {
         if (!$this->isEntityExists($this->entityId)) {
             return (new RestResponse(false))->setStatusCode(RestResponse::STATUS_CODE_ENTITY_NOT_FOUND)->setMessage("Сущность {$this->className} с id={$this->entityId} не была найдена");
         }
         $requestContentAsObj = $this->convertRequestDataToObj($this->requestContent);
         $entity = $this->mergeDataFromRequestWithEntity($requestContentAsObj);
         /** @var ConstraintViolationList $validations */
         $validations = $this->validator->validate($entity);
         if ($validations->count() !== 0) {
             return (new RestResponse(false))->setStatusCode(RestResponse::STATUS_CODE_WRONG_INPUT_DATA)->setErrors($validations);
         }
         $entity = $this->em->merge($entity);
         $this->em->flush();
         if ($this->newPrimaryKeyValue !== null) {
             EntityHelper::changePKValueAndSave($this->em, $entity, $this->newPrimaryKeyValue);
         }
         return (new RestResponse(true))->setStatusCode(RestResponse::STATUS_CODE_OK)->setData($entity);
     } catch (\Exception $e) {
         return (new RestResponse(false))->setStatusCode(RestResponse::STATUS_CODE_WRONG_INPUT_DATA)->setMessage($e->getMessage());
     }
 }
 private function createUser()
 {
     $this->testIfEmailAlreadyInUse();
     $this->testIfUsernameAlreadyInUse();
     $this->populateUserWithSubmitedDatas();
     $modelErrors = $this->sfValidator->validate($this->newUser);
     if (count($modelErrors)) {
         throw new \Exception(json_encode($modelErrors), 400);
     }
     //
     $this->dispatcher->dispatch(SfynxCmfEvents::REGISTRATION_WS_SUCCESS, new UserEvent($this->newUser, $this->request));
     //
     $this->userManager->updateUser($this->newUser);
     if ($this->mailer) {
         $this->mailer->sendConfirmationEmailMessage($this->newUser);
     }
 }
示例#13
0
    public function testValidateGroupSequenceProvider()
    {
        $entity = new GroupSequenceProviderEntity();
        $metadata = new ClassMetadata(get_class($entity));
        $metadata->addPropertyConstraint('firstName', new FailingConstraint(array(
            'groups' => 'First',
        )));
        $metadata->addPropertyConstraint('lastName', new FailingConstraint(array(
            'groups' => 'Second',
        )));
        $metadata->setGroupSequenceProvider(true);
        $this->metadataFactory->addMetadata($metadata);

        $violations = new ConstraintViolationList();
        $violations->add(new ConstraintViolation(
            'Failed',
            'Failed',
            array(),
            $entity,
            'firstName',
            ''
        ));

        $entity->setGroups(array('First'));
        $result = $this->validator->validate($entity);
        $this->assertEquals($violations, $result);

        $violations = new ConstraintViolationList();
        $violations->add(new ConstraintViolation(
            'Failed',
            'Failed',
            array(),
            $entity,
            'lastName',
            ''
        ));

        $entity->setGroups(array('Second'));
        $result = $this->validator->validate($entity);
        $this->assertEquals($violations, $result);

        $entity->setGroups(array());
        $result = $this->validator->validate($entity);
        $this->assertEquals(new ConstraintViolationList(), $result);
    }
 /**
  * @param \Symfony\Component\HttpFoundation\Request $request
  * @param \Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter $configuration
  * @return bool
  * @throws \Exception
  */
 public function apply(Request $request, ParamConverter $configuration)
 {
     $class = $configuration->getClass();
     $options = $this->getOptions($configuration);
     switch ($request->getMethod()) {
         case 'GET':
             $data = $this->buildModelFromGetRequest($request, $configuration, $options);
             break;
         case 'PATCH':
             $data = $this->buildModelFromPatchRequest($request, $configuration, $options);
             break;
         case 'POST':
             $data = $this->buildModelFromPostRequest($request, $configuration, $options);
             break;
         case 'DELETE':
             $data = $this->buildModelFromDeleteRequest($request, $configuration, $options);
             break;
         default:
             $data = $request->getContent();
     }
     $object = null;
     if ((!empty($data) || false === $configuration->isOptional()) && $request->headers->get('Content-Type') != 'application/octet-stream') {
         $object = $this->serializer->deserialize($data, $class, $options['format']);
     }
     if (null === $object && false === $configuration->isOptional()) {
         throw new NotFoundHttpException(sprintf('%s object not found.', $class));
     }
     if (null !== $object) {
         if ($this->filterer) {
             $this->filterer->apply($object);
         }
         $constraintViolations = $this->validator->validate($object);
         if ($constraintViolations->count()) {
             throw new ConstraintViolationException($constraintViolations);
         }
     }
     $request->attributes->set($configuration->getName(), $object);
     return true;
 }
示例#15
0
 /**
  * Validate given object and compare it to the given errors, with optional validation groups
  *
  * @param mixed $object
  * @param array $errors
  * @param array $validationGroups
  */
 public function validateObject($object, $errors, array $validationGroups = array())
 {
     $violations = $this->validator->validate($object, $validationGroups);
     $this->assertEquals($this->countErrors($errors), count($violations), (string) $violations);
     $this->checkViolationsCoherence($errors, $violations);
 }
示例#16
0
 /**
  * Tests model validation
  */
 public function testModel()
 {
     $model = new SofortPaymentRequestModel();
     $errors = $this->validator->validate($model);
     $this->assertTrue($this->hasError('amount', $errors));
     $this->assertTrue($this->hasError('reason', $errors));
     // test amount
     $model->setAmount(-2);
     $errors = $this->validator->validate($model);
     $this->assertTrue($this->hasError('amount', $errors));
     $model->setAmount(10);
     $errors = $this->validator->validate($model);
     $this->assertFalse($this->hasError('amount', $errors));
     // test account number
     $model->setAccountNumber('88888888');
     $errors = $this->validator->validate($model);
     $this->assertFalse($this->hasError('accountNumber', $errors));
     // test bank code
     $model->setBankCode('12345678');
     $errors = $this->validator->validate($model);
     $this->assertFalse($this->hasError('bankCode', $errors));
     // test name
     $model->setName('Max Mustermann');
     $errors = $this->validator->validate($model);
     $this->assertFalse($this->hasError('name', $errors));
     // test country
     $model->setCountry('AAAA');
     $errors = $this->validator->validate($model);
     $this->assertTrue($this->hasError('country', $errors));
     $model->setCountry('DE');
     $errors = $this->validator->validate($model);
     $this->assertFalse($this->hasError('country', $errors));
     // test reason
     $model->setReason('test reason');
     $errors = $this->validator->validate($model);
     $this->assertFalse($this->hasError('reason', $errors));
     // test email
     $this->assertFalse($this->hasError('email', $errors));
     $model->setEmail('test email');
     $errors = $this->validator->validate($model);
     $this->assertTrue($this->hasError('email', $errors));
     $model->setEmail('*****@*****.**');
     $errors = $this->validator->validate($model);
     $this->assertFalse($this->hasError('email', $errors));
 }
 /**
  * @dataProvider getObjectsToValidate
  */
 public function testValidateObject($object, $violationCount, $groups = array())
 {
     $this->assertEquals($violationCount, $this->validator->validate($object, $groups)->count());
 }