Document Validation (CNPJ/CPF)

@param $documentNumber
@return string
@throws \GuzzleHttp\Exception\GuzzleException
558607
public function validateDocument($documentNumber)
    {
        $data = $this->execute(
            self::HTTP_GET,
            self::DOMUSERP_API_PEDIDOVENDA . '/pessoas/validarDocumento',
            ['query' => ['num' => $documentNumber]]
        );

        return $data;
    }
175497
protected function validateString(/** @noinspection PhpUnusedParameterInspection */
        &$document_data, &$data, array $data_pointer, array $parent_data_pointer, ISchema $document, $schema, ValidationResult $bag): bool
    {
        $ok = true;

        // minLength
        if (property_exists($schema, 'minLength')) {
            if (!is_int($schema->minLength)) {
                throw new SchemaKeywordException(
                    $schema,
                    'minLength',
                    $schema->minLength,
                    "'minLength' keyword must be an integer, " . gettype($schema->minLength) . " given"
                );
            }
            if ($schema->minLength < 0) {
                throw new SchemaKeywordException(
                    $schema,
                    'minLength',
                    $schema->minLength,
                    "'minLength' keyword must be positive, " . $schema->minLength . " given"
                );
            }
            $len = $this->helper->stringLength($data);
            if ($len < $schema->minLength) {
                $ok = false;
                $bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'minLength', [
                    'min' => $schema->minLength,
                    'length' => $len,
                ]));
                if ($bag->isFull()) {
                    return false;
                }
            }
            unset($len);
        }

        // maxLength
        if (property_exists($schema, 'maxLength')) {
            if (!is_int($schema->maxLength)) {
                throw new SchemaKeywordException(
                    $schema,
                    'maxLength',
                    $schema->maxLength,
                    "'maxLength' keyword must be an integer, " . gettype($schema->maxLength) . " given"
                );
            }
            if ($schema->maxLength < 0) {
                throw new SchemaKeywordException(
                    $schema,
                    'maxLength',
                    $schema->maxLength,
                    "'maxLength' keyword must be positive, " . $schema->maxLength . " given"
                );
            }
            $len = $this->helper->stringLength($data);
            if ($len > $schema->maxLength) {
                $ok = false;
                $bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'maxLength', [
                    'max' => $schema->maxLength,
                    'length' => $len,
                ]));
                if ($bag->isFull()) {
                    return false;
                }
            }
            unset($len);
        }

        // pattern
        if (property_exists($schema, 'pattern')) {
            if (!is_string($schema->pattern)) {
                throw new SchemaKeywordException(
                    $schema,
                    'pattern',
                    $schema->pattern,
                    "'pattern' keyword must be a string, " . gettype($schema->pattern) . " given"
                );
            }
            if ($schema->pattern === '') {
                throw new SchemaKeywordException(
                    $schema,
                    'pattern',
                    $schema->pattern,
                    "'pattern' keyword must not be empty"
                );
            }
            $match = @preg_match(self::BELL . $schema->pattern . self::BELL . 'u', $data);
            if ($match === false) {
                throw new SchemaKeywordException(
                    $schema,
                    'pattern',
                    $schema->pattern,
                    "'pattern' keyword must be a valid regex"
                );
            }
            if (!$match) {
                $ok = false;
                $bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'pattern', [
                    'pattern' => $schema->pattern,
                ]));
                if ($bag->isFull()) {
                    return false;
                }
            }
        }

        // content encoding
        if (property_exists($schema, 'contentEncoding')) {
            if (!is_string($schema->contentEncoding)) {
                throw new SchemaKeywordException(
                    $schema,
                    'contentEncoding',
                    $schema->contentEncoding,
                    "'contentEncoding' keyword must be a string, " . gettype($schema->contentEncoding) . " given"
                );
            }

            switch ($schema->contentEncoding) {
                case "binary":
                    $decoded = $data;
                    break;
                case "base64":
                    $decoded = base64_decode($data, true);
                    break;
                default:
                    $decoded = false;
                    break;
            }

            if ($decoded === false) {
                $ok = false;
                $bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'contentEncoding', [
                    'encoding' => $schema->contentEncoding,
                ]));
                if ($bag->isFull()) {
                    return false;
                }
            }
        }

        // media type
        if (property_exists($schema, 'contentMediaType')) {
            if (!is_string($schema->contentMediaType)) {
                throw new SchemaKeywordException(
                    $schema,
                    'contentMediaType',
                    $schema->contentMediaType,
                    "'contentMediaType' keyword must be a string, " . gettype($schema->contentMediaType) . " given"
                );
            }

            if (!$this->mediaTypes) {
                throw new UnknownMediaTypeException($schema, $schema->contentMediaType);
            }

            if (!isset($decoded)) {
                // is set in contentEncoding if any
                $decoded = $data;
            }

            $valid = false;

            if ($decoded !== false) {
                $media = $this->mediaTypes->resolve($schema->contentMediaType);
                if ($media === null) {
                    throw new UnknownMediaTypeException($schema, $schema->contentMediaType);
                } else {
                    $valid = $media->validate($decoded, $schema->contentMediaType);
                }
            }

            if (!$valid) {
                $ok = false;
                $bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'contentMediaType', [
                    'media' => $schema->contentMediaType,
                ]));
                if ($bag->isFull()) {
                    return false;
                }
            }
        }

        return $ok;
    }
398792
public function validate($element) {
        $this->last_error = null;
        $celement   = realpath($element);
        $cvalidator = realpath($this->location.DIRECTORY_SEPARATOR.$this->type);
        $result = (empty($celement) || empty($cvalidator));
        if (!$result) {
            $xml_error = new libxml_errors_mgr();
            $doc = new DOMDocument();
            $doc->validateOnParse = false;
            $result = $doc->load($celement, LIBXML_NONET) &&
                      $doc->schemaValidate($cvalidator);
        }
        return $result;
    }
550726
private function getSignature(): string
    {
        if (!empty($this->secret)) {
            return $this->encode->signature(
                $this->jsonEncode($this->getHeader()),
                $this->jsonEncode($this->getPayload()),
                $this->secret
            );
        }

        throw new ValidateException('Invalid secret.', 9);
    }
1336862
private function validateNew(string $vatNumber): bool
    {
        $multiplier = 34;
        $substractor = 100;
        if (ctype_digit($vatNumber[0])) {
            $multiplier = 24;
            $substractor = 10;
        }

        $checkCharacter = array_flip(str_split($this->alphabet));
        $checkval = ($checkCharacter[$vatNumber[0]] * $multiplier) + $checkCharacter[$vatNumber[1]] - $substractor;

        return (((intval(substr($vatNumber, 2)) + ($checkval / 11) + 1) % 11) == $checkval % 11);
    }
1208645
public function getPage($pageNumber)
    {
        if (!\is_numeric($pageNumber)) {
            throw new \InvalidArgumentException(
                'Page number needs to be a number.'
            );
        }

        if ($pageNumber < 1 || $pageNumber > $this->getPageCount()) {
            throw new \InvalidArgumentException(
                \sprintf(
                    'Page number "%s" out of available page range (1 - %s)',
                    $pageNumber,
                    $this->getPageCount()
                )
            );
        }

        $this->readPages();

        $page = $this->pages[$pageNumber - 1];

        if ($page instanceof PdfIndirectObjectReference) {
            $readPages = function ($kids) use (&$readPages) {
                $kids = PdfArray::ensure($kids);

                /** @noinspection LoopWhichDoesNotLoopInspection */
                foreach ($kids->value as $reference) {
                    $reference = PdfIndirectObjectReference::ensure($reference);
                    $object = $this->parser->getIndirectObject($reference->value);
                    $type = PdfDictionary::get($object->value, 'Type');

                    if ($type->value === 'Pages') {
                        return $readPages(PdfDictionary::get($object->value, 'Kids'));
                    }

                    return $object;
                }

                throw new PdfReaderException(
                    'Kids array cannot be empty.',
                    PdfReaderException::KIDS_EMPTY
                );
            };

            $page = $this->parser->getIndirectObject($page->value);
            $dict = PdfType::resolve($page, $this->parser);
            $type = PdfDictionary::get($dict, 'Type');
            if ($type->value === 'Pages') {
                $kids = PdfType::resolve(PdfDictionary::get($dict, 'Kids'), $this->parser);
                $page = $this->pages[$pageNumber - 1] = $readPages($kids);
            } else {
                $this->pages[$pageNumber - 1] = $page;
            }
        }

        return new Page($page, $this->parser);
    }
751609
public function getImportedExternalPageLinks($pageNumber)
	{
		$links = [];

		$reader = $this->getPdfReader($this->currentReaderId);
		$parser = $reader->getParser();

		$page = $reader->getPage($pageNumber);
		$page->getPageDictionary();

		$annotations = $page->getAttribute('Annots');
		if ($annotations instanceof PdfIndirectObjectReference) {
			$annotations = PdfType::resolve($parser->getIndirectObject($annotations->value), $parser);
		}

		if ($annotations instanceof PdfArray) {

			$getAttribute = function ($array, $key) {
				if (isset($array[$key]->value)) {
					return $array[$key]->value;
				}

				return '';
			};

			foreach ($annotations->value as $annotation) {
				$annotation = PdfType::resolve($annotation, $parser)->value;

				/* Skip over any annotations that aren't links */
				$type = $getAttribute($annotation, 'Type');
				$subtype = $getAttribute($annotation, 'Subtype');
				if ($type !== 'Annot' || $subtype !== 'Link' || !isset($annotation['A'])) {
					continue;
				}

				/* Calculate the link positioning */
				$position = $getAttribute($annotation, 'Rect');

				if (count($position) !== 4) {
					continue;
				}

				$x1 = $getAttribute($position, 0) / Mpdf::SCALE;
				$y1 = $getAttribute($position, 1) / Mpdf::SCALE;
				$x2 = $getAttribute($position, 2) / Mpdf::SCALE;
				$y2 = $getAttribute($position, 3) / Mpdf::SCALE;
				$width = $x2 - $x1;
				$height = $y2 - $y1;

				$link = $annotation['A'] instanceof PdfIndirectObjectReference ? PdfType::resolve($annotation['A'], $parser)->value : $getAttribute($annotation, 'A');

				if (isset($link['URI'])) {
					$links[] = [
						'x' => $x1,
						'y' => $y1,
						'width' => $width,
						'height' => $height,
						'url' => $getAttribute($link, 'URI')
					];
				}
			}
		}

		return $links;
	}
442831
protected function validateNumber(/** @noinspection PhpUnusedParameterInspection */
        &$document_data, &$data, array $data_pointer, array $parent_data_pointer, ISchema $document, $schema, ValidationResult $bag): bool
    {
        $ok = true;

        // minimum, exclusiveMinimum
        if (property_exists($schema, 'minimum')) {
            if (!is_int($schema->minimum) && !is_float($schema->minimum)) {
                throw new SchemaKeywordException(
                    $schema,
                    'minimum',
                    $schema->minimum,
                    "'minimum' keyword must be an integer or a float, " . gettype($schema->minimum) . " given"
                );
            }

            $exclusive = false;
            if (property_exists($schema, 'exclusiveMinimum')) {
                if (!is_bool($schema->exclusiveMinimum)) {
                    throw new SchemaKeywordException(
                        $schema,
                        'exclusiveMinimum',
                        $schema->exclusiveMinimum,
                        "'exclusiveMinimum' keyword must be a boolean if 'minimum' keyword is present, " . gettype($schema->exclusiveMinimum) . " given"
                    );
                }
                $exclusive = $schema->exclusiveMinimum;
            }

            if ($exclusive && $data == $schema->minimum) {
                $ok = false;
                $bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'exclusiveMinimum', [
                    'min' => $schema->minimum
                ]));
                if ($bag->isFull()) {
                    return false;
                }
            } elseif ($data < $schema->minimum) {
                $ok = false;
                $bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'minimum', [
                    'min' => $schema->minimum
                ]));
                if ($bag->isFull()) {
                    return false;
                }
            }
        } elseif (property_exists($schema, 'exclusiveMinimum')) {
            if (!is_int($schema->exclusiveMinimum) && !is_float($schema->exclusiveMinimum)) {
                throw new SchemaKeywordException(
                    $schema,
                    'exclusiveMinimum',
                    $schema->exclusiveMinimum,
                    "'exclusiveMinimum' keyword must be an integer or a float if 'minimum' keyword is not present, " . gettype($schema->exclusiveMinimum) . " given"
                );
            }
            if ($data <= $schema->exclusiveMinimum) {
                $ok = false;
                $bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'exclusiveMinimum', [
                    'min' => $schema->exclusiveMinimum
                ]));
                if ($bag->isFull()) {
                    return false;
                }
            }
        }

        // maximum, exclusiveMaximum
        if (property_exists($schema, 'maximum')) {
            if (!is_int($schema->maximum) && !is_float($schema->maximum)) {
                throw new SchemaKeywordException(
                    $schema,
                    'maximum',
                    $schema->maximum,
                    "'maximum' keyword must be an integer or a float, " . gettype($schema->maximum) . " given"
                );
            }

            $exclusive = false;
            if (property_exists($schema, 'exclusiveMaximum')) {
                if (!is_bool($schema->exclusiveMaximum)) {
                    throw new SchemaKeywordException(
                        $schema,
                        'exclusiveMaximum',
                        $schema->exclusiveMaximum,
                        "'exclusiveMaximum' keyword must be a boolean is 'maximum' keyword is present, " . gettype($schema->exclusiveMaximum) . " given"
                    );
                }
                $exclusive = $schema->exclusiveMaximum;
            }

            if ($exclusive && $data == $schema->maximum) {
                $ok = false;
                $bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'exclusiveMaximum', [
                    'max' => $schema->maximum
                ]));
                if ($bag->isFull()) {
                    return false;
                }
            } elseif ($data > $schema->maximum) {
                $ok = false;
                $bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'maximum', [
                    'max' => $schema->maximum
                ]));
                if ($bag->isFull()) {
                    return false;
                }
            }
        } elseif (property_exists($schema, 'exclusiveMaximum')) {
            if (!is_int($schema->exclusiveMaximum) && !is_float($schema->exclusiveMaximum)) {
                throw new SchemaKeywordException(
                    $schema,
                    'exclusiveMaximum',
                    $schema->exclusiveMaximum,
                    "'exclusiveMaximum' keyword must be an integer or a float if 'maximum' keyword is not present, " . gettype($schema->exclusiveMaximum) . " given"
                );
            }
            if ($data >= $schema->exclusiveMaximum) {
                $ok = false;
                $bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'exclusiveMaximum', [
                    'max' => $schema->exclusiveMaximum
                ]));
                if ($bag->isFull()) {
                    return false;
                }
            }
        }

        // multipleOf
        if (property_exists($schema, 'multipleOf')) {
            if (!is_int($schema->multipleOf) && !is_float($schema->multipleOf)) {
                throw new SchemaKeywordException(
                    $schema,
                    'multipleOf',
                    $schema->multipleOf,
                    "'multipleOf' keyword must be an integer or a float, " . gettype($schema->multipleOf) . " given"
                );
            }
            if ($schema->multipleOf <= 0) {
                throw new SchemaKeywordException(
                    $schema,
                    'multipleOf',
                    $schema->multipleOf,
                    "'multipleOf' keyword must be greater than 0"
                );
            }
            if (!$this->helper->isMultipleOf($data, $schema->multipleOf)) {
                $ok = false;
                $bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'multipleOf', [
                    'divisor' => $schema->multipleOf
                ]));
                if ($bag->isFull()) {
                    return false;
                }
            }
        }

        return $ok;
    }
1010973
public function validateDocument(DOMDocument $xml)
    {
        $errors = [];

        $xpath = new \DOMXPath($xml);
        $xpath->registerNamespace('docbook', 'http://docbook.org/ns/docbook');

        foreach (['link', 'ezlink'] as $tagName) {
            $xpathExpression = $this->getXPathForLinkTag($tagName);
            /** @var \DOMElement $element */
            foreach ($xpath->query($xpathExpression) as $element) {
                $url = $element->getAttribute('xlink:href');
                preg_match('~^(.+)://([^#]*)?(#.*|\\s*)?$~', $url, $matches);
                list(, $scheme, $id) = $matches;

                if (empty($id)) {
                    continue;
                }

                if (!$this->validate($scheme, $id)) {
                    $errors[] = $this->getInvalidLinkError($scheme, $url);
                }
            }
        }

        return $errors;
    }
508568
protected function validateRef(&$document_data, &$data, array $data_pointer, array $parent_data_pointer, ISchema $document, stdClass $schema, ValidationResult $bag): bool
    {
        $ref = $schema->{'$ref'};

        // $vars
        if ($this->varsSupport) {
            $ref = URI::parseTemplate($ref, $this->getVars($document_data, $data_pointer, $schema));
        }

        $map_used = $this->mapSupport && property_exists($schema, Schema::MAP_PROP);

        // $map
        if ($map_used) {
            unset($data);
            $data = $this->deepClone($schema->{Schema::MAP_PROP});
            $this->resolveVars($data,$document_data, $data_pointer);

            unset($document_data);
            $document_data = &$data;

            if ($data_pointer) {
                $parent_data_pointer = array_merge($parent_data_pointer, $data_pointer);
                $data_pointer = [];
            }
        }

        // Check if is relative json pointer
        if ($relative = JsonPointer::parseRelativePointer($ref, true)) {
            if (!JsonPointer::isEscapedPointer($ref)) {
                throw new InvalidJsonPointerException($ref);
            }

            $schema = JsonPointer::getDataByRelativePointer(
                $document->resolve(),
                $relative,
                $schema->{Schema::PATH_PROP} ?? [],
                $this
            );
            if ($schema === $this) {
                throw new InvalidJsonPointerException($ref);
            }

            return $this->validateSchema($document_data, $data, $data_pointer, $parent_data_pointer, $document, $schema, $bag);
        }

        // Check if is a json pointer relative to this document
        if (isset($ref[0]) && $ref[0] === '#') {
            $pointer = substr($ref, 1);
            if (JsonPointer::isPointer($pointer)) {
                if (!JsonPointer::isEscapedPointer($pointer)) {
                    throw new InvalidJsonPointerException($pointer);
                }
                $schema = JsonPointer::getDataByPointer($document->resolve(), $pointer, $this);
                if ($schema === $this) {
                    throw new InvalidJsonPointerException($pointer);
                }

                return $this->validateSchema($document_data, $data, $data_pointer, $parent_data_pointer, $document, $schema, $bag);
            }
            unset($pointer);
        }

        // Merge uris
        $ref = URI::merge($ref, $schema->{Schema::BASE_ID_PROP} ?? '', true);

        list($base_ref, $fragment) = explode('#', $ref, 2);

        if (JsonPointer::isPointer($fragment)) {
            if (!JsonPointer::isEscapedPointer($fragment)) {
                throw new InvalidJsonPointerException($fragment);
            }

            // try to resolve locally
            $schema = $document->resolve($base_ref . '#');

            if ($schema === null) {
                if (!$this->loader) {
                    throw new SchemaNotFoundException($base_ref);
                }
                // use loader
                $document = $this->loader->loadSchema($base_ref);
                if (!($document instanceof ISchema)) {
                    throw new SchemaNotFoundException($base_ref);
                }

                if ($fragment === '' || $fragment === '/') {
                    $schema = $document->resolve();
                } else {
                    $schema = JsonPointer::getDataByPointer($document->resolve(), $fragment, $this);
                    if ($schema === $this) {
                        throw new InvalidJsonPointerException($fragment);
                    }
                }

                if (!$map_used) {
                    unset($document_data);
                    $document_data = &$data;
                    if ($data_pointer) {
                        $parent_data_pointer = array_merge($parent_data_pointer, $data_pointer);
                        $data_pointer = [];
                    }
                }
            } else {
                if ($fragment !== '' && $fragment !== '/') {
                    $schema = JsonPointer::getDataByPointer($schema, $fragment, $this);
                    if ($schema === $this) {
                        throw new InvalidJsonPointerException($fragment);
                    }
                }
            }

            return $this->validateSchema($document_data, $data, $data_pointer, $parent_data_pointer, $document, $schema, $bag);
        }

        // Not a json pointer
        $schema = $document->resolve($ref);
        if ($schema !== null) {
            return $this->validateSchema($document_data, $data, $data_pointer, $parent_data_pointer, $document, $schema, $bag);
        }

        if (!$this->loader) {
            throw new SchemaNotFoundException($base_ref);
        }
        // use loader
        $document = $this->loader->loadSchema($base_ref);
        if (!($document instanceof ISchema)) {
            throw new SchemaNotFoundException($base_ref);
        }

        $schema = $document->resolve($ref);

        if (!$map_used) {
            unset($document_data);
            $document_data = &$data;
            if ($data_pointer) {
                $parent_data_pointer = array_merge($parent_data_pointer, $data_pointer);
                $data_pointer = [];
            }
        }

        return $this->validateSchema($document_data, $data, $data_pointer, $parent_data_pointer, $document, $schema, $bag);
    }
1109006
public function schemaValidate($filename = '')
    {
        if (empty($filename)) {
            $filename = XmlUtils::getSchemaLocation($this->getVersion());
        }

        if (is_readable($filename)) {

            $oldErrorConfig = libxml_use_internal_errors(true);

            $doc = $this->getDomDocument();
            if (@$doc->schemaValidate($filename) === false) {

                $libXmlErrors = libxml_get_errors();
                $formattedErrors = self::formatLibXmlErrors($libXmlErrors);

                libxml_clear_errors();
                libxml_use_internal_errors($oldErrorConfig);

                $msg = "The document could not be validated with XML Schema:\n${formattedErrors}";
                throw new XmlStorageException($msg, XmlStorageException::XSD_VALIDATION, null, new LibXmlErrorCollection($libXmlErrors));
            }
        } else {
            $msg = "Schema '${filename}' cannot be read. Does this file exist? Is it readable?";
            throw new InvalidArgumentException($msg);
        }
    }
684058
function documentFactory(validators) {
    function documentValidator(doc, attr, debug) {
      doc = doc || {};
      attr = attr || {};
      
      var errors = [];

      _.each(validators, function (valset, field) {
        var err = null;
        var value = doc[field];

        // turn validators into an array if it isn't one
        valset = _.arrayify(valset);

        // run all the validation for this field
        _.each(valset, function (validator) {

          // if there's already an error, don't bother
          if (err) return;
          err = validator(value, attr, (field == 'badge'));

        });

        // set the correct field on the error
        if (err) err.field = field;

        // jam it into the array with the rest of 'em
        errors.push(err);
      });

      // throw out any undefined or nulls that snuck in there
      errors = _.reject(errors, _.isMissing);

      if (errors.length) {
        return { name: 'doc', errors: errors };
      }
    }
    documentValidator.meta = { name : 'doc' };
    return documentValidator;
  }
173842
public function getAnnotationsCount($pageNumber)
    {

        $strURI = Product::$baseProductUri . '/pdf/' . $this->getFileName() . '/pages/' . $pageNumber . '/annotations';
        $signedURI = Utils::sign($strURI);
        $responseStream = Utils::processCommand($signedURI, 'GET', '', '');
        $json = json_decode($responseStream);
        return count($json->Annotations->List);
    }
971891
protected function parse($object)
    {
        if (! is_object($object)) {
            throw new ValidationException(
                'DocumentLink has to be an object, "' . gettype($object) . '" given.'
            );
        }

        $links = get_object_vars($object);

        if (array_key_exists('self', $links)) {
            if (! is_string($links['self']) and ! is_object($links['self'])) {
                throw new ValidationException(
                    'property "self" has to be a string or object, "' .
                    gettype($links['self']) . '" given.'
                );
            }

            $this->setLink('self', $links['self']);

            unset($links['self']);
        }

        if (array_key_exists('related', $links)) {
            if (! is_string($links['related']) and ! is_object($links['related'])) {
                throw new ValidationException(
                    'property "related" has to be a string or object, "' .
                    gettype($links['related']) . '" given.'
                );
            }

            $this->setLink('related', $links['related']);

            unset($links['related']);
        }

        // Pagination links, if data in parent attributes exists
        if ($this->getParent()->has('data')) {
            if (array_key_exists('first', $links)) {
                $this->setPaginationLink('first', $links['first']);

                unset($links['first']);
            }

            if (array_key_exists('last', $links)) {
                $this->setPaginationLink('last', $links['last']);

                unset($links['last']);
            }

            if (array_key_exists('prev', $links)) {
                $this->setPaginationLink('prev', $links['prev']);

                unset($links['prev']);
            }

            if (array_key_exists('next', $links)) {
                $this->setPaginationLink('next', $links['next']);

                unset($links['next']);
            }
        }

        // custom links
        foreach ($links as $name => $value) {
            $this->setLink($name, $value);
        }
    }
843311
public function getDocumentById($documentId)
    {
        /* @var $query SearchQuery */
        $query = $this->queryBuilder->newSearchQuery($documentId)->useQueryFields(QueryFields::fromString('id'))->getQuery();
        $response = $this->search->search($query, 0, 1);
        $parsedData = $response->getParsedData();
        $resultDocument = isset($parsedData->response->docs[0]) ? $parsedData->response->docs[0] : null;

        if (!$resultDocument instanceof Document) {
            throw new \UnexpectedValueException("Response did not contain a valid Document object");
        }

        return $this->searchResultBuilder->fromApacheSolrDocument($resultDocument);
    }
41128
public static function validar($cnpj)
    {
        $cnpj = static::digitos($cnpj);

        if (strlen($cnpj) <> 14) {
            return false;
        }

        $regex = "/^0+$|^1+$|^2+$|^3+$|^4+$|^5+$|^6+$|^7+$|^8+$|^9+$/";
        if (preg_match($regex, $cnpj)) {
            return false;
        }

        // Primeiro dígito
        $multiplicadores = array (5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2);
        $soma            = 0;
        for ($i = 0; $i <= 11; $i++) {
            $soma += $multiplicadores[$i] * $cnpj[$i];
        }
        $d1 = 11 - ($soma % 11);
        if ($d1 >= 10) {
            $d1 = 0;
        }

        // Segundo dígito
        $multiplicadores = array (6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2);
        $soma            = 0;
        for ($i = 0; $i <= 12; $i++) {
            $soma += $multiplicadores[$i] * $cnpj[$i];
        }
        $d2 = 11 - ($soma % 11);
        if ($d2 >= 10) {
            $d2 = 0;
        }

        return $d1 == $cnpj[12] && $d2 == $cnpj[13];
    }
863605
public static DocumentBuilderFactory getStandardDocumentBuilderFactory(boolean validating) {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

        try {
            // enable validation (must specify a grammar)
            dbf.setValidating(validating);
            dbf.setFeature("http://xml.org/sax/features/validation", validating);

            dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", validating);
            dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", validating);

            dbf.setFeature("http://apache.org/xml/features/validation/schema", true);
            dbf.setFeature("http://xml.org/sax/features/namespaces", true);

            dbf.setFeature("http://apache.org/xml/features/dom/include-ignorable-whitespace", false);
        } catch (ParserConfigurationException pce) {
            throw new RuntimeException("Cannot load standard DocumentBuilderFactory. " + pce.getMessage(), pce);
        }

        dbf.setNamespaceAware(true);
        dbf.setIgnoringComments(true);
        dbf.setExpandEntityReferences(true);

        return dbf;
    }