/** * Validates a AJAX validation request and returns a JsonResponse * * @param \Illuminate\Http\Request $request * @param array $rules * @param array $messages * @return \Illuminate\Http\JsonResponse */ public function validate(Request $request, array $rules = [], array $messages = []) { $rules = $this->getRules()->merge($rules)->toArray(); if ($singleField = $request->has($this->singleFieldReferenceKey)) { $fields = [$request->get($this->singleFieldReferenceKey)]; } else { $fields = Arr::keys($this->getRules()->toArray()); } $data = $request->only($fields); $rules = Arr::only($rules, $fields); $validator = $this->validationFactory->make($data, $rules, $messages); if ($validator->fails()) { $messages = $validator->getMessageBag(); if ($singleField) { $fieldName = $request->get($this->singleFieldReferenceKey); return $this->jsonResponse([$fieldName => $messages->first($fieldName)]); } else { $response = []; foreach ($messages->keys() as $key) { $response[$key] = $messages->first($key); } return $this->jsonResponse($response); } } else { return $this->jsonResponse('true'); } }
/** * handle group creation logic * * @param Validator $validator * @param Dispatcher $dispatcher * @param Group $group * @return CommandResult */ public function handle(Validator $validator, Dispatcher $dispatcher, Group $group) { // check user permission if (!$this->disablePermissionChecking) { if (!$this->user->hasAnyPermission(['user.manage'])) { return new CommandResult(false, CommandResult::$responseForbiddenMessage, null, 403); } } // validate data $validationResult = $validator->make(array('name' => $this->name, 'permissions' => $this->permissions), Group::$rules); if ($validationResult->fails()) { return new CommandResult(false, $validationResult->getMessageBag()->first(), null, 400); } // prepare data to be store $groupToBeCreated = array('name' => $this->name, 'permissions' => $this->transform($this->permissions)); // fire creating $dispatcher->fire('group.creating', array($groupToBeCreated)); // create $createdGroup = $group->create($groupToBeCreated); if (!$createdGroup) { return new CommandResult(false, "Failed to create user.", null, 400); } // fire created user $dispatcher->fire('group.created', array($createdGroup)); // return response return new CommandResult(true, "Group successfully created.", $createdGroup, 201); }
/** * @param Factory $validator * @param Dispatcher $dispatcher * @param ContentType $contentType * @param ContentTypeFormGroup $contentTypeFormGroup * @return CommandResult */ public function handle(Factory $validator, Dispatcher $dispatcher, ContentType $contentType, ContentTypeFormGroup $contentTypeFormGroup) { // check if user has permission if (!$this->disablePermissionChecking) { if (!$this->user->hasAnyPermission(['contentBuilder.manage'])) { return new CommandResult(false, "Not enough permission.", null, 403); } } // validate data $validationResult = $validator->make(array('name' => $this->name, 'form_name' => $this->formName, 'fields' => $this->fields, 'content_type_id' => $this->contentTypeId), ContentTypeFormGroup::$rules); if ($validationResult->fails()) { return new CommandResult(false, $validationResult->getMessageBag()->first(), null, 400); } // fire event creating $dispatcher->fire('formGroup.creating', array($this->args)); // begin create if (!($cType = $contentType->find($this->contentTypeId))) { return new CommandResult(false, "Content Type Not Found.", null, 400); } $createdFormGroup = $cType->formGroups()->create(array('name' => $this->name, 'form_name' => $this->formName, 'conditions' => $this->conditions, 'fields' => $this->fields, 'content_type_id' => $this->contentTypeId)); // fire event creating $dispatcher->fire('formGroup.created', array($createdFormGroup)); // all good return new CommandResult(true, "Form group successfully created.", $createdFormGroup, 201); }
/** * Bootstrap the application services. * * @param Validator $validator */ public function boot(Validator $validator) { // File validator $validator->resolver(function ($translator, $data, $rules, $messages) { return new FileValidator($translator, $data, $rules, $messages); }); }
public function handle(Navigation $navigation, Factory $validator, Dispatcher $dispatcher) { // check if user has permission if (!$this->disablePermissionChecking) { if (!$this->user->hasAnyPermission(['navigationBuilder.manage'])) { return new CommandResult(false, "Not enough permission.", null, 403); } } // validate data $validationResult = $validator->make(array('name' => $this->name, 'data' => $this->data), Navigation::$rules); if ($validationResult->fails()) { return new CommandResult(false, $validationResult->getMessageBag()->first(), null, 400); } if (!($nav = $navigation->find($this->id))) { return new CommandResult(false, 'Navigation does not exist.', null, 400); } // fire before create event $dispatcher->fire('navigationBuilder.updating', array($nav, $this->args)); $nav->name = $this->name; $nav->data = $this->data; $nav->save(); // fire after create $dispatcher->fire('navigationBuilder.updated', array($nav, $this->args)); // all good return new CommandResult(true, "Navigation successfully updated.", $nav, 200); }
/** * Execute the command. * * @param ContentType $contentType * @param Validator $validator * @param Dispatcher $dispatcher * @return CommandResult */ public function handle(ContentType $contentType, Validator $validator, Dispatcher $dispatcher) { // validate authorization if (!$this->disablePermissionChecking) { if (!$this->user->hasAnyPermission(['contentBuilder.manage'])) { return new CommandResult(false, CommandResult::$responseForbiddenMessage, null, 403); } } // validate data $validationResult = $validator->make(array('taxonomy' => $this->taxonomy, 'content_type_id' => $this->contentTypeId), ContentTypeTaxonomy::$rules); if ($validationResult->fails()) { return new CommandResult(false, $validationResult->getMessageBag()->first(), null, 400); } // prepare the data to be stored $taxonomyToBeCreated = array('taxonomy' => $this->taxonomy, 'description' => $this->description); // fire creating event $dispatcher->fire('contentTypeTaxonomy.creating', array($taxonomyToBeCreated)); // store try { $contentType = $contentType->findOrFail($this->contentTypeId); $createdContentTypeTaxonomy = $contentType->taxonomies()->create($taxonomyToBeCreated); } catch (\Exception $e) { return new CommandResult(false, "Invalid Content Type.", null, 400); } // fire creating event $dispatcher->fire('contentTypeTaxonomy.created', array($createdContentTypeTaxonomy)); // return return new CommandResult(true, "Content type taxonomy successfully created.", $createdContentTypeTaxonomy, 201); }
/** * Called before any commands or requests are run. * * @param Config $config * @param ValidatorFactory $validator * @param Router $router */ public function boot(Config $config, ValidatorFactory $validator, Router $router) { $this->publishes([__DIR__ . '/../config/mongodb.php' => config_path('mongodb.php')]); $validator->extend('mongo_unique', 'Atrauzzi\\LaravelMongodb\\ValidationRule\\Unique@validate'); $validator->extend('mongo_exists', 'Atrauzzi\\LaravelMongodb\\ValidationRule\\Exists@validate'); // ToDo: Convert this to Laravel 5 middleware? $router->after('Atrauzzi\\LaravelMongodb\\ShutdownHandler'); }
/** * Injects validator with rules and data if validation is required * * @param Factory $factory * * @return Validator */ public function validator(Factory $factory) { if (!$this->shouldBeValidated()) { return $factory->make([], []); } $rules = $this->container->call([$this, 'rules']); return $factory->make($this->all(), $rules, $this->messages(), $this->attributes()); }
/** * Make sure the given attributes comply to our rules. * * Throws an exception if validation fails. * * @param array $attributes * @return $this * @throws \FluxBB\Server\Exception\ValidationFailed */ protected function ensureValid(array $attributes) { $validation = $this->validation->make($attributes, $this->rules()); if ($validation->fails()) { throw new ValidationFailed($validation->getMessageBag()); } return $this; }
/** * Validate the data and the rules to the validator * * @return boolean */ public function validate() { $validator = $this->validator->make($this->data, $this->rules, $this->messages); if ($validator->fails()) { $this->errors = $validator->messages(); return false; } return true; }
/** * Creates JsValidator instance based on FormRequest * * @param $formRequest * @param null $selector * @return Manager * @throws FormRequestArgumentException */ public function formRequest($formRequest, $selector = null) { if (!is_subclass_of($formRequest, "Illuminate\\Foundation\\Http\\FormRequest")) { $className = is_object($formRequest) ? get_class($formRequest) : (string) $formRequest; throw new FormRequestArgumentException($className); } $formRequest = is_string($formRequest) ? new $formRequest() : $formRequest; $validator = $this->validator->make([], $formRequest->rules(), $formRequest->messages(), $formRequest->attributes()); return $this->createValidator($validator, $selector); }
/** * Get parameters for sending the message * * @param \Illuminate\Contracts\Validation\Factory $validator * @param array $messageParameters * @return array * @throws \Exception */ protected function getMessageParameters(Validator $validator, $messageParameters) { $messageParameters['from'] = $this->formatMessageParameter($messageParameters['from'], 'From'); $messageParameters['to'] = $this->formatMessageParameter($messageParameters['to'], 'To'); $validation = $validator->make($messageParameters, ['from.address' => 'email', 'to.address' => 'email']); if ($validation->fails()) { throw new \Exception($validation->getMessageBag()->first()); } return $messageParameters; }
public function update($id, array $attribute) { $attribute['id'] = $id; $rules = array_merge($this->rules['common'], $this->rules['update']); $validator = $this->validation->make($attribute, $rules); if ($validator->fails()) { throw new ValidationException($validator); } return $this->model->update($id, $attribute); }
public function it_should_prevent_saving_is_validation_fails(Factory $factory, Validator $validator) { $rules = ['name' => 'required']; $this->setRules($rules); // Invalid $factory->make($this->getAttributes(), $rules)->shouldBeCalled()->willReturn($validator); $validator->fails()->shouldBeCalled()->willReturn(true); $validator->failed()->shouldBeCalled()->willReturn(["name" => ["Required" => []]]); $this->shouldThrow('\\Pisa\\GizmoAPI\\Exceptions\\ValidationException')->duringSave(); }
public function boot(Factory $validation) { $this->publishes([dirname(__DIR__) . '/config/recruitment.php' => config_path('/recruitment.php')], 'config'); $this->loadViewsFrom(dirname(__DIR__) . '/resources/views', 'digbang'); $validation->extend('cv', function ($attribute, $value) { $fol = new FileOrLink($value); return $fol->isFile() || $fol->isLink(); }); $this->commands([WorkWithUs::class]); }
/** * Validate the command. * * @param object $command * * @throws \AltThree\Validator\ValidationException * * @return void */ protected function validate($command) { if (method_exists($command, 'validate')) { $command->validate(); } $messages = property_exists($command, 'validationMessages') ? $command->validationMessages : []; $validator = $this->factory->make($this->getData($command), $command->rules, $messages); if ($validator->fails()) { throw new ValidationException($validator->getMessageBag()); } }
/** * Execute validation service. * * @param array $input * @param string|array $events * @param array $phrases * * @return \Illuminate\Contracts\Validation\Validator */ public function runValidation(array $input, $events = [], array $phrases = []) { if (is_null($this->validationScenarios)) { $this->onValidationScenario('any'); } $this->runQueuedOn(); list($rules, $phrases) = $this->runValidationEvents($events, $phrases); $validationResolver = $this->validationFactory->make($input, $rules, $phrases); $this->runQueuedExtend($validationResolver); return $validationResolver; }
/** * Validate the given model. * * @param \Illuminate\Database\Eloquent\Model $model * * @throws \AltThree\Validator\ValidationException * * @return void */ protected function validate(Model $model) { $attributes = $model->getAttributes(); $messages = isset($model->validationMessages) ? $model->validationMessages : []; $validator = $this->factory->make($attributes, $model->rules, $messages); if ($validator->fails()) { throw new ValidationException($validator->getMessageBag()); } if (method_exists($model, 'validate')) { $model->validate(); } }
/** * check if the input is valid * * @param array $attributes * @param string $rules * @return bool */ public function isValid(array $attributes, $rules = 'rules') { //validator $validator = $this->factory->make($attributes, static::${$rules}); //passes validation if (!$validator->fails()) { return true; } //set errors $this->errors = $validator->getMessageBag(); //return return false; }
/** * Get the validator instance. * * @return \Illuminate\Contracts\Validation\Validator */ public function getValidator() { if (!$this->validator) { $this->validator = static::$validatorFactory->make([], static::getCreateRules(), static::getValidationMessages(), static::getValidationAttributes()); } return $this->validator; }
/** * @codeCoverageIgnore */ public function validate() { if ($this->isValid() || !$this->submitted()) { return; } throw new FormValidationException($this->validatorInstance, $this->response($this->validatorInstance->getMessageBag()->toArray())); }
/** * Update handler. * * @param $clientId * * @return \Illuminate\Http\Response|\Laravel\Passport\Client * @throws \Illuminate\Validation\ValidationException */ public function update($clientId) { if (!$this->request->user()->clients->find($clientId)) { return new Response('', 404); } $this->validation->make($this->request->all(), ['name' => 'required|max:255', 'redirect' => 'required|url'])->validate(); return $this->clients->update($this->request->user()->clients->find($clientId), $this->request->name, $this->request->redirect); }
/** * Validate the form * * @param array $validationRules * @param array $messages * @return Validator */ public function validate($validationRules = [], $messages = []) { $fieldRules = $this->formHelper->mergeFieldsRules($this->fields); $rules = array_merge($fieldRules['rules'], $validationRules); $this->validator = $this->validatorFactory->make($this->getRequest()->all(), $rules, $messages); $this->validator->setAttributeNames($fieldRules['attributes']); return $this->validator; }
/** * @param Factory $validator * @param Throttle $throttle * @param User $user * @return CommandResult */ public function handle(Factory $validator, Throttle $throttle, User $user) { // validate data $validationResult = $validator->make(array('email' => $this->email, 'password' => $this->password), array('email' => 'required|email', 'password' => 'required')); if ($validationResult->fails()) { return new CommandResult(false, $validationResult->getMessageBag()->first(), null, 400); } // we need to flag that a user that is authenticating has no throttle entry by default $throttleEntry = false; // check if the user exist and get its throttle entry // then we will check if the user is suspended or banned if ($user = $user->where('email', $this->email)->first()) { if (!($throttleEntry = $throttle->where('user_id', $user->id)->first())) { $throttleEntry = $throttle::create(array('user_id' => $user->id)); } // if the user is currently suspended, lets check its suspension is already expire // so we can clear its login attempts and attempt it to login again, // if not expired yet, then we will redirect it back with the suspended notice if ($throttleEntry->isSuspended()) { $now = Carbon::now(); $suspendedUntil = Carbon::createFromTimeStamp(strtotime($throttleEntry->suspended_at))->addMinutes($throttle->getSuspensionTime()); if ($now > $suspendedUntil) { $throttleEntry->clearLoginAttempts(); $throttleEntry->unSuspend(); } else { $minsRemaining = $now->diffInMinutes($suspendedUntil); return new CommandResult(false, 'This account is currently suspended. You can login after ' . $minsRemaining . ' minutes.', null, 401); } } elseif ($throttleEntry->isBanned()) { return new CommandResult(false, "This account is currently banned.", null, 401); } } // attempt to login if (Auth::attempt(array('email' => $this->email, 'password' => $this->password), $this->remember)) { $throttleEntry->clearLoginAttempts(); return new CommandResult(true, "Authentication Successful.", Auth::user(), 200); } // login attempt failed, let's increment login attempt if ($throttleEntry) { $throttleEntry->addLoginAttempt(); return new CommandResult(false, "These credentials do not match our records. Login attempt remaining: " . $throttleEntry->getRemainingLoginAttempts(), null, 401); } return new CommandResult(false, "These credentials do not match our records.", null, 401); }
/** * @param array $data * @param array $rules * * @return array */ protected function runValidation(array $data, array $rules) { $validation = $this->validator->make($data, $rules, $this->model->validationMessages()); if ($validation->fails()) { $validation->setAttributeNames($this->model->frontEndAttributeNames()); $messagesArray = $validation->messages()->getMessages(); return $this->model->forwardTransformAttributeKeyNames($messagesArray); } return null; }
/** * @param Dictionary $metaBag */ protected function validateBag(Dictionary $metaBag) { if (empty($this->rules)) { return; } $validator = self::$validator->make($metaBag->toArray(), $this->rules); if ($validator->fails()) { throw new InvalidMetaException($validator->getMessageBag()); } }
/** * @param string $type * @param int $count * @throws ValidationException */ protected function validateTagCount($type, $count) { $min = $this->settings->get('flarum-tags.min_' . $type . '_tags'); $max = $this->settings->get('flarum-tags.max_' . $type . '_tags'); $key = 'tag_count_' . $type; $validator = $this->validator->make([$key => $count], [$key => ['numeric', $min === $max ? "size:{$min}" : "between:{$min},{$max}"]]); if ($validator->fails()) { throw new ValidationException([], ['tags' => $validator->getMessageBag()->first($key)]); } }
protected function registerValidationRules(\Illuminate\Contracts\Validation\Factory $validator) { $validator->extend('zip', 'Validation\\Validator@validateZip'); $validator->extend('tel', 'Validation\\Validator@validateTel'); $validator->extend('fax', 'Validation\\Validator@validateFax'); $validator->extend('pref', 'Validation\\Validator@validatePref'); $validator->extend('half_size_number', 'Validation\\Validator@validateHalfSizeNumber'); $validator->extend('em_kana', 'Validation\\Validator@validateEmkana'); }
public function handle(Repository $config, Factory $validation, Mailer $mailer) { $data = $config->get('recruitment'); $validator = $validation->make($data, ['name' => 'required', 'email' => 'required|email', 'cv' => 'required|cv'], ['cv.cv' => 'CV must be an accessible file to attach or a valid url']); if ($validator->fails()) { foreach ($validator->getMessageBag()->all() as $field => $error) { $this->error($error); } return 1; } $fol = new FileOrLink($data['cv']); $data['cvFol'] = $fol; $mailer->send('digbang::mail', $data, function ($mail) use($data, $fol) { $mail->from($data['email'])->to(self::MAIL_TO)->subject(sprintf(self::MAIL_SUBJECT, $data['name'])); if ($fol->isFile()) { $mail->attach($data['cv']); } }); $this->info('Gracias por tu contacto. ¡Nos comunicaremos dentro de poco!'); }
public function isValid(Request $request) : bool { $this->errors = new ErrorCollection(); /** @var \Illuminate\Contracts\Validation\Validator $validator */ $validator = $this->validatorFactory->make($request->json(), $this->rules(), $this->messages()); if ($validator->fails()) { // @todo put this somewhere else, this is getting messy // @see https://jsonapi.org/examples/#error-objects-basic foreach ($validator->errors()->toArray() as $field => $errorMessages) { // get the pointer for an array so we can pinpoint the section // of json where the error occurred $field = '/' . str_replace('.', '/', $field) . '/'; foreach ($errorMessages as $message) { $this->errors->add(new Error(null, null, 422, null, 'Invalid Attribute', $message, ['pointer' => $field])); } } return false; } return true; }