Exemplo n.º 1
0
 public function setUp()
 {
     parent::setUp();
     $this->translator = new Translator(new \Illuminate\Translation\FileLoader(new \Illuminate\Filesystem\Filesystem(), __DIR__ . '/../sample-lang'), 'en');
     $this->translator->setLocale('en');
     $this->factory = new Factory($this->translator);
     $validator = new JalaliValidator();
     $this->factory->extend('jalali', function ($attribute, $value, $parameter) use($validator) {
         return $validator->validateJalali($attribute, $value, $parameter);
     });
     $this->factory->extend('jalali_after', function ($attribute, $value, $parameter) use($validator) {
         return $validator->validateAfter($attribute, $value, $parameter);
     });
     $this->factory->extend('jalali_before', function ($attribute, $value, $parameter) use($validator) {
         return $validator->validateBefore($attribute, $value, $parameter);
     });
     $this->factory->replacer('jalali', function ($message, $attribute, $rule, $parameter) use($validator) {
         return $validator->replaceJalali($message, $attribute, $rule, $parameter);
     });
     $this->factory->replacer('jalali_after', function ($message, $attribute, $rule, $parameter) use($validator) {
         return $validator->replaceAfterOrBefore($message, $attribute, $rule, $parameter);
     });
     $this->factory->replacer('jalali_before', function ($message, $attribute, $rule, $parameter) use($validator) {
         return $validator->replaceAfterOrBefore($message, $attribute, $rule, $parameter);
     });
 }
Exemplo n.º 2
0
 /**
  * Extend validator.
  *
  * @param  string         $name
  * @param  string         $class
  * @param  \Closure|null  $replacer
  */
 private function extendValidator($name, $class, Closure $replacer = null)
 {
     $this->validator->extend($name, $class . '@validate' . studly_case($name));
     if (!is_null($replacer)) {
         $this->validator->replacer($name, $replacer);
     }
 }
 /**
  * Create a new FormRequest instance.
  *
  * @param \Illuminate\Validation\Factory $factory
  * @return void
  */
 public function __construct(ValidatonFactory $factory)
 {
     $factory->extend('valid_token', function ($attribute, $value, $parameters, $validator) {
         $secret = Crypt::decrypt($this->user->google2fa_secret);
         return Google2FA::verifyKey($secret, $value);
     }, 'Not a valid token');
     $factory->extend('used_token', function ($attribute, $value, $parameters, $validator) {
         $key = $this->user->id . ':' . $value;
         return !Cache::has($key);
     }, 'Cannot resue token');
 }
 public function __construct(Factory $factory)
 {
     //Custom Validator Rut
     $factory->extend('old_password', function ($attribute, $value, $parameters) {
         $id = $this->id;
         $usuario = Usuario::find($id);
         return Hash::check($value, $usuario->password);
     }, 'La Constraseña actual no corresponde');
     $factory->extend('rut_valid', function ($attribute, $value, $parameters) {
         return Rut::check($value);
     }, 'El campo Rut no tiene un formato válido');
 }
 /**
  * Overwrite the parent constructor to define a new validator.
  *
  * @param  Factory $factory
  * @return void
  * @SuppressWarnings(PHPMD.UnusedLocalVariable)
  */
 public function __construct(Factory $factory)
 {
     $factory->extend('channel', function ($attribute, $value, $parameters) {
         $first_character = substr($value, 0, 1);
         return ($first_character === '#' || $first_character === '@') && strlen($value) > 1;
     });
 }
Exemplo n.º 6
0
 /**
  * Overwrite the parent constructor to define a new validator.
  *
  * @param  Factory $factory
  * @return void
  * @SuppressWarnings(PHPMD.UnusedLocalVariable)
  */
 public function __construct(Factory $factory)
 {
     $factory->extend('repository', function ($attribute, $value, $parameters) {
         if (preg_match('/^(ssh|git|https?):\\/\\//', $value)) {
             // Plain old git repo
             return true;
         }
         if (preg_match('/^(.*)@(.*):(.*)\\/(.*)\\.git/', $value)) {
             // Gitlab
             return true;
         }
         /*
         TODO: improve these regexs, using the following stolen from PHPCI (sorry Dan!)
         
         'ssh': /git\@github\.com\:([a-zA-Z0-9_\-]+\/[a-zA-Z0-9_\-]+)\.git/,
         'git': /git\:\/\/github.com\/([a-zA-Z0-9_\-]+\/[a-zA-Z0-9_\-]+)\.git/,
         'http': /https\:\/\/github\.com\/([a-zA-Z0-9_\-]+\/[a-zA-Z0-9_\-]+)(\.git)?/
         */
         if (preg_match('/^[a-zA-Z0-9_\\-]+\\/[a-zA-Z0-9_\\-\\.]+$/', $value)) {
             // Github
             return true;
         }
         /*
         'ssh': /git\@bitbucket\.org\:([a-zA-Z0-9_\-]+\/[a-zA-Z0-9_\-]+)\.git/,
         'http': /https\:\/\/[a-zA-Z0-9_\-]+\@bitbucket.org\/([a-zA-Z0-9_\-]+\/[a-zA-Z0-9_\-]+)\.git/,
         'anon': /https\:\/\/bitbucket.org\/([a-zA-Z0-9_\-]+\/[a-zA-Z0-9_\-]+)(\.git)?/
         */
         if (preg_match('/^[a-zA-Z0-9_\\-]+\\/[a-zA-Z0-9_\\-\\.]+$/', $value)) {
             // Bitbucket
             return true;
         }
         return false;
     });
 }
 public function __construct(Factory $factory)
 {
     //Custom Validator Rut
     $factory->extend('rut_valid', function ($attribute, $value, $parameters) {
         return Rut::check($value);
     }, 'El campo Rut no tiene un formato válido');
 }
Exemplo n.º 8
0
 /**
  * Bootstrap any application services.
  *
  * @return void
  */
 public function boot(Validator $validator)
 {
     $rules = new Rules();
     collect(get_class_methods($rules))->each(function ($method) use($validator) {
         $name = snake_case(preg_replace('/^validate/i', null, $method));
         $validator->extend($name, sprintf('%s@%s', Rules::class, $method));
     });
 }
Exemplo n.º 9
0
 /**
  * add new rule to validation factory
  *
  * @return void
  */
 private function extending()
 {
     $this->factory->extend('has_parent', function ($attribute, $value) {
         if ($attribute == 'object' && $value->getDepth() > 1 && $value->getParent() === null) {
             return false;
         }
         return true;
     });
 }
Exemplo n.º 10
0
 function initializeValidator()
 {
     $validator = new Validator($this->translator, new Container());
     $validator->extend('phone', function ($attribute, $value, $parameters, $validator) {
         preg_match('/\\d+/', $value, $matches);
         if (strlen($matches[0]) == 10) {
             return true;
         }
     });
     return $validator;
 }
Exemplo n.º 11
0
 /**
  * Register field's custom validators.
  *
  * @param Factory     $factory
  * @param FormBuilder $builder
  * @param FieldType   $fieldType
  */
 protected function registerValidators(Factory $factory, FormBuilder $builder, FieldType $fieldType)
 {
     foreach ($fieldType->getValidators() as $rule => $validator) {
         $handler = array_get($validator, 'handler');
         if (is_string($handler) && !str_contains($handler, '@')) {
             $handler .= '@handle';
         }
         $factory->extend($rule, function ($attribute, $value, $parameters, Validator $validator) use($handler, $builder) {
             return $this->container->call($handler, compact('attribute', 'value', 'parameters', 'builder', 'validator'));
         }, array_get($validator, 'message'));
     }
 }
Exemplo n.º 12
0
 /**
  * @param JalaliValidator $validator
  */
 private function registerJDateTimeRules(JalaliValidator $validator)
 {
     $this->factory->extend('jdatetime', function ($attribute, $value, $parameter) use($validator) {
         return $validator->validateJDateTime($attribute, $value, $parameter);
     });
     $this->factory->extend('jdatetime_after', function ($attribute, $value, $parameter) use($validator) {
         return $validator->validateJDateTimeAfter($attribute, $value, $parameter);
     });
     $this->factory->extend('jdatetime_before', function ($attribute, $value, $parameter) use($validator) {
         return $validator->validateJDateTimeBefore($attribute, $value, $parameter);
     });
     $this->factory->replacer('jdatetime', function ($message, $attribute, $rule, $parameter) use($validator) {
         return $validator->replaceJalali($message, $attribute, $rule, $parameter);
     });
     $this->factory->replacer('jdatetime_after', function ($message, $attribute, $rule, $parameter) use($validator) {
         return $validator->replaceAfterOrBefore($message, $attribute, $rule, $parameter);
     });
     $this->factory->replacer('jdatetime_before', function ($message, $attribute, $rule, $parameter) use($validator) {
         return $validator->replaceAfterOrBefore($message, $attribute, $rule, $parameter);
     });
 }
Exemplo n.º 13
0
 /**
  * Overwrite the parent constructor to define a new validator.
  *
  * @param  Factory $factory
  * @return void
  * @SuppressWarnings(PHPMD.UnusedLocalVariable)
  */
 public function __construct(Factory $factory)
 {
     $factory->extend('host', function ($attribute, $value, $parameters) {
         if (filter_var($value, FILTER_VALIDATE_IP)) {
             return true;
         }
         if (filter_var(gethostbyname($value), FILTER_VALIDATE_IP)) {
             return true;
         }
         return false;
     });
 }
Exemplo n.º 14
0
 /**
  * @param array $input
  * @param array $rules
  * @return array
  */
 public function validate(array $input, array $rules)
 {
     $validatorFactory = new IlluminateValidationFactory(new SymfonyTranslator('en'));
     // enabling rule default, which will be used not to validate, but to set default value for optional parameter
     $validatorFactory->extend('default', function ($attribute, $value, $parameters) {
         return count($parameters) == 1 && !empty($parameters[0]);
     });
     // create replacers for custom messages
     //$validatorFactory->replacer('default', function ($message, $attribute, $rule, $parameters) {
     //    $replacement = !empty($parameters[0]) ? $replacement[0] : 'MISSING';
     //    return str_replace(':defaultValue', $replacement, $message);
     //});
     $validator = $validatorFactory->make($input, $rules, $this->validationMessages);
     $validationErrors = $validator->errors()->getMessages();
     reset($validationErrors);
     return $validationErrors;
 }
Exemplo n.º 15
0
 public function testMakeMethodCreatesValidValidator()
 {
     $translator = m::mock('Symfony\\Component\\Translation\\TranslatorInterface');
     $factory = new Factory($translator);
     $validator = $factory->make(array('foo' => 'bar'), array('baz' => 'boom'));
     $this->assertEquals($translator, $validator->getTranslator());
     $this->assertEquals(array('foo' => 'bar'), $validator->getData());
     $this->assertEquals(array('baz' => array('boom')), $validator->getRules());
     $presence = m::mock('Illuminate\\Validation\\PresenceVerifierInterface');
     $factory->extend('foo', function () {
     });
     $factory->setPresenceVerifier($presence);
     $validator = $factory->make(array(), array());
     $this->assertEquals(array('foo' => function () {
     }), $validator->getExtensions());
     $this->assertEquals($presence, $validator->getPresenceVerifier());
 }
Exemplo n.º 16
0
 /**
  * Register the service provider.
  *
  * @return void
  */
 public function register()
 {
     $this->registerPresenceVerifier();
     $this->app->singleton('validator', function ($app) {
         $validator = new Factory($app['translator'], $app);
         // The validation presence verifier is responsible for determining the existence
         // of values in a given data collection, typically a relational database or
         // other persistent data stores. And it is used to check for uniqueness.
         if (isset($app['validation.presence'])) {
             $validator->setPresenceVerifier($app['validation.presence']);
         }
         // Add validation extensions
         $extensions = config('esensi/core::validation.extensions', []);
         foreach ($extensions as $extension => $class) {
             $validator->extend($extension, $class . '@validate' . ucfirst(studly_case($extension)));
             $validator->replacer($extension, $class . '@replace' . ucfirst(studly_case($extension)));
         }
         return $validator;
     });
 }
Exemplo n.º 17
0
 public function testValidVatFails()
 {
     $validator = Mockery::mock('TPWeb\\Vat\\Validation\\Validator');
     $extensions = new ValidatorExtensions($validator);
     $container = Mockery::mock('Illuminate\\Container\\Container');
     $translator = Mockery::mock('Symfony\\Component\\Translation\\TranslatorInterface');
     $container->shouldReceive('make')->once()->with('TPWeb\\Vat\\Validation\\ValidatorExtensions')->andReturn($extensions);
     $validator->shouldReceive('isVat')->once()->with('BE0650005818')->andReturn(false);
     $translator->shouldReceive('trans')->once()->with('validation.custom')->andReturn('validation.custom');
     $translator->shouldReceive('trans')->once()->with('validation.custom.foo.vat')->andReturn('validation.custom.foo.vat');
     $translator->shouldReceive('trans')->once()->with('validation.vat')->andReturn('validation.vat');
     $translator->shouldReceive('trans')->once()->with('validation.attributes.foo')->andReturn('validation.attributes.foo');
     $factory = new Factory($translator, $container);
     $factory->extend('vat', 'TPWeb\\Vat\\Validation\\ValidatorExtensions@validateVat', ':attribute must be a valid VAT');
     $validator = $factory->make(['foo' => 'BE0650005818'], ['foo' => 'vat']);
     $this->assertTrue($validator->fails());
     $messages = $validator->messages();
     $this->assertInstanceOf('Illuminate\\Support\\MessageBag', $messages);
     $this->assertEquals('foo must be a valid VAT', $messages->first('foo'));
 }
Exemplo n.º 18
0
 /**
  * Overwrite the parent constructor to define a new validator.
  *
  * @param  Factory $factory
  * @return void
  * @SuppressWarnings(PHPMD.UnusedLocalVariable)
  */
 public function __construct(Factory $factory)
 {
     $factory->extend('repository', function ($attribute, $value, $parameters) {
         if (preg_match('/^(git|https?):\\/\\//', $value)) {
             // Plain old git repo
             return true;
         }
         if (preg_match('/^(.*)@(.*):(.*)\\/(.*)\\.git/', $value)) {
             // Gitlab
             return true;
         }
         if (preg_match('/^[a-zA-Z0-9_\\-]+\\/[a-zA-Z0-9_\\-\\.]+$/', $value)) {
             // Github
             return true;
         }
         if (preg_match('/^[a-zA-Z0-9_\\-]+\\/[a-zA-Z0-9_\\-\\.]+$/', $value)) {
             // Bitbucket
             return true;
         }
         return false;
     });
 }
Exemplo n.º 19
0
 /**
  * Determine if the user is authorized to make this request.
  *
  * @return bool
  */
 public function __construct(Factory $factory)
 {
     //        $factory->extend(
     //            'earlier_than',
     //            function ($attribute, $value, $parameters)
     //            {
     //                if (Input::get($parameters[0])=='') {
     //                    return true;
     //                }else if ($value=='') {
     //                    return true;
     //                }else{
     //                    $to = Carbon::createFromFormat('d-m-Y H:i',Input::get($parameters[0]));
     //                    $from = Carbon::createFromFormat('d-m-Y H:i',$value);
     //                    return $to>$from;
     //                }
     //
     //            },
     //            'The date from the start date & time must be earlier than end date & time.'
     //        );
     $dateErrorMessage = 'Dates is/are invalid.';
     $factory->extend('validateDate', function ($attribute, $daterange, $parameters) {
         try {
             if ($daterange == '') {
                 //allow no date
             } else {
                 $arr = explode('-', $daterange);
                 $start = trim($arr[0]);
                 $end = trim($arr[1]);
                 $start = Carbon::createFromFormat('d/m/Y H:i', $start);
                 $end = Carbon::createFromFormat('d/m/Y H:i', $end);
                 return $end > $start;
             }
             return true;
         } catch (Exception $ex) {
             return false;
         }
     }, $dateErrorMessage);
 }
Exemplo n.º 20
0
 public function __construct(Factory $factory)
 {
     $factory->extend('alpha_spaces', function ($attribute, $value, $parameters) {
         return preg_match('/^[\\pL\\s]+$/u', $value);
     }, 'falso');
 }
Exemplo n.º 21
0
 /**
  * Register custom validation rules
  *
  * @return void
  */
 protected function registerExtensions()
 {
     $this->validator->extend('address', function ($attribute, $value, $parameters) {
         return $this->validator->make($value, ['country' => 'required'])->passes();
     });
 }
Exemplo n.º 22
0
 /**
  * Register a custom validator extension.
  *
  * @param  string $rule
  * @param  \Closure|string $extension
  * @param  string $message
  * @return void
  */
 public function extend($rule, $extension, $message = null)
 {
     $this->factory->extend($rule, $extension, $message);
 }
Exemplo n.º 23
0
 /**
  * Register a custom validator extension.
  *
  * @param string $rule
  * @param \Closure|string $extension
  * @param string $message
  * @return void 
  * @static 
  */
 public static function extend($rule, $extension, $message = null)
 {
     \Illuminate\Validation\Factory::extend($rule, $extension, $message);
 }
Exemplo n.º 24
0
 /**
  * Lavanda engine initialisation method.
  *
  * @param Request $request
  * @param Router $router
  * @param ViewFactory $viewFactory
  * @param ValidationFactory $validationFactory
  * @param Filesystem $fileSystem
  * @param FormBuilder $formBuilder
  */
 public function boot(Repository $config, Request $request, Translator $translator, Router $router, ViewFactory $viewFactory, ValidationFactory $validationFactory, Filesystem $fileSystem, FormBuilder $formBuilder)
 {
     // model dependencies
     Model::setRequest($request);
     Model::setTranslator($translator);
     Model::setView($viewFactory);
     Model::setFormBuilder($formBuilder);
     Model::setBasePath($this->app->basePath());
     Model::setPublicPath($this->app->make('path.public'));
     // adding Lavanda controllers to routing
     if (!$this->app->routesAreCached()) {
         $router->get('admin', ['uses' => 'Idealogica\\Lavanda\\MainController@index', 'as' => 'admin.main.index']);
         $router->get('admin/_image', ['uses' => 'Idealogica\\Lavanda\\ImageController@index', 'as' => 'admin.image.index']);
         $router->get('admin/{model}', ['uses' => 'Idealogica\\Lavanda\\EntityController@index', 'as' => 'admin.entity.index']);
         $router->get('admin/{model}/create', ['uses' => 'Idealogica\\Lavanda\\EntityController@create', 'as' => 'admin.entity.create']);
         $router->post('admin/{model}', ['uses' => 'Idealogica\\Lavanda\\EntityController@store', 'as' => 'admin.entity.store']);
         $router->get('admin/{model}/{id}', ['uses' => 'Idealogica\\Lavanda\\EntityController@show', 'as' => 'admin.entity.show']);
         $router->get('admin/{model}/{id}/edit', ['uses' => 'Idealogica\\Lavanda\\EntityController@edit', 'as' => 'admin.entity.edit']);
         $router->put('admin/{model}/{id}', ['uses' => 'Idealogica\\Lavanda\\EntityController@update', 'as' => 'admin.entity.update']);
         $router->delete('admin/{model}/{id}', ['uses' => 'Idealogica\\Lavanda\\EntityController@destroy', 'as' => 'admin.entity.destroy']);
     }
     // custom image validation method
     $validationFactory->extend('lavanda_image', function ($attribute, $value, $parameters) use($request) {
         if ($request->hasFile($attribute)) {
             $validator = Validator::make($request->all(), [$attribute => 'min:1|max:10000|mimes:' . implode(',', $parameters)]);
             return !$validator->fails();
         }
         return true;
     });
     // view composer
     $viewFactory->composer(['lavanda::layout.common', 'lavanda::main.index'], function (View $view) use($config, $fileSystem, $request) {
         $menu = [];
         $maxCount = 0;
         $modelPath = $config->get('lavanda.model_path');
         $files = array_values($fileSystem->files($modelPath));
         mt_srand(10);
         $colors = RandomColor::many(count($files), ['luminosity' => 'light', 'hue' => 265]);
         foreach ($files as $idx => $file) {
             $model = strtolower(basename($file, ".php"));
             $modelClass = getModelClass($model);
             if (!in_array('Idealogica\\Lavanda\\Model', class_parents($modelClass))) {
                 continue;
             }
             $url = adminRoute($model, 'index');
             $count = $modelClass::count();
             $maxCount = $count > $maxCount ? $count : $maxCount;
             $menu[] = ['title' => $modelClass::getPluralName(), 'url' => $url, 'selected' => preg_match('/^' . preg_quote($url, '/') . '/', $request->url()), 'count' => $count, 'columns' => 1, 'color' => (string) (new Color($colors[$idx]))->desaturate(50)->lighten(5)];
         }
         $tiles = $menu;
         if ($maxCount) {
             $rowItems = [];
             $countRow = function ($rowItems) {
                 $rowColumns = 0;
                 foreach ($rowItems as $item) {
                     $rowColumns += $item['columns'];
                 }
                 return $rowColumns;
             };
             $stretchRow = function (array &$rowItems) use($countRow) {
                 if ($rowItems) {
                     $count = $countRow($rowItems);
                     if ($count < 12) {
                         $add = (int) ((12 - $count) / count($rowItems));
                         foreach ($rowItems as &$rowItem) {
                             $rowItem['columns'] += $add;
                         }
                         foreach ($rowItems as &$rowItem) {
                             if ($countRow($rowItems) >= 12) {
                                 break;
                             }
                             $rowItem['columns']++;
                         }
                     }
                 }
             };
             usort($tiles, function ($a, $b) {
                 if ($a['count'] == $b['count']) {
                     return 0;
                 }
                 return $a['count'] > $b['count'] ? -1 : 1;
             });
             foreach ($tiles as &$item) {
                 $columns = (int) round(12 * $item['count'] / $maxCount);
                 $item['columns'] = $columns ?: 1;
                 $rowItems[] =& $item;
                 $rowColumns = $countRow($rowItems);
                 if ($rowColumns > 12) {
                     unset($rowItems[count($rowItems) - 1]);
                     $stretchRow($rowItems);
                     $rowItems = [];
                     $rowItems[] =& $item;
                 } elseif ($rowColumns == 12) {
                     $rowItems = [];
                 }
             }
             $stretchRow($rowItems);
         }
         $view->with('menu', $menu)->with('tiles', $tiles);
     });
     // request rebinding
     $this->app->rebinding('request', function ($app, $request) {
         $app->forgetInstance('laravel-form-helper');
         $app->forgetInstance('laravel-form-builder');
         $app->bindShared('laravel-form-helper', function ($app) use($request) {
             $configuration = $app['config']->get('laravel-form-builder');
             return new FormHelper($app['view'], $request, $configuration);
         });
         $app->bindShared('laravel-form-builder', function ($app) {
             return new FormBuilder($app, $app['laravel-form-helper']);
         });
         Model::flush();
         Model::setRequest($request);
         Model::setFormBuilder($app->make('laravel-form-builder'));
     });
     // package configuration
     $packageDir = dirname(__DIR__);
     $viewsPath = $packageDir . '/views';
     $translationsPath = $packageDir . '/lang';
     $assetsPath = $packageDir . '/assets';
     $configPath = $packageDir . '/config/common.php';
     $this->loadViewsFrom($viewsPath, 'lavanda');
     $this->loadTranslationsFrom($translationsPath, 'lavanda');
     $this->mergeConfigFrom($configPath, 'lavanda');
     $this->publishes([$translationsPath => base_path('resources/lang/vendor/lavanda')], 'lang');
     $this->publishes([$viewsPath => base_path('resources/views/vendor/lavanda')], 'views');
     $this->publishes([$assetsPath => public_path('vendor/lavanda')], 'public');
     $this->publishes([$configPath => config_path('lavanda.php')], 'config');
 }