/**
  * {@inheritdoc}
  */
 public function validateBlock(ErrorElement $errorElement, BlockInterface $block)
 {
     if (($name = $block->getSetting('menu_name')) && $name !== '' && !$this->menuProvider->has($name)) {
         // If we specified a menu_name, check that it exists
         $errorElement->with('menu_name')->addViolation('sonata.block.menu.not_existing', array('name' => $name))->end();
     }
 }
 public function validate(ErrorElement $errorElement, $object)
 {
     //Verificar que el usuario tiene una agencia asignada
     $usuario = $this->getConfigurationPool()->getContainer()->get('security.context')->getToken()->getUser();
     if ($usuario->getAgencia() == null) {
         $errorElement->with('nombre')->addViolation($this->getTranslator()->trans('_usuario_no_agencia_'))->end();
     }
     //Verificar que todos los campos esten configurados
     foreach ($object->getVariables() as $variable) {
         $campos_no_configurados = $this->getModelManager()->findBy('IndicadoresBundle:Campo', array('origenDato' => $variable->getOrigenDatos(), 'significado' => null));
         if (count($campos_no_configurados) > 0) {
             $errorElement->with('variables')->addViolation($variable->getIniciales() . ': ' . $this->getTranslator()->trans('origen_no_configurado'))->end();
         }
     }
     //Obtener las variables marcadas
     $variables_sel = array();
     foreach ($object->getVariables() as $variable) {
         $variables_sel[] = $variable->getIniciales();
     }
     if (count($variables_sel) == 0) {
         $errorElement->with('variables')->addViolation($this->getTranslator()->trans('elija_al_menos_una_variable'))->end();
     } else {
         //Obtener las variables utilizadas en la fórmula
         //Quitar todos los espacios en blanco de la fórmula
         $vars_formula = array();
         $formula = str_replace(' ', '', $object->getFormula());
         preg_match_all('/\\{([\\w]+)\\}/', $formula, $vars_formula);
         //Para que la fórmula sea válida la cantidad de variables seleccionadas
         //debe coincidir con las utilizadas en la fórmula
         if (count(array_diff($variables_sel, $vars_formula[1])) > 0 or count(array_diff($vars_formula[1], $variables_sel)) > 0) {
             $errorElement->with('formula')->addViolation($this->getTranslator()->trans('vars_sel_diff_vars_formula'))->end();
         }
         // ******** Verificar si matematicamente la fórmula es correcta
         // 1) Sustituir las variables por valores aleatorios entre 1 y 100
         // Quitar las palabras permitidas
         $formula_check = str_replace(array('AVG', 'MAX', 'MIN', 'SUM', 'COUNT'), array('', '', '', '', ''), strtoupper($object->getFormula()));
         $formula_valida = true;
         $result = '';
         foreach ($vars_formula[0] as $var) {
             $formula_check = str_replace($var, rand(1, 100), $formula_check);
         }
         //Verificar que no tenga letras, para evitar un ataque de inyección
         if (preg_match('/[A-Z]+/i', $formula_check) != 0) {
             $formula_valida = false;
             $mensaje = 'sintaxis_invalida_variables_entre_llaves';
         } else {
             //evaluar la formula, evitar que se muestren los errores por si los lleva
             ob_start();
             $test = eval('$result=' . $formula_check . ';');
             ob_end_clean();
             if (!is_numeric($result)) {
                 $formula_valida = false;
                 $mensaje = 'sintaxis_invalida';
             }
         }
         if ($formula_valida == false) {
             $errorElement->with('formula')->addViolation($this->getTranslator()->trans($mensaje))->end();
         }
     }
 }
 public function validate(ErrorElement $errorElement, $object)
 {
     $campos_no_configurados = $this->getModelManager()->findBy('IndicadoresBundle:Campo', array('origenDato' => $object->getOrigenDatos(), 'significado' => null));
     if (count($campos_no_configurados) > 0) {
         $errorElement->with('origenDatos')->addViolation($this->getTranslator()->trans('origen_no_configurado'))->end();
     }
 }
 public function validate(ErrorElement $errorElement, $obj)
 {
     $errorElement->with('name')->assertLength(array('max' => 255))->end();
     if (empty($obj->getPost()->getSlug())) {
         $obj->getPost()->setSlug($obj->getPost()->getTitle());
     }
 }
Beispiel #5
0
 public function validate(ErrorElement $errorElement, $object)
 {
     /** @var Administrator $object */
     if (!$object->getId()) {
         $errorElement->with('plainPassword')->addConstraint(new NotBlank())->end();
     }
 }
 public function validate(ErrorElement $errorElement, $object)
 {
     //Marcó la opción que se usará en catálogo pero no ha elegido un catálog
     if ($object->getUsoEnCatalogo() == true and $object->getCatalogo() != '') {
         $errorElement->with('catalogo')->addViolation($this->getTranslator()->trans('no_catalogo_y_describir_catalogo'))->end();
     }
 }
 public function validate(ErrorElement $errorElement, $object)
 {
     if ($object->getEsFusionado() == false) {
         if ($object->file == '' and $object->getArchivoNombre() == '' and $object->getSentenciaSql() == '') {
             $errorElement->with('sentenciaSql')->addViolation($this->getTranslator()->trans('validacion.sentencia_o_archivo'))->end();
         }
         if ($object->file != '' and $object->getSentenciaSql() != '') {
             $errorElement->with('sentenciaSql')->addViolation($this->getTranslator()->trans('validacion.sentencia_o_archivo_no_ambas'))->end();
         }
         echo count($object->getConexiones());
         if ($object->getSentenciaSql() != '' and count($object->getConexiones()) == 0) {
             $errorElement->with('conexiones')->addViolation($this->getTranslator()->trans('validacion.requerido'))->end();
         }
     }
     // Revisar la validación, no me reconoce los archivos con los tipos que debería
     /*
     * 'application/octet-stream',
      'text/comma-separated-values',
      'application/zip',
      'text/x-c++'
     */
     /* $errorElement
        ->with('file')
        ->assertFile(array(
        'mimeTypes' => array("application/vnd.ms-excel",
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        'text/csv','application/vnd.oasis.opendocument.spreadsheet',
        'application/vnd.ms-office'
        )))
        ->end()
        ; */
     return true;
 }
 public function validate(ErrorElement $errorElement, $object)
 {
     $nip = $object->getInvoiceNip();
     if (!NipType::isValid($nip)) {
         $msg = sprintf('Wartość "%s" nie jest poprawnym numerem NIP.', $nip);
         $errorElement->addViolation($msg);
     }
 }
 public function validate(ErrorElement $errorElement, $object)
 {
     if (!($object->getCategoryStaticContent() && !$object->getStaticContent() && !$object->getEmission() && !$object->getPodcast() && !$object->getCustumItem() || !$object->getCategoryStaticContent() && $object->getStaticContent() && !$object->getEmission() && !$object->getPodcast() && !$object->getCustumItem() || !$object->getCategoryStaticContent() && !$object->getStaticContent() && $object->getEmission() && !$object->getPodcast() && !$object->getCustumItem() || !$object->getCategoryStaticContent() && !$object->getStaticContent() && !$object->getEmission() && $object->getPodcast() && !$object->getCustumItem() || !$object->getCategoryStaticContent() && !$object->getStaticContent() && !$object->getEmission() && !$object->getPodcast() && $object->getCustumItem())) {
         $errorElement->with('value')->addViolation('un item doit contenir un et un seul champ de référence')->end();
     }
     /*  $errorElement
         ->with('title')
         ->assertMaxLength(array('limit' => 32))
         ->end()*/
 }
 public function validate(ErrorElement $errorElement, $object)
 {
     $errorElement->addConstraint(new UniqueObject(array('fields' => 'alias', 'message' => $this->trans('fc.label.admin.alias', array(), $this->getTranslationDomain()) . ': ' . $this->trans('fc.constraint.admin.not_unique', array(), 'validators'))));
     /** @var FcForm $object */
     if ($this->field_chain->hasField($object->getAlias())) {
         $errorElement->addViolation($this->trans('fc.message.admin.form.alias_conflicts', array(), $this->getTranslationDomain()));
     }
     if ($object->isColumnModified(FcFormPeer::IS_WIDGET) && !$object->getIsWidget() && $object->isUsedAsWidget()) {
         $errorElement->addViolation($this->trans('fc.message.admin.form.is_used_as_widget', array(), $this->getTranslationDomain()));
     }
 }
Beispiel #11
0
 /**
  * The validator asks each product repository to validate the related basket element.
  *
  * @param BasketInterface $basket
  * @param Constraint      $constraint
  */
 public function validate($basket, Constraint $constraint)
 {
     foreach ($basket->getBasketElements() as $pos => $basketElement) {
         // create a new ErrorElement object
         $errorElement = new ErrorElement($basket, $this->constraintValidatorFactory, $this->context, $this->context->getGroup());
         $errorElement->with('basketElements[' . $pos . ']');
         // validate the basket element through the related service provider
         $this->productPool->getProvider($basketElement->getProductCode())->validateFormBasketElement($errorElement, $basketElement, $basket);
     }
     if (count($this->context->getViolations()) > 0) {
         $this->context->addViolationAt('basketElements', $constraint->message);
     }
 }
 public function validate(ErrorElement $errorElement, $object)
 {
     if ($object->getUbicacion() != null) {
         // Si elije una ubicación en particular para este compromiso
         // solo debe seleccionar el establecimiento al que pertenece
         // la ubicación
         foreach ($object->getEstablecimientos() as $e) {
             if ($e->getCodigo() != $object->getUbicacion()->getEstablecimiento()->getCodigo()) {
                 $errorElement->with('ubicacion')->addViolation($this->getTranslator()->trans('_solo_establecimiento_de_ubicacion_'))->end()->with('establecimientos')->addViolation($this->getTranslator()->trans('_solo_establecimiento_de_ubicacion_'))->end();
                 break;
             }
         }
     }
 }
 public function validate(ErrorElement $errorElement, $song)
 {
     if (empty($song->getLyrics())) {
         $musixmatchApi = $this->container->get('tncy_school.musixmatchapi');
         $musixmatch = json_decode($musixmatchApi->get_musixmatch_lyrics($song->getArtist(), $song->getName()));
         if ($musixmatch->message->header->status_code == 200) {
             $lyrics = $musixmatch->message->body->lyrics->lyrics_body;
             $song->setLyrics($lyrics);
         } else {
             $error = "Error: Any lyrics was found for " . $song->getArtist() . " : " . $song->getName();
             $errorElement->with('name')->addViolation($error)->end()->with('artist')->addViolation($error)->end();
         }
     }
     //TODO: rajouter un message si les mots à trouver est vide => error
 }
 /**
  * @{inheritdoc}
  */
 public function validate(ErrorElement $errorElement, $object)
 {
     // find object with toLink
     $fromPath = $this->modelManager->findOneBy($this->getClass(), array('fromPath' => $object->getFromPath()));
     // @formatter:off
     if (null !== $fromPath && $fromPath->getId() !== $object->getId()) {
         $errorElement->with('fromPath')->addViolation('This link is already being redirected somewhere else!')->end();
     }
     if (substr($object->getToPath(), 0, 1) !== '/') {
         $errorElement->with('toPath')->addViolation('Invalid path! A path start with a "/"')->end();
     }
     if (substr($object->getFromPath(), 0, 1) !== '/') {
         $errorElement->with('fromPath')->addViolation('Invalid path! A path start with a "/"')->end();
     }
     // @formatter:on
 }
Beispiel #15
0
 public function validate(ErrorElement $errorElement, $object)
 {
     /** @var AdminMenu $object */
     if ($object->getType() == AdminMenu::TYPE_MODULE) {
         $errorElement->with('serviceId')->addConstraint(new NotBlank())->end();
     }
 }
Beispiel #16
0
 /**
  * @param ErrorElement $errorElement
  * @param Barcode $object
  */
 public function validate(ErrorElement $errorElement, $object)
 {
     if (!$object->getWithCounter()) {
         if ($object->getBasecode() < 0 || $object->getBasecode() > 99999) {
             $errorElement->with('basecode')->addViolation('Recuerde que son cinco dígitos desde 00000 a 99999')->end();
         } else {
             /** @var QueryBuilder $query */
             $query = $this->getModelManager()->createQuery($this->getClass(), 'o');
             $barcode = $query->where('o.code = :code')->setParameter('code', $object->generateCode())->getQuery()->execute();
             if (!empty($barcode)) {
                 $errorElement->with('basecode')->addViolation('El código está en uso')->end();
             }
         }
     } else {
         do {
             $object->getTrademark()->incCounter();
             $query = $this->getModelManager()->createQuery($this->getClass(), 'o');
             $barcode = $query->where('o.code = :code')->setParameter('code', $object->generateCode())->getQuery()->execute();
         } while (!empty($barcode));
     }
 }
Beispiel #17
0
 public function validate(ErrorElement $errorElement, $object)
 {
     $vars_formula = array();
     $formula = str_replace(' ', '', $object->getFormula());
     preg_match_all('/(\\{[\\w]+\\})/', $formula, $vars_formula);
     //Verificar que haya utilizado solo campos existentes en el origen de datos
     foreach ($object->getOrigenDato()->getCampos() as $campo) {
         if ($campo->getSignificado() and $campo->getTipoCampo()) {
             $campos[$campo->getSignificado()->getCodigo()] = $campo->getTipoCampo()->getCodigo();
         }
     }
     //Verificar que todas las variables sean campos del origen de datos
     foreach ($vars_formula[0] as $var) {
         if (!array_key_exists(str_replace(array('{', '}'), '', $var), $campos)) {
             $errorElement->with('formula')->addViolation('<span style="color:red">' . $var . '</span> ' . $this->getTranslator()->trans('_variable_no_campo_'))->end();
             return;
         }
     }
     // ******** Verificar si matematicamente la fórmula es correcta
     // 1) Sustituir las variables por valores aleatorios entre 1 y 100
     foreach ($vars_formula[0] as $var) {
         $variable = str_replace(array('{', '}'), '', $var);
         if ($campos[$variable] == 'integer' or $campos[$variable] == 'float') {
             $formula = str_replace($var, rand(1, 100), $formula);
         } elseif ($campos[$variable] == 'date') {
             $formula = str_replace($var, ' current_date ', $formula);
         } else {
             $formula = str_replace($var, "'texto'", $formula);
         }
     }
     //evaluar la formula
     try {
         $sql = 'SELECT ' . $formula;
         $this->getConfigurationPool()->getContainer()->get('doctrine')->getEntityManager()->getConnection()->executeQuery($sql);
     } catch (\Doctrine\DBAL\DBALException $exc) {
         $errorElement->with('formula')->addViolation($this->getTranslator()->trans('sintaxis_invalida') . $exc->getMessage())->end();
     }
 }
Beispiel #18
0
 public function validate(ErrorElement $errorElement, $object)
 {
     $translator = $this->getConfigurationPool()->getContainer()->get('translator');
     /**
      * @var UploadedFile $file
      * @var Ad $object
      */
     $file = $object->getUploadedFile();
     if (!$file instanceof UploadedFile and $object->getPath() === null) {
         $errorElement->addViolation($translator->trans('errors.no_image_file', array(), 'SiciarekAdRotator'));
     }
     if ($file instanceof UploadedFile) {
         $def = $object->getType()->getDefinition();
         $extensions = explode(';', $def['formats']);
         $width = $def['width'];
         $height = $def['height'];
         $ext = $file->getClientOriginalExtension();
         // Check file extension:
         if (!in_array($ext, $extensions)) {
             $msg = $translator->trans('errors.invalid_file_format', array('EXTS' => implode(', ', $extensions), 'EXT' => $ext), 'SiciarekAdRotator');
             $errorElement->addViolation($msg);
             return;
         }
         $bin = $file->getRealPath();
         $imageinfo = getimagesize($bin);
         if ($ext === 'svg') {
             // @ - Suppress warning about invalid file content:
             @($xml = simplexml_load_file($bin));
             if ($xml instanceof \SimpleXMLElement) {
                 $width = intval($xml->attributes()->width);
                 $height = intval($xml->attributes()->height);
                 $imageinfo = array($width, $height, IMAGETYPE_UNKNOWN, sprintf('width="%d" height="%d"', $width, $height), 'mime' => 'image/svg+xml');
             } else {
                 $imageinfo = false;
             }
         }
         if (!is_array($imageinfo)) {
             $msg = $translator->trans('errors.invalid_file_content', array(), 'SiciarekAdRotator');
             $msg = sprintf($msg);
             $errorElement->addViolation($msg);
             return;
         }
         $expected = array($width, $height);
         $given = array($imageinfo[0], $imageinfo[1]);
         // Check image width and height:
         if ($expected !== $given) {
             $msg = $translator->trans('errors.invalid_image_size', array('WIDTH' => $width, 'HEIGHT' => $height, 'XWIDTH' => $imageinfo[0], 'XHEIGHT' => $imageinfo[1]), 'SiciarekAdRotator');
             $errorElement->addViolation($msg);
         }
     }
 }
Beispiel #19
0
 public function validate(ErrorElement $errorElement, $object)
 {
     $errorElement->with('title')->assertLength(array('max' => 255))->assertNotBlank()->assertNotNull()->end();
 }
 public function validateBlock(ErrorElement $errorElement, BlockInterface $block)
 {
     $errorElement->with('settings.url')->assertNotNull(array())->assertNotBlank()->end()->with('settings.title')->assertNotNull(array())->assertNotBlank()->assertMaxLength(array('limit' => 50))->end();
 }
Beispiel #21
0
 public function validate(ErrorElement $errorElement, $object)
 {
     $errorElement->end();
 }
 public function validate(ErrorElement $errorElement, $object)
 {
     $errorElement->with('name')->assertLength(array('max' => 100))->assertNotBlank()->end();
 }
 /**
  * {@inheritdoc}
  */
 public function validateBlock(ErrorElement $errorElement, BlockInterface $block)
 {
     $errorElement->with('settings[blockId]')->addConstraint(new NotBlank())->end();
 }
 /**
  * {@inheritdoc}
  */
 public function validateBlock(ErrorElement $errorElement, BlockInterface $block)
 {
     $errorElement->with('settings[url]')->assertNotNull(array())->assertNotBlank()->end()->with('settings[title]')->assertNotNull(array())->assertNotBlank()->assertLength(array('max' => 50))->end();
 }
Beispiel #25
0
 /**
  * {@inheritdoc}
  */
 public function validate(ErrorElement $errorElement, MediaInterface $media)
 {
     if (!$media->getBinaryContent() instanceof \SplFileInfo) {
         return;
     }
     if ($media->getBinaryContent() instanceof UploadedFile) {
         $fileName = $media->getBinaryContent()->getClientOriginalName();
     } elseif ($media->getBinaryContent() instanceof File) {
         $fileName = $media->getBinaryContent()->getFilename();
     } else {
         throw new \RuntimeException(sprintf('Invalid binary content type: %s', get_class($media->getBinaryContent())));
     }
     if (!in_array(strtolower(pathinfo($fileName, PATHINFO_EXTENSION)), $this->allowedExtensions)) {
         $errorElement->with('binaryContent')->addViolation('Invalid extensions')->end();
     }
     if (!in_array($media->getBinaryContent()->getMimeType(), $this->allowedMimeTypes)) {
         $errorElement->with('binaryContent')->addViolation('Invalid mime type : %type%', array('%type%' => $media->getBinaryContent()->getMimeType()))->end();
     }
 }
 public function validate(ErrorElement $errorElement, $object)
 {
     $errorElement->with('title')->assertLength(array('max' => 32))->end();
 }
 /**
  * {@inheritdoc}
  */
 public function validate(ErrorElement $errorElement, $object)
 {
     $errorElement->assertCallback(array('validateOneMainCategory'));
 }
Beispiel #28
0
 /**
  * {@inheritdoc}
  */
 public function validateFormBasketElement(ErrorElement $errorElement, BasketElementInterface $basketElement, BasketInterface $basket)
 {
     // the item is flagged as deleted, no need to validate the item
     if ($basketElement->getDelete() || 0 === $basketElement->getQuantity()) {
         return;
     }
     // refresh the product from the database
     $product = $basketElement->getProduct();
     // check if the product is still in database
     if (!$product) {
         $errorElement->addViolation('product_not_available');
         return;
     }
     // check if the product is still enabled
     if (!$basketElement->getProduct()->getEnabled()) {
         $errorElement->addViolation('product_not_enabled');
         return;
     }
     // check if the quantity is numeric
     if (!is_numeric($basketElement->getQuantity())) {
         $errorElement->with('quantity')->addViolation('product_quantity_not_numeric')->end();
         return;
     }
     $errorElement->with('quantity')->assertRange(array('min' => 1, 'max' => $this->getStockAvailable($basketElement->getProduct()), 'minMessage' => 'basket_quantity_limit_min', 'maxMessage' => 'basket_quantity_limit_max'))->end();
 }
 public function validate(ErrorElement $errorElement, $object)
 {
     $errorElement->with('artist')->assertLength(array('max' => 255))->end()->with('label')->assertLength(array('max' => 255))->end()->with('manufacturer')->assertLength(array('max' => 255))->end()->with('publisher')->assertLength(array('max' => 255))->end()->with('releaseDate')->assertDateTime()->end()->with('studio')->assertLength(array('max' => 255))->end()->with('title')->assertLength(array('max' => 255))->assertNotNull()->assertNotBlank()->end();
 }
 public function validate(ErrorElement $errorElement, $object)
 {
     $errorElement->with('artist')->assertLength(array('max' => 255))->end()->with('genre')->assertLength(array('max' => 255))->end()->with('label')->assertLength(array('max' => 255))->end()->with('manufacturer')->assertLength(array('max' => 255))->end()->with('publisher')->assertLength(array('max' => 255))->end()->with('releaseDate')->assertDateTime()->end()->with('studio')->assertLength(array('max' => 255))->end()->with('trackSequence')->assertGreaterThan(array('value' => 0))->end()->with('runningTime')->assertGreaterThan(array('value' => 0))->end()->with('title')->assertLength(array('max' => 255))->assertNotNull()->assertNotBlank()->end();
 }