src/Validator/Validator.php line 88

Open in your IDE?
  1. <?php
  2. namespace App\Validator;
  3. use Symfony\Component\Validator\Constraints as Assert;
  4. use Symfony\Component\PropertyAccess\PropertyAccess;
  5. use Symfony\Component\Validator\Validator\ValidatorInterface;
  6. use Pimcore\Translation\Translator;
  7. use App\Validator\ContainsWhitespace;
  8. use App\Validator\ContainsUniqueInClass;
  9. use App\Validator\ContainsExistValueInClass;
  10. class Validator
  11. {
  12.     CONST PREFIX_MESSAGE 'validate.message.';
  13.     CONST FILE_FIELDS = ['image''imageArray''file'];
  14.     CONST REQUIRED_FUNCTION 'required';
  15.     protected $validator;
  16.     protected $translator;
  17.     public function __construct(ValidatorInterface $validatorTranslator $translator)
  18.     {
  19.         $this->validator $validator;
  20.         $this->translator $translator;
  21.     }
  22.     private function checkExist($request$field$isFile)
  23.     {
  24.         if ($request->getMethod() === 'POST' ) {
  25.             return $isFile $request->files->has($field) : $request->request->has($field);
  26.         }
  27.         return $request->query->has($field);
  28.     }
  29.     /**
  30.      * Return an error response.
  31.      * 
  32.      * @param array $parameters
  33.      * @param Request $request
  34.      *  
  35.      */
  36.     public function validate(array $parameters$request)
  37.     {
  38.         $errorMessages null;
  39.         $constraintsArray = [];
  40.         $violationsArray = [];
  41.         foreach ($parameters as $field => $param) {
  42.             $violationsArray[$field] = !is_array($request->get($field)) ? trim($request->get($field)) : $request->get($field);
  43.             $constraintsArray[$field] = [];
  44.             $arrayParam explode('|'$param);
  45.             foreach ($arrayParam as $node) {
  46.                 $arrNode explode(':'$node); 
  47.                 $functionName $arrNode[0];
  48.                 $isFile false;
  49.                 if (in_array($functionNameself::FILE_FIELDS)) {
  50.                     $isFile true;
  51.                     $violationsArray[$field] = $request->files->get($field);
  52.                 }
  53.                 $addToValidator false;
  54.                 // nếu field CÓ truyền lên
  55.                 if ($this->checkExist($request$field$isFile)) {
  56.                     $addToValidator true;
  57.                 } else {
  58.                     // KHÔNG truyền lên nhưng CÓ điều kiện required
  59.                     if (in_array(self::REQUIRED_FUNCTION$arrayParam)) {
  60.                         $addToValidator true;
  61.                     }
  62.                 }
  63.                 if ($addToValidator && method_exists($this$functionName)) {
  64.                     $params = isset($arrNode[1]) ? $arrNode[1] : null;
  65.                     array_push($constraintsArray[$field], $this->$functionName($field$params));   
  66.                 } 
  67.             }
  68.         }
  69.         $constraints = new Assert\Collection(['fields' => $constraintsArray]);
  70.         $violations $this->validator->validate($violationsArray$constraints);
  71.         if (count($violations) > 0) {
  72.             $errorMessages = [];
  73.             $accessor PropertyAccess::createPropertyAccessor();
  74.             foreach ($violations as $violation) {
  75.                 $message $this->translator->trans($violation->getMessage());
  76.                 $accessor->setValue($errorMessages$violation->getPropertyPath(), $message);
  77.             }
  78.         }
  79.         return $errorMessages;
  80.     }
  81.     /**
  82.      * Return first error message.
  83.      *
  84.      * @param array $errorMessages
  85.      *  
  86.      */
  87.     public function getError(array $errorMessages)
  88.     {
  89.         if (!empty($errorMessages)) {
  90.             foreach ($errorMessages as $field => $message) {
  91.                 return [
  92.                     'message' => $message,
  93.                     'field' => $field
  94.                 ];
  95.             }
  96.         }
  97.         return '';
  98.     }
  99.     /**
  100.      * Format: 'required'
  101.      */
  102.     function required($key$params null)
  103.     {
  104.         $options = [
  105.             "message" => self::PREFIX_MESSAGE __FUNCTION__,
  106.         ];
  107.         return new Assert\NotBlank($options);
  108.     }
  109.     /**
  110.      * Format: 'positive'
  111.      */
  112.     function positive($key$params null)
  113.     {
  114.         $options = [
  115.             "message" => self::PREFIX_MESSAGE __FUNCTION__,
  116.         ];
  117.         return new Assert\Positive($options);
  118.     }
  119.     /**
  120.      * Format: 'date'
  121.      */
  122.     function date($key$params null)
  123.     {
  124.         $options = [
  125.             "message" => self::PREFIX_MESSAGE __FUNCTION__,
  126.         ];
  127.         return new Assert\Date($options);
  128.     }
  129.     /**
  130.      * Format: 'datetime'
  131.      */
  132.     function datetime($key$params null)
  133.     {
  134.         $options = [
  135.             "message" => self::PREFIX_MESSAGE __FUNCTION__,
  136.         ];
  137.         return new Assert\DateTime($options);
  138.     }
  139.     /**
  140.      * Format: 'email'
  141.      */
  142.     function email($key$params null)
  143.     {
  144.         $options = [
  145.             "message" => self::PREFIX_MESSAGE __FUNCTION__,
  146.             "mode" => "strict"
  147.         ];
  148.         return new Assert\Email($options);
  149.     }
  150.     /**
  151.      * Check if string consists of all letters or digits (azAZ09)
  152.      * Format: 'alnum'
  153.      */
  154.     function alnum($key)
  155.     {
  156.         return $this->type(__FUNCTION__);
  157.     }
  158.     /**
  159.      * Format: 'array'
  160.      */
  161.     function array($key)
  162.     {
  163.         return $this->type(__FUNCTION__);
  164.     }
  165.     /**
  166.      * Format: 'numeric'
  167.      */
  168.     function numeric($key$params null)
  169.     {
  170.         return $this->type(__FUNCTION__);
  171.     }
  172.     /**
  173.      * Format: 'string'
  174.      */
  175.     function string($key)
  176.     {
  177.         return $this->type(__FUNCTION__);
  178.     }
  179.     /**
  180.      * Check type of input
  181.      */
  182.     function type($type$function null)
  183.     {
  184.         $function $function ?? $type;
  185.         $options = [
  186.             "type" => $type,
  187.             "message" => self::PREFIX_MESSAGE $function,
  188.         ];
  189.         return new Assert\Type($options);
  190.     }
  191.     /**
  192.      * Format: 'choice:<option1>,<option2>'
  193.      * Example: 'choice:desc,asc'
  194.      */
  195.     function choice($key$params null)
  196.     {
  197.         $options = [
  198.             "message" => self::PREFIX_MESSAGE __FUNCTION__,
  199.         ];
  200.         
  201.         if ($params) {
  202.             $arrParam explode(','$params);
  203.             $options["choices"] = $arrParam;
  204.         }
  205.         
  206.         return new Assert\Choice($options);
  207.     }
  208.     /**
  209.      * Format: 'lessthan:<value>'
  210.      */
  211.     function lessthan($key$params null)
  212.     {
  213.         $options = [
  214.             "message" => self::PREFIX_MESSAGE __FUNCTION__,
  215.         ];
  216.         
  217.         if ($params) {
  218.             $options["value"] = $params;
  219.         }
  220.         
  221.         return new Assert\LessThan($options);
  222.     }
  223.     /**
  224.      * Count elements of an array. Input value must be type of array.
  225.      * Format: 'count:min,1,max,5'
  226.      */
  227.     function count($key$params null)
  228.     {
  229.         $options = [
  230.             "minMessage" => self::PREFIX_MESSAGE __FUNCTION__ '.min',
  231.             "maxMessage" => self::PREFIX_MESSAGE __FUNCTION__ '.max',
  232.             "exactMessage" => self::PREFIX_MESSAGE __FUNCTION__ '.exact',
  233.         ];
  234.         if ($params) {
  235.             $arrParam explode(','$params);
  236.             foreach ($arrParam as $key => $value) {
  237.                 if (($key 2) == 0) {
  238.                     $options[$value] = (int) $arrParam[($key 1)];
  239.                 }
  240.             }
  241.         }
  242.         return new Assert\Count($options);
  243.     }
  244.     /**
  245.      * Format: 'file:maxSize,5M,mimeTypes,image/jpeg#image/png'
  246.      */
  247.     function file($key$params null)
  248.     {
  249.         $options = [
  250.             "maxSizeMessage" => self::PREFIX_MESSAGE __FUNCTION__ .'.maxSize',
  251.             "mimeTypesMessage" => self::PREFIX_MESSAGE __FUNCTION__ .'.mimeTypes',
  252.         ];
  253.         if ($params) {
  254.             $arrParam explode(','$params);
  255.             foreach ($arrParam as $key => $value) {
  256.                 if (($key 2) == 0) {
  257.                     if ($value == "mimeTypes") {
  258.                         $options[$value] = explode("#"$arrParam[($key 1)]);
  259.                     } else {
  260.                         $options[$value] = $arrParam[($key 1)];
  261.                     }
  262.                 }
  263.             }
  264.         }
  265.         return new Assert\File($options);
  266.     }
  267.     /**
  268.      * Format: 'image:maxSize,5M,mimeTypes,image/jpeg#image/png'
  269.      */
  270.     function image($key$params null)
  271.     {
  272.         $options = [
  273.             "maxSizeMessage" => self::PREFIX_MESSAGE __FUNCTION__ .'.maxSize',
  274.             "mimeTypesMessage" => self::PREFIX_MESSAGE __FUNCTION__ .'.mimeTypes',
  275.         ];
  276.         if ($params) {
  277.             $arrParam explode(','$params);
  278.             foreach ($arrParam as $key => $value) {
  279.                 if (($key 2) == 0) {
  280.                     if ($value == "mimeTypes") {
  281.                         $options[$value] = explode("#"$arrParam[($key 1)]);
  282.                     } else {
  283.                         $options[$value] = $arrParam[($key 1)];
  284.                     }
  285.                 }
  286.             }
  287.         }
  288.         return new Assert\Image($options);
  289.     }
  290.     function imageArray($key$params null)
  291.     {
  292.         $options = [
  293.             "maxSizeMessage" => self::PREFIX_MESSAGE __FUNCTION__ .'.maxSize',
  294.             "mimeTypesMessage" => self::PREFIX_MESSAGE __FUNCTION__ .'.mimeTypes',
  295.         ];
  296.         if ($params) {
  297.             $arrParam explode(','$params);
  298.             foreach ($arrParam as $key => $value) {
  299.                 if (($key 2) == 0) {
  300.                     if ($value == "mimeTypes") {
  301.                         $options[$value] = explode("#"$arrParam[($key 1)]);
  302.                     } else {
  303.                         $options[$value] = $arrParam[($key 1)];
  304.                     }
  305.                 }
  306.             }
  307.         }
  308.         return new Assert\All([new Assert\Image($options)]);
  309.     }
  310.     /**
  311.      * Format: 'length:min,1,max,5'
  312.      */
  313.     function length($key$params null)
  314.     {
  315.         $options = [
  316.             "minMessage" => self::PREFIX_MESSAGE __FUNCTION__ .'min',
  317.             "maxMessage" => self::PREFIX_MESSAGE __FUNCTION__ .'max'
  318.         ];
  319.         
  320.         if ($params) {
  321.             $arrParam explode(','$params);
  322.             foreach ($arrParam as $key => $value) {
  323.                 if (($key 2) == 0) {
  324.                     $options[$value] = $arrParam[($key 1)];
  325.                 }
  326.             }
  327.         }
  328.         return new Assert\Length($options);
  329.     }
  330.     /**
  331.      * Check if input == value
  332.      * Format: 'confirm:<value>'
  333.      * Example: confirm:123abc
  334.      */
  335.     function confirm($key$params)
  336.     {
  337.         $arrParam explode(','$params);
  338.         $options = [
  339.             'message' => self::PREFIX_MESSAGE __FUNCTION__,
  340.             'value' => $arrParam[0]
  341.         ];
  342.         return new Assert\EqualTo($options);
  343.     }
  344.     /**
  345.      * Check if value valid with regex expression
  346.      * Format: 'regex:expression'
  347.      */
  348.     function regex($key$expression null) {
  349.         $options = [
  350.             'message' => self::PREFIX_MESSAGE __FUNCTION__,
  351.             'pattern' => '/'$expression '/'
  352.         ];
  353.         return new Assert\Regex($options);
  354.     }
  355.     // CUSTOM -------------------------------------------------------------------
  356.     /**
  357.      * Format: 'whitespace'
  358.      */
  359.     function whitespace($key$params)
  360.     {
  361.         $options = [
  362.             'message' => self::PREFIX_MESSAGE __FUNCTION__,
  363.         ];
  364.         return new ContainsWhitespace($options);
  365.     }
  366.     /**
  367.      * Check if value already existed in a field in a class
  368.      * Format: 'unique:<className>'
  369.      * Example: existsValue:Product
  370.      */
  371.     function unique($key$class null) {
  372.         $options = [
  373.             'message' => self::PREFIX_MESSAGE __FUNCTION__,
  374.         ];
  375.         if ($class) {
  376.             $options['class'] = $class;
  377.             $options['field'] = $key;
  378.         }
  379.         return new ContainsUniqueInClass($options);
  380.     }
  381.     /**
  382.      * Check if value is valid with a field in Class
  383.      * Format: existsValue:<className><-field>
  384.      * Example: existsValue:Product || existsValue:Product-id
  385.      */
  386.     function existsValue($key$classField) {
  387.         $options = [
  388.             'message' => self::PREFIX_MESSAGE __FUNCTION__,
  389.         ];
  390.         if ($classField) {
  391.             $array explode('-'$classField);
  392.             $options['class'] = $array[0];
  393.             $options['field'] = count($array) == $array[1] : $key;
  394.         }
  395.         return new ContainsExistValueInClass($options);
  396.     }
  397. }