repo stringlengths 7 63 | file_url stringlengths 81 284 | file_path stringlengths 5 200 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:02:33 2026-01-05 05:24:06 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Status.php | src/CfdiUtils/Validate/Status.php | <?php
namespace CfdiUtils\Validate;
/**
* Status (immutable value object)
* Define the status used in an assertion
*/
class Status implements \Stringable
{
public const STATUS_ERROR = 'ERROR';
public const STATUS_WARNING = 'WARN';
public const STATUS_NONE = 'NONE';
public const STATUS_OK = 'OK';
public const ORDER_MAP = [
self::STATUS_ERROR => 1,
self::STATUS_WARNING => 2,
self::STATUS_NONE => 3,
self::STATUS_OK => 4,
];
private string $status;
public function __construct(string $value)
{
// using values as keys for speed access
if (
self::STATUS_ERROR !== $value && self::STATUS_WARNING !== $value
&& self::STATUS_OK !== $value && self::STATUS_NONE !== $value
) {
throw new \UnexpectedValueException('The status is not one of the defined valid constants');
}
$this->status = $value;
}
public static function ok(): self
{
return new self(self::STATUS_OK);
}
public static function error(): self
{
return new self(self::STATUS_ERROR);
}
public static function warn(): self
{
return new self(self::STATUS_WARNING);
}
public static function none(): self
{
return new self(self::STATUS_NONE);
}
public function isError(): bool
{
return self::STATUS_ERROR === $this->status;
}
public function isWarning(): bool
{
return self::STATUS_WARNING === $this->status;
}
public function isOk(): bool
{
return self::STATUS_OK === $this->status;
}
public function isNone(): bool
{
return self::STATUS_NONE === $this->status;
}
public static function when(bool $condition, ?self $errorStatus = null): self
{
if ($condition) {
return self::ok();
}
return $errorStatus ?? self::error();
}
public function equalsTo(self $status): bool
{
return $status->status === $this->status;
}
public function compareTo(self $status): int
{
return $this->comparableValue($this) <=> $this->comparableValue($status);
}
public static function comparableValue(self $status): int
{
return self::ORDER_MAP[$status->status];
}
public function __toString(): string
{
return $this->status;
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Assert.php | src/CfdiUtils/Validate/Assert.php | <?php
namespace CfdiUtils\Validate;
class Assert implements \Stringable
{
private Status $status;
/**
* Assert constructor.
* @param Status|null $status If null the status will be NONE
*/
public function __construct(
private string $code,
private string $title = '',
?Status $status = null,
private string $explanation = '',
) {
if ('' === $this->code) {
throw new \UnexpectedValueException('Code cannot be an empty string');
}
$this->setStatus($status ?: Status::none());
}
public function getTitle(): string
{
return $this->title;
}
public function getStatus(): Status
{
return $this->status;
}
public function getExplanation(): string
{
return $this->explanation;
}
public function getCode(): string
{
return $this->code;
}
public function setTitle(string $title): void
{
$this->title = $title;
}
public function setStatus(Status $status, ?string $explanation = null): void
{
$this->status = $status;
if (null !== $explanation) {
$this->setExplanation($explanation);
}
}
public function setExplanation(string $explanation): void
{
$this->explanation = $explanation;
}
public function __toString(): string
{
return sprintf('%s: %s - %s', $this->status, $this->code, $this->title);
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/MultiValidatorFactory.php | src/CfdiUtils/Validate/MultiValidatorFactory.php | <?php
namespace CfdiUtils\Validate;
use CfdiUtils\Validate\Cfdi40\Xml\XmlDefinition;
use CfdiUtils\Validate\Xml\XmlFollowSchema;
class MultiValidatorFactory
{
private Discoverer $discoverer;
public function __construct(?Discoverer $discoverer = null)
{
$this->discoverer = $discoverer ?: new Discoverer();
}
public function getDiscoverer(): Discoverer
{
return $this->discoverer;
}
public function newCreated33(): MultiValidator
{
$multiValidator = new MultiValidator('3.3');
$multiValidator->add(new XmlFollowSchema());
$this->addDiscovered($multiValidator, __NAMESPACE__ . '\Cfdi33\Standard', __DIR__ . '/Cfdi33/Standard');
$this->addDiscovered(
$multiValidator,
__NAMESPACE__ . '\Cfdi33\RecepcionPagos',
__DIR__ . '/Cfdi33/RecepcionPagos'
);
return $multiValidator;
}
public function newReceived33(): MultiValidator
{
return $this->newCreated33();
}
public function newCreated40(): MultiValidator
{
$multiValidator = new MultiValidator('4.0');
$multiValidator->add(new XmlFollowSchema());
$multiValidator->add(new XmlDefinition());
$this->addDiscovered($multiValidator, __NAMESPACE__ . '\Cfdi40\Standard', __DIR__ . '/Cfdi40/Standard');
return $multiValidator;
}
public function newReceived40(): MultiValidator
{
return $this->newCreated40();
}
public function addDiscovered(MultiValidator $multiValidator, string $namespacePrefix, string $directory): void
{
$multiValidator->addMulti(
...$this->discoverer->discoverInFolder($namespacePrefix, $directory)
);
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Xml/XmlFollowSchema.php | src/CfdiUtils/Validate/Xml/XmlFollowSchema.php | <?php
namespace CfdiUtils\Validate\Xml;
use CfdiUtils\Nodes\NodeInterface;
use CfdiUtils\Nodes\XmlNodeUtils;
use CfdiUtils\Validate\Asserts;
use CfdiUtils\Validate\Contracts\RequireXmlResolverInterface;
use CfdiUtils\Validate\Contracts\RequireXmlStringInterface;
use CfdiUtils\Validate\Contracts\ValidatorInterface;
use CfdiUtils\Validate\Status;
use CfdiUtils\Validate\Traits\XmlStringPropertyTrait;
use CfdiUtils\XmlResolver\XmlResolverPropertyInterface;
use CfdiUtils\XmlResolver\XmlResolverPropertyTrait;
use Eclipxe\XmlSchemaValidator\Schema;
use Eclipxe\XmlSchemaValidator\Schemas;
use Eclipxe\XmlSchemaValidator\SchemaValidator;
/**
* XmlFollowSchema
* Esta clase no es descubrible, esto es porque generalmente se busca que sea la primera validación.
* Si falla el objeto Asserts devuelto tiene la bandera mustStop activa.
*
* Valida que:
* - XSD01: El contenido XML sigue los esquemas XSD
*
* Para poder generar la validación se necesita el contenido XML, este puede ser establecido por sus propiedades.
* En caso de no existir entonces el contenido se generará desde el atributo Node.
* Para poder usar el resolvedor de recursos (usar archivos xsd locales) se debe especificar el XmlResolver.
*
* A pesar de no ser descubierto, se puede hidratar el objeto con sus interfaces y el uso de un Hydrater
*/
class XmlFollowSchema implements
ValidatorInterface,
XmlResolverPropertyInterface,
RequireXmlStringInterface,
RequireXmlResolverInterface
{
use XmlStringPropertyTrait;
use XmlResolverPropertyTrait;
public function canValidateCfdiVersion(string $version): bool
{
return true;
}
public function validate(NodeInterface $comprobante, Asserts $asserts): void
{
$assert = $asserts->put('XSD01', 'El contenido XML sigue los esquemas XSD');
// obtain content
if ('' === $content = $this->getXmlString()) {
$content = XmlNodeUtils::nodeToXmlString($comprobante);
}
// create the schema validator object
$schemaValidator = SchemaValidator::createFromString($content);
// validate using resolver->retriever or using the simple method
try {
$schemas = $schemaValidator->buildSchemas();
if ($this->hasXmlResolver() && $this->getXmlResolver()->hasLocalPath()) {
$schemas = $this->changeSchemasUsingRetriever($schemas);
}
$schemaValidator->validateWithSchemas($schemas);
} catch (\Throwable $exception) {
// validate failure
$assert->setStatus(Status::error(), $exception->getMessage());
$asserts->mustStop(true);
return;
}
// set final status
$assert->setStatus(Status::ok());
}
private function changeSchemasUsingRetriever(Schemas $schemas): Schemas
{
// obtain the retriever, throw its own exception if non set
$retriever = $this->getXmlResolver()->newXsdRetriever();
// replace the schemas locations with the retrieved local path
/** @var Schema $schema */
foreach ($schemas as $schema) {
$location = $schema->getLocation();
$localPath = $retriever->buildPath($location);
if (! file_exists($localPath)) {
$retriever->retrieve($location);
}
// this call will change the value, not insert a new entry
$schemas->insert(new Schema($schema->getNamespace(), $localPath));
}
return $schemas;
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Traits/XmlStringPropertyTrait.php | src/CfdiUtils/Validate/Traits/XmlStringPropertyTrait.php | <?php
namespace CfdiUtils\Validate\Traits;
trait XmlStringPropertyTrait
{
private string $xmlString = '';
public function setXmlString(string $xmlString): void
{
$this->xmlString = $xmlString;
}
public function getXmlString(): string
{
return $this->xmlString;
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Common/TimbreFiscalDigitalVersionValidatorTrait.php | src/CfdiUtils/Validate/Common/TimbreFiscalDigitalVersionValidatorTrait.php | <?php
namespace CfdiUtils\Validate\Common;
use CfdiUtils\Nodes\NodeInterface;
use CfdiUtils\Validate\Asserts;
use CfdiUtils\Validate\Status;
trait TimbreFiscalDigitalVersionValidatorTrait
{
public function validate(NodeInterface $comprobante, Asserts $asserts): void
{
$asserts->put(
'TFDVERSION01',
'Si existe el complemento timbre fiscal digital, entonces su versión debe ser 1.1'
);
$tfdVersion = $comprobante->searchNode('cfdi:Complemento', 'tfd:TimbreFiscalDigital');
if (null !== $tfdVersion) {
$asserts->putStatus(
'TFDVERSION01',
Status::when('1.1' === $tfdVersion['Version'])
);
}
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Common/SelloDigitalCertificadoValidatorTrait.php | src/CfdiUtils/Validate/Common/SelloDigitalCertificadoValidatorTrait.php | <?php
namespace CfdiUtils\Validate\Common;
use CfdiUtils\CadenaOrigen\XsltBuilderPropertyTrait;
use CfdiUtils\Certificado\Certificado;
use CfdiUtils\Certificado\NodeCertificado;
use CfdiUtils\Nodes\NodeInterface;
use CfdiUtils\Validate\Asserts;
use CfdiUtils\Validate\Status;
use CfdiUtils\Validate\Traits\XmlStringPropertyTrait;
use CfdiUtils\XmlResolver\XmlResolverPropertyTrait;
trait SelloDigitalCertificadoValidatorTrait
{
use XmlResolverPropertyTrait;
use XmlStringPropertyTrait;
use XsltBuilderPropertyTrait;
private Asserts $asserts;
private Certificado $certificado;
private function registerAsserts(): void
{
$asserts = [
'SELLO01' => 'Se puede obtener el certificado del comprobante',
'SELLO02' => 'El número de certificado del comprobante igual al encontrado en el certificado',
'SELLO03' => 'El RFC del comprobante igual al encontrado en el certificado',
'SELLO04' => 'El nombre del emisor del comprobante es igual al encontrado en el certificado',
'SELLO05' => 'La fecha del documento es mayor o igual a la fecha de inicio de vigencia del certificado',
'SELLO06' => 'La fecha del documento menor o igual a la fecha de fin de vigencia del certificado',
'SELLO07' => 'El sello del comprobante está en base 64',
'SELLO08' => 'El sello del comprobante coincide con el certificado y la cadena de origen generada',
];
foreach ($asserts as $code => $title) {
$this->asserts->put($code, $title);
}
}
public function validate(NodeInterface $comprobante, Asserts $asserts): void
{
$this->asserts = $asserts;
$this->registerAsserts();
// create the certificate
$extractor = new NodeCertificado($comprobante);
try {
$certificado = $extractor->obtain();
$version = $extractor->getVersion();
} catch (\Exception $exception) {
$this->asserts->putStatus('SELLO01', Status::error(), $exception->getMessage());
return;
}
$this->certificado = $certificado;
$this->asserts->putStatus('SELLO01', Status::ok());
// start validations
$this->validateNoCertificado($comprobante['NoCertificado']);
$hasRegistroFiscal = $comprobante->searchNodes(
'cfdi:Complemento',
'registrofiscal:CFDIRegistroFiscal'
)->count() > 0;
$noCertificadoSAT = $comprobante->searchAttribute(
'cfdi:Complemento',
'tfd:TimbreFiscalDigital',
'NoCertificadoSAT'
);
if (! $hasRegistroFiscal || $comprobante['NoCertificado'] !== $noCertificadoSAT) {
// validate emisor rfc
$this->validateRfc($comprobante->searchAttribute('cfdi:Emisor', 'Rfc'));
// validate emisor nombre
$this->validateNombre(
$comprobante->searchAttribute('cfdi:Emisor', 'Nombre'),
$comprobante->searchAttribute('cfdi:Emisor', 'Rfc')
);
}
$this->validateFecha($comprobante['Fecha']);
$this->validateSello($comprobante['Sello'], $version);
}
private function buildCadenaOrigen(string $version): string
{
$xsltLocation = $this->getXmlResolver()->resolveCadenaOrigenLocation($version);
return $this->getXsltBuilder()->build($this->getXmlString(), $xsltLocation);
}
private function validateNoCertificado(string $noCertificado): void
{
$expectedNumber = $this->certificado->getSerial();
$this->asserts->putStatus(
'SELLO02',
Status::when($expectedNumber === $noCertificado),
sprintf('Certificado: %s, Comprobante: %s', $expectedNumber, $noCertificado)
);
}
private function validateRfc(string $emisorRfc): void
{
$expectedRfc = $this->certificado->getRfc();
$this->asserts->put(
'SELLO03',
'El RFC del comprobante igual al encontrado en el certificado',
Status::when($expectedRfc === $emisorRfc),
sprintf('Rfc certificado: %s, Rfc comprobante: %s', $expectedRfc, $emisorRfc)
);
}
abstract protected function validateNombre(string $emisorNombre, string $rfc): void;
private function validateFecha(string $fechaSource): void
{
$fecha = ('' === $fechaSource) ? 0 : intval(strtotime($fechaSource));
if (0 === $fecha) {
return;
}
$validFrom = $this->certificado->getValidFrom();
$validTo = $this->certificado->getValidTo();
$explanation = vsprintf('Validez del certificado: %s hasta %s, Fecha comprobante: %s', [
date('Y-m-d H:i:s', $validFrom),
date('Y-m-d H:i:s', $validTo),
date('Y-m-d H:i:s', $fecha),
]);
$this->asserts->putStatus('SELLO05', Status::when($fecha >= $validFrom), $explanation);
$this->asserts->putStatus('SELLO06', Status::when($fecha <= $validTo), $explanation);
}
private function validateSello(string $selloBase64, string $version): void
{
$sello = $this->obtainSello($selloBase64);
if ('' === $sello) {
return;
}
$cadena = $this->buildCadenaOrigen($version);
$selloIsValid = $this->certificado->verify($cadena, $sello, OPENSSL_ALGO_SHA256);
$this->asserts->putStatus(
'SELLO08',
Status::when($selloIsValid),
'La verificación del sello del CFDI no coincide, probablemente el CFDI fue alterado o mal generado'
);
}
private function obtainSello(string $selloBase64): string
{
// this silence error operator is intentional, if $selloBase64 is malformed
// then it will return false, and I will recognize the error
$sello = @base64_decode($selloBase64, true);
$this->asserts->putStatus('SELLO07', Status::when(false !== $sello));
return (string) $sello;
}
protected function compareNames(string $first, string $second): bool
{
return $this->castNombre($first) === $this->castNombre($second);
}
protected function castNombre(string $nombre): string
{
$nombre = iconv('UTF-8', 'ASCII//TRANSLIT', $nombre) ?: '';
$nombre = str_replace([' ', '-', ',', '.', '#', '&', "'", '"', '~', '¨', '^'], '', $nombre);
return mb_strtoupper($nombre);
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Common/TimbreFiscalDigitalSelloValidatorTrait.php | src/CfdiUtils/Validate/Common/TimbreFiscalDigitalSelloValidatorTrait.php | <?php
namespace CfdiUtils\Validate\Common;
use CfdiUtils\CadenaOrigen\XsltBuilderPropertyTrait;
use CfdiUtils\Certificado\Certificado;
use CfdiUtils\Certificado\SatCertificateNumber;
use CfdiUtils\Internals\TemporaryFile;
use CfdiUtils\Nodes\NodeInterface;
use CfdiUtils\Nodes\XmlNodeUtils;
use CfdiUtils\TimbreFiscalDigital\TfdCadenaDeOrigen;
use CfdiUtils\Validate\Asserts;
use CfdiUtils\Validate\Status;
use CfdiUtils\XmlResolver\XmlResolverPropertyTrait;
trait TimbreFiscalDigitalSelloValidatorTrait
{
use XmlResolverPropertyTrait;
use XsltBuilderPropertyTrait;
public function validate(NodeInterface $comprobante, Asserts $asserts): void
{
$assert = $asserts->put(
'TFDSELLO01',
'El Sello SAT del Timbre Fiscal Digital corresponde al certificado SAT'
);
if (! $this->hasXmlResolver()) {
$assert->setExplanation('No se puede hacer la validación porque carece de un objeto resolvedor');
return;
}
$tfd = $comprobante->searchNode('cfdi:Complemento', 'tfd:TimbreFiscalDigital');
if (null === $tfd) {
$assert->setExplanation('El CFDI no contiene un Timbre Fiscal Digital');
return;
}
if ('1.1' !== $tfd['Version']) {
$assert->setExplanation('La versión del timbre fiscal digital no es 1.1');
return;
}
$validationSellosMatch = $comprobante['Sello'] !== $tfd['SelloCFD'];
if ($validationSellosMatch) {
$assert->setStatus(
Status::error(),
'El atributo SelloCFD del Timbre Fiscal Digital no coincide con el atributo Sello del Comprobante'
);
return;
}
$certificadoSAT = $tfd['NoCertificadoSAT'];
if (! SatCertificateNumber::isValidCertificateNumber($certificadoSAT)) {
$assert->setStatus(
Status::error(),
sprintf('El atributo NoCertificadoSAT con el valor "%s" no es válido', $certificadoSAT)
);
return;
}
try {
$resolver = $this->getXmlResolver();
$certificadoUrl = (new SatCertificateNumber($certificadoSAT))->remoteUrl();
if (! $resolver->hasLocalPath()) {
$temporaryFile = TemporaryFile::create();
$certificadoFile = $temporaryFile->getPath();
$resolver->getDownloader()->downloadTo($certificadoUrl, $certificadoFile);
$certificado = new Certificado($certificadoFile);
$temporaryFile->remove();
} else {
$certificadoFile = $resolver->resolve($certificadoUrl, $resolver::TYPE_CER);
$certificado = new Certificado($certificadoFile);
}
} catch (\Throwable $ex) {
$assert->setStatus(
Status::error(),
sprintf('No se ha podido obtener el certificado %s: %s', $certificadoSAT, $ex->getMessage())
);
return;
}
$tfdCadenaOrigen = new TfdCadenaDeOrigen($resolver, $this->getXsltBuilder());
$source = $tfdCadenaOrigen->build(XmlNodeUtils::nodeToXmlString($tfd), $tfd['Version']);
$signature = strval(base64_decode($tfd['SelloSAT']));
$verification = $certificado->verify($source, $signature, OPENSSL_ALGO_SHA256);
if (! $verification) {
$assert->setStatus(
Status::error(),
'La verificación del timbrado fue negativa,'
. ' posiblemente el CFDI fue modificado después de general el sello'
);
return;
}
$assert->setStatus(Status::ok());
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Contracts/DiscoverableCreateInterface.php | src/CfdiUtils/Validate/Contracts/DiscoverableCreateInterface.php | <?php
namespace CfdiUtils\Validate\Contracts;
interface DiscoverableCreateInterface
{
public static function createDiscovered(): ValidatorInterface;
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Contracts/ValidatorInterface.php | src/CfdiUtils/Validate/Contracts/ValidatorInterface.php | <?php
namespace CfdiUtils\Validate\Contracts;
use CfdiUtils\Nodes\NodeInterface;
use CfdiUtils\Validate\Asserts;
interface ValidatorInterface
{
public function validate(NodeInterface $comprobante, Asserts $asserts): void;
public function canValidateCfdiVersion(string $version): bool;
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Contracts/RequireXsltBuilderInterface.php | src/CfdiUtils/Validate/Contracts/RequireXsltBuilderInterface.php | <?php
namespace CfdiUtils\Validate\Contracts;
use CfdiUtils\CadenaOrigen\XsltBuilderPropertyInterface;
interface RequireXsltBuilderInterface extends XsltBuilderPropertyInterface
{
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Contracts/RequireXmlResolverInterface.php | src/CfdiUtils/Validate/Contracts/RequireXmlResolverInterface.php | <?php
namespace CfdiUtils\Validate\Contracts;
use CfdiUtils\XmlResolver\XmlResolverPropertyInterface;
interface RequireXmlResolverInterface extends XmlResolverPropertyInterface
{
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Contracts/RequireXmlStringInterface.php | src/CfdiUtils/Validate/Contracts/RequireXmlStringInterface.php | <?php
namespace CfdiUtils\Validate\Contracts;
interface RequireXmlStringInterface
{
public function setXmlString(string $xmlString): void;
public function getXmlString(): string;
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Cfdi40/Abstracts/AbstractVersion40.php | src/CfdiUtils/Validate/Cfdi40/Abstracts/AbstractVersion40.php | <?php
namespace CfdiUtils\Validate\Cfdi40\Abstracts;
use CfdiUtils\Validate\Contracts\ValidatorInterface;
abstract class AbstractVersion40 implements ValidatorInterface
{
public function canValidateCfdiVersion(string $version): bool
{
return '4.0' === $version;
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Cfdi40/Abstracts/AbstractDiscoverableVersion40.php | src/CfdiUtils/Validate/Cfdi40/Abstracts/AbstractDiscoverableVersion40.php | <?php
namespace CfdiUtils\Validate\Cfdi40\Abstracts;
use CfdiUtils\Validate\Contracts\DiscoverableCreateInterface;
use CfdiUtils\Validate\Contracts\ValidatorInterface;
abstract class AbstractDiscoverableVersion40 extends AbstractVersion40 implements DiscoverableCreateInterface
{
final public function __construct()
{
}
public static function createDiscovered(): ValidatorInterface
{
return new static();
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Cfdi40/Xml/XmlDefinition.php | src/CfdiUtils/Validate/Cfdi40/Xml/XmlDefinition.php | <?php
namespace CfdiUtils\Validate\Cfdi40\Xml;
use CfdiUtils\Nodes\NodeInterface;
use CfdiUtils\Validate\Asserts;
use CfdiUtils\Validate\Cfdi40\Abstracts\AbstractDiscoverableVersion40;
use CfdiUtils\Validate\Status;
/**
* XmlDefinition
*
* Valida que:
* - XML01: El XML implementa el namespace %s con el prefijo cfdi
* - XML02: El nodo principal se llama cfdi:Comprobante
* - XML03: La versión es 4.0
*/
final class XmlDefinition extends AbstractDiscoverableVersion40
{
private const CFDI40_NAMESPACE = 'http://www.sat.gob.mx/cfd/4';
public function validate(NodeInterface $comprobante, Asserts $asserts): void
{
$asserts->put(
'XML01',
sprintf('El XML implementa el namespace %s con el prefijo cfdi', self::CFDI40_NAMESPACE),
Status::when(self::CFDI40_NAMESPACE === $comprobante['xmlns:cfdi']),
sprintf('Valor de xmlns:cfdi: %s', $comprobante['xmlns:cfdi'])
);
$asserts->put(
'XML02',
'El nodo principal se llama cfdi:Comprobante',
Status::when('cfdi:Comprobante' === $comprobante->name()),
sprintf('Nombre: %s', $comprobante->name())
);
$asserts->put(
'XML03',
'La versión es 4.0',
Status::when('4.0' === $comprobante['Version']),
sprintf('Versión: %s', $comprobante['Version'])
);
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Cfdi40/Standard/TimbreFiscalDigitalVersion.php | src/CfdiUtils/Validate/Cfdi40/Standard/TimbreFiscalDigitalVersion.php | <?php
namespace CfdiUtils\Validate\Cfdi40\Standard;
use CfdiUtils\Validate\Cfdi40\Abstracts\AbstractDiscoverableVersion40;
use CfdiUtils\Validate\Common\TimbreFiscalDigitalVersionValidatorTrait;
/**
* TimbreFiscalDigitalVersion
*
* Valida que:
* - TFDVERSION01: Si existe el complemento timbre fiscal digital, entonces su versión debe ser 1.1
*/
class TimbreFiscalDigitalVersion extends AbstractDiscoverableVersion40
{
use TimbreFiscalDigitalVersionValidatorTrait;
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Cfdi40/Standard/SelloDigitalCertificado.php | src/CfdiUtils/Validate/Cfdi40/Standard/SelloDigitalCertificado.php | <?php
namespace CfdiUtils\Validate\Cfdi40\Standard;
use CfdiUtils\Validate\Cfdi40\Abstracts\AbstractDiscoverableVersion40;
use CfdiUtils\Validate\Common\SelloDigitalCertificadoValidatorTrait;
use CfdiUtils\Validate\Contracts\RequireXmlResolverInterface;
use CfdiUtils\Validate\Contracts\RequireXmlStringInterface;
use CfdiUtils\Validate\Contracts\RequireXsltBuilderInterface;
use CfdiUtils\Validate\Status;
/**
* SelloDigitalCertificado
*
* Valida que:
* - SELLO01: Se puede obtener el certificado del comprobante
* - SELLO02: El número de certificado del comprobante igual al encontrado en el certificado
* - SELLO03: El RFC del comprobante igual al encontrado en el certificado
* - SELLO04: El nombre del emisor del comprobante es igual al encontrado en el certificado
* - SELLO05: La fecha del documento es mayor o igual a la fecha de inicio de vigencia del certificado
* - SELLO06: La fecha del documento menor o igual a la fecha de fin de vigencia del certificado
* - SELLO07: El sello del comprobante está en base 64
* - SELLO08: El sello del comprobante coincide con el certificado y la cadena de origen generada
*/
class SelloDigitalCertificado extends AbstractDiscoverableVersion40 implements
RequireXmlStringInterface,
RequireXmlResolverInterface,
RequireXsltBuilderInterface
{
use SelloDigitalCertificadoValidatorTrait;
protected function validateNombre(string $emisorNombre, string $rfc): void
{
if ('' === $emisorNombre) {
$this->asserts->putStatus('SELLO04', Status::error(), 'Nombre del emisor vacío');
return;
}
// Remove régimen de capital from name when is "Persona Moral" only.
$removeSuffixFromName = 12 === mb_strlen($rfc);
$this->asserts->putStatus(
'SELLO04',
Status::when($this->certificado->getName($removeSuffixFromName) === $emisorNombre),
sprintf('Nombre certificado: %s, Nombre comprobante: %s.', $this->certificado->getName(), $emisorNombre)
);
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Cfdi40/Standard/TimbreFiscalDigitalSello.php | src/CfdiUtils/Validate/Cfdi40/Standard/TimbreFiscalDigitalSello.php | <?php
namespace CfdiUtils\Validate\Cfdi40\Standard;
use CfdiUtils\Validate\Cfdi40\Abstracts\AbstractDiscoverableVersion40;
use CfdiUtils\Validate\Common\TimbreFiscalDigitalSelloValidatorTrait;
use CfdiUtils\Validate\Contracts\RequireXmlResolverInterface;
use CfdiUtils\Validate\Contracts\RequireXsltBuilderInterface;
/**
* TimbreFiscalDigitalSello
*
* Valida que:
* - TFDSELLO01: El Sello SAT del Timbre Fiscal Digital corresponde al certificado SAT
*/
class TimbreFiscalDigitalSello extends AbstractDiscoverableVersion40 implements
RequireXmlResolverInterface,
RequireXsltBuilderInterface
{
use TimbreFiscalDigitalSelloValidatorTrait;
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Cfdi33/Abstracts/AbstractRecepcionPagos10.php | src/CfdiUtils/Validate/Cfdi33/Abstracts/AbstractRecepcionPagos10.php | <?php
namespace CfdiUtils\Validate\Cfdi33\Abstracts;
use CfdiUtils\Nodes\NodeInterface;
use CfdiUtils\Validate\Asserts;
use CfdiUtils\Validate\Contracts\DiscoverableCreateInterface;
use CfdiUtils\Validate\Contracts\ValidatorInterface;
abstract class AbstractRecepcionPagos10 extends AbstractVersion33 implements DiscoverableCreateInterface
{
final public function __construct()
{
}
abstract public function validateRecepcionPagos(NodeInterface $comprobante, Asserts $asserts);
public function validate(NodeInterface $comprobante, Asserts $asserts): void
{
// do not run anything if not found
$pagos10 = $comprobante->searchNode('cfdi:Complemento', 'pago10:Pagos');
if (
'3.3' !== $comprobante['Version']
|| 'P' !== $comprobante['TipoDeComprobante']
|| null === $pagos10
|| '1.0' !== $pagos10['Version']
) {
return;
}
$this->validateRecepcionPagos($comprobante, $asserts);
}
public static function createDiscovered(): ValidatorInterface
{
return new static();
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Cfdi33/Abstracts/AbstractVersion33.php | src/CfdiUtils/Validate/Cfdi33/Abstracts/AbstractVersion33.php | <?php
namespace CfdiUtils\Validate\Cfdi33\Abstracts;
use CfdiUtils\Validate\Contracts\ValidatorInterface;
abstract class AbstractVersion33 implements ValidatorInterface
{
public function canValidateCfdiVersion(string $version): bool
{
return '3.3' === $version;
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Cfdi33/Abstracts/AbstractDiscoverableVersion33.php | src/CfdiUtils/Validate/Cfdi33/Abstracts/AbstractDiscoverableVersion33.php | <?php
namespace CfdiUtils\Validate\Cfdi33\Abstracts;
use CfdiUtils\Validate\Contracts\DiscoverableCreateInterface;
use CfdiUtils\Validate\Contracts\ValidatorInterface;
abstract class AbstractDiscoverableVersion33 extends AbstractVersion33 implements DiscoverableCreateInterface
{
final public function __construct()
{
}
public static function createDiscovered(): ValidatorInterface
{
return new static();
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Cfdi33/Utils/AssertFechaFormat.php | src/CfdiUtils/Validate/Cfdi33/Utils/AssertFechaFormat.php | <?php
namespace CfdiUtils\Validate\Cfdi33\Utils;
use CfdiUtils\Utils\Format;
use CfdiUtils\Validate\Asserts;
use CfdiUtils\Validate\Status;
class AssertFechaFormat
{
public static function assertFormat(Asserts $asserts, string $code, string $label, string $text): bool
{
$hasFormat = static::hasFormat($text);
$asserts->put(
$code,
sprintf('La fecha %s cumple con el formato', $label),
Status::when($hasFormat),
sprintf('Contenido del campo: "%s"', $text)
);
return $hasFormat;
}
public static function hasFormat(string $format): bool
{
if ('' === $format) {
return false;
}
$value = (int) strtotime($format);
$expecteFormat = Format::datetime($value);
return $expecteFormat === $format;
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Cfdi33/Standard/EmisorRfc.php | src/CfdiUtils/Validate/Cfdi33/Standard/EmisorRfc.php | <?php
namespace CfdiUtils\Validate\Cfdi33\Standard;
use CfdiUtils\Nodes\NodeInterface;
use CfdiUtils\Utils\Rfc;
use CfdiUtils\Validate\Asserts;
use CfdiUtils\Validate\Cfdi33\Abstracts\AbstractDiscoverableVersion33;
use CfdiUtils\Validate\Status;
/**
* EmisorRfc
*
* Valida que:
* - EMISORRFC01: El RFC del emisor del comprobante debe ser válido y diferente de XAXX010101000 y XEXX010101000
*/
class EmisorRfc extends AbstractDiscoverableVersion33
{
public function validate(NodeInterface $comprobante, Asserts $asserts): void
{
$assert = $asserts->put(
'EMISORRFC01',
'El RFC del emisor del comprobante debe ser válido y diferente de XAXX010101000 y XEXX010101000'
);
$emisorRfc = $comprobante->searchAttribute('cfdi:Emisor', 'Rfc');
try {
Rfc::checkIsValid($emisorRfc, Rfc::DISALLOW_GENERIC | Rfc::DISALLOW_FOREIGN);
} catch (\Exception $exception) {
$assert->setStatus(
Status::error(),
sprintf('Rfc: "%s". %s', $emisorRfc, $exception->getMessage())
);
return;
}
$assert->setStatus(Status::ok());
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Cfdi33/Standard/ComprobanteFormaPago.php | src/CfdiUtils/Validate/Cfdi33/Standard/ComprobanteFormaPago.php | <?php
namespace CfdiUtils\Validate\Cfdi33\Standard;
use CfdiUtils\Nodes\NodeInterface;
use CfdiUtils\Validate\Asserts;
use CfdiUtils\Validate\Cfdi33\Abstracts\AbstractDiscoverableVersion33;
use CfdiUtils\Validate\Status;
/**
* ComprobanteFormaPago
*
* Valida que:
* - FORMAPAGO01: El campo forma de pago no debe existir cuando existe el complemento para recepción de pagos
* (CFDI33103)
*/
class ComprobanteFormaPago extends AbstractDiscoverableVersion33
{
public function validate(NodeInterface $comprobante, Asserts $asserts): void
{
$assert = $asserts->put(
'FORMAPAGO01',
'El campo forma de pago no debe existir cuando existe el complemento para recepción de pagos (CFDI33103)',
Status::none()
);
$existsComplementoPagos = (null !== $comprobante->searchNode('cfdi:Complemento', 'pago10:Pagos'));
if ($existsComplementoPagos) {
$existsFormaPago = $comprobante->exists('FormaPago');
$assert->setStatus(Status::when(! $existsFormaPago));
}
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Cfdi33/Standard/TimbreFiscalDigitalVersion.php | src/CfdiUtils/Validate/Cfdi33/Standard/TimbreFiscalDigitalVersion.php | <?php
namespace CfdiUtils\Validate\Cfdi33\Standard;
use CfdiUtils\Validate\Cfdi33\Abstracts\AbstractDiscoverableVersion33;
use CfdiUtils\Validate\Common\TimbreFiscalDigitalVersionValidatorTrait;
/**
* TimbreFiscalDigitalVersion
*
* Valida que:
* - TFDVERSION01: Si existe el complemento timbre fiscal digital, entonces su versión debe ser 1.1
*/
class TimbreFiscalDigitalVersion extends AbstractDiscoverableVersion33
{
use TimbreFiscalDigitalVersionValidatorTrait;
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Cfdi33/Standard/ComprobanteImpuestos.php | src/CfdiUtils/Validate/Cfdi33/Standard/ComprobanteImpuestos.php | <?php
namespace CfdiUtils\Validate\Cfdi33\Standard;
use CfdiUtils\Nodes\NodeInterface;
use CfdiUtils\Validate\Asserts;
use CfdiUtils\Validate\Cfdi33\Abstracts\AbstractDiscoverableVersion33;
use CfdiUtils\Validate\Status;
/**
* ConceptoImpuestos
*
* Valida que:
* - COMPIMPUESTOSC01: Si existe el nodo impuestos entonces debe incluir el total de traslados
* y/o el total de retenciones
* - COMPIMPUESTOSC02: Si existe al menos un traslado entonces debe existir el total de traslados
* - COMPIMPUESTOSC03: Si existe al menos una retención entonces debe existir el total de retenciones
*/
class ComprobanteImpuestos extends AbstractDiscoverableVersion33
{
private function registerAsserts(Asserts $asserts): void
{
$assertDescriptions = [
'COMPIMPUESTOSC01' => 'Si existe el nodo impuestos entonces debe incluir el total de traslados y/o'
. ' el total de retenciones',
'COMPIMPUESTOSC02' => 'Si existe al menos un traslado entonces debe existir el total de traslados',
'COMPIMPUESTOSC03' => 'Si existe al menos una retención entonces debe existir el total de retenciones',
];
foreach ($assertDescriptions as $code => $title) {
$asserts->put($code, $title);
}
}
public function validate(NodeInterface $comprobante, Asserts $asserts): void
{
$this->registerAsserts($asserts);
$nodeImpuestos = $comprobante->searchNode('cfdi:Impuestos');
if (null === $nodeImpuestos) {
return;
}
$existsTotalTrasladados = $nodeImpuestos->exists('TotalImpuestosTrasladados');
$existsTotalRetenidos = $nodeImpuestos->exists('TotalImpuestosRetenidos');
$asserts->putStatus(
'COMPIMPUESTOSC01',
Status::when($existsTotalTrasladados || $existsTotalRetenidos)
);
$hasTraslados = (null !== $nodeImpuestos->searchNode('cfdi:Traslados', 'cfdi:Traslado'));
$asserts->putStatus(
'COMPIMPUESTOSC02',
Status::when(! ($hasTraslados && ! $existsTotalTrasladados))
);
$hasRetenciones = (null !== $nodeImpuestos->searchNode('cfdi:Retenciones', 'cfdi:Retencion'));
$asserts->putStatus(
'COMPIMPUESTOSC03',
Status::when(! ($hasRetenciones && ! $existsTotalRetenidos))
);
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Cfdi33/Standard/ReceptorRfc.php | src/CfdiUtils/Validate/Cfdi33/Standard/ReceptorRfc.php | <?php
namespace CfdiUtils\Validate\Cfdi33\Standard;
use CfdiUtils\Nodes\NodeInterface;
use CfdiUtils\Utils\Rfc;
use CfdiUtils\Validate\Asserts;
use CfdiUtils\Validate\Cfdi33\Abstracts\AbstractDiscoverableVersion33;
use CfdiUtils\Validate\Status;
/**
* ReceptorRfc
*
* Valida que:
* - RECRFC01: El RFC del receptor del comprobante debe ser válido
*/
class ReceptorRfc extends AbstractDiscoverableVersion33
{
public function validate(NodeInterface $comprobante, Asserts $asserts): void
{
$assert = $asserts->put('RECRFC01', 'El RFC del receptor del comprobante debe ser válido');
$receptorRfc = $comprobante->searchAttribute('cfdi:Receptor', 'Rfc');
try {
Rfc::checkIsValid($receptorRfc);
} catch (\Exception $exception) {
$assert->setStatus(
Status::error(),
sprintf('Rfc: "%s". %s', $receptorRfc, $exception->getMessage())
);
return;
}
$assert->setStatus(Status::ok());
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Cfdi33/Standard/ComprobanteTipoCambio.php | src/CfdiUtils/Validate/Cfdi33/Standard/ComprobanteTipoCambio.php | <?php
namespace CfdiUtils\Validate\Cfdi33\Standard;
use CfdiUtils\Nodes\NodeInterface;
use CfdiUtils\Validate\Asserts;
use CfdiUtils\Validate\Cfdi33\Abstracts\AbstractDiscoverableVersion33;
use CfdiUtils\Validate\Status;
/**
* ComprobanteTipoCambio
*
* Valida que:
* - TIPOCAMBIO01: La moneda exista y no tenga un valor vacío
* - TIPOCAMBIO02: Si la moneda es "MXN", entonces el tipo de cambio debe tener el valor "1"
* o no debe existir (CFDI33113)
* - TIPOCAMBIO03: Si la moneda es "XXX", entonces el tipo de cambio no debe existir (CFDI33115)
* - TIPOCAMBIO04: Si la moneda no es "MXN" ni "XXX", entonces el tipo de cambio entonces
* el tipo de cambio debe seguir el patrón [0-9]{1,18}(.[0-9]{1,6})? (CFDI33114, CFDI33117)
*/
class ComprobanteTipoCambio extends AbstractDiscoverableVersion33
{
private function registerAsserts(Asserts $asserts): void
{
$assertDescriptions = [
'TIPOCAMBIO01' => 'La moneda exista y no tenga un valor vacío',
'TIPOCAMBIO02' => 'Si la moneda es "MXN", entonces el tipo de cambio debe tener el valor "1"'
. ' o no debe existir (CFDI33113)',
'TIPOCAMBIO03' => 'Si la moneda es "XXX", entonces el tipo de cambio no debe existir (CFDI33115)',
'TIPOCAMBIO04' => 'Si la moneda no es "MXN" ni "XXX", entonces el tipo de cambio'
. ' debe seguir el patrón [0-9]{1,18}(.[0-9]{1,6}?) (CFDI33114, CFDI33117)',
];
foreach ($assertDescriptions as $code => $title) {
$asserts->put($code, $title);
}
}
public function validate(NodeInterface $comprobante, Asserts $asserts): void
{
$this->registerAsserts($asserts);
$existsTipoCambio = $comprobante->exists('TipoCambio');
$tipoCambio = $comprobante['TipoCambio'];
$moneda = $comprobante['Moneda'];
$asserts->putStatus('TIPOCAMBIO01', Status::when('' !== $moneda));
if ('' === $moneda) {
return;
}
if ('MXN' === $moneda) {
$asserts->putStatus(
'TIPOCAMBIO02',
Status::when(! $existsTipoCambio || abs(floatval($tipoCambio) - 1) < 0.0000001)
);
}
if ('XXX' === $moneda) {
$asserts->putStatus('TIPOCAMBIO03', Status::when(! $existsTipoCambio));
}
if ('MXN' !== $moneda && 'XXX' !== $moneda) {
$pattern = '/^\d{1,18}(\.\d{1,6})?$/';
$asserts->putStatus('TIPOCAMBIO04', Status::when((bool) preg_match($pattern, $tipoCambio)));
}
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Cfdi33/Standard/ConceptoImpuestos.php | src/CfdiUtils/Validate/Cfdi33/Standard/ConceptoImpuestos.php | <?php
namespace CfdiUtils\Validate\Cfdi33\Standard;
use CfdiUtils\Nodes\NodeInterface;
use CfdiUtils\Validate\Asserts;
use CfdiUtils\Validate\Cfdi33\Abstracts\AbstractDiscoverableVersion33;
use CfdiUtils\Validate\Status;
/**
* ConceptoImpuestos
*
* Valida que:
* - CONCEPIMPC01: El nodo impuestos de un concepto debe incluir traslados y/o retenciones (CFDI33152)
* - CONCEPIMPC02: Los traslados de los impuestos de un concepto deben tener una base y ser mayor a cero (CFDI33154)
* - CONCEPIMPC03: No se debe registrar la tasa o cuota ni el importe cuando
* el tipo de factor de traslado es exento (CFDI33157)
* - CONCEPIMPC04: Se debe registrar la tasa o cuota y el importe cuando
* el tipo de factor de traslado es tasa o cuota (CFDI33158)
* - CONCEPIMPC05: Las retenciones de los impuestos de un concepto deben tener una base y ser mayor a cero (CFDI33154)
* - CONCEPIMPC06: Las retenciones de los impuestos de un concepto deben tener
* un tipo de factor diferente de exento (CFDI33166)
*/
class ConceptoImpuestos extends AbstractDiscoverableVersion33
{
private function registerAsserts(Asserts $asserts): void
{
$assertDescriptions = [
'CONCEPIMPC01' => 'El nodo impuestos de un concepto debe incluir traslados y/o retenciones (CFDI33152)',
'CONCEPIMPC02' => 'Los traslados de los impuestos de un concepto deben tener una base y ser mayor a cero'
. ' (CFDI33154)',
'CONCEPIMPC03' => 'No se debe registrar la tasa o cuota ni el importe cuando el tipo de factor de traslado'
. ' es exento (CFDI33157)',
'CONCEPIMPC04' => 'Se debe registrar la tasa o cuota y el importe cuando el tipo de factor de traslado'
. ' es tasa o cuota (CFDI33158)',
'CONCEPIMPC05' => 'Las retenciones de los impuestos de un concepto deben tener una base y ser mayor a cero'
. '(CFDI33154)',
'CONCEPIMPC06' => ' Las retenciones de los impuestos de un concepto deben tener un tipo de factor diferente'
. ' de exento (CFDI33166)',
];
foreach ($assertDescriptions as $code => $title) {
$asserts->put($code, $title);
}
}
public function validate(NodeInterface $comprobante, Asserts $asserts): void
{
$this->registerAsserts($asserts);
$status01 = Status::ok();
$status02 = Status::ok();
$status03 = Status::ok();
$status04 = Status::ok();
$status05 = Status::ok();
$status06 = Status::ok();
foreach ($comprobante->searchNodes('cfdi:Conceptos', 'cfdi:Concepto') as $i => $concepto) {
if ($status01->isOk() && ! $this->conceptoImpuestosHasTrasladosOrRetenciones($concepto)) {
$status01 = Status::error();
$asserts->get('CONCEPIMPC01')->setExplanation(sprintf('Concepto #%d', $i));
}
$traslados = $concepto->searchNodes('cfdi:Impuestos', 'cfdi:Traslados', 'cfdi:Traslado');
foreach ($traslados as $k => $traslado) {
if ($status02->isOk() && ! $this->impuestoHasBaseGreaterThanZero($traslado)) {
$status02 = Status::error();
$asserts->get('CONCEPIMPC02')->setExplanation(sprintf('Concepto #%d, Traslado #%d', $i, $k));
}
if ($status03->isOk() && ! $this->trasladoHasTipoFactorExento($traslado)) {
$status03 = Status::error();
$asserts->get('CONCEPIMPC03')->setExplanation(sprintf('Concepto #%d, Traslado #%d', $i, $k));
}
if ($status04->isOk() && ! $this->trasladoHasTipoFactorTasaOCuota($traslado)) {
$status04 = Status::error();
$asserts->get('CONCEPIMPC04')->setExplanation(sprintf('Concepto #%d, Traslado #%d', $i, $k));
}
}
$retenciones = $concepto->searchNodes('cfdi:Impuestos', 'cfdi:Retenciones', 'cfdi:Retencion');
foreach ($retenciones as $k => $retencion) {
if ($status05->isOk() && ! $this->impuestoHasBaseGreaterThanZero($retencion)) {
$status05 = Status::error();
$asserts->get('CONCEPIMPC05')->setExplanation(sprintf('Concepto #%d, Retención #%d', $i, $k));
}
if ($status06->isOk() && 'Exento' === $retencion['TipoFactor']) {
$status06 = Status::error();
$asserts->get('CONCEPIMPC06')->setExplanation(sprintf('Concepto #%d, Retención #%d', $i, $k));
}
}
}
$asserts->putStatus('CONCEPIMPC01', $status01);
$asserts->putStatus('CONCEPIMPC02', $status02);
$asserts->putStatus('CONCEPIMPC03', $status03);
$asserts->putStatus('CONCEPIMPC04', $status04);
$asserts->putStatus('CONCEPIMPC05', $status05);
$asserts->putStatus('CONCEPIMPC06', $status06);
}
private function conceptoImpuestosHasTrasladosOrRetenciones(NodeInterface $concepto): bool
{
$impuestos = $concepto->searchNode('cfdi:Impuestos');
if (null === $impuestos) {
return true;
}
return $impuestos->searchNodes('cfdi:Traslados', 'cfdi:Traslado')->count()
|| $impuestos->searchNodes('cfdi:Retenciones', 'cfdi:Retencion')->count();
}
private function impuestoHasBaseGreaterThanZero(NodeInterface $impuesto): bool
{
if (! $impuesto->exists('Base')) {
return false;
}
if (! is_numeric($impuesto['Base'])) {
return false;
}
return (float) $impuesto['Base'] >= 0.000001;
}
private function trasladoHasTipoFactorExento(NodeInterface $traslado): bool
{
if ('Exento' === $traslado['TipoFactor']) {
if ($traslado->exists('TasaOCuota')) {
return false;
}
if ($traslado->exists('Importe')) {
return false;
}
}
return true;
}
private function trasladoHasTipoFactorTasaOCuota(NodeInterface $traslado): bool
{
if ('Tasa' === $traslado['TipoFactor'] || 'Cuota' === $traslado['TipoFactor']) {
if ('' === $traslado['TasaOCuota']) {
return false;
}
if ('' === $traslado['Importe']) {
return false;
}
}
return true;
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Cfdi33/Standard/ComprobanteTotal.php | src/CfdiUtils/Validate/Cfdi33/Standard/ComprobanteTotal.php | <?php
namespace CfdiUtils\Validate\Cfdi33\Standard;
use CfdiUtils\Nodes\NodeInterface;
use CfdiUtils\Validate\Asserts;
use CfdiUtils\Validate\Cfdi33\Abstracts\AbstractDiscoverableVersion33;
use CfdiUtils\Validate\Status;
/**
* ComprobanteTotal
*
* Valida que:
* - TOTAL01: El atributo Total existe, no está vacío y cumple con el patrón [0-9]+(.[0-9]+)?
*/
class ComprobanteTotal extends AbstractDiscoverableVersion33
{
public function validate(NodeInterface $comprobante, Asserts $asserts): void
{
$pattern = '/^\d+(\.\d+)?$/';
$asserts->put(
'TOTAL01',
'El atributo Total existe, no está vacío y cumple con el patrón [0-9]+(.[0-9]+)?',
Status::when('' !== $comprobante['Total'] && preg_match($pattern, $comprobante['Total']))
);
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Cfdi33/Standard/ComprobanteTipoDeComprobante.php | src/CfdiUtils/Validate/Cfdi33/Standard/ComprobanteTipoDeComprobante.php | <?php
namespace CfdiUtils\Validate\Cfdi33\Standard;
use CfdiUtils\Nodes\NodeInterface;
use CfdiUtils\Validate\Asserts;
use CfdiUtils\Validate\Cfdi33\Abstracts\AbstractDiscoverableVersion33;
use CfdiUtils\Validate\Status;
/**
* ComprobanteTipoDeComprobante
*
* Valida que:
* - TIPOCOMP01: Si el tipo de comprobante es T, P ó N, entonces no debe existir las condiciones de pago
* - TIPOCOMP02: Si el tipo de comprobante es T, P ó N, entonces no debe existir la definición de impuestos (CFDI33179)
* - TIPOCOMP03: Si el tipo de comprobante es T ó P, entonces no debe existir la forma de pago
* - TIPOCOMP04: Si el tipo de comprobante es T ó P, entonces no debe existir el método de pago (CFDI33123)
* - TIPOCOMP05: Si el tipo de comprobante es T ó P, entonces no debe existir el descuento del comprobante (CFDI33110)
* - TIPOCOMP06: Si el tipo de comprobante es T ó P, entonces no debe existir el descuento de los conceptos (CFDI33179)
* - TIPOCOMP07: Si el tipo de comprobante es T ó P, entonces el subtotal debe ser cero (CFDI33108)
* - TIPOCOMP08: Si el tipo de comprobante es T ó P, entonces el total debe ser cero
* - TIPOCOMP09: Si el tipo de comprobante es I, E ó N, entonces el valor unitario de todos los conceptos
* debe ser mayor que cero
* - TIPOCOMP010: Si el tipo de comprobante es N, entonces la moneda debe ser MXN
*/
class ComprobanteTipoDeComprobante extends AbstractDiscoverableVersion33
{
private function registerAsserts(Asserts $asserts): void
{
$assertsDescriptions = [
'TIPOCOMP01' => 'Si el tipo de comprobante es T, P ó N,'
. ' entonces no debe existir las condiciones de pago',
'TIPOCOMP02' => 'Si el tipo de comprobante es T, P ó N,'
. ' entonces no debe existir la definición de impuestos (CFDI33179)',
'TIPOCOMP03' => 'Si el tipo de comprobante es T ó P, entonces no debe existir la forma de pago',
'TIPOCOMP04' => 'Si el tipo de comprobante es T ó P,'
. ' entonces no debe existir el método de pago (CFDI33123)',
'TIPOCOMP05' => 'Si el tipo de comprobante es T ó P,'
. ' entonces no debe existir el descuento del comprobante (CFDI33110)',
'TIPOCOMP06' => 'Si el tipo de comprobante es T ó P,'
. ' entonces no debe existir el descuento de los conceptos (CFDI33179)',
'TIPOCOMP07' => 'Si el tipo de comprobante es T ó P, entonces el subtotal debe ser cero (CFDI33108)',
'TIPOCOMP08' => 'Si el tipo de comprobante es T ó P entonces el total debe ser cero',
'TIPOCOMP09' => 'Si el tipo de comprobante es I, E ó N,'
. ' entonces el valor unitario de todos los conceptos debe ser mayor que cero',
'TIPOCOMP10' => 'Si el tipo de comprobante es N entonces, la moneda debe ser MXN',
];
foreach ($assertsDescriptions as $code => $title) {
$asserts->put($code, $title);
}
}
public function validate(NodeInterface $comprobante, Asserts $asserts): void
{
$this->registerAsserts($asserts);
$tipoComprobante = $comprobante['TipoDeComprobante'];
if ('T' === $tipoComprobante || 'P' === $tipoComprobante || 'N' === $tipoComprobante) {
$asserts->putStatus(
'TIPOCOMP01',
Status::when(! $comprobante->exists('CondicionesDePago'))
);
$asserts->putStatus(
'TIPOCOMP02',
Status::when(null === $comprobante->searchNode('cfdi:Impuestos'))
);
}
if ('T' === $tipoComprobante || 'P' === $tipoComprobante) {
$asserts->putStatus(
'TIPOCOMP03',
Status::when(! $comprobante->exists('FormaPago'))
);
$asserts->putStatus(
'TIPOCOMP04',
Status::when(! $comprobante->exists('MetodoPago'))
);
$asserts->putStatus(
'TIPOCOMP05',
Status::when(! $comprobante->exists('Descuento'))
);
$asserts->putStatus(
'TIPOCOMP06',
Status::when($this->checkConceptosDoesNotHaveDescuento($comprobante))
);
$asserts->putStatus(
'TIPOCOMP07',
Status::when($this->isZero($comprobante['SubTotal']))
);
$asserts->putStatus(
'TIPOCOMP08',
Status::when($this->isZero($comprobante['Total']))
);
}
if ('I' === $tipoComprobante || 'E' === $tipoComprobante || 'N' === $tipoComprobante) {
$asserts->putStatus(
'TIPOCOMP09',
Status::when($this->checkConceptosValorUnitarioIsGreaterThanZero($comprobante))
);
}
if ('N' === $tipoComprobante) {
$asserts->putStatus(
'TIPOCOMP10',
Status::when('MXN' === $comprobante['Moneda'])
);
}
}
private function checkConceptosDoesNotHaveDescuento(NodeInterface $comprobante): bool
{
foreach ($comprobante->searchNodes('cfdi:Conceptos', 'cfdi:Concepto') as $concepto) {
if ($concepto->exists('Descuento')) {
return false;
}
}
return true;
}
private function checkConceptosValorUnitarioIsGreaterThanZero(NodeInterface $comprobante): bool
{
foreach ($comprobante->searchNodes('cfdi:Conceptos', 'cfdi:Concepto') as $concepto) {
if (! $this->isGreaterThanZero($concepto['ValorUnitario'])) {
return false;
}
}
return true;
}
private function isZero(string $value): bool
{
if ('' === $value || ! is_numeric($value)) {
return false;
}
return abs((float) $value) < 0.0000001;
}
private function isGreaterThanZero(string $value): bool
{
if ('' === $value || ! is_numeric($value)) {
return false;
}
return abs((float) $value) > 0.0000001;
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Cfdi33/Standard/ComprobanteDecimalesMoneda.php | src/CfdiUtils/Validate/Cfdi33/Standard/ComprobanteDecimalesMoneda.php | <?php
namespace CfdiUtils\Validate\Cfdi33\Standard;
use CfdiUtils\Nodes\NodeInterface;
use CfdiUtils\Utils\CurrencyDecimals;
use CfdiUtils\Validate\Assert;
use CfdiUtils\Validate\Asserts;
use CfdiUtils\Validate\Cfdi33\Abstracts\AbstractDiscoverableVersion33;
use CfdiUtils\Validate\Status;
/**
* ComprobanteDecimalesMoneda
*
* Valida que:
* - MONDEC01: El subtotal del comprobante no contiene más de los decimales de la moneda (CFDI33106)
* - MONDEC02: El descuento del comprobante no contiene más de los decimales de la moneda (CFDI33111)
* - MONDEC03: El total del comprobante no contiene más de los decimales de la moneda
* - MONDEC04: El total de impuestos trasladados no contiene más de los decimales de la moneda (CFDI33182)
* - MONDEC05: El total de impuestos retenidos no contiene más de los decimales de la moneda (CFDI33180)
*/
class ComprobanteDecimalesMoneda extends AbstractDiscoverableVersion33
{
private ?Asserts $asserts = null;
private ?CurrencyDecimals $currency = null;
private function registerAsserts(): void
{
$asserts = [
'MONDEC01' => 'El subtotal del comprobante no contiene más de los decimales de la moneda (CFDI33106)',
'MONDEC02' => 'El descuento del comprobante no contiene más de los decimales de la moneda (CFDI33111)',
'MONDEC03' => 'El total del comprobante no contiene más de los decimales de la moneda',
'MONDEC04' => 'El total de impuestos trasladados no contiene más de los decimales de la moneda (CFDI33182)',
'MONDEC05' => 'El total de impuestos retenidos no contiene más de los decimales de la moneda (CFDI33180)',
];
foreach ($asserts as $code => $title) {
$this->asserts->put($code, $title);
}
}
public function validate(NodeInterface $comprobante, Asserts $asserts): void
{
$this->asserts = $asserts;
$this->registerAsserts();
try {
$this->currency = CurrencyDecimals::newFromKnownCurrencies($comprobante['Moneda']);
} catch (\OutOfBoundsException $exception) {
$this->asserts->get('MONDEC01')->setExplanation($exception->getMessage());
return;
}
// SubTotal, Descuento, Total
$this->validateValue('MONDEC01', $comprobante, 'SubTotal', true);
$this->validateValue('MONDEC02', $comprobante, 'Descuento');
$this->validateValue('MONDEC03', $comprobante, 'Total', true);
$impuestos = $comprobante->searchNode('cfdi:Impuestos');
if (null !== $impuestos) {
$this->validateValue('MONDEC04', $impuestos, 'TotalImpuestosTrasladados');
$this->validateValue('MONDEC05', $impuestos, 'TotalImpuestosRetenidos');
}
}
private function validateValue(string $code, NodeInterface $node, string $attribute, bool $required = false): Assert
{
return $this->asserts->putStatus(
$code,
Status::when($this->checkValue($node, $attribute, $required)),
vsprintf('Valor: "%s", Moneda: "%s - %d decimales"', [
$node[$attribute],
$this->currency->currency(),
$this->currency->decimals(),
])
);
}
private function checkValue(NodeInterface $node, string $attribute, bool $required): bool
{
if ($required && ! $node->exists($attribute)) {
return false;
}
return $this->currency->doesNotExceedDecimals($node[$attribute]);
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Cfdi33/Standard/SumasConceptosComprobanteImpuestos.php | src/CfdiUtils/Validate/Cfdi33/Standard/SumasConceptosComprobanteImpuestos.php | <?php
namespace CfdiUtils\Validate\Cfdi33\Standard;
use CfdiUtils\Nodes\NodeInterface;
use CfdiUtils\SumasConceptos\SumasConceptos;
use CfdiUtils\Validate\Asserts;
use CfdiUtils\Validate\Cfdi33\Abstracts\AbstractDiscoverableVersion33;
use CfdiUtils\Validate\Status;
/**
* SumasConceptosComprobanteImpuestos
*
* Esta clase genera la suma de subtotal, descuento, total e impuestos a partir de las sumas de los conceptos.
* Con estas sumas valida contra los valores del comprobante, los valores de impuestos
* y la lista de impuestos trasladados y retenidos
*
* Valida que:
* - SUMAS01: La suma de los importes de conceptos es igual a el subtotal del comprobante
* - SUMAS02: La suma de los descuentos es igual a el descuento del comprobante
* - SUMAS03: El cálculo del total es igual a el total del comprobante
*
* - SUMAS04: El cálculo de impuestos trasladados es igual a el total de impuestos trasladados
* - SUMAS05: Todos los impuestos trasladados existen en el comprobante
* - SUMAS06: Todos los valores de los impuestos trasladados conciden con el comprobante
* - SUMAS07: No existen más nodos de impuestos trasladados en el comprobante de los que se han calculado
*
* - SUMAS08: El cálculo de impuestos retenidos es igual a el total de impuestos retenidos
* - SUMAS09: Todos los impuestos retenidos existen en el comprobante
* - SUMAS10: Todos los valores de los impuestos retenidos conciden con el comprobante
* - SUMAS11: No existen más nodos de impuestos trasladados en el comprobante de los que se han calculado
*
* - SUMAS12: El cálculo del descuento debe ser menor o igual al cálculo del subtotal
*
* - Adicionalmente, para SUMAS06 y SUMAS10 se generan: SUMASxx:yyy donde
* - xx puede ser 06 o 10
* - yyy es el consecutivo de la línea del impuesto
* - Se valida que El importe dek impuesto del Grupo X Impuesto X Tipo factor X Tasa o cuota X
* es igual a el importe del nodo
*/
class SumasConceptosComprobanteImpuestos extends AbstractDiscoverableVersion33
{
private ?NodeInterface $comprobante = null;
private ?Asserts $asserts = null;
private ?SumasConceptos $sumasConceptos = null;
private function registerAsserts(): void
{
$asserts = [
'SUMAS01' => 'La suma de los importes de conceptos es igual a el subtotal del comprobante',
'SUMAS02' => 'La suma de los descuentos es igual a el descuento del comprobante',
'SUMAS03' => 'El cálculo del total es igual a el total del comprobante',
'SUMAS04' => 'El cálculo de impuestos trasladados es igual a el total de impuestos trasladados',
'SUMAS05' => 'Todos los impuestos trasladados existen en el comprobante',
'SUMAS06' => 'Todos los valores de los impuestos trasladados conciden con el comprobante',
'SUMAS07' => 'No existen más nodos de impuestos trasladados en el comprobante de los que se han calculado',
'SUMAS08' => 'El cálculo de impuestos retenidos es igual a el total de impuestos retenidos',
'SUMAS09' => 'Todos los impuestos retenidos existen en el comprobante',
'SUMAS10' => 'Todos los valores de los impuestos retenidos conciden con el comprobante',
'SUMAS11' => 'No existen más nodos de impuestos trasladados en el comprobante de los que se han calculado',
'SUMAS12' => 'El cálculo del descuento debe ser menor o igual al cálculo del subtotal',
];
foreach ($asserts as $code => $title) {
$this->asserts->put($code, $title);
}
}
public function validate(NodeInterface $comprobante, Asserts $asserts): void
{
$this->asserts = $asserts;
$this->comprobante = $comprobante;
$this->registerAsserts();
$this->sumasConceptos = new SumasConceptos($comprobante);
$this->validateSubTotal();
$this->validateDescuento();
$this->validateTotal();
$this->validateImpuestosTrasladados();
$this->validateTrasladosMatch();
$this->validateImpuestosRetenidos();
$this->validateRetencionesMatch();
$this->validateDescuentoLessOrEqualThanSubTotal();
}
private function validateSubTotal(): void
{
$this->validateValues(
'SUMAS01',
'Calculado',
$this->sumasConceptos->getSubTotal(),
'Comprobante',
(float) $this->comprobante['SubTotal']
);
}
private function validateDescuento(): void
{
$this->validateValues(
'SUMAS02',
'Calculado',
$this->sumasConceptos->getDescuento(),
'Comprobante',
(float) $this->comprobante['Descuento']
);
}
private function validateDescuentoLessOrEqualThanSubTotal(): void
{
$subtotal = (float) $this->comprobante['SubTotal'];
$descuento = (float) $this->comprobante['Descuento'];
$this->asserts->putStatus(
'SUMAS12',
Status::when($subtotal >= $descuento),
vsprintf('SubTotal: %s, Descuento: %s', [$this->comprobante['SubTotal'], $this->comprobante['Descuento']])
);
}
private function validateTotal(): void
{
$this->validateValues(
'SUMAS03',
'Calculado',
$this->sumasConceptos->getTotal(),
'Comprobante',
(float) $this->comprobante['Total']
);
}
private function validateImpuestosTrasladados(): void
{
$this->validateValues(
'SUMAS04',
'Calculado',
$this->sumasConceptos->getImpuestosTrasladados(),
'Comprobante',
(float) $this->comprobante->searchAttribute('cfdi:Impuestos', 'TotalImpuestosTrasladados')
);
}
private function validateImpuestosRetenidos(): void
{
$this->validateValues(
'SUMAS08',
'Calculado',
$this->sumasConceptos->getImpuestosRetenidos(),
'Comprobante',
(float) $this->comprobante->searchAttribute('cfdi:Impuestos', 'TotalImpuestosRetenidos')
);
}
private function validateTrasladosMatch(): void
{
$this->validateImpuestosMatch(
5,
'traslado',
$this->sumasConceptos->getTraslados(),
['cfdi:Impuestos', 'cfdi:Traslados', 'cfdi:Traslado'],
['Impuesto', 'TipoFactor', 'TasaOCuota']
);
}
private function validateRetencionesMatch(): void
{
$this->validateImpuestosMatch(
9,
'retención',
$this->sumasConceptos->getRetenciones(),
['cfdi:Impuestos', 'cfdi:Retenciones', 'cfdi:Retencion'],
['Impuesto']
);
}
private function validateImpuestosMatch(
int $assertOffset,
string $type,
array $expectedItems,
array $impuestosPath,
array $impuestosKeys,
): void {
$extractedItems = [];
foreach ($this->comprobante->searchNodes(...$impuestosPath) as $extracted) {
$new = [];
foreach ($impuestosKeys as $impuestosKey) {
$new[$impuestosKey] = $extracted[$impuestosKey];
}
$new['Importe'] = $extracted['Importe'];
$new['Encontrado'] = false;
$newKey = SumasConceptos::impuestoKey(
$extracted['Impuesto'],
$extracted['TipoFactor'],
$extracted['TasaOCuota']
);
$extractedItems[$newKey] = $new;
}
// check that all elements are found and mark extracted item as found
$allExpectedAreFound = true;
$allValuesMatch = true;
$expectedOffset = 0;
foreach ($expectedItems as $expectedKey => $expectedItem) {
$expectedOffset = $expectedOffset + 1;
if (! array_key_exists($expectedKey, $extractedItems)) {
$allExpectedAreFound = false;
$extractedItem = ['Importe' => ''];
} else {
// set found flag
$extractedItems[$expectedKey]['Encontrado'] = true;
// check value match
$extractedItem = $extractedItems[$expectedKey];
}
$code = sprintf('SUMAS%02d:%03d', $assertOffset + 1, $expectedOffset);
$thisValueMatch = $this->validateImpuestoImporte($type, $code, $expectedItem, $extractedItem);
$allValuesMatch = $allValuesMatch && $thisValueMatch;
}
$extractedWithoutMatch = array_filter($extractedItems, fn (array $item): bool => ! $item['Encontrado']);
$this->asserts->putStatus(sprintf('SUMAS%02d', $assertOffset), Status::when($allExpectedAreFound));
$this->asserts->putStatus(sprintf('SUMAS%02d', $assertOffset + 1), Status::when($allValuesMatch));
$this->asserts->putStatus(
sprintf('SUMAS%02d', $assertOffset + 2), // SUMAS07
Status::when([] === $extractedWithoutMatch),
sprintf(
'No encontrados: %d impuestos. %s.',
count($extractedWithoutMatch),
implode('; ', array_map(
function (array $values): string {
unset($values['Encontrado']);
$text = [];
foreach ($values as $key => $value) {
$text[] = sprintf('%s: %s', $key, $value);
}
return implode(', ', $text);
},
$extractedWithoutMatch,
))
)
);
}
private function validateImpuestoImporte(string $type, string $code, array $expected, array $extracted): bool
{
$label = sprintf('Grupo %s Impuesto %s', $type, $expected['Impuesto']);
if (array_key_exists('TipoFactor', $expected)) {
$label .= sprintf(' Tipo factor %s', $expected['TipoFactor']);
}
if (array_key_exists('TasaOCuota', $expected)) {
$label .= sprintf(' Tasa o cuota %s', $expected['TasaOCuota']);
}
$this->asserts->put($code, sprintf('El importe del impuesto %s es igual a el importe del nodo', $label));
return $this->validateValues(
$code,
'Calculado',
(float) $expected['Importe'],
'Encontrado',
(float) $extracted['Importe']
);
}
private function validateValues(
string $code,
string $expectedLabel,
float $expectedValue,
string $compareLabel,
float $compareValue,
?Status $errorStatus = null,
): bool {
$condition = $this->compareImportesAreEqual($expectedValue, $compareValue);
$this->asserts->putStatus(
$code,
Status::when($condition, $errorStatus),
sprintf('%s: %s, %s: %s', $expectedLabel, $expectedValue, $compareLabel, $compareValue)
);
return $condition;
}
private function compareImportesAreEqual(float $first, float $second, ?float $delta = null): bool
{
if (null === $delta) {
$delta = 0.000001;
}
return abs($first - $second) <= $delta;
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Cfdi33/Standard/SelloDigitalCertificado.php | src/CfdiUtils/Validate/Cfdi33/Standard/SelloDigitalCertificado.php | <?php
namespace CfdiUtils\Validate\Cfdi33\Standard;
use CfdiUtils\Validate\Cfdi33\Abstracts\AbstractDiscoverableVersion33;
use CfdiUtils\Validate\Common\SelloDigitalCertificadoValidatorTrait;
use CfdiUtils\Validate\Contracts\RequireXmlResolverInterface;
use CfdiUtils\Validate\Contracts\RequireXmlStringInterface;
use CfdiUtils\Validate\Contracts\RequireXsltBuilderInterface;
use CfdiUtils\Validate\Status;
/**
* SelloDigitalCertificado
*
* Valida que:
* - SELLO01: Se puede obtener el certificado del comprobante
* - SELLO02: El número de certificado del comprobante igual al encontrado en el certificado
* - SELLO03: El RFC del comprobante igual al encontrado en el certificado
* - SELLO04: El nombre del emisor del comprobante es igual al encontrado en el certificado
* - SELLO05: La fecha del documento es mayor o igual a la fecha de inicio de vigencia del certificado
* - SELLO06: La fecha del documento menor o igual a la fecha de fin de vigencia del certificado
* - SELLO07: El sello del comprobante está en base 64
* - SELLO08: El sello del comprobante coincide con el certificado y la cadena de origen generada
*/
class SelloDigitalCertificado extends AbstractDiscoverableVersion33 implements
RequireXmlStringInterface,
RequireXmlResolverInterface,
RequireXsltBuilderInterface
{
use SelloDigitalCertificadoValidatorTrait;
protected function validateNombre(string $emisorNombre, string $rfc): void
{
if ('' === $emisorNombre) {
return; // name is optional
}
$this->asserts->putStatus(
'SELLO04',
Status::when($this->compareNames($this->certificado->getName(), $emisorNombre)),
sprintf('Nombre certificado: %s, Nombre comprobante: %s.', $this->certificado->getName(), $emisorNombre)
);
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Cfdi33/Standard/EmisorRegimenFiscal.php | src/CfdiUtils/Validate/Cfdi33/Standard/EmisorRegimenFiscal.php | <?php
namespace CfdiUtils\Validate\Cfdi33\Standard;
use CfdiUtils\Nodes\NodeInterface;
use CfdiUtils\Validate\Asserts;
use CfdiUtils\Validate\Cfdi33\Abstracts\AbstractDiscoverableVersion33;
use CfdiUtils\Validate\Status;
/**
* EmisorRegimenFiscal
*
* Valida que:
* - REGFIS01: El régimen fiscal contenga un valor apropiado según el tipo de RFC emisor (CFDI33130 y CFDI33131)
*
* Nota: No valida que el RFC sea válido, esa responsabilidad no es de este validador.
*/
class EmisorRegimenFiscal extends AbstractDiscoverableVersion33
{
public function validate(NodeInterface $comprobante, Asserts $asserts): void
{
$regimenFiscal = $comprobante->searchAttribute('cfdi:Emisor', 'RegimenFiscal');
$emisorRfc = $comprobante->searchAttribute('cfdi:Emisor', 'Rfc');
$length = mb_strlen($emisorRfc);
if (12 === $length) {
$validCodes = [
'601', '603', '609', '610', '620', '622', '623', '624', '626', '628',
];
} elseif (13 === $length) {
$validCodes = [
'605', '606', '607', '608', '610', '611', '612', '614', '615', '616', '621', '625', '626', '629', '630',
];
} else {
$validCodes = [];
}
$asserts->put(
'REGFIS01',
'El régimen fiscal contenga un valor apropiado según el tipo de RFC emisor (CFDI33130 y CFDI33131)',
Status::when(in_array($regimenFiscal, $validCodes, true)),
sprintf('Rfc: "%s", Regimen Fiscal: "%s"', $emisorRfc, $regimenFiscal)
);
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Cfdi33/Standard/ComprobanteDescuento.php | src/CfdiUtils/Validate/Cfdi33/Standard/ComprobanteDescuento.php | <?php
namespace CfdiUtils\Validate\Cfdi33\Standard;
use CfdiUtils\Nodes\NodeInterface;
use CfdiUtils\Validate\Asserts;
use CfdiUtils\Validate\Cfdi33\Abstracts\AbstractDiscoverableVersion33;
use CfdiUtils\Validate\Status;
/**
* ComprobanteDescuento
*
* Valida que:
* - DESCUENTO01: Si existe el atributo descuento, entonces debe ser menor o igual que el subtotal
* y mayor o igual que cero (CFDI33109)
*/
class ComprobanteDescuento extends AbstractDiscoverableVersion33
{
public function validate(NodeInterface $comprobante, Asserts $asserts): void
{
$asserts->put(
'DESCUENTO01',
'Si existe el atributo descuento,'
. ' entonces debe ser menor o igual que el subtotal y mayor o igual que cero (CFDI33109)'
);
if ($comprobante->exists('Descuento')) {
$descuento = (float) $comprobante['Descuento'];
$subtotal = (float) $comprobante['SubTotal'];
$asserts->putStatus(
'DESCUENTO01',
Status::when('' !== $comprobante['Descuento'] && $descuento >= 0 && $descuento <= $subtotal),
sprintf('Descuento: "%s", SubTotal: "%s"', $comprobante['Descuento'], $comprobante['SubTotal'])
);
}
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Cfdi33/Standard/TimbreFiscalDigitalSello.php | src/CfdiUtils/Validate/Cfdi33/Standard/TimbreFiscalDigitalSello.php | <?php
namespace CfdiUtils\Validate\Cfdi33\Standard;
use CfdiUtils\Validate\Cfdi33\Abstracts\AbstractDiscoverableVersion33;
use CfdiUtils\Validate\Common\TimbreFiscalDigitalSelloValidatorTrait;
use CfdiUtils\Validate\Contracts\RequireXmlResolverInterface;
use CfdiUtils\Validate\Contracts\RequireXsltBuilderInterface;
/**
* TimbreFiscalDigitalSello
*
* Valida que:
* - TFDSELLO01: El Sello SAT del Timbre Fiscal Digital corresponde al certificado SAT
*/
class TimbreFiscalDigitalSello extends AbstractDiscoverableVersion33 implements
RequireXmlResolverInterface,
RequireXsltBuilderInterface
{
use TimbreFiscalDigitalSelloValidatorTrait;
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Cfdi33/Standard/FechaComprobante.php | src/CfdiUtils/Validate/Cfdi33/Standard/FechaComprobante.php | <?php
namespace CfdiUtils\Validate\Cfdi33\Standard;
use CfdiUtils\Nodes\NodeInterface;
use CfdiUtils\Validate\Asserts;
use CfdiUtils\Validate\Cfdi33\Abstracts\AbstractDiscoverableVersion33;
use CfdiUtils\Validate\Cfdi33\Utils\AssertFechaFormat;
use CfdiUtils\Validate\Status;
/**
* FechaComprobante
*
* Valida que:
* - FECHA01: La fecha del comprobante cumple con el formato
* - FECHA02: La fecha existe en el comprobante y es mayor que 2017-07-01 y menor que el futuro
* - La fecha en el futuro se puede configurar a un valor determinado
* - La fecha en el futuro es por defecto el momento de validación más una tolerancia
* - La tolerancia puede ser configurada y es por defecto 300 segundos
*/
class FechaComprobante extends AbstractDiscoverableVersion33
{
private ?int $maximumDate = null;
/** @var int Tolerancia en segundos */
private int $tolerance = 300;
public function getMinimumDate(): int
{
return mktime(0, 0, 0, 7, 1, 2017);
}
public function getMaximumDate(): int
{
if (null === $this->maximumDate) {
return time() + $this->getTolerance();
}
return $this->maximumDate;
}
public function setMaximumDate(?int $maximumDate = null): void
{
$this->maximumDate = $maximumDate;
}
public function getTolerance(): int
{
return $this->tolerance;
}
public function setTolerance(int $tolerance): void
{
$this->tolerance = $tolerance;
}
public function validate(NodeInterface $comprobante, Asserts $asserts): void
{
$fechaSource = $comprobante['Fecha'];
$hasFormat = AssertFechaFormat::assertFormat($asserts, 'FECHA01', 'del comprobante', $fechaSource);
$assertBetween = $asserts->put(
'FECHA02',
'La fecha existe en el comprobante y es mayor que 2017-07-01 y menor que el futuro'
);
if (! $hasFormat) {
return;
}
$exists = $comprobante->exists('Fecha');
$testDate = ('' !== $fechaSource) ? strtotime($fechaSource) : 0;
$minimumDate = $this->getMinimumDate();
$maximumDate = $this->getMaximumDate();
$assertBetween->setStatus(
Status::when($testDate >= $minimumDate && $testDate <= $maximumDate),
vsprintf('Fecha: "%s" (%s), Máxima: %s', [
$fechaSource,
($exists) ? 'Existe' : 'No existe',
date('Y-m-d H:i:s', $maximumDate),
])
);
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Cfdi33/Standard/ConceptoDescuento.php | src/CfdiUtils/Validate/Cfdi33/Standard/ConceptoDescuento.php | <?php
namespace CfdiUtils\Validate\Cfdi33\Standard;
use CfdiUtils\Nodes\NodeInterface;
use CfdiUtils\Validate\Asserts;
use CfdiUtils\Validate\Cfdi33\Abstracts\AbstractDiscoverableVersion33;
use CfdiUtils\Validate\Status;
/**
* ConceptoDescuento
*
* Valida que:
* - CONCEPDESC01: Si existe el atributo descuento en el concepto,
* entonces debe ser menor o igual que el importe y mayor o igual que cero (CFDI33151)
*/
class ConceptoDescuento extends AbstractDiscoverableVersion33
{
public function validate(NodeInterface $comprobante, Asserts $asserts): void
{
$asserts->put(
'CONCEPDESC01',
'Si existe el atributo descuento en el concepto,'
. ' entonces debe ser menor o igual que el importe y mayor o igual que cero (CFDI33151)'
);
$checked = 0;
foreach ($comprobante->searchNodes('cfdi:Conceptos', 'cfdi:Concepto') as $i => $concepto) {
$checked = $checked + 1;
if ($this->conceptoHasInvalidDiscount($concepto)) {
$explanation = sprintf(
'Concepto #%d, Descuento: "%s", Importe: "%s"',
$i,
$concepto['Descuento'],
$concepto['Importe']
);
$asserts->putStatus('CONCEPDESC01', Status::error(), $explanation);
}
}
if ($checked > 0 && $asserts->get('CONCEPDESC01')->getStatus()->isNone()) {
$asserts->putStatus('CONCEPDESC01', Status::ok(), sprintf('Revisados %d conceptos', $checked));
}
}
public function conceptoHasInvalidDiscount(NodeInterface $concepto): bool
{
if (! $concepto->exists('Descuento')) {
return false;
}
$descuento = (float) $concepto['Descuento'];
$importe = (float) $concepto['Importe'];
return ! ($descuento >= 0 && $descuento <= $importe);
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Cfdi33/Standard/ReceptorResidenciaFiscal.php | src/CfdiUtils/Validate/Cfdi33/Standard/ReceptorResidenciaFiscal.php | <?php
namespace CfdiUtils\Validate\Cfdi33\Standard;
use CfdiUtils\Nodes\Node;
use CfdiUtils\Nodes\NodeInterface;
use CfdiUtils\Validate\Asserts;
use CfdiUtils\Validate\Cfdi33\Abstracts\AbstractDiscoverableVersion33;
use CfdiUtils\Validate\Status;
/**
* ReceptorResidenciaFiscal
*
* Valida que:
* - RESFISC01: Si el RFC no es XEXX010101000, entonces la residencia fiscal no debe existir (CFDI33134)
* - RESFISC02: Si el RFC sí es XEXX010101000 y existe el complemento de comercio exterior,
* entonces la residencia fiscal debe establecerse y no puede ser "MEX" (CFDI33135 y CFDI33136)
* - RESFISC03: Si el RFC sí es XEXX010101000 y se registró el número de registro de identificación fiscal,
* entonces la residencia fiscal debe establecerse y no puede ser "MEX" (CFDI33135 y CFDI33136)
*/
class ReceptorResidenciaFiscal extends AbstractDiscoverableVersion33
{
private function registerAsserts(Asserts $asserts): void
{
$assertDescriptions = [
'RESFISC01' => 'Si el RFC no es XEXX010101000, entonces la residencia fiscal no debe existir (CFDI33134)',
'RESFISC02' => 'Si el RFC sí es XEXX010101000 y existe el complemento de comercio exterior,'
. ' entonces la residencia fiscal debe establecerse y no puede ser "MEX" (CFDI33135 y CFDI33136)',
'RESFISC03' => 'Si el RFC sí es XEXX010101000 y se registró el número de registro de identificación fiscal,'
. ' entonces la residencia fiscal debe establecerse y no puede ser "MEX" (CFDI33135 y CFDI33136)',
];
foreach ($assertDescriptions as $code => $title) {
$asserts->put($code, $title);
}
}
public function validate(NodeInterface $comprobante, Asserts $asserts): void
{
$this->registerAsserts($asserts);
$receptor = $comprobante->searchNode('cfdi:Receptor');
if (null === $receptor) {
$receptor = new Node('cfdi:Receptor');
}
if ('XEXX010101000' !== $receptor['Rfc']) {
$asserts->putStatus(
'RESFISC01',
Status::when(! $receptor->exists('ResidenciaFiscal'))
);
return;
}
$existsComercioExterior = (null !== $comprobante->searchNode('cfdi:Complemento', 'cce11:ComercioExterior'));
$isValidResidenciaFiscal = '' !== $receptor['ResidenciaFiscal'] && 'MEX' !== $receptor['ResidenciaFiscal'];
if ($existsComercioExterior) {
$asserts->putStatus(
'RESFISC02',
Status::when($isValidResidenciaFiscal)
);
}
if ($receptor->exists('NumRegIdTrib')) {
$asserts->putStatus(
'RESFISC03',
Status::when($isValidResidenciaFiscal)
);
}
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/ComprobantePagos.php | src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/ComprobantePagos.php | <?php
namespace CfdiUtils\Validate\Cfdi33\RecepcionPagos;
use CfdiUtils\Nodes\NodeInterface;
use CfdiUtils\Validate\Asserts;
use CfdiUtils\Validate\Cfdi33\Abstracts\AbstractRecepcionPagos10;
use CfdiUtils\Validate\Status;
/**
* ComprobantePagos - Valida los datos relacionados al nodo Comprobante cuando es un CFDI de recepción de pagos
*
* - PAGCOMP01: Debe existir un solo nodo que represente el complemento de pagos
* - PAGCOMP02: La forma de pago no debe existir (CRP104)
* - PAGCOMP03: Las condiciones de pago no deben existir (CRP106)
* - PAGCOMP04: El método de pago no deben existir (CRP105)
* - PAGCOMP05: La moneda debe ser "XXX" (CRP103)
* - PAGCOMP06: El tipo de cambio no debe existir (CRP108)
* - PAGCOMP07: El descuento no debe existir (CRP107)
* - PAGCOMP08: El subtotal del documento debe ser cero "0" (CRP102)
* - PAGCOMP09: El total del documento debe ser cero "0" (CRP109)
* - PAGCOMP10: No se debe registrar el apartado de Impuestos en el CFDI (CRP122)
*/
class ComprobantePagos extends AbstractRecepcionPagos10
{
public function validateRecepcionPagos(NodeInterface $comprobante, Asserts $asserts): void
{
$pagos = $comprobante->searchNodes('cfdi:Complemento', 'pago10:Pagos');
$asserts->put(
'PAGCOMP01',
'Debe existir un solo nodo que represente el complemento de pagos',
Status::when(1 === $pagos->count()),
sprintf('Encontrados: %d', $pagos->count())
);
$asserts->put(
'PAGCOMP02',
'La forma de pago no debe existir (CRP104)',
Status::when(! $comprobante->exists('FormaPago'))
);
$asserts->put(
'PAGCOMP03',
'Las condiciones de pago no deben existir (CRP106)',
Status::when(! $comprobante->exists('CondicionesDePago'))
);
$asserts->put(
'PAGCOMP04',
'El método de pago no deben existir (CRP105)',
Status::when(! $comprobante->exists('MetodoPago'))
);
$asserts->put(
'PAGCOMP05',
'La moneda debe ser "XXX" (CRP103)',
Status::when('XXX' === $comprobante['Moneda']),
sprintf('Moneda: "%s"', $comprobante['Moneda'])
);
$asserts->put(
'PAGCOMP06',
'El tipo de cambio no debe existir (CRP108)',
Status::when(! $comprobante->exists('TipoCambio'))
);
$asserts->put(
'PAGCOMP07',
'El descuento no debe existir (CRP107)',
Status::when(! $comprobante->exists('Descuento'))
);
$asserts->put(
'PAGCOMP08',
'El subtotal del documento debe ser cero "0" (CRP102)',
Status::when('0' === $comprobante['SubTotal']),
sprintf('SubTotal: "%s"', $comprobante['SubTotal'])
);
$asserts->put(
'PAGCOMP09',
'El total del documento debe ser cero "0" (CRP109)',
Status::when('0' === $comprobante['Total']),
sprintf('Total: "%s"', $comprobante['Total'])
);
$asserts->put(
'PAGCOMP10',
'No se debe registrar el apartado de Impuestos en el CFDI (CRP122)',
Status::when(0 === $comprobante->searchNodes('cfdi:Impuestos')->count())
);
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/ComplementoPagos.php | src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/ComplementoPagos.php | <?php
namespace CfdiUtils\Validate\Cfdi33\RecepcionPagos;
use CfdiUtils\Nodes\Node;
use CfdiUtils\Nodes\NodeInterface;
use CfdiUtils\Validate\Asserts;
use CfdiUtils\Validate\Cfdi33\Abstracts\AbstractDiscoverableVersion33;
use CfdiUtils\Validate\Status;
/**
* ComplementoPagos
*
* Este complemento se ejecuta siempre
*
* - COMPPAG01: El complemento de pagos debe existir si el tipo de comprobante es P y viceversa
* - COMPPAG02: Si el complemento de pagos existe su version debe ser 1.0
* - COMPPAG03: Si el tipo de comprobante es P su versión debe ser 3.3
* - COMPPAG04: No debe existir el nodo impuestos del complemento de pagos (CRP237)
*/
class ComplementoPagos extends AbstractDiscoverableVersion33
{
public function validate(NodeInterface $comprobante, Asserts $asserts): void
{
$asserts->put('COMPPAG01', 'El complemento de pagos debe existir si el tipo de comprobante es P y viceversa');
$asserts->put('COMPPAG02', 'Si el complemento de pagos existe su version debe ser 1.0');
$asserts->put('COMPPAG03', 'Si el tipo de comprobante es P su versión debe ser 3.3');
$asserts->put('COMPPAG04', 'No debe existir el nodo impuestos del complemento de pagos (CRP237)');
$pagosExists = true;
$pagos10 = $comprobante->searchNode('cfdi:Complemento', 'pago10:Pagos');
if (null === $pagos10) {
$pagosExists = false;
$pagos10 = new Node('pago10:Pagos'); // avoid accessing a null object
}
$isTipoPago = ('P' === $comprobante['TipoDeComprobante']);
$asserts->putStatus(
'COMPPAG01',
Status::when(! ($isTipoPago xor $pagosExists)),
sprintf(
'TipoDeComprobante: "%s", Complemento: %s',
$comprobante['TipoDeComprobante'],
$pagosExists ? 'existe' : 'no existe'
)
);
if ($pagosExists) {
$asserts->putStatus('COMPPAG02', Status::when('1.0' === $pagos10['Version']));
}
if ($isTipoPago) {
$asserts->putStatus('COMPPAG03', Status::when('3.3' === $comprobante['Version']));
}
$asserts->putStatus(
'COMPPAG04',
Status::when(null === $pagos10->searchNode('pago10:Impuestos'))
);
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Pagos.php | src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Pagos.php | <?php
namespace CfdiUtils\Validate\Cfdi33\RecepcionPagos;
use CfdiUtils\Nodes\NodeInterface;
use CfdiUtils\Validate\Asserts;
use CfdiUtils\Validate\Cfdi33\Abstracts\AbstractRecepcionPagos10;
use CfdiUtils\Validate\Status;
/**
* Pagos - Valida el contenido del nodo del complemento de pago
*
* - PAGOS01: Debe existir al menos un pago en el complemento de pagos
*/
class Pagos extends AbstractRecepcionPagos10
{
public function validateRecepcionPagos(NodeInterface $comprobante, Asserts $asserts): void
{
$assert = $asserts->put('PAGOS01', 'Debe existir al menos un pago en el complemento de pagos');
$pagoCollection = $comprobante->searchNodes('cfdi:Complemento', 'pago10:Pagos', 'pago10:Pago');
$assert->setStatus(
Status::when($pagoCollection->count() > 0),
'Debe existir al menos un pago en el complemento de pagos'
);
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/UsoCfdi.php | src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/UsoCfdi.php | <?php
namespace CfdiUtils\Validate\Cfdi33\RecepcionPagos;
use CfdiUtils\Nodes\NodeInterface;
use CfdiUtils\Validate\Asserts;
use CfdiUtils\Validate\Cfdi33\Abstracts\AbstractRecepcionPagos10;
use CfdiUtils\Validate\Status;
/**
* UsoCfdi
*
* - PAGUSO01: El uso del CFDI debe ser "P01" (CRP110)
*/
class UsoCfdi extends AbstractRecepcionPagos10
{
public function validateRecepcionPagos(NodeInterface $comprobante, Asserts $asserts): void
{
$assert = $asserts->put('PAGUSO01', 'El uso del CFDI debe ser "P01" (CRP110)');
$receptor = $comprobante->searchNode('cfdi:Receptor');
if (null === $receptor) {
$assert->setStatus(Status::error(), 'No se encontró el nodo Receptor');
return;
}
$assert->setStatus(
Status::when('P01' === $receptor['UsoCFDI']),
sprintf('Uso CFDI: "%s"', $receptor['UsoCFDI'])
);
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/CfdiRelacionados.php | src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/CfdiRelacionados.php | <?php
namespace CfdiUtils\Validate\Cfdi33\RecepcionPagos;
use CfdiUtils\Nodes\NodeInterface;
use CfdiUtils\Validate\Asserts;
use CfdiUtils\Validate\Cfdi33\Abstracts\AbstractRecepcionPagos10;
use CfdiUtils\Validate\Status;
/**
* CfdiRelacionados
*
* - PAGREL01: El tipo de relación en los CFDI relacionados debe ser "04"
*/
class CfdiRelacionados extends AbstractRecepcionPagos10
{
public function validateRecepcionPagos(NodeInterface $comprobante, Asserts $asserts): void
{
$assert = $asserts->put('PAGREL01', 'El tipo de relación en los CFDI relacionados debe ser "04"');
$cfdiRelacionados = $comprobante->searchNode('cfdi:CfdiRelacionados');
if (null === $cfdiRelacionados) {
return;
}
$assert->setStatus(
Status::when('04' === $cfdiRelacionados['TipoRelacion']),
sprintf('Tipo de relación: "%s"', $cfdiRelacionados['TipoRelacion'])
);
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Pago.php | src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Pago.php | <?php
namespace CfdiUtils\Validate\Cfdi33\RecepcionPagos;
use CfdiUtils\Nodes\NodeInterface;
use CfdiUtils\Validate\Asserts;
use CfdiUtils\Validate\Cfdi33\Abstracts\AbstractRecepcionPagos10;
use CfdiUtils\Validate\Status;
/**
* Pago - Valida los nodos de pago dentro del complemento de pagos
*
* Se generan mensajes de error en los pagos con clave:
* PAGO??-XX donde ?? es el número de validación general y XX es el número del nodo con problemas
*
* Se generan mensajes de error en los documentos relacionados con clave:
* PAGO??-XX-YY donde YY es el número del nodo con problemas
*/
class Pago extends AbstractRecepcionPagos10
{
/** @var Asserts|null This is the asserts object used in the validation process */
private ?Asserts $asserts = null;
/** @var Pagos\AbstractPagoValidator[]|null */
private ?array $validators = null;
/**
* @return Pagos\AbstractPagoValidator[]
*/
public function createValidators(): array
{
return [
new Pagos\Fecha(), // PAGO02
new Pagos\FormaDePago(), // PAGO03
new Pagos\MonedaPago(), // PAGO04
new Pagos\TipoCambioExists(), // PAGO05
new Pagos\TipoCambioValue(), // PAGO6
new Pagos\MontoGreaterThanZero(), // PAGO07
new Pagos\MontoDecimals(), // PAGO08
new Pagos\MontoBetweenIntervalSumOfDocuments(), // PAGO09
new Pagos\BancoOrdenanteRfcCorrecto(), // PAGO10
new Pagos\BancoOrdenanteNombreRequerido(), // PAGO11
new Pagos\BancoOrdenanteRfcProhibido(), // PAGO12
new Pagos\CuentaOrdenanteProhibida(), // PAGO13
new Pagos\CuentaOrdenantePatron(), // PAGO14
new Pagos\BancoBeneficiarioRfcCorrecto(), // PAGO15
new Pagos\BancoBeneficiarioRfcProhibido(), // PAGO16
new Pagos\CuentaBeneficiariaProhibida(), // PAGO17
new Pagos\CuentaBeneficiariaPatron(), // PAGO18
new Pagos\TipoCadenaPagoProhibido(), // PAGO19
new Pagos\TipoCadenaPagoCertificado(), // PAGO20
new Pagos\TipoCadenaPagoCadena(), // PAGO21
new Pagos\TipoCadenaPagoSello(), // PAGO22
new Pagos\DoctoRelacionado(), // PAGO23 ... PAGO29
new Pagos\MontoGreaterOrEqualThanSumOfDocuments(), // PAGO30
];
}
/**
* @return Pagos\AbstractPagoValidator[]
*/
public function getValidators(): array
{
if (null === $this->validators) {
$this->validators = $this->createValidators();
}
return $this->validators;
}
public function validateRecepcionPagos(NodeInterface $comprobante, Asserts $asserts): void
{
$this->asserts = $asserts;
// create pago validators array
$validators = $this->createValidators();
// register pago validators array into asserts
foreach ($validators as $validator) {
$validator->registerInAssets($asserts);
}
// obtain the pago nodes
$pagoNodes = $comprobante->searchNodes('cfdi:Complemento', 'pago10:Pagos', 'pago10:Pago');
foreach ($pagoNodes as $index => $pagoNode) {
// pass each pago node thru validators
foreach ($validators as $validator) {
try {
if (! $validator->validatePago($pagoNode)) {
throw new \Exception(
sprintf('The validation of pago %s %s return false', $index, $validator::class)
);
}
} catch (Pagos\DoctoRelacionado\ValidateDoctoException $exception) {
$this->setDoctoRelacionadoStatus(
$exception->getValidatorCode(),
$index,
$exception->getIndex(),
$exception->getStatus(),
$exception->getMessage()
);
} catch (Pagos\ValidatePagoException $exception) {
$this->setPagoStatus(
$validator->getCode(),
$index,
$exception->getStatus(),
$exception->getMessage()
);
}
}
}
}
private function setPagoStatus(string $code, int $index, Status $errorStatus, string $explanation = ''): void
{
$assert = $this->asserts->get($code);
$assert->setStatus($errorStatus);
$this->asserts->put(
sprintf('%s-%02d', $assert->getCode(), $index),
$assert->getTitle(),
$errorStatus,
$explanation
);
}
private function setDoctoRelacionadoStatus(
string $code,
int $pagoIndex,
int $doctoIndex,
Status $errorStatus,
string $explanation = '',
): void {
$assert = $this->asserts->get($code);
$doctoCode = sprintf('%s-%02d-%02d', $assert->getCode(), $pagoIndex, $doctoIndex);
$this->setPagoStatus($code, $pagoIndex, $errorStatus);
$this->asserts->put(
$doctoCode,
$assert->getTitle(),
$errorStatus,
$explanation
);
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Conceptos.php | src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Conceptos.php | <?php
namespace CfdiUtils\Validate\Cfdi33\RecepcionPagos;
use CfdiUtils\Nodes\NodeInterface;
use CfdiUtils\Validate\Asserts;
use CfdiUtils\Validate\Cfdi33\Abstracts\AbstractRecepcionPagos10;
use CfdiUtils\Validate\Status;
/**
* Conceptos
* En un CFDI de recepción de pagos el Concepto del CFDI debe tener datos fijos,
* puede ver el problema específico en la explicación del issue
*
* - PAGCON01: Se debe usar el concepto predefinido (CRP107 - CRP121)
*/
class Conceptos extends AbstractRecepcionPagos10
{
public const REQUIRED_CLAVEPRODSERV = '84111506';
public const REQUIRED_CANTIDAD = '1';
public const REQUIRED_CLAVEUNIDAD = 'ACT';
public const REQUIRED_DESCRIPCION = 'Pago';
public const REQUIRED_VALORUNITARIO = '0';
public const REQUIRED_IMPORTE = '0';
public function validateRecepcionPagos(NodeInterface $comprobante, Asserts $asserts): void
{
$assert = $asserts->put('PAGCON01', 'Se debe usar el concepto predefinido (CRP107 - CRP121)');
// get conceptos
try {
$this->checkConceptos($comprobante);
} catch (\Exception $exception) {
$assert->setStatus(Status::error(), $exception->getMessage());
return;
}
$assert->setStatus(Status::ok());
}
private function checkConceptos(NodeInterface $comprobante): void
{
$conceptos = $comprobante->searchNode('cfdi:Conceptos');
if (null === $conceptos) {
throw new \Exception('No se encontró el nodo Conceptos');
}
// check conceptos count
$conceptosCount = $conceptos->children()->count();
if (1 !== $conceptosCount) {
throw new \Exception(
sprintf('Se esperaba encontrar un solo hijo de conceptos, se encontraron %s', $conceptosCount)
);
}
// check it contains a Concepto
$concepto = $conceptos->searchNode('cfdi:Concepto');
if (null === $concepto) {
throw new \Exception('No se encontró el nodo Concepto');
}
// check concepto does not have any children
$conceptoCount = $concepto->children()->count();
if (0 !== $conceptoCount) {
throw new \Exception(
sprintf('Se esperaba encontrar ningún hijo de concepto, se encontraron %s', $conceptoCount)
);
}
if (static::REQUIRED_CLAVEPRODSERV !== $concepto['ClaveProdServ']) {
throw new \Exception(sprintf(
'La clave del producto o servicio debe ser "%s" y se registró "%s"',
static::REQUIRED_CLAVEPRODSERV,
$concepto['ClaveProdServ']
));
}
if ($concepto->exists('NoIdentificacion')) {
throw new \Exception('No debe existir el número de identificación');
}
if (static::REQUIRED_CANTIDAD !== $concepto['Cantidad']) {
throw new \Exception(sprintf(
'La cantidad debe ser "%s" y se registró "%s"',
static::REQUIRED_CANTIDAD,
$concepto['Cantidad']
));
}
if (static::REQUIRED_CLAVEUNIDAD !== $concepto['ClaveUnidad']) {
throw new \Exception(sprintf(
'La clave de unidad debe ser "%s" y se registró "%s"',
static::REQUIRED_CLAVEUNIDAD,
$concepto['ClaveUnidad']
));
}
if ($concepto->exists('Unidad')) {
throw new \Exception('No debe existir la unidad');
}
if (static::REQUIRED_DESCRIPCION !== $concepto['Descripcion']) {
throw new \Exception(sprintf(
'La descripción debe ser "%s" y se registró "%s"',
static::REQUIRED_DESCRIPCION,
$concepto['Descripcion']
));
}
if (static::REQUIRED_VALORUNITARIO !== $concepto['ValorUnitario']) {
throw new \Exception(sprintf(
'El valor unitario debe ser "%s" y se registró "%s"',
static::REQUIRED_VALORUNITARIO,
$concepto['ValorUnitario']
));
}
if (static::REQUIRED_IMPORTE !== $concepto['Importe']) {
throw new \Exception(sprintf(
'El valor unitario debe ser "%s" y se registró "%s"',
static::REQUIRED_IMPORTE,
$concepto['Importe']
));
}
if ($concepto->exists('Descuento')) {
throw new \Exception('No debe existir descuento');
}
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Helpers/FormaPagoEntry.php | src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Helpers/FormaPagoEntry.php | <?php
namespace CfdiUtils\Validate\Cfdi33\RecepcionPagos\Helpers;
class FormaPagoEntry
{
private string $key;
private string $description;
private string $senderAccountPattern;
private string $receiverAccountPattern;
public function __construct(
string $key,
string $description,
private bool $allowSenderRfc,
private bool $allowSenderAccount,
string $senderAccountPattern,
private bool $allowReceiverRfc,
private bool $allowReceiverAccount,
string $receiverAccountPattern,
private bool $allowPaymentSignature,
) {
if ('' === $key) {
throw new \UnexpectedValueException('The FormaPago key cannot be empty');
}
if ('' === $description) {
throw new \UnexpectedValueException('The FormaPago description cannot be empty');
}
$this->key = $key;
$this->description = $description;
$this->senderAccountPattern = $this->pattern($this->allowSenderAccount, $senderAccountPattern);
$this->receiverAccountPattern = $this->pattern($this->allowReceiverAccount, $receiverAccountPattern);
}
private function pattern(bool $allowed, string $pattern): string
{
if (! $allowed || '' === $pattern) {
return '/^$/';
}
return $pattern;
}
public function key(): string
{
return $this->key;
}
public function description(): string
{
return $this->description;
}
public function allowSenderRfc(): bool
{
return $this->allowSenderRfc;
}
public function allowSenderAccount(): bool
{
return $this->allowSenderAccount;
}
public function senderAccountPattern(): string
{
return $this->senderAccountPattern;
}
public function allowReceiverRfc(): bool
{
return $this->allowReceiverRfc;
}
public function allowReceiverAccount(): bool
{
return $this->allowReceiverAccount;
}
public function receiverAccountPattern(): string
{
return $this->receiverAccountPattern;
}
public function allowPaymentSignature(): bool
{
return $this->allowPaymentSignature;
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Helpers/FormaPagoCatalog.php | src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Helpers/FormaPagoCatalog.php | <?php
namespace CfdiUtils\Validate\Cfdi33\RecepcionPagos\Helpers;
class FormaPagoCatalog
{
public function obtain(string $key): FormaPagoEntry
{
$map = [
[
'key' => '01',
'description' => 'Efectivo',
'useSenderRfc' => false,
'useSenderAccount' => false,
'useSenderAccountRegExp' => '',
'useReceiverRfc' => false,
'useReceiverAccount' => false,
'useReceiverAccountRegExp' => '',
'allowPaymentSignature' => false,
],
[
'key' => '02',
'description' => 'Cheque nominativo',
'useSenderRfc' => true,
'useSenderAccount' => true,
'useSenderAccountRegExp' => '/^(\d{11}|\d{18})$/',
'useReceiverRfc' => true,
'useReceiverAccount' => true,
'useReceiverAccountRegExp' => '/^(\d{10,11}|\d{15,16}|\d{18}|[A-Z0-9_]{10,50})$/',
'allowPaymentSignature' => false,
],
[
'key' => '03',
'description' => 'Transferencia electrónica de fondos',
'useSenderRfc' => true,
'useSenderAccount' => true,
'useSenderAccountRegExp' => '/^(\d{10}|\d{16}|\d{18})$/',
'useReceiverRfc' => true,
'useReceiverAccount' => true,
'useReceiverAccountRegExp' => '/^(\d{10}|\d{18})$/',
'allowPaymentSignature' => true,
],
[
'key' => '04',
'description' => 'Tarjeta de crédito',
'useSenderRfc' => true,
'useSenderAccount' => true,
'useSenderAccountRegExp' => '/^(\d{16})$/',
'useReceiverRfc' => true,
'useReceiverAccount' => true,
'useReceiverAccountRegExp' => '/^(\d{10,11}|\d{15,16}|\d{18}|[A-Z0-9_]{10,50})$/',
'allowPaymentSignature' => false,
],
[
'key' => '05',
'description' => 'Monedero electrónico',
'useSenderRfc' => true,
'useSenderAccount' => true,
'useSenderAccountRegExp' => '/^(\d{10,11}|\d{15,16}|\d{18}|[A-Z0-9_]{10,50})$/',
'useReceiverRfc' => true,
'useReceiverAccount' => true,
'useReceiverAccountRegExp' => '/^(\d{10,11}|\d{15,16}|\d{18}|[A-Z0-9_]{10,50})$/',
'allowPaymentSignature' => false,
],
[
'key' => '06',
'description' => 'Dinero electrónico',
'useSenderRfc' => true,
'useSenderAccount' => true,
'useSenderAccountRegExp' => '/^(\d{10})$/',
'useReceiverRfc' => false,
'useReceiverAccount' => false,
'useReceiverAccountRegExp' => '',
'allowPaymentSignature' => false,
],
[
'key' => '08',
'description' => 'Vales de despensa',
'useSenderRfc' => false,
'useSenderAccount' => false,
'useSenderAccountRegExp' => '',
'useReceiverRfc' => false,
'useReceiverAccount' => false,
'useReceiverAccountRegExp' => '',
'allowPaymentSignature' => false,
],
[
'key' => '12',
'description' => 'Dación en pago',
'useSenderRfc' => false,
'useSenderAccount' => false,
'useSenderAccountRegExp' => '',
'useReceiverRfc' => false,
'useReceiverAccount' => false,
'useReceiverAccountRegExp' => '',
'allowPaymentSignature' => false,
],
[
'key' => '13',
'description' => 'Pago por subrogación',
'useSenderRfc' => false,
'useSenderAccount' => false,
'useSenderAccountRegExp' => '',
'useReceiverRfc' => false,
'useReceiverAccount' => false,
'useReceiverAccountRegExp' => '',
'allowPaymentSignature' => false,
],
[
'key' => '14',
'description' => 'Pago por consignación',
'useSenderRfc' => false,
'useSenderAccount' => false,
'useSenderAccountRegExp' => '',
'useReceiverRfc' => false,
'useReceiverAccount' => false,
'useReceiverAccountRegExp' => '',
'allowPaymentSignature' => false,
],
[
'key' => '15',
'description' => 'Condonación',
'useSenderRfc' => false,
'useSenderAccount' => false,
'useSenderAccountRegExp' => '',
'useReceiverRfc' => false,
'useReceiverAccount' => false,
'useReceiverAccountRegExp' => '',
'allowPaymentSignature' => false,
],
[
'key' => '17',
'description' => 'Compensación',
'useSenderRfc' => false,
'useSenderAccount' => false,
'useSenderAccountRegExp' => '',
'useReceiverRfc' => false,
'useReceiverAccount' => false,
'useReceiverAccountRegExp' => '',
'allowPaymentSignature' => false,
],
[
'key' => '23',
'description' => 'Novación',
'useSenderRfc' => false,
'useSenderAccount' => false,
'useSenderAccountRegExp' => '',
'useReceiverRfc' => false,
'useReceiverAccount' => false,
'useReceiverAccountRegExp' => '',
'allowPaymentSignature' => false,
],
[
'key' => '24',
'description' => 'Confusión',
'useSenderRfc' => false,
'useSenderAccount' => false,
'useSenderAccountRegExp' => '',
'useReceiverRfc' => false,
'useReceiverAccount' => false,
'useReceiverAccountRegExp' => '',
'allowPaymentSignature' => false,
],
[
'key' => '25',
'description' => 'Remisión de deuda',
'useSenderRfc' => false,
'useSenderAccount' => false,
'useSenderAccountRegExp' => '',
'useReceiverRfc' => false,
'useReceiverAccount' => false,
'useReceiverAccountRegExp' => '',
'allowPaymentSignature' => false,
],
[
'key' => '26',
'description' => 'Prescripción o caducidad',
'useSenderRfc' => false,
'useSenderAccount' => false,
'useSenderAccountRegExp' => '',
'useReceiverRfc' => false,
'useReceiverAccount' => false,
'useReceiverAccountRegExp' => '',
'allowPaymentSignature' => false,
],
[
'key' => '27',
'description' => 'A satisfacción del acreedor',
'useSenderRfc' => false,
'useSenderAccount' => false,
'useSenderAccountRegExp' => '',
'useReceiverRfc' => false,
'useReceiverAccount' => false,
'useReceiverAccountRegExp' => '',
'allowPaymentSignature' => false,
],
[
'key' => '28',
'description' => 'Tarjeta de débito',
'useSenderRfc' => true,
'useSenderAccount' => true,
'useSenderAccountRegExp' => '/^(\d{16})$/',
'useReceiverRfc' => true,
'useReceiverAccount' => true,
'useReceiverAccountRegExp' => '/^(\d{10,11}|\d{15,16}|\d{18}|[A-Z0-9_]{10,50})$/',
'allowPaymentSignature' => false,
],
[
'key' => '29',
'description' => 'Tarjeta de servicios',
'useSenderRfc' => true,
'useSenderAccount' => true,
'useSenderAccountRegExp' => '/^(\d{15,16})$/',
'useReceiverRfc' => true,
'useReceiverAccount' => true,
'useReceiverAccountRegExp' => '/^(\d{10,11}|\d{15,16}|\d{18}|[A-Z0-9_]{10,50})$/',
'allowPaymentSignature' => false,
],
[
'key' => '30',
'description' => 'Aplicación de anticipos',
'useSenderRfc' => false,
'useSenderAccount' => false,
'useSenderAccountRegExp' => '',
'useReceiverRfc' => false,
'useReceiverAccount' => false,
'useReceiverAccountRegExp' => '',
'allowPaymentSignature' => false,
],
[
'key' => '31',
'description' => 'Intermediario pagos',
'useSenderRfc' => false,
'useSenderAccount' => false,
'useSenderAccountRegExp' => '',
'useReceiverRfc' => false,
'useReceiverAccount' => false,
'useReceiverAccountRegExp' => '',
'allowPaymentSignature' => false,
],
[
'key' => '99',
'description' => 'Por definir',
'useSenderRfc' => true,
'useSenderAccount' => true,
'useSenderAccountRegExp' => '/^\S*$/',
'useReceiverRfc' => true,
'useReceiverAccount' => true,
'useReceiverAccountRegExp' => '/^\S*$/',
'allowPaymentSignature' => true,
],
];
$keys = array_column($map, 'key');
$index = array_search($key, $keys, true);
if (false === $index) {
throw new \OutOfBoundsException("Key '$key' was not found in the catalog");
}
return new FormaPagoEntry(...array_values($map[$index]));
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Helpers/CalculateDocumentAmountTrait.php | src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Helpers/CalculateDocumentAmountTrait.php | <?php
namespace CfdiUtils\Validate\Cfdi33\RecepcionPagos\Helpers;
use CfdiUtils\Nodes\NodeInterface;
trait CalculateDocumentAmountTrait
{
public function calculateDocumentAmount(NodeInterface $doctoRelacionado, NodeInterface $pago): float
{
// el importe pagado es el que está en el documento
if ($doctoRelacionado->exists('ImpPagado')) {
return (float) $doctoRelacionado['ImpPagado'];
}
// el importe pagado es el que está en el pago
$doctosCount = $pago->searchNodes('pago10:DoctoRelacionado')->count();
if (1 === $doctosCount && ! $doctoRelacionado->exists('TipoCambioDR')) {
return (float) $pago['Monto'];
}
// no hay importe pagado
return 0.0;
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Pagos/AbstractPagoValidator.php | src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Pagos/AbstractPagoValidator.php | <?php
namespace CfdiUtils\Validate\Cfdi33\RecepcionPagos\Pagos;
use CfdiUtils\Nodes\NodeInterface;
use CfdiUtils\Utils\CurrencyDecimals;
use CfdiUtils\Validate\Asserts;
use CfdiUtils\Validate\Cfdi33\RecepcionPagos\Helpers\FormaPagoCatalog;
use CfdiUtils\Validate\Cfdi33\RecepcionPagos\Helpers\FormaPagoEntry;
use CfdiUtils\Validate\Status;
abstract class AbstractPagoValidator
{
protected string $code = '';
protected string $title = '';
public function getCode(): string
{
return $this->code;
}
public function getTitle(): string
{
return $this->title;
}
public function registerInAssets(Asserts $asserts): void
{
$asserts->put($this->getCode(), $this->getTitle(), Status::ok());
}
/**
* In this method is where all validations must occur
*
* @throws ValidatePagoException then validation fails
* @throws \Exception in the implementer if it does not return TRUE
* @return true|bool
*/
abstract public function validatePago(NodeInterface $pago): bool;
protected function isGreaterThan(float $value, float $compare): bool
{
return $value - $compare > 0.0000001;
}
protected function isEqual(float $expected, float $value): bool
{
return abs($expected - $value) < 0.0000001;
}
protected function createCurrencyDecimals(string $currency): CurrencyDecimals
{
try {
return CurrencyDecimals::newFromKnownCurrencies($currency);
} catch (\Throwable) {
return new CurrencyDecimals($currency ?: 'XXX', 0);
}
}
protected function createPaymentType(string $paymentType): FormaPagoEntry
{
try {
return (new FormaPagoCatalog())->obtain($paymentType);
} catch (\Throwable) {
throw new ValidatePagoException(sprintf('La forma de pago "%s" no está definida', $paymentType));
}
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Pagos/MontoDecimals.php | src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Pagos/MontoDecimals.php | <?php
namespace CfdiUtils\Validate\Cfdi33\RecepcionPagos\Pagos;
use CfdiUtils\Nodes\NodeInterface;
/**
* PAGO08: En un pago, el monto debe tener hasta la cantidad de decimales que soporte la moneda (CRP208)
*/
class MontoDecimals extends AbstractPagoValidator
{
protected string $code = 'PAGO08';
protected string $title = 'En un pago, el monto debe tener hasta la cantidad de decimales'
. ' que soporte la moneda (CRP208)';
public function validatePago(NodeInterface $pago): bool
{
$currency = $this->createCurrencyDecimals($pago['MonedaP']);
if (! $currency->doesNotExceedDecimals($pago['Monto'])) {
throw new ValidatePagoException(
sprintf('Monto: "%s", MaxDecimals: %s', $pago['Monto'], $currency->decimals())
);
}
return true;
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Pagos/Fecha.php | src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Pagos/Fecha.php | <?php
namespace CfdiUtils\Validate\Cfdi33\RecepcionPagos\Pagos;
use CfdiUtils\Nodes\NodeInterface;
use CfdiUtils\Validate\Cfdi33\Utils\AssertFechaFormat;
/**
* PAGO02: En un pago, la fecha debe cumplir con el formato específico
*/
class Fecha extends AbstractPagoValidator
{
protected string $code = 'PAGO02';
protected string $title = 'En un pago, la fecha debe cumplir con el formato específico';
public function validatePago(NodeInterface $pago): bool
{
if (! AssertFechaFormat::hasFormat($pago['FechaPago'])) {
throw new ValidatePagoException(sprintf('FechaPago: "%s"', $pago['FechaPago']));
}
return true;
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Pagos/TipoCambioValue.php | src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Pagos/TipoCambioValue.php | <?php
namespace CfdiUtils\Validate\Cfdi33\RecepcionPagos\Pagos;
use CfdiUtils\Nodes\NodeInterface;
use CfdiUtils\Utils\CurrencyDecimals;
/**
* PAGO06: En un pago, el tipo de cambio debe ser numérico, no debe exceder 6 decimales y debe ser mayor a "0.000001"
*/
class TipoCambioValue extends AbstractPagoValidator
{
protected string $code = 'PAGO06';
protected string $title = 'En un pago, el tipo de cambio debe ser numérico,'
. ' no debe exceder 6 decimales y debe ser mayor a "0.000001"';
public function validatePago(NodeInterface $pago): bool
{
if (! $pago->exists('TipoCambioP')) {
return true;
}
$reason = '';
if (! is_numeric($pago['TipoCambioP'])) {
$reason = 'No es numérico';
} elseif (CurrencyDecimals::decimalsCount((string) $pago['TipoCambioP']) > 6) {
$reason = 'Tiene más de 6 decimales';
} elseif (! $this->isGreaterThan((float) $pago['TipoCambioP'], 0.000001)) {
$reason = 'No es mayor a "0.000001"';
}
if ('' !== $reason) {
throw new ValidatePagoException(sprintf('TipoCambioP: "%s", %s', $pago['TipoCambioP'], $reason));
}
return true;
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Pagos/TipoCadenaPagoProhibido.php | src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Pagos/TipoCadenaPagoProhibido.php | <?php
namespace CfdiUtils\Validate\Cfdi33\RecepcionPagos\Pagos;
use CfdiUtils\Nodes\NodeInterface;
/**
* PAGO19: En un pago, cuando la forma de pago no sea 03 o 99 el tipo de cadena de pago no debe existir (CRP216)
*/
class TipoCadenaPagoProhibido extends AbstractPagoValidator
{
protected string $code = 'PAGO19';
protected string $title = 'En un pago, cuando la forma de pago no sea 03 o 99'
. ' el tipo de cadena de pago no debe existir (CRP216)';
public function validatePago(NodeInterface $pago): bool
{
$payment = $this->createPaymentType($pago['FormaDePagoP']);
// si NO es bancarizado y está establecida la cuenta ordenante existe
if (! $payment->allowPaymentSignature() && $pago->exists('TipoCadPago')) {
throw new ValidatePagoException(
sprintf('Forma de pago: "%s", Tipo cadena pago: "%s"', $pago['FormaDePagoP'], $pago['TipoCadPago'])
);
}
return true;
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Pagos/MontoBetweenIntervalSumOfDocuments.php | src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Pagos/MontoBetweenIntervalSumOfDocuments.php | <?php
namespace CfdiUtils\Validate\Cfdi33\RecepcionPagos\Pagos;
use CfdiUtils\Nodes\NodeInterface;
use CfdiUtils\Utils\CurrencyDecimals;
use CfdiUtils\Validate\Cfdi33\RecepcionPagos\Helpers\CalculateDocumentAmountTrait;
/**
* PAGO09: En un pago, el monto del pago debe encontrarse entre límites mínimo y máximo de la suma
* de los valores registrados en el importe pagado de los documentos relacionados (Guía llenado)
*/
class MontoBetweenIntervalSumOfDocuments extends AbstractPagoValidator
{
use CalculateDocumentAmountTrait;
protected string $code = 'PAGO09';
protected string $title = 'En un pago, el monto del pago debe encontrarse entre límites mínimo y máximo de la suma'
. ' de los valores registrados en el importe pagado de los documentos relacionados (Guía llenado)';
public function validatePago(NodeInterface $pago): bool
{
$pagoAmount = floatval($pago['Monto']);
$bounds = $this->calculateDocumentsAmountBounds($pago);
$currencyDecimals = CurrencyDecimals::newFromKnownCurrencies($pago['MonedaP'], 2);
$lower = $currencyDecimals->round($bounds['lower']);
$upper = $currencyDecimals->round($bounds['upper']);
if ($pagoAmount < $lower || $pagoAmount > $upper) {
throw new ValidatePagoException(
sprintf('Monto del pago: "%s", Suma mínima: "%s", Suma máxima: "%s"', $pagoAmount, $lower, $upper)
);
}
return true;
}
public function calculateDocumentsAmountBounds(NodeInterface $pago): array
{
$documents = $pago->searchNodes('pago10:DoctoRelacionado');
$values = [];
foreach ($documents as $document) {
$values[] = $this->calculateDocumentAmountBounds($document, $pago);
}
return [
'lower' => array_sum(array_column($values, 'lower')),
'upper' => array_sum(array_column($values, 'upper')),
];
}
public function calculateDocumentAmountBounds(NodeInterface $doctoRelacionado, NodeInterface $pago): array
{
$amount = $this->calculateDocumentAmount($doctoRelacionado, $pago);
$impPagado = $doctoRelacionado['ImpPagado'] ?? $amount;
$tipoCambioDr = $doctoRelacionado['TipoCambioDR'];
$exchangeRate = 1;
if ('' !== $tipoCambioDr && $pago['MonedaP'] !== $pago['MonedaDR']) {
$exchangeRate = floatval($tipoCambioDr);
}
$numDecimalsAmount = $this->getNumDecimals($impPagado);
$numDecimalsExchangeRate = $this->getNumDecimals($tipoCambioDr);
if (0 === $numDecimalsExchangeRate) {
return [
'lower' => $amount / $exchangeRate,
'upper' => $amount / $exchangeRate,
];
}
$almostTwo = 2 - (10 ** -10);
$lowerAmount = $amount - 10 ** -$numDecimalsAmount / 2;
$lowerExchangeRate = $exchangeRate + (10 ** (-$numDecimalsExchangeRate) / $almostTwo);
$upperAmount = $amount + 10 ** -$numDecimalsAmount / $almostTwo;
$upperExchangeRate = $exchangeRate - (10 ** (-$numDecimalsExchangeRate) / 2);
return [
'lower' => $lowerAmount / $lowerExchangeRate,
'upper' => $upperAmount / $upperExchangeRate,
];
}
public function getNumDecimals(string $numeric): int
{
if (! is_numeric($numeric)) {
return 0;
}
$pointPosition = strpos($numeric, '.');
if (false === $pointPosition) {
return 0;
}
return strlen($numeric) - 1 - $pointPosition;
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Pagos/BancoOrdenanteNombreRequerido.php | src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Pagos/BancoOrdenanteNombreRequerido.php | <?php
namespace CfdiUtils\Validate\Cfdi33\RecepcionPagos\Pagos;
use CfdiUtils\Nodes\NodeInterface;
use CfdiUtils\Utils\Rfc;
/**
* PAGO11: En un pago, cuando el RFC del banco emisor sea "XEXX010101000" el nombre del banco es requerido (CRP211)
*/
class BancoOrdenanteNombreRequerido extends AbstractPagoValidator
{
protected string $code = 'PAGO11';
protected string $title = 'En un pago, cuando el RFC del banco emisor sea "XEXX010101000"'
. ' el nombre del banco es requerido (CRP211)';
public function validatePago(NodeInterface $pago): bool
{
if (Rfc::RFC_FOREIGN === $pago['RfcEmisorCtaOrd'] && '' === $pago['NomBancoOrdExt']) {
throw new ValidatePagoException(
sprintf('Rfc: "%s, Nombre: %s"', $pago['RfcEmisorCtaOrd'], $pago['NomBancoOrdExt'])
);
}
return true;
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Pagos/BancoOrdenanteRfcCorrecto.php | src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Pagos/BancoOrdenanteRfcCorrecto.php | <?php
namespace CfdiUtils\Validate\Cfdi33\RecepcionPagos\Pagos;
use CfdiUtils\Nodes\NodeInterface;
use CfdiUtils\Utils\Rfc;
/**
* PAGO10: En un pago, cuando el RFC del banco emisor de la cuenta ordenante existe
* debe ser válido y diferente de "XAXX010101000"
*/
class BancoOrdenanteRfcCorrecto extends AbstractPagoValidator
{
protected string $code = 'PAGO10';
protected string $title = 'En un pago, cuando el RFC del banco emisor de la cuenta ordenante existe'
. ' debe ser válido y diferente de "XAXX010101000"';
public function validatePago(NodeInterface $pago): bool
{
if ($pago->exists('RfcEmisorCtaOrd')) {
try {
Rfc::checkIsValid($pago['RfcEmisorCtaOrd'], Rfc::DISALLOW_GENERIC);
} catch (\UnexpectedValueException $exception) {
throw new ValidatePagoException($exception->getMessage());
}
}
return true;
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Pagos/CuentaBeneficiariaProhibida.php | src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Pagos/CuentaBeneficiariaProhibida.php | <?php
namespace CfdiUtils\Validate\Cfdi33\RecepcionPagos\Pagos;
use CfdiUtils\Nodes\NodeInterface;
/**
* PAGO17: En un pago, cuando la forma de pago no sea 02, 03, 04, 05, 28, 29 o 99
* la cuenta beneficiaria no debe existir (CRP215)
*/
class CuentaBeneficiariaProhibida extends AbstractPagoValidator
{
protected string $code = 'PAGO17';
protected string $title = 'En un pago, cuando la forma de pago no sea 02, 03, 04, 05, 28, 29 o 99'
. ' la cuenta beneficiaria no debe existir (CRP215)';
public function validatePago(NodeInterface $pago): bool
{
$payment = $this->createPaymentType($pago['FormaDePagoP']);
// si NO es banzarizado y está establecida la cuenta beneficiaria
if (! $payment->allowReceiverAccount() && $pago->exists('CtaBeneficiario')) {
throw new ValidatePagoException(
sprintf('Forma de pago: "%s", Cuenta: "%s"', $pago['FormaDePagoP'], $pago['CtaBeneficiario'])
);
}
return true;
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Pagos/MontoGreaterOrEqualThanSumOfDocuments.php | src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Pagos/MontoGreaterOrEqualThanSumOfDocuments.php | <?php
namespace CfdiUtils\Validate\Cfdi33\RecepcionPagos\Pagos;
use CfdiUtils\Nodes\NodeInterface;
use CfdiUtils\Utils\CurrencyDecimals;
use CfdiUtils\Validate\Cfdi33\RecepcionPagos\Helpers\CalculateDocumentAmountTrait;
/**
* PAGO30: En un pago, la suma de los valores registrados o predeterminados en el importe pagado
* de los documentos relacionados debe ser menor o igual que el monto del pago (CRP206)
*/
class MontoGreaterOrEqualThanSumOfDocuments extends AbstractPagoValidator
{
use CalculateDocumentAmountTrait;
protected string $code = 'PAGO30';
protected string $title = 'En un pago, la suma de los valores registrados o predeterminados en el importe pagado'
. ' de los documentos relacionados debe ser menor o igual que el monto del pago (CRP206)';
public function validatePago(NodeInterface $pago): bool
{
$currency = $this->createCurrencyDecimals($pago['MonedaP']);
$sumOfDocuments = $this->calculateSumOfDocuments($pago, $currency);
$pagoAmount = (float) $pago['Monto'];
if ($this->isGreaterThan($sumOfDocuments, $pagoAmount)) {
throw new ValidatePagoException(
sprintf('Monto del pago: "%s", Suma de documentos: "%s"', $pagoAmount, $sumOfDocuments)
);
}
return true;
}
public function calculateSumOfDocuments(NodeInterface $pago, CurrencyDecimals $currency): float
{
$sumOfDocuments = 0;
$documents = $pago->searchNodes('pago10:DoctoRelacionado');
foreach ($documents as $document) {
$exchangeRate = (float) $document['TipoCambioDR'];
if ($this->isEqual($exchangeRate, 0)) {
$exchangeRate = 1;
}
$sumOfDocuments += $currency->round($this->calculateDocumentAmount($document, $pago) / $exchangeRate);
}
return $sumOfDocuments;
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Pagos/DoctoRelacionado.php | src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Pagos/DoctoRelacionado.php | <?php
namespace CfdiUtils\Validate\Cfdi33\RecepcionPagos\Pagos;
use CfdiUtils\Nodes\NodeInterface;
use CfdiUtils\Validate\Asserts;
class DoctoRelacionado extends AbstractPagoValidator
{
/** @var DoctoRelacionado\AbstractDoctoRelacionadoValidator[] */
protected array $validators;
public function __construct()
{
$this->validators = $this->createValidators();
}
/**
* @return DoctoRelacionado\AbstractDoctoRelacionadoValidator[]
*/
public function getValidators(): array
{
return $this->validators;
}
/**
* @return DoctoRelacionado\AbstractDoctoRelacionadoValidator[]
*/
public function createValidators(): array
{
return [
new DoctoRelacionado\Moneda(), // PAGO23
new DoctoRelacionado\TipoCambioRequerido(), // PAGO24
new DoctoRelacionado\TipoCambioValor(), // PAGO25
new DoctoRelacionado\ImporteSaldoAnteriorValor(), // PAGO26
new DoctoRelacionado\ImportePagadoValor(), // PAGO27
new DoctoRelacionado\ImporteSaldoInsolutoValor(), // PAGO28
new DoctoRelacionado\ImportesDecimales(), // PAGO29
new DoctoRelacionado\ImportePagadoRequerido(), // PAGO30
new DoctoRelacionado\NumeroParcialidadRequerido(), // PAGO31
new DoctoRelacionado\ImporteSaldoAnteriorRequerido(), // PAGO32
new DoctoRelacionado\ImporteSaldoInsolutoRequerido(), // PAGO33
];
}
// override registerInAssets to add validators instead of itself
public function registerInAssets(Asserts $asserts): void
{
foreach ($this->validators as $validator) {
$validator->registerInAssets($asserts);
}
}
public function validatePago(NodeInterface $pago): bool
{
// when validate pago perform validators on all documents
$validators = $this->getValidators();
foreach ($pago->searchNodes('pago10:DoctoRelacionado') as $index => $doctoRelacionado) {
foreach ($validators as $validator) {
$validator->setPago($pago);
$validator->setIndex($index);
$validator->validateDoctoRelacionado($doctoRelacionado);
}
}
return true;
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Pagos/TipoCadenaPagoCadena.php | src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Pagos/TipoCadenaPagoCadena.php | <?php
namespace CfdiUtils\Validate\Cfdi33\RecepcionPagos\Pagos;
use CfdiUtils\Nodes\NodeInterface;
/**
* PAGO21: En un pago, si existe el tipo de cadena de pago debe existir
* la cadena del pago y viceversa (CRP229 y CRP230)
*/
class TipoCadenaPagoCadena extends AbstractPagoValidator
{
protected string $code = 'PAGO21';
protected string $title = 'En un pago, si existe el tipo de cadena de pago debe existir'
. ' la cadena del pago y viceversa (CRP229 y CRP230)';
public function validatePago(NodeInterface $pago): bool
{
if (
(('' !== $pago['TipoCadPago']) xor ('' !== $pago['CadPago']))
|| ($pago->exists('TipoCadPago') xor $pago->exists('CadPago'))
) {
throw new ValidatePagoException(
sprintf('Tipo cadena pago: "%s", Cadena: "%s"', $pago['TipoCadPago'], $pago['CadPago'])
);
}
return true;
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Pagos/BancoBeneficiarioRfcCorrecto.php | src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Pagos/BancoBeneficiarioRfcCorrecto.php | <?php
namespace CfdiUtils\Validate\Cfdi33\RecepcionPagos\Pagos;
use CfdiUtils\Nodes\NodeInterface;
use CfdiUtils\Utils\Rfc;
/**
* PAGO15: En un pago, cuando el RFC del banco emisor de la cuenta beneficiaria existe
* debe ser válido y diferente de "XAXX010101000"
*/
class BancoBeneficiarioRfcCorrecto extends AbstractPagoValidator
{
protected string $code = 'PAGO15';
protected string $title = 'En un pago, cuando el RFC del banco emisor de la cuenta beneficiaria existe'
. ' debe ser válido y diferente de "XAXX010101000"';
public function validatePago(NodeInterface $pago): bool
{
if ($pago->exists('RfcEmisorCtaBen')) {
try {
Rfc::checkIsValid($pago['RfcEmisorCtaBen'], Rfc::DISALLOW_GENERIC);
} catch (\UnexpectedValueException $exception) {
throw new ValidatePagoException($exception->getMessage());
}
}
return true;
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Pagos/CuentaOrdenantePatron.php | src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Pagos/CuentaOrdenantePatron.php | <?php
namespace CfdiUtils\Validate\Cfdi33\RecepcionPagos\Pagos;
use CfdiUtils\Nodes\NodeInterface;
/**
* PAGO14: En un pago, cuando la cuenta ordenante existe debe cumplir con su patrón específico (CRP213)
*/
class CuentaOrdenantePatron extends AbstractPagoValidator
{
protected string $code = 'PAGO14';
protected string $title = 'En un pago, cuando la cuenta ordenante existe debe cumplir con'
. ' su patrón específico (CRP213)';
public function validatePago(NodeInterface $pago): bool
{
// Solo validar si está establecida la cuenta ordenante
if ($pago->exists('CtaOrdenante')) {
$payment = $this->createPaymentType($pago['FormaDePagoP']);
$pattern = $payment->senderAccountPattern();
if (! preg_match($pattern, $pago['CtaOrdenante'])) {
throw new ValidatePagoException(sprintf('Cuenta: "%s". Patrón "%s"', $pago['CtaOrdenante'], $pattern));
}
}
return true;
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Pagos/BancoBeneficiarioRfcProhibido.php | src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Pagos/BancoBeneficiarioRfcProhibido.php | <?php
namespace CfdiUtils\Validate\Cfdi33\RecepcionPagos\Pagos;
use CfdiUtils\Nodes\NodeInterface;
/**
* PAGO16: En un pago, cuando la forma de pago no sea 02, 03, 04, 05, 28, 29 o 99
* el RFC del banco de la cuenta beneficiaria no debe existir (CRP214)
*/
class BancoBeneficiarioRfcProhibido extends AbstractPagoValidator
{
protected string $code = 'PAGO16';
protected string $title = 'En un pago, cuando la forma de pago no sea 02, 03, 04, 05, 28, 29 o 99'
. ' el RFC del banco de la cuenta beneficiaria no debe existir (CRP214)';
public function validatePago(NodeInterface $pago): bool
{
$payment = $this->createPaymentType($pago['FormaDePagoP']);
if (! $payment->allowReceiverRfc() && $pago->exists('RfcEmisorCtaBen')) {
throw new ValidatePagoException(
sprintf('FormaDePago: "%s", Rfc: "%s"', $pago['FormaDePagoP'], $pago['RfcEmisorCtaBen'])
);
}
return true;
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Pagos/TipoCambioExists.php | src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Pagos/TipoCambioExists.php | <?php
namespace CfdiUtils\Validate\Cfdi33\RecepcionPagos\Pagos;
use CfdiUtils\Nodes\NodeInterface;
/**
* PAGO05: En un pago, cuando la moneda no es "MXN" no debe existir tipo de cambio,
* de lo contrario el tipo de cambio debe existir (CRP203, CRP204)
*/
class TipoCambioExists extends AbstractPagoValidator
{
protected string $code = 'PAGO05';
protected string $title = 'En un pago, cuando la moneda no es "MXN" no debe existir tipo de cambio,'
. ' de lo contrario el tipo de cambio debe existir (CRP203, CRP204)';
public function validatePago(NodeInterface $pago): bool
{
if (! (('MXN' === $pago['MonedaP']) xor ('' !== $pago['TipoCambioP']))) {
throw new ValidatePagoException(
sprintf('Moneda: "%s", Tipo de cambio: "%s"', $pago['MonedaP'], $pago['TipoCambioP'])
);
}
return true;
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Pagos/BancoOrdenanteRfcProhibido.php | src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Pagos/BancoOrdenanteRfcProhibido.php | <?php
namespace CfdiUtils\Validate\Cfdi33\RecepcionPagos\Pagos;
use CfdiUtils\Nodes\NodeInterface;
/**
* PAGO12: En un pago, cuando la forma de pago no sea bancarizada el RFC del banco emisor no debe existir (CRP238)
*/
class BancoOrdenanteRfcProhibido extends AbstractPagoValidator
{
protected string $code = 'PAGO12';
protected string $title = 'En un pago, cuando la forma de pago no sea bancarizada'
. ' el RFC del banco emisor no debe existir (CRP238)';
public function validatePago(NodeInterface $pago): bool
{
if ('' === $pago['FormaDePagoP']) {
throw new ValidatePagoException('No está establecida la forma de pago');
}
$payment = $this->createPaymentType($pago['FormaDePagoP']);
// si NO es banzarizado y está establecido el RFC del Emisor de la cuenta ordenante
if (! $payment->allowSenderRfc() && $pago->exists('RfcEmisorCtaOrd')) {
throw new ValidatePagoException(sprintf('Bancarizado: Sí, Rfc: "%s"', $pago['RfcEmisorCtaOrd']));
}
return true;
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Pagos/TipoCadenaPagoCertificado.php | src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Pagos/TipoCadenaPagoCertificado.php | <?php
namespace CfdiUtils\Validate\Cfdi33\RecepcionPagos\Pagos;
use CfdiUtils\Nodes\NodeInterface;
/**
* PAGO20: En un pago, si existe el tipo de cadena de pago debe existir
* el certificado del pago y viceversa (CRP227 y CRP228)
*/
class TipoCadenaPagoCertificado extends AbstractPagoValidator
{
protected string $code = 'PAGO20';
protected string $title = 'En un pago, si existe el tipo de cadena de pago debe existir'
. ' el certificado del pago y viceversa (CRP227 y CRP228)';
public function validatePago(NodeInterface $pago): bool
{
if (
(('' !== $pago['TipoCadPago']) xor ('' !== $pago['CertPago']))
|| ($pago->exists('TipoCadPago') xor $pago->exists('CertPago'))
) {
throw new ValidatePagoException(
sprintf('Tipo cadena pago: "%s", Certificado: "%s"', $pago['TipoCadPago'], $pago['CertPago'])
);
}
return true;
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Pagos/CuentaOrdenanteProhibida.php | src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Pagos/CuentaOrdenanteProhibida.php | <?php
namespace CfdiUtils\Validate\Cfdi33\RecepcionPagos\Pagos;
use CfdiUtils\Nodes\NodeInterface;
/**
* PAGO13: En un pago, cuando la forma de pago no sea bancarizada la cuenta ordenante no debe existir (CRP212)
*/
class CuentaOrdenanteProhibida extends AbstractPagoValidator
{
protected string $code = 'PAGO13';
protected string $title = 'En un pago, cuando la forma de pago no sea bancarizada'
. ' la cuenta ordenante no debe existir (CRP212)';
public function validatePago(NodeInterface $pago): bool
{
$payment = $this->createPaymentType($pago['FormaDePagoP']);
// si NO es banzarizado y está establecida la cuenta ordenante existe
if (! $payment->allowSenderAccount() && $pago->exists('CtaOrdenante')) {
throw new ValidatePagoException(sprintf('Bancarizado: Sí, Cuenta: "%s"', $pago['CtaOrdenante']));
}
return true;
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Pagos/MonedaPago.php | src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Pagos/MonedaPago.php | <?php
namespace CfdiUtils\Validate\Cfdi33\RecepcionPagos\Pagos;
use CfdiUtils\Nodes\NodeInterface;
/**
* PAGO04: En un pago, la moneda debe existir y no puede ser "XXX" (CRP202)
*/
class MonedaPago extends AbstractPagoValidator
{
protected string $code = 'PAGO04';
protected string $title = 'En un pago, la moneda debe existir y no puede ser "XXX" (CRP202)';
public function validatePago(NodeInterface $pago): bool
{
if ('' === $pago['MonedaP'] || 'XXX' === $pago['MonedaP']) {
throw new ValidatePagoException(sprintf('Moneda: "%s"', $pago['MonedaP']));
}
return true;
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Pagos/ValidatePagoException.php | src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Pagos/ValidatePagoException.php | <?php
namespace CfdiUtils\Validate\Cfdi33\RecepcionPagos\Pagos;
use CfdiUtils\Validate\Status;
class ValidatePagoException extends \Exception
{
private ?Status $status = null;
public function getStatus(): Status
{
return $this->status ?: Status::error();
}
public function setStatus(Status $status): self
{
$this->status = $status;
return $this;
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Pagos/FormaDePago.php | src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Pagos/FormaDePago.php | <?php
namespace CfdiUtils\Validate\Cfdi33\RecepcionPagos\Pagos;
use CfdiUtils\Nodes\NodeInterface;
/**
* PAGO03: En un pago, la forma de pago debe existir y no puede ser "99" (CRP201)
*/
class FormaDePago extends AbstractPagoValidator
{
protected string $code = 'PAGO03';
protected string $title = 'En un pago, la forma de pago debe existir y no puede ser "99" (CRP201)';
public function validatePago(NodeInterface $pago): bool
{
try {
$paymentType = $this->createPaymentType($pago['FormaDePagoP']);
if ('99' === $paymentType->key()) {
throw new ValidatePagoException('Cannot be "99"');
}
} catch (ValidatePagoException $exception) {
throw new ValidatePagoException(
sprintf('FormaDePagoP: "%s" %s', $pago['FormaDePagoP'], $exception->getMessage())
);
}
return true;
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Pagos/TipoCadenaPagoSello.php | src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Pagos/TipoCadenaPagoSello.php | <?php
namespace CfdiUtils\Validate\Cfdi33\RecepcionPagos\Pagos;
use CfdiUtils\Nodes\NodeInterface;
/**
* PAGO22: En un pago, si existe el tipo de cadena de pago debe existir
* el sello del pago y viceversa (CRP231 y CRP232)
*/
class TipoCadenaPagoSello extends AbstractPagoValidator
{
protected string $code = 'PAGO22';
protected string $title = 'En un pago, si existe el tipo de cadena de pago debe existir'
. ' el sello del pago y viceversa (CRP231 y CRP232)';
public function validatePago(NodeInterface $pago): bool
{
if (
(('' !== $pago['TipoCadPago']) xor ('' !== $pago['SelloPago']))
|| ($pago->exists('TipoCadPago') xor $pago->exists('SelloPago'))
) {
throw new ValidatePagoException(
sprintf('Tipo cadena pago: "%s", Sello: "%s"', $pago['TipoCadPago'], $pago['SelloPago'])
);
}
return true;
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Pagos/MontoGreaterThanZero.php | src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Pagos/MontoGreaterThanZero.php | <?php
namespace CfdiUtils\Validate\Cfdi33\RecepcionPagos\Pagos;
use CfdiUtils\Nodes\NodeInterface;
/**
* PAGO07: En un pago, el monto debe ser mayor a cero (CRP207)
*/
class MontoGreaterThanZero extends AbstractPagoValidator
{
protected string $code = 'PAGO07';
protected string $title = 'En un pago, el monto debe ser mayor a cero (CRP207)';
public function validatePago(NodeInterface $pago): bool
{
if (! $this->isGreaterThan((float) $pago['Monto'], 0)) {
throw new ValidatePagoException(sprintf('Monto: "%s"', $pago['Monto']));
}
return true;
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Pagos/CuentaBeneficiariaPatron.php | src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Pagos/CuentaBeneficiariaPatron.php | <?php
namespace CfdiUtils\Validate\Cfdi33\RecepcionPagos\Pagos;
use CfdiUtils\Nodes\NodeInterface;
/**
* PAGO18: En un pago, cuando la cuenta beneficiaria existe debe cumplir con su patrón específico (CRP239)
*/
class CuentaBeneficiariaPatron extends AbstractPagoValidator
{
protected string $code = 'PAGO18';
protected string $title = 'En un pago, cuando la cuenta beneficiaria existe'
. ' debe cumplir con su patrón específico (CRP213)';
public function validatePago(NodeInterface $pago): bool
{
// Solo validar si está establecida la cuenta ordenante
if ($pago->exists('CtaBeneficiario')) {
$payment = $this->createPaymentType($pago['FormaDePagoP']);
$pattern = $payment->receiverAccountPattern();
if (! preg_match($pattern, $pago['CtaBeneficiario'])) {
throw new ValidatePagoException(sprintf('Cuenta: "%s". Patrón "%s"', $pago['CtaOrdenante'], $pattern));
}
}
return true;
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Pagos/DoctoRelacionado/ImportesDecimales.php | src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Pagos/DoctoRelacionado/ImportesDecimales.php | <?php
namespace CfdiUtils\Validate\Cfdi33\RecepcionPagos\Pagos\DoctoRelacionado;
use CfdiUtils\Nodes\NodeInterface;
/**
* PAGO29: En un documento relacionado, los importes de importe pagado, saldo anterior y saldo insoluto
* deben tener hasta la cantidad de decimales que soporte la moneda (CRP222, CRP224, CRP225)
*/
class ImportesDecimales extends AbstractDoctoRelacionadoValidator
{
protected string $code = 'PAGO29';
protected string $title = 'En un documento relacionado, los importes de importe pagado,'
. ' saldo anterior y saldo insoluto deben tener hasta la cantidad de decimales que'
. ' soporte la moneda (CRP222, CRP224, CRP225)';
public function validateDoctoRelacionado(NodeInterface $docto): bool
{
$currency = $this->createCurrencyDecimals($docto['MonedaDR']);
if (! $currency->doesNotExceedDecimals($docto['ImpSaldoAnt'])) {
throw $this->exception(
sprintf('ImpSaldoAnt: "%s", Decimales: %d', $docto['ImpSaldoAnt'], $currency->decimals())
);
}
if ($docto->exists('ImpPagado') && ! $currency->doesNotExceedDecimals($docto['ImpPagado'])) {
throw $this->exception(
sprintf('ImpPagado: "%s", Decimales: %d', $docto['ImpPagado'], $currency->decimals())
);
}
if (! $currency->doesNotExceedDecimals($docto['ImpSaldoInsoluto'])) {
throw $this->exception(
sprintf('ImpSaldoInsoluto: "%s", Decimales: %d', $docto['ImpSaldoInsoluto'], $currency->decimals())
);
}
return true;
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Pagos/DoctoRelacionado/ImportePagadoRequerido.php | src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Pagos/DoctoRelacionado/ImportePagadoRequerido.php | <?php
namespace CfdiUtils\Validate\Cfdi33\RecepcionPagos\Pagos\DoctoRelacionado;
use CfdiUtils\Nodes\NodeInterface;
/**
* PAGO30: En un documento relacionado, el importe pagado es requerido cuando
* el tipo de cambio existe o existe más de un documento relacionado (CRP235)
*/
class ImportePagadoRequerido extends AbstractDoctoRelacionadoValidator
{
protected string $code = 'PAGO30';
protected string $title = 'En un documento relacionado, el importe pagado es requerido cuando'
. ' el tipo de cambio existe o existe más de un documento relacionado (CRP235)';
public function validateDoctoRelacionado(NodeInterface $docto): bool
{
if (! $docto->exists('ImpPagado')) {
$documentsCount = $this->getPago()->searchNodes('pago10:DoctoRelacionado')->count();
if ($documentsCount > 1) {
throw $this->exception('No hay importe pagado y hay más de 1 documento en el pago');
}
if ($docto->exists('TipoCambioDR')) {
throw $this->exception('No hay importe pagado y existe el tipo de cambio del documento');
}
}
return true;
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Pagos/DoctoRelacionado/NumeroParcialidadRequerido.php | src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Pagos/DoctoRelacionado/NumeroParcialidadRequerido.php | <?php
namespace CfdiUtils\Validate\Cfdi33\RecepcionPagos\Pagos\DoctoRelacionado;
use CfdiUtils\Nodes\NodeInterface;
/**
* PAGO31: En un documento relacionado, el número de parcialidad es requerido cuando
* el tipo de cambio existe o existe más de un documento relacionado (CRP234)
*/
class NumeroParcialidadRequerido extends AbstractDoctoRelacionadoValidator
{
protected string $code = 'PAGO31';
protected string $title = 'En un documento relacionado, el número de parcialidad es requerido cuando'
. ' el tipo de cambio existe o existe más de un documento relacionado (CRP233)';
public function validateDoctoRelacionado(NodeInterface $docto): bool
{
if (! $docto->exists('NumParcialidad') && 'PPD' === $docto['MetodoDePagoDR']) {
throw $this->exception('No hay número de parcialidad y el método de pago es PPD');
}
return true;
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Pagos/DoctoRelacionado/Moneda.php | src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Pagos/DoctoRelacionado/Moneda.php | <?php
namespace CfdiUtils\Validate\Cfdi33\RecepcionPagos\Pagos\DoctoRelacionado;
use CfdiUtils\Nodes\NodeInterface;
/**
* PAGO23: En un documento relacionado, la moneda no puede ser "XXX" (CRP217)
*/
class Moneda extends AbstractDoctoRelacionadoValidator
{
protected string $code = 'PAGO23';
protected string $title = 'En un documento relacionado, la moneda no puede ser "XXX" (CRP217)';
public function validateDoctoRelacionado(NodeInterface $docto): bool
{
if ('XXX' === $docto['MonedaDR']) {
throw $this->exception(sprintf('MonedaDR: "%s"', $docto['MonedaDR']));
}
return true;
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Pagos/DoctoRelacionado/AbstractDoctoRelacionadoValidator.php | src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Pagos/DoctoRelacionado/AbstractDoctoRelacionadoValidator.php | <?php
namespace CfdiUtils\Validate\Cfdi33\RecepcionPagos\Pagos\DoctoRelacionado;
use CfdiUtils\Nodes\NodeInterface;
use CfdiUtils\Validate\Cfdi33\RecepcionPagos\Pagos\AbstractPagoValidator;
abstract class AbstractDoctoRelacionadoValidator extends AbstractPagoValidator
{
private NodeInterface $pago;
private int $index;
abstract public function validateDoctoRelacionado(NodeInterface $docto): bool;
public function exception(string $message): ValidateDoctoException
{
$exception = new ValidateDoctoException($message);
$exception->setIndex($this->getIndex());
$exception->setValidatorCode($this->getCode());
return $exception;
}
public function validatePago(NodeInterface $pago): bool
{
throw new \LogicException('This method must not be called');
}
public function getPago(): NodeInterface
{
return $this->pago;
}
public function setPago(NodeInterface $pago): void
{
$this->pago = $pago;
}
public function getIndex(): int
{
return $this->index;
}
public function setIndex(int $index): void
{
$this->index = $index;
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Pagos/DoctoRelacionado/TipoCambioRequerido.php | src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Pagos/DoctoRelacionado/TipoCambioRequerido.php | <?php
namespace CfdiUtils\Validate\Cfdi33\RecepcionPagos\Pagos\DoctoRelacionado;
use CfdiUtils\Nodes\NodeInterface;
/**
* PAGO24: En un documento relacionado, el tipo de cambio debe existir cuando la moneda del pago
* es diferente a la moneda del documento y viceversa (CRP218, CRP219)
*/
class TipoCambioRequerido extends AbstractDoctoRelacionadoValidator
{
protected string $code = 'PAGO24';
protected string $title = 'En un documento relacionado, el tipo de cambio debe existir cuando la moneda del pago'
. ' es diferente a la moneda del documento y viceversa (CRP218, CRP219)';
public function validateDoctoRelacionado(NodeInterface $docto): bool
{
$pago = $this->getPago();
$currencyIsEqual = $pago['MonedaP'] === $docto['MonedaDR'];
if (! ($currencyIsEqual xor $docto->exists('TipoCambioDR'))) {
throw $this->exception(sprintf(
'Moneda pago: "%s", Moneda documento: "%s", Tipo cambio docto: "%s"',
$pago['MonedaP'],
$docto['MonedaDR'],
$docto['TipoCambioDR']
));
}
return true;
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Pagos/DoctoRelacionado/TipoCambioValor.php | src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Pagos/DoctoRelacionado/TipoCambioValor.php | <?php
namespace CfdiUtils\Validate\Cfdi33\RecepcionPagos\Pagos\DoctoRelacionado;
use CfdiUtils\Nodes\NodeInterface;
/**
* PAGO25: En un documento relacionado, el tipo de cambio debe tener el valor "1"
* cuando la moneda del documento es MXN y diferente de la moneda del pago (CRP220)
*/
class TipoCambioValor extends AbstractDoctoRelacionadoValidator
{
protected string $code = 'PAGO25';
protected string $title = 'En un documento relacionado, el tipo de cambio debe tener el valor "1"'
. ' cuando la moneda del documento es MXN y diferente de la moneda del pago (CRP220)';
public function validateDoctoRelacionado(NodeInterface $docto): bool
{
$pago = $this->getPago();
if (
'MXN' === $docto['MonedaDR']
&& $pago['MonedaP'] !== $docto['MonedaDR']
&& '1' !== $docto['TipoCambioDR']
) {
throw $this->exception(sprintf(
'Moneda pago: "%s", Moneda documento: "%s", Tipo cambio docto: "%s"',
$pago['MonedaP'],
$docto['MonedaDR'],
$docto['TipoCambioDR']
));
}
return true;
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Pagos/DoctoRelacionado/ImporteSaldoAnteriorRequerido.php | src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Pagos/DoctoRelacionado/ImporteSaldoAnteriorRequerido.php | <?php
namespace CfdiUtils\Validate\Cfdi33\RecepcionPagos\Pagos\DoctoRelacionado;
use CfdiUtils\Nodes\NodeInterface;
/**
* PAGO32: En un documento relacionado, el saldo anterior es requerido cuando
* el tipo de cambio existe o existe más de un documento relacionado (CRP234)
*/
class ImporteSaldoAnteriorRequerido extends AbstractDoctoRelacionadoValidator
{
protected string $code = 'PAGO32';
protected string $title = 'En un documento relacionado, el saldo anterior es requerido cuando'
. ' el tipo de cambio existe o existe más de un documento relacionado (CRP234)';
public function validateDoctoRelacionado(NodeInterface $docto): bool
{
if (! $docto->exists('ImpSaldoAnt') && 'PPD' === $docto['MetodoDePagoDR']) {
throw $this->exception('No hay saldo anterior y el método de pago es PPD');
}
return true;
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Pagos/DoctoRelacionado/ImporteSaldoInsolutoRequerido.php | src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Pagos/DoctoRelacionado/ImporteSaldoInsolutoRequerido.php | <?php
namespace CfdiUtils\Validate\Cfdi33\RecepcionPagos\Pagos\DoctoRelacionado;
use CfdiUtils\Nodes\NodeInterface;
/**
* PAGO33: En un documento relacionado, el saldo insoluto es requerido cuando
* el tipo de cambio existe o existe más de un documento relacionado (CRP234)
*/
class ImporteSaldoInsolutoRequerido extends AbstractDoctoRelacionadoValidator
{
protected string $code = 'PAGO33';
protected string $title = 'En un documento relacionado, el saldo insoluto es requerido cuando'
. ' el tipo de cambio existe o existe más de un documento relacionado (CRP233)';
public function validateDoctoRelacionado(NodeInterface $docto): bool
{
if (! $docto->exists('ImpSaldoInsoluto') && 'PPD' === $docto['MetodoDePagoDR']) {
throw $this->exception('No hay saldo insoluto y el método de pago es PPD');
}
return true;
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Pagos/DoctoRelacionado/ValidateDoctoException.php | src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Pagos/DoctoRelacionado/ValidateDoctoException.php | <?php
namespace CfdiUtils\Validate\Cfdi33\RecepcionPagos\Pagos\DoctoRelacionado;
use CfdiUtils\Validate\Cfdi33\RecepcionPagos\Pagos\ValidatePagoException;
class ValidateDoctoException extends ValidatePagoException
{
private ?int $index = null;
private ?string $validatorCode = null;
public function setIndex(int $index): self
{
$this->index = $index;
return $this;
}
public function setValidatorCode(string $validatorCode): self
{
$this->validatorCode = $validatorCode;
return $this;
}
public function getIndex(): int
{
return $this->index;
}
public function getValidatorCode(): string
{
return $this->validatorCode;
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Pagos/DoctoRelacionado/ImporteSaldoInsolutoValor.php | src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Pagos/DoctoRelacionado/ImporteSaldoInsolutoValor.php | <?php
namespace CfdiUtils\Validate\Cfdi33\RecepcionPagos\Pagos\DoctoRelacionado;
use CfdiUtils\Nodes\NodeInterface;
use CfdiUtils\Validate\Cfdi33\RecepcionPagos\Helpers\CalculateDocumentAmountTrait;
/**
* PAGO28: En un documento relacionado, el importe del saldo insoluto debe ser mayor o igual a cero
* e igual a la resta del importe del saldo anterior menos el importe pagado (CRP226)
*/
class ImporteSaldoInsolutoValor extends AbstractDoctoRelacionadoValidator
{
use CalculateDocumentAmountTrait;
protected string $code = 'PAGO28';
protected string $title = 'En un documento relacionado, el importe del saldo insoluto debe ser mayor o igual a cero'
. ' e igual a la resta del importe del saldo anterior menos el importe pagado (CRP226)';
public function validateDoctoRelacionado(NodeInterface $docto): bool
{
$value = (float) $docto['ImpSaldoInsoluto'];
if (! $this->isEqual(0, $value) && ! $this->isGreaterThan($value, 0)) {
throw $this->exception(sprintf('ImpSaldoInsoluto: "%s"', $docto['ImpSaldoInsoluto']));
}
$expected = (float) $docto['ImpSaldoAnt'] - $this->calculateDocumentAmount($docto, $this->getPago());
if (! $this->isEqual($expected, $value)) {
throw $this->exception(
sprintf('ImpSaldoInsoluto: "%s", Esperado: %F', $docto['ImpSaldoInsoluto'], $expected)
);
}
return true;
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Pagos/DoctoRelacionado/ImporteSaldoAnteriorValor.php | src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Pagos/DoctoRelacionado/ImporteSaldoAnteriorValor.php | <?php
namespace CfdiUtils\Validate\Cfdi33\RecepcionPagos\Pagos\DoctoRelacionado;
use CfdiUtils\Nodes\NodeInterface;
/**
* PAGO26: En un documento relacionado, el importe del saldo anterior debe ser mayor a cero (CRP221)
*/
class ImporteSaldoAnteriorValor extends AbstractDoctoRelacionadoValidator
{
protected string $code = 'PAGO26';
protected string $title = 'En un documento relacionado, el importe del saldo anterior'
. ' debe ser mayor a cero (CRP221)';
public function validateDoctoRelacionado(NodeInterface $docto): bool
{
$value = (float) $docto['ImpSaldoAnt'];
if (! $this->isGreaterThan($value, 0)) {
throw $this->exception(sprintf('ImpSaldoAnt: "%s"', $docto['ImpSaldoAnt']));
}
return true;
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Pagos/DoctoRelacionado/ImportePagadoValor.php | src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Pagos/DoctoRelacionado/ImportePagadoValor.php | <?php
namespace CfdiUtils\Validate\Cfdi33\RecepcionPagos\Pagos\DoctoRelacionado;
use CfdiUtils\Nodes\NodeInterface;
use CfdiUtils\Validate\Cfdi33\RecepcionPagos\Helpers\CalculateDocumentAmountTrait;
/**
* PAGO27: En un documento relacionado, el importe pagado debe ser mayor a cero (CRP223)
*/
class ImportePagadoValor extends AbstractDoctoRelacionadoValidator
{
use CalculateDocumentAmountTrait;
protected string $code = 'PAGO27';
protected string $title = 'En un documento relacionado, el importe pagado debe ser mayor a cero (CRP223)';
public function validateDoctoRelacionado(NodeInterface $docto): bool
{
if ($docto->exists('ImpPagado')) {
$value = (float) $docto['ImpPagado'];
} else {
$value = $this->calculateDocumentAmount($docto, $this->getPago());
}
if (! $this->isGreaterThan($value, 0)) {
throw $this->exception(sprintf('ImpPagado: "%s", valor: %F', $docto['ImpPagado'], $value));
}
return true;
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/QuickReader/QuickReader.php | src/CfdiUtils/QuickReader/QuickReader.php | <?php
namespace CfdiUtils\QuickReader;
class QuickReader extends \stdClass implements \ArrayAccess, \Stringable
{
protected string $name;
/** @var array<string, string> */
protected array $attributes;
/** @var self[] */
protected array $children;
/**
* QuickReader constructor.
* @param array<string, string> $attributes
* @param self[] $children
*/
public function __construct(string $name, array $attributes = [], array $children = [])
{
if ('' === $name) {
throw new \LogicException('Property name cannot be empty');
}
foreach ($attributes as $key => $value) {
if (! is_string($key) || '' === $key) {
throw new \LogicException('There is an attibute with empty or non string name');
}
if (! is_string($value)) {
throw new \LogicException("The attribute '$key' has a non string value");
}
}
foreach ($children as $index => $child) {
if (! $child instanceof static) {
throw new \LogicException("The child $index is not an instance of " . static::class);
}
}
$this->name = $name;
$this->attributes = $attributes;
$this->children = $children;
}
public function __toString(): string
{
return $this->name;
}
/** @return self[] */
public function __invoke(string $name = ''): array
{
if ('' === $name) {
return $this->children;
}
return array_values(array_filter(
$this->children,
fn (self $item): bool => $this->namesAreEqual($name, (string) $item)
));
}
/** @return self */
public function __get(string $name)
{
$child = $this->getChildByName($name);
if (null === $child) {
$child = new self($name);
}
return $child;
}
public function __set($name, $value): void
{
throw new \LogicException('Cannot change children');
}
/** @return self[] */
public function getChildren(string $name = ''): array
{
return $this->__invoke($name);
}
/** @return array<string, string> */
public function getAttributes(): array
{
return $this->attributes;
}
protected function getChildByName(string $name): ?self
{
foreach ($this->children as $child) {
if ($this->namesAreEqual($name, (string) $child)) {
return $child;
}
}
return null;
}
public function __isset(string $name): bool
{
return $this->getChildByName($name) instanceof static;
}
protected function getAttributeByName(string $name): ?string
{
foreach ($this->attributes as $key => $value) {
if ($this->namesAreEqual($name, $key)) {
return $value;
}
}
return null;
}
public function offsetExists($offset): bool
{
return null !== $this->getAttributeByName((string) $offset);
}
public function offsetGet($offset): string
{
return $this->getAttributeByName((string) $offset) ?? '';
}
#[\ReturnTypeWillChange]
public function offsetSet($offset, $value): void
{
throw new \LogicException('Cannot change attributes');
}
#[\ReturnTypeWillChange]
public function offsetUnset($offset): void
{
throw new \LogicException('Cannot change attributes');
}
protected function namesAreEqual(string $first, string $second): bool
{
return 0 === strcasecmp($first, $second);
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/QuickReader/QuickReaderImporter.php | src/CfdiUtils/QuickReader/QuickReaderImporter.php | <?php
namespace CfdiUtils\QuickReader;
use CfdiUtils\Utils\Xml;
use DOMDocument;
use DOMNode;
class QuickReaderImporter
{
public function importDocument(DOMDocument $document): QuickReader
{
return $this->importNode(Xml::documentElement($document));
}
public function importNode(DOMNode $node): QuickReader
{
return $this->createQuickReader(
$this->extractNameFromNode($node),
$this->extractAttributes($node),
$this->extractChildren($node)
);
}
protected function extractNameFromNode(DOMNode $node): string
{
// localName property has the tagName without namespace prefix
return $node->localName;
}
protected function extractAttributes(DOMNode $node): array
{
$attributes = [];
/** @var DOMNode $attribute */
foreach ($node->attributes as $attribute) {
$attributes[$attribute->nodeName] = $attribute->nodeValue;
}
return $attributes;
}
/**
* @return QuickReader[]
*/
protected function extractChildren(DOMNode $node): array
{
$children = [];
/** @var DOMNode $childNode */
foreach ($node->childNodes as $childNode) {
if (XML_ELEMENT_NODE === $childNode->nodeType) {
$children[] = $this->importNode($childNode);
}
}
return $children;
}
/**
* @param QuickReader[] $children
*/
protected function createQuickReader(string $name, array $attributes, array $children): QuickReader
{
return new QuickReader($name, $attributes, $children);
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/TimbreFiscalDigital/TfdVersion.php | src/CfdiUtils/TimbreFiscalDigital/TfdVersion.php | <?php
namespace CfdiUtils\TimbreFiscalDigital;
use CfdiUtils\VersionDiscovery\VersionDiscoverer;
/**
* This class provides static methods to retrieve the version attribute from a
* Timbre Fiscal Digital (TFD)
*
* It will not check anything but the value of the correct attribute
* It will not care if the cfdi is following a schema or element's name
*
* Possible values are always 1.0, 1.1 or empty string
*/
class TfdVersion extends VersionDiscoverer
{
public function rules(): array
{
return [
'1.1' => 'Version',
'1.0' => 'version',
];
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/TimbreFiscalDigital/TfdCadenaDeOrigen.php | src/CfdiUtils/TimbreFiscalDigital/TfdCadenaDeOrigen.php | <?php
namespace CfdiUtils\TimbreFiscalDigital;
use CfdiUtils\CadenaOrigen\DOMBuilder;
use CfdiUtils\CadenaOrigen\XsltBuilderInterface;
use CfdiUtils\CadenaOrigen\XsltBuilderPropertyInterface;
use CfdiUtils\CadenaOrigen\XsltBuilderPropertyTrait;
use CfdiUtils\XmlResolver\XmlResolver;
use CfdiUtils\XmlResolver\XmlResolverPropertyInterface;
use CfdiUtils\XmlResolver\XmlResolverPropertyTrait;
class TfdCadenaDeOrigen implements XmlResolverPropertyInterface, XsltBuilderPropertyInterface
{
use XmlResolverPropertyTrait;
use XsltBuilderPropertyTrait;
public const TFD_10 = 'http://www.sat.gob.mx/sitio_internet/timbrefiscaldigital/cadenaoriginal_TFD_1_0.xslt';
public const TFD_11 = 'http://www.sat.gob.mx/sitio_internet/cfd/TimbreFiscalDigital/cadenaoriginal_TFD_1_1.xslt';
public function __construct(?XmlResolver $xmlResolver = null, ?XsltBuilderInterface $xsltBuilder = null)
{
$this->setXmlResolver($xmlResolver ?: new XmlResolver());
$this->setXsltBuilder($xsltBuilder ?: new DOMBuilder());
}
public function build(string $tdfXmlString, string $version = ''): string
{
// this will throw an exception if no resolver is set
$resolver = $this->getXmlResolver();
// obtain version if it was not set
if ('' === $version) {
$version = (new TfdVersion())->getFromXmlString($tdfXmlString);
}
// get remote location of the xslt
$defaultXslt = $this->xsltLocation($version);
// get local xslt
$localXsd = $resolver->resolve($defaultXslt);
// return transformation
return $this->getXsltBuilder()->build($tdfXmlString, $localXsd);
}
public static function xsltLocation(string $version): string
{
if ('1.1' === $version) {
return static::TFD_11;
}
if ('1.0' === $version) {
return static::TFD_10;
}
throw new \UnexpectedValueException("Cannot get the xslt location for version '$version'");
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/estadosat.php | tests/estadosat.php | <?php
use CfdiUtils\Cfdi;
use CfdiUtils\ConsultaCfdiSat\RequestParameters;
use CfdiUtils\ConsultaCfdiSat\WebService;
require __DIR__ . '/bootstrap.php';
exit(call_user_func(function (string $command, string ...$arguments): int {
$askForHelp = ([] !== array_intersect(['-h', '--help'], $arguments));
$files = array_filter($arguments);
if ($askForHelp || [] === $files) {
echo implode(PHP_EOL, [
basename($command) . ' [-h|--help] cfdi.xml...',
' -h, --help Show this help',
" cfdi.xml Files to check, as many as needed, don't allow wilcards",
' WARNING: This program can change at any time! Do not depend on this file or its results!',
]), PHP_EOL;
return 0;
}
$webService = new WebService();
foreach ($files as $file) {
if (! file_exists($file)) {
echo "El archivo $file no existe", PHP_EOL;
continue;
}
$cfdi = Cfdi::newFromString((string) file_get_contents($file));
$request = RequestParameters::createFromCfdi($cfdi);
$response = $webService->request($request);
echo implode(PHP_EOL, [
" Archivo: $file",
" Expresión: {$request->expression()}",
" Petición: {$response->getCode()}",
"Estado CFDI: {$response->getCfdi()}",
" Cancelable: {$response->getCancellable()}",
"Cancelación: {$response->getCancellationStatus()}",
" EFOS: {$response->getValidationEfos()}",
]), PHP_EOL;
}
return 0;
}, ...$argv));
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/bootstrap.php | tests/bootstrap.php | <?php
// report all errors
error_reporting(-1);
// require composer autoloader
require_once __DIR__ . '/../vendor/autoload.php';
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/validate.php | tests/validate.php | <?php
use CfdiUtils\Cfdi;
use CfdiUtils\CfdiValidator33;
use CfdiUtils\CfdiValidator40;
use CfdiUtils\Cleaner\Cleaner;
use CfdiUtils\Validate\Assert;
use CfdiUtils\Validate\Asserts;
require __DIR__ . '/bootstrap.php';
exit(call_user_func(new class (...$argv) {
/** @var string[] */
private array $arguments;
/** @var array<CfdiValidator33|CfdiValidator40> */
private array $validators;
private const SUCCESS = 0;
private const ERROR = 1;
private const FAILURE = 2;
public function __construct(private string $command, string ...$arguments)
{
$this->arguments = $arguments;
$this->validators = [
'3.3' => new CfdiValidator33(),
'4.0' => new CfdiValidator40(),
];
}
public function __invoke(): int
{
if ([] !== array_intersect(['-h', '--help'], $this->arguments)) {
$this->printHelp();
return self::SUCCESS;
}
$files = [];
$noCache = false;
$clean = false;
foreach ($this->arguments as $argument) {
if (in_array($argument, ['-c', '--clean'], true)) {
$clean = true;
continue;
}
if ('--no-cache' === $argument) {
$noCache = true;
continue;
}
$files[] = $argument;
}
$files = array_unique(array_filter($files));
if ([] === $files) {
printf("FAIL: No files were specified\n");
return 2;
}
if ($noCache) {
foreach ($this->validators as $validator) {
$validator->getXmlResolver()->setLocalPath('');
}
}
set_error_handler(function (int $number, string $message): void {
throw new Error($message, $number);
});
$exitCode = self::SUCCESS;
foreach ($files as $file) {
printf("File: %s\n", $file);
try {
$asserts = $this->validateFile($file, $clean);
} catch (Throwable $exception) {
printf("FAIL: (%s) %s\n\n", $exception::class, $exception->getMessage());
$exitCode = self::FAILURE;
continue;
}
if (! $this->printAsserts($asserts)) {
$exitCode = self::ERROR;
}
printf("\n");
}
return $exitCode;
}
private function printHelp(): void
{
$command = basename($this->command);
echo <<< EOH
$command Validates CFDI files
Syntax:
$command [-h|--help] [-c|--clean] [--no-cache] cfdi.xml ...
Arguments:
-h, --help Show this help
-c, --clean Clean CFDI before validation
--no-cache Tell resolver to not use local cache
cfdi.xml Files to check, as many as needed
Exit codes:
0 - All files were validated with success
1 - At least one file contains errors or warnings
2 - At least one file produce an exception
WARNING: This program can change at any time! Do not depend on this file or its results!
EOH;
}
private function printAsserts(Asserts $asserts): bool
{
$warnings = $asserts->warnings();
$errors = $asserts->errors();
printf(
"Asserts: %s total, %s executed, %s ignored, %s success, %s warnings, %s errors.\n",
$asserts->count(),
$asserts->count() - count($asserts->nones()),
count($asserts->nones()),
count($asserts->oks()),
count($warnings),
count($errors)
);
foreach ($warnings as $warning) {
$this->printAssert('WARNING', $warning);
}
foreach ($errors as $error) {
$this->printAssert('ERROR', $error);
}
return [] === $errors && [] === $warnings;
}
private function printAssert(string $type, Assert $assert): void
{
$explanation = '';
if ($assert->getExplanation()) {
$explanation = sprintf("\n%s%s", str_repeat(' ', mb_strlen($type) + 2), $assert->getExplanation());
}
printf("%s: %s - %s%s\n", $type, $assert->getCode(), $assert->getTitle(), $explanation);
}
private function validateFile(string $file, bool $clean): Asserts
{
$xmlContent = (string) file_get_contents($file);
if ($clean) {
$xmlContent = Cleaner::staticClean($xmlContent);
}
return $this->validateXmlContent($xmlContent);
}
private function validateXmlContent(string $xmlContent): Asserts
{
$cfdi = Cfdi::newFromString($xmlContent);
return $this->validateCfdi($cfdi);
}
private function validateCfdi(Cfdi $cfdi): Asserts
{
$validator = $this->getValidatorForVersion($cfdi->getVersion());
return $validator->validate($cfdi->getSource(), $cfdi->getNode());
}
/** @return CfdiValidator33|CfdiValidator40 */
private function getValidatorForVersion(string $version)
{
if (! isset($this->validators[$version])) {
throw new Exception(sprintf('There is no validator for "%s"', $version));
}
return $this->validators[$version];
}
}));
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/CfdiValidator40Test.php | tests/CfdiUtilsTests/CfdiValidator40Test.php | <?php
namespace CfdiUtilsTests;
use CfdiUtils\Cfdi;
use CfdiUtils\CfdiValidator40;
use CfdiUtils\Nodes\Node;
final class CfdiValidator40Test extends TestCase
{
public function testConstructWithoutArguments(): void
{
$validator = new CfdiValidator40();
$this->assertTrue($validator->hasXmlResolver());
}
public function testConstructWithResolver(): void
{
$xmlResolver = $this->newResolver();
$validator = new CfdiValidator40($xmlResolver);
$this->assertSame($xmlResolver, $validator->getXmlResolver());
}
public function testValidateWithIncorrectXmlString(): void
{
$validator = new CfdiValidator40();
$asserts = $validator->validateXml('<not-a-cfdi/>');
$this->assertTrue($asserts->hasErrors());
}
public function testValidateWithIncorrectNode(): void
{
$validator = new CfdiValidator40();
$asserts = $validator->validateNode(new Node('not-a-cfdi'));
$this->assertTrue($asserts->hasErrors());
}
public function testValidateWithCorrectData(): void
{
$cfdiFile = $this->utilAsset('cfdi40-valid.xml');
$cfdi = Cfdi::newFromString(strval(file_get_contents($cfdiFile)));
// install PAC testing certificate
$this->installCertificate($this->utilAsset('certs/30001000000500003456.cer'));
$validator = new CfdiValidator40();
$asserts = $validator->validate($cfdi->getSource(), $cfdi->getNode());
// print_r($asserts->errors());
$this->assertFalse(
$asserts->hasErrors(),
'The validation of an expected cfdi40 valid file fails,'
. ' maybe you are creating a new discoverable standard validator that found a bug. Excelent!'
);
}
public function testValidateThrowsExceptionIfEmptyContent(): void
{
$validator = new CfdiValidator40();
$this->expectException(\UnexpectedValueException::class);
$this->expectExceptionMessage('empty');
$validator->validate('', new Node('root'));
}
public function testValidateCfdi40Real(): void
{
$cfdiFile = $this->utilAsset('cfdi40-real.xml');
$cfdi = Cfdi::newFromString(strval(file_get_contents($cfdiFile)));
// install PAC certificate, prevent if SAT service is down
$this->installCertificate($this->utilAsset('certs/00001000000708361114.cer'));
$validator = new CfdiValidator40($this->newResolver());
$asserts = $validator->validate($cfdi->getSource(), $cfdi->getNode());
// $asserts->hasErrors() && print_r($asserts->errors());
$this->assertFalse(
$asserts->hasErrors(),
'The validation of an expected cfdi40 real file fails'
);
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/CfdiCreator40FromExistentTest.php | tests/CfdiUtilsTests/CfdiCreator40FromExistentTest.php | <?php
namespace CfdiUtilsTests;
use CfdiUtils\Certificado\Certificado;
use CfdiUtils\CfdiCreator40;
use CfdiUtils\Nodes\XmlNodeUtils;
final class CfdiCreator40FromExistentTest extends TestCase
{
public function testNewUsingNode(): void
{
$xmlSource = strval(file_get_contents($this->utilAsset('cfdi40-real.xml')));
$nodeSource = XmlNodeUtils::nodeFromXmlString($xmlSource);
$creator = CfdiCreator40::newUsingNode($nodeSource);
$this->assertXmlStringEqualsXmlString($xmlSource, $creator->asXml());
}
public function testNewImportingNode(): void
{
$xmlSource = strval(file_get_contents($this->utilAsset('cfdi40-real.xml')));
$nodeSource = XmlNodeUtils::nodeFromXmlString($xmlSource);
$creator = CfdiCreator40::newUsingNode($nodeSource);
$this->assertXmlStringEqualsXmlString($xmlSource, $creator->asXml());
}
public function testPutCertificadoFromCreatorUsingNode(): void
{
$xmlSource = strval(file_get_contents($this->utilAsset('cfdi40-real.xml')));
$nodeSource = XmlNodeUtils::nodeFromXmlString($xmlSource);
$creator = CfdiCreator40::newUsingNode($nodeSource);
$creator->putCertificado(new Certificado($this->utilAsset('certs/EKU9003173C9.cer')));
$comprobante = $creator->comprobante();
$this->assertCount(1, $comprobante->searchNodes('cfdi:Emisor'));
$this->assertSame('ESCUELA KEMPER URGATE', $comprobante->searchAttribute('cfdi:Emisor', 'Nombre'));
$this->assertSame('EKU9003173C9', $comprobante->searchAttribute('cfdi:Emisor', 'Rfc'));
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/CfdiCreator33FromExistentTest.php | tests/CfdiUtilsTests/CfdiCreator33FromExistentTest.php | <?php
namespace CfdiUtilsTests;
use CfdiUtils\Certificado\Certificado;
use CfdiUtils\CfdiCreator33;
use CfdiUtils\Nodes\XmlNodeUtils;
final class CfdiCreator33FromExistentTest extends TestCase
{
public function testNewUsingNode(): void
{
$xmlSource = strval(file_get_contents($this->utilAsset('cfdi33-real.xml')));
$nodeSource = XmlNodeUtils::nodeFromXmlString($xmlSource);
$creator = CfdiCreator33::newUsingNode($nodeSource);
$this->assertXmlStringEqualsXmlString($xmlSource, $creator->asXml());
}
public function testNewImportingNode(): void
{
$xmlSource = strval(file_get_contents($this->utilAsset('cfdi33-real.xml')));
$nodeSource = XmlNodeUtils::nodeFromXmlString($xmlSource);
$creator = CfdiCreator33::newUsingNode($nodeSource);
$this->assertXmlStringEqualsXmlString($xmlSource, $creator->asXml());
}
public function testPutCertificadoFromCreatorUsingNode(): void
{
$xmlSource = strval(file_get_contents($this->utilAsset('cfdi33-real.xml')));
$nodeSource = XmlNodeUtils::nodeFromXmlString($xmlSource);
$creator = CfdiCreator33::newUsingNode($nodeSource);
$creator->putCertificado(new Certificado($this->utilAsset('certs/EKU9003173C9.cer')), true);
$comprobante = $creator->comprobante();
$this->assertCount(1, $comprobante->searchNodes('cfdi:Emisor'));
$this->assertSame('ESCUELA KEMPER URGATE SA DE CV', $comprobante->searchAttribute('cfdi:Emisor', 'Nombre'));
$this->assertSame('EKU9003173C9', $comprobante->searchAttribute('cfdi:Emisor', 'Rfc'));
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/tests/CfdiUtilsTests/CreateComprobante33CaseTest.php | tests/CfdiUtilsTests/CreateComprobante33CaseTest.php | <?php
namespace CfdiUtilsTests;
use CfdiUtils\Certificado\Certificado;
use CfdiUtils\CfdiCreator33;
use CfdiUtils\Utils\Format;
use CfdiUtils\Validate\Status;
final class CreateComprobante33CaseTest extends TestCase
{
public function testCreateCfdiUsingComprobanteElement(): void
{
$cerfile = $this->utilAsset('certs/EKU9003173C9.cer');
$keyfile = $this->utilAsset('certs/EKU9003173C9.key.pem');
$certificado = new Certificado($cerfile);
$fecha = strtotime('2023-06-18 19:20:21');
// create comprobante using creator with attributes
// did not set the XmlResolver then a new XmlResolver is created using the default location
$creator = new CfdiCreator33([
'Serie' => 'XXX',
'Folio' => '0000123456',
'Fecha' => Format::datetime($fecha),
'FormaPago' => '01', // efectivo
'Moneda' => 'USD',
'TipoCambio' => Format::number(18.9008, 4), // taken from banxico
'TipoDeComprobante' => 'I', // ingreso
'LugarExpedicion' => '52000',
], $certificado);
$comprobante = $creator->comprobante();
$comprobante['MetodoPago'] = 'PUE'; // Pago en una sola exhibición
$comprobante->addEmisor([
'RegimenFiscal' => '601', // General de Ley Personas Morales
]);
$comprobante->addReceptor([
'Rfc' => 'COSC8001137NA',
'Nombre' => 'Carlos Cortés Soto', // note is an "e" with accent
'UsoCFDI' => 'G01', // Adquisición de mercancias
]);
// add concepto #1
$concepto = $comprobante->addConcepto([
'ClaveProdServ' => '52161557', // Consola portátil de juegos de computador
'NoIdentificacion' => 'GAMEPAD007',
'Cantidad' => '4',
'ClaveUnidad' => 'H87', // Pieza
'Unidad' => 'PIEZA',
'Descripcion' => 'Portable tetris gamepad pro++',
'ValorUnitario' => '500',
'Importe' => '2000',
'Descuento' => '500', // hot sale: take 4, pay only 3
]);
$concepto->addTraslado([
'Base' => '1500',
'Impuesto' => '002', // IVA
'TipoFactor' => 'Tasa', // this is a catalog
'TasaOCuota' => '0.160000', // this is also a catalog
'Importe' => '240',
]);
$concepto->multiInformacionAduanera(
['NumeroPedimento' => '17 24 3420 7010987'],
['NumeroPedimento' => '17 24 3420 7010123']
);
// add concepto #2
$comprobante->addConcepto([
'ClaveProdServ' => '43211914', // Pantalla pasiva lcd
'NoIdentificacion' => 'SCREEN5004',
'Cantidad' => '1',
'ClaveUnidad' => 'H87', // Pieza
'Unidad' => 'PIEZA',
'Descripcion' => 'Pantalla led 3x4" con entrada HDMI',
'ValorUnitario' => '1000',
'Importe' => '1000',
])->addTraslado([
'Base' => '1000',
'Impuesto' => '002', // IVA
'TipoFactor' => 'Tasa', // this is a catalog
'TasaOCuota' => '0.160000', // this is also a catalog
'Importe' => '160',
]);
// concepto #3 (freight)
$comprobante->addConcepto([
// - Servicios de Transporte, Almacenaje y Correo
// - Manejo y embalaje de material
// - Servicios de manejo de materiales
// - Tarifa de los fletes
'ClaveProdServ' => '78121603', // Tarifa de los fletes
'NoIdentificacion' => 'FLETE-MX',
'Cantidad' => '1',
'ClaveUnidad' => 'E48', // Unidad de servicio
'Unidad' => 'SERVICIO',
'Descripcion' => 'Servicio de envío de mercancías',
'ValorUnitario' => '300',
'Importe' => '300',
])->addTraslado([
'Base' => '300',
'Impuesto' => '002', // IVA
'TipoFactor' => 'Tasa', // this is a catalog
'TasaOCuota' => '0.160000', // this is also a catalog
'Importe' => '48',
]);
// add additional calculated information sumas sello
$creator->addSumasConceptos(null, 2);
$creator->addSello('file://' . $keyfile);
// validate the comprobante and check it has no errors or warnings
$asserts = $creator->validate();
$this->assertFalse($asserts->hasErrors());
$this->assertFalse($asserts->hasStatus(Status::warn()));
// check the xml
$expectedFileContents = $this->utilAsset('created-with-discounts-33.xml');
$xmlContents = $creator->asXml();
$this->assertXmlStringEqualsXmlFile($expectedFileContents, $xmlContents);
$this->assertStringStartsWith('<?xml', $xmlContents);
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.