Custom validator to check Dni

@param ExecutionContextInterface $context
512732
public function validateDni(ExecutionContextInterface $context)
    {
        $dni = $this->getDni();

        if(0 === preg_match('/^\d{8}[a-zA-Z]{1}$/', $dni) & 0 === preg_match('/^[XYZ]{1}\d{7}[a-zA-Z0-9]{1}$/', $dni) & 0 === preg_match('/^[ABCDEFGHJNPQRSUVW]{1}/', $dni)  & strlen($dni)>0){
            $context->addViolationAt('dni', 'Formato incorrecto');
            return;
        }

        //DNI & NIE
        if(preg_match('/^\d{8}[a-zA-Z]{1}$/', $dni) || preg_match('/^[XYZ]{1}\d{7}[a-zA-Z0-9]{1}$/', $dni)){
            //Posibles valores para la letra final
            $letters = array(
                0 => 'T', 1 => 'R', 2 => 'W', 3 => 'A', 4 => 'G', 5 => 'M',
                6 => 'Y', 7 => 'F', 8 => 'P', 9 => 'D', 10 => 'X', 11 => 'B',
                12 => 'N', 13 => 'J', 14 => 'Z', 15 => 'S', 16 => 'Q', 17 => 'V',
                18 => 'H', 19 => 'L', 20 => 'C', 21 => 'K',22 => 'E'
            );

            //Comprobar si es un DNI
            if (preg_match('/^\d{8}[a-zA-Z]{1}$/', $dni))
            {
                if (strtoupper($dni[strlen($dni) - 1]) != $letters[((int) substr($dni, 0, strlen($dni) - 1)) % 23]){
                    $context->addViolationAt('dni', 'dni.invalid.number');
                    return;
                }
            }
            //Comprobar si es un NIE
            else if (preg_match('/^[XYZ]{1}\d{7}[a-zA-Z0-9]{1}$/', $dni))
            {
                //Comprobar letra
                if (strtoupper($dni[strlen($dni) - 1]) !=$letters[((int) substr($dni, 1, strlen($dni) - 2)) % 23]){
                    $context->addViolationAt('dni', 'nie.invalid.number');
                    return;
                }
            }
        }
        //CIF
        if(preg_match('/^[ABCDEFGHJNPQRSUVW]{1}/', $dni)){
            $sum = 0;
            for ($i=2; $i<strlen($dni)-1; $i+=2) {
                $sum += substr($dni, $i, 1);
            }

            for ($i=1; $i<strlen($dni)-1; $i+=2) {
                $t = substr($dni, $i, 1) * 2;
                $sum += ($t>9)?($t-9):$t;
            }

            $control = 10 - ($sum % 10);

            if ( !(substr($dni, 8, 1) == $control || strtoupper(substr($dni, 8, 1)) == substr('JABCDEFGHI', $control, 1 ))){
                $context->addViolationAt('dni', 'cif.invalid');

                return;
            }
        }

    }
1062133
protected function checkHost(\SwaggerValidator\Common\Context $context)
    {
        if (!isset($this->host)) {
            return true;
        }

        if ($context->getDataValue() === null) {
            return true;
        }

        if (strtolower($context->getDataValue()) && strtolower($this->host)) {
            return true;
        }

        return $context->setValidationError(\SwaggerValidator\Common\Context::VALIDATION_TYPE_HOSTNAME_ERROR, 'HostName requested is not allowed', __METHOD__, __LINE__);
    }
751706
public function isGroupCenterPresentOnce(ExecutionContextInterface $context)
    {
        $groupCentersIds = array();
        foreach ($this->getGroupCenters() as $groupCenter) {
            if (in_array($groupCenter->getId(), $groupCentersIds)) {
                $context->buildViolation("The user has already those permissions")
                        ->addViolation();
                
            } else {
                $groupCentersIds[] = $groupCenter->getId();
            }
        }
    }
28374
public static function execute($value, ContextInterface $context): array
    {
        return is_int($value) === true ?
            static::createSuccessReply($value) :
            static::createErrorReply($context, $value, ErrorCodes::IS_INT, Messages::IS_INT, []);
    }
447486
public function validate(
        string $path,
        $model,
        ValidatorContextInterface $context,
        ValidatorInterface $validator = null
    ) {
        if (null === $model) {
            return [];
        }

        $criteria = $this->getCriteria($model);

        $modelClass = get_class($model);

        if (null === $persistedModel = $this->objectManager->getRepository($modelClass)->findOneBy($criteria)) {
            return [];
        }

        $metadata = $this->objectManager->getClassMetadata($modelClass);

        if ($this->isValueSameAsPersistedValue($metadata->getIdentifier(), $model, $persistedModel)) {
            return [];
        }

        $errors = [];

        foreach ($this->uniqueProperties as $uniqueProperty) {
            $errors[] = new Error(
                '' !== $path ? $path.'.'.$uniqueProperty : $uniqueProperty,
                'constraint.unique.notunique',
                ['uniqueProperties' => implode(', ', $this->uniqueProperties)]
            );
        }

        return $errors;
    }
902419
protected static function validate_contextlist_contexts(approved_contextlist $contextlist) {
        return array_reduce($contextlist->get_contexts(), function($carry, $context) {
            if ($context->contextlevel == CONTEXT_COURSE) {
                $carry[] = $context;
            }
            return $carry;
        }, []);
    }
1146373
private void executeValidate(FacesContext context) {
        try {
            validate(context);
        } catch (RuntimeException e) {
            context.renderResponse();
            throw e;
        }

        if (!isValid()) {
            context.validationFailed();
            context.renderResponse();
        }
    }
775390
public function checkExpirationDate(ExecutionContext $context)
    {
        $expirationDate = $this->expirationDate;

        if (is_null($expirationDate)) {
            $context->addViolationAt("expirationDate", "La fecha de vencimiento es invalida", array(), null);
        } else {
            $ts = $expirationDate->format('U');
            if ($ts<=time()) {
                $context->addViolationAt("expirationDate", "La fecha de vencimiento es invalida", array(), null);
            }
        }

    }
373535
protected function executeProcessors(ContextInterface $context)
    {
        $processors = $this->processorBag->getProcessors($context);
        /** @var ProcessorInterface $processor */
        foreach ($processors as $processor) {
            try {
                $processor->process($context);
            } catch (\Exception $e) {
                throw new ExecutionFailedException(
                    $processors->getProcessorId(),
                    $processors->getAction(),
                    $processors->getGroup(),
                    $e
                );
            }
        }
    }
335070
public function getVisitor(ValidationContext $context)
    {
        return [
            NodeKind::OPERATION_DEFINITION => function (OperationDefinitionNode $node) use ($context) {
                if ($node->operation === 'subscription') {
                    if (count($node->selectionSet->selections) !== 1) {
                        $context->reportError(
                            new Error(
                                $this->singleFieldOnlyMessage($node->name ? $node->name->value : null),
                                array_slice($node->selectionSet->selections, 1)
                            )
                        );
                    }
                }
            }
        ];
    }
193648
protected function _onEntityValidate(AnCommandContext $context)
    {
        if ($this->nodeA->id === $this->nodeB->id) {
            return false;
        }

        return true;
    }
243533
public function validate(
        string $path,
        $value,
        ValidatorContextInterface $context,
        ValidatorInterface $validator = null
    ) {
        if (null === $value) {
            return [];
        }

        if (!is_array($value) && !$value instanceof \Countable) {
            return [new Error(
                $path,
                'constraint.count.invalidtype',
                ['type' => is_object($value) ? get_class($value) : gettype($value)]
            )];
        }

        $count = count($value);

        if (null !== $this->min && $count < $this->min || null !== $this->max && $count > $this->max) {
            return [
                new Error(
                    $path,
                    'constraint.count.outofrange',
                    ['count' => $count, 'min' => $this->min, 'max' => $this->max]
                ),
            ];
        }

        return [];
    }
1234516
public function validate(
        string $path,
        $value,
        ValidatorContextInterface $context,
        ValidatorInterface $validator = null
    ) {
        if (null === $value || '' === $value) {
            return [];
        }

        if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString'))) {
            return [new Error(
                $path,
                'constraint.coordinate.invalidtype',
                ['type' => is_object($value) ? get_class($value) : gettype($value)]
            )];
        }

        $value = (string) $value;

        $matches = [];

        if (!preg_match(self::PATTERN, $value, $matches)) {
            return [new Error($path, 'constraint.coordinate.invalidformat', ['value' => $value])];
        }

        $lat = (float) $matches[1];
        $lon = (float) $matches[3];

        if ($lat < -90 || $lat > 90 || $lon < -180 || $lon > 180) {
            return [new Error($path, 'constraint.coordinate.invalidvalue', ['value' => $value])];
        }

        return [];
    }
667215
public static function validate($object, ExecutionContextInterface $context)
    {
        if (!method_exists($object, 'getParent')) {
            return;
        }

        $tempObject = $object->getParent();

        while ($tempObject !== null) {
            if ($tempObject === $object) {
                $context->buildViolation(
                    'Circular reference error. '
                    . 'An object can not reference with a parent to itself nor to an ancestor of itself'
                )
                    ->atPath('parent')
                    ->addViolation();

                break;
            }

            $tempObject = $tempObject->getParent();
        }
    }
804157
def set_execution_context(self, execution_context):
        """"""
        if self._execution_context:
            raise errors.AlreadyInContextError

        self._execution_context = execution_context
157491
public function checkContext(ContextInterface $context)
    {
        try {
            $checkedCode = $this->preprocessor->preprocess($context->getCheckedCode());
            $parsedStatements = $this->parser->parse($checkedCode);
            $this->traverser->traverse($parsedStatements, $context, $this->lexer->getTokens());
        } catch (\Exception $e) {
            $context->addError(new CheckError($e->getMessage()));
        } catch (\ParseException $e) {
            $context->addError(new CheckError($e->getMessage(), $e->getLine()));
        }
    }
688986
public static function validate_context($context) {
        global $CFG, $PAGE;

        if (empty($context)) {
            throw new invalid_parameter_exception('Context does not exist');
        }
        if (empty(self::$contextrestriction)) {
            self::$contextrestriction = context_system::instance();
        }
        $rcontext = self::$contextrestriction;

        if ($rcontext->contextlevel == $context->contextlevel) {
            if ($rcontext->id != $context->id) {
                throw new restricted_context_exception();
            }
        } else if ($rcontext->contextlevel > $context->contextlevel) {
            throw new restricted_context_exception();
        } else {
            $parents = $context->get_parent_context_ids();
            if (!in_array($rcontext->id, $parents)) {
                throw new restricted_context_exception();
            }
        }

        $PAGE->reset_theme_and_output();
        list($unused, $course, $cm) = get_context_info_array($context->id);
        require_login($course, false, $cm, false, true);
        $PAGE->set_context($context);
    }