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/Elements/Cfdi33/Parte.php | src/CfdiUtils/Elements/Cfdi33/Parte.php | <?php
namespace CfdiUtils\Elements\Cfdi33;
use CfdiUtils\Elements\Cfdi33\Traits\InformacionAduaneraTrait;
use CfdiUtils\Elements\Common\AbstractElement;
class Parte extends AbstractElement
{
use InformacionAduaneraTrait;
public function getElementName(): string
{
return 'cfdi:Parte';
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Elements/Cfdi33/CfdiRelacionado.php | src/CfdiUtils/Elements/Cfdi33/CfdiRelacionado.php | <?php
namespace CfdiUtils\Elements\Cfdi33;
use CfdiUtils\Elements\Common\AbstractElement;
class CfdiRelacionado extends AbstractElement
{
public function getElementName(): string
{
return 'cfdi:CfdiRelacionado';
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Elements/Cfdi33/Traslado.php | src/CfdiUtils/Elements/Cfdi33/Traslado.php | <?php
namespace CfdiUtils\Elements\Cfdi33;
use CfdiUtils\Elements\Common\AbstractElement;
class Traslado extends AbstractElement
{
public function getElementName(): string
{
return 'cfdi:Traslado';
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Elements/Cfdi33/Receptor.php | src/CfdiUtils/Elements/Cfdi33/Receptor.php | <?php
namespace CfdiUtils\Elements\Cfdi33;
use CfdiUtils\Elements\Common\AbstractElement;
class Receptor extends AbstractElement
{
public function getElementName(): string
{
return 'cfdi:Receptor';
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Elements/Cfdi33/ConceptoImpuestos.php | src/CfdiUtils/Elements/Cfdi33/ConceptoImpuestos.php | <?php
namespace CfdiUtils\Elements\Cfdi33;
class ConceptoImpuestos extends Impuestos
{
public function getChildrenOrder(): array
{
return [
'cfdi:Traslados',
'cfdi:Retenciones',
];
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Elements/Cfdi33/Traslados.php | src/CfdiUtils/Elements/Cfdi33/Traslados.php | <?php
namespace CfdiUtils\Elements\Cfdi33;
use CfdiUtils\Elements\Common\AbstractElement;
class Traslados extends AbstractElement
{
public function getElementName(): string
{
return 'cfdi:Traslados';
}
public function addTraslado(array $attributes = []): Traslado
{
$traslado = new Traslado($attributes);
$this->addChild($traslado);
return $traslado;
}
public function multiTraslado(array ...$elementAttributes): self
{
foreach ($elementAttributes as $attributes) {
$this->addTraslado($attributes);
}
return $this;
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Elements/Cfdi33/ComplementoConcepto.php | src/CfdiUtils/Elements/Cfdi33/ComplementoConcepto.php | <?php
namespace CfdiUtils\Elements\Cfdi33;
use CfdiUtils\Elements\Common\AbstractElement;
class ComplementoConcepto extends AbstractElement
{
public function getElementName(): string
{
return 'cfdi:ComplementoConcepto';
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Elements/Cfdi33/CuentaPredial.php | src/CfdiUtils/Elements/Cfdi33/CuentaPredial.php | <?php
namespace CfdiUtils\Elements\Cfdi33;
use CfdiUtils\Elements\Common\AbstractElement;
class CuentaPredial extends AbstractElement
{
public function getElementName(): string
{
return 'cfdi:CuentaPredial';
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Elements/Cfdi33/Retencion.php | src/CfdiUtils/Elements/Cfdi33/Retencion.php | <?php
namespace CfdiUtils\Elements\Cfdi33;
use CfdiUtils\Elements\Common\AbstractElement;
class Retencion extends AbstractElement
{
public function getElementName(): string
{
return 'cfdi:Retencion';
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Elements/Cfdi33/InformacionAduanera.php | src/CfdiUtils/Elements/Cfdi33/InformacionAduanera.php | <?php
namespace CfdiUtils\Elements\Cfdi33;
use CfdiUtils\Elements\Common\AbstractElement;
class InformacionAduanera extends AbstractElement
{
public function getElementName(): string
{
return 'cfdi:InformacionAduanera';
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Elements/Cfdi33/CfdiRelacionados.php | src/CfdiUtils/Elements/Cfdi33/CfdiRelacionados.php | <?php
namespace CfdiUtils\Elements\Cfdi33;
use CfdiUtils\Elements\Common\AbstractElement;
class CfdiRelacionados extends AbstractElement
{
public function getElementName(): string
{
return 'cfdi:CfdiRelacionados';
}
public function addCfdiRelacionado(array $attributes = []): CfdiRelacionado
{
$cfdiRelacionado = new CfdiRelacionado($attributes);
$this->addChild($cfdiRelacionado);
return $cfdiRelacionado;
}
public function multiCfdiRelacionado(array ...$elementAttributes): self
{
foreach ($elementAttributes as $attributes) {
$this->addCfdiRelacionado($attributes);
}
return $this;
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Elements/Cfdi33/Emisor.php | src/CfdiUtils/Elements/Cfdi33/Emisor.php | <?php
namespace CfdiUtils\Elements\Cfdi33;
use CfdiUtils\Elements\Common\AbstractElement;
class Emisor extends AbstractElement
{
public function getElementName(): string
{
return 'cfdi:Emisor';
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Elements/Cfdi33/Concepto.php | src/CfdiUtils/Elements/Cfdi33/Concepto.php | <?php
namespace CfdiUtils\Elements\Cfdi33;
use CfdiUtils\Elements\Cfdi33\Traits\ImpuestosTrait;
use CfdiUtils\Elements\Cfdi33\Traits\InformacionAduaneraTrait;
use CfdiUtils\Elements\Common\AbstractElement;
class Concepto extends AbstractElement
{
use ImpuestosTrait;
use InformacionAduaneraTrait;
public function getElementName(): string
{
return 'cfdi:Concepto';
}
public function getChildrenOrder(): array
{
return [
'cfdi:Impuestos',
'cfdi:InformacionAduanera',
'cfdi:CuentaPredial',
'cfdi:ComplementoConcepto',
'cfdi:Parte',
];
}
public function getImpuestos(): ConceptoImpuestos
{
return $this->helperGetOrAdd(new ConceptoImpuestos());
}
public function getCuentaPredial(): CuentaPredial
{
return $this->helperGetOrAdd(new CuentaPredial());
}
public function addCuentaPredial(array $attributes = []): CuentaPredial
{
$cuentaPredial = $this->getCuentaPredial();
$cuentaPredial->addAttributes($attributes);
return $cuentaPredial;
}
public function getComplementoConcepto(): ComplementoConcepto
{
return $this->helperGetOrAdd(new ComplementoConcepto());
}
public function addComplementoConcepto(array $attributes = [], array $children = []): ComplementoConcepto
{
$complementoConcepto = $this->getComplementoConcepto();
$complementoConcepto->addAttributes($attributes);
$complementoConcepto->children()->importFromArray($children);
return $complementoConcepto;
}
public function addParte(array $attributes = [], array $children = []): Parte
{
$parte = new Parte($attributes, $children);
$this->addChild($parte);
return $parte;
}
public function multiParte(array ...$elementAttributes): self
{
foreach ($elementAttributes as $attributes) {
$this->addParte($attributes);
}
return $this;
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Elements/Cfdi33/Conceptos.php | src/CfdiUtils/Elements/Cfdi33/Conceptos.php | <?php
namespace CfdiUtils\Elements\Cfdi33;
use CfdiUtils\Elements\Common\AbstractElement;
class Conceptos extends AbstractElement
{
public function getElementName(): string
{
return 'cfdi:Conceptos';
}
public function addConcepto(array $attributes = [], array $children = []): Concepto
{
$concepto = new Concepto($attributes, $children);
$this->addChild($concepto);
return $concepto;
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Elements/Cfdi33/Complemento.php | src/CfdiUtils/Elements/Cfdi33/Complemento.php | <?php
namespace CfdiUtils\Elements\Cfdi33;
use CfdiUtils\Elements\Common\AbstractElement;
use CfdiUtils\Nodes\NodeInterface;
class Complemento extends AbstractElement
{
public function getElementName(): string
{
return 'cfdi:Complemento';
}
public function add(NodeInterface $child): self
{
$this->children()->add($child);
return $this;
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Elements/Cfdi33/Retenciones.php | src/CfdiUtils/Elements/Cfdi33/Retenciones.php | <?php
namespace CfdiUtils\Elements\Cfdi33;
use CfdiUtils\Elements\Common\AbstractElement;
class Retenciones extends AbstractElement
{
public function getElementName(): string
{
return 'cfdi:Retenciones';
}
public function addRetencion(array $attributes = []): Retencion
{
$retencion = new Retencion($attributes);
$this->addChild($retencion);
return $retencion;
}
public function multiRetencion(array ...$elementAttributes): self
{
foreach ($elementAttributes as $attributes) {
$this->addRetencion($attributes);
}
return $this;
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Elements/Cfdi33/Comprobante.php | src/CfdiUtils/Elements/Cfdi33/Comprobante.php | <?php
namespace CfdiUtils\Elements\Cfdi33;
use CfdiUtils\Elements\Cfdi33\Traits\ImpuestosTrait;
use CfdiUtils\Elements\Common\AbstractElement;
use CfdiUtils\Nodes\NodeInterface;
class Comprobante extends AbstractElement
{
use ImpuestosTrait;
public function getElementName(): string
{
return 'cfdi:Comprobante';
}
public function getCfdiRelacionados(): CfdiRelacionados
{
return $this->helperGetOrAdd(new CfdiRelacionados());
}
public function addCfdiRelacionados(array $attributes = []): CfdiRelacionados
{
$cfdiRelacionados = $this->getCfdiRelacionados();
$cfdiRelacionados->addAttributes($attributes);
return $cfdiRelacionados;
}
public function addCfdiRelacionado(array $attributes = []): CfdiRelacionado
{
return $this->getCfdiRelacionados()->addCfdiRelacionado($attributes);
}
public function multiCfdiRelacionado(array ...$elementAttributes): self
{
$this->getCfdiRelacionados()->multiCfdiRelacionado(...$elementAttributes);
return $this;
}
public function getEmisor(): Emisor
{
return $this->helperGetOrAdd(new Emisor());
}
public function addEmisor(array $attributes = []): Emisor
{
$emisor = $this->getEmisor();
$emisor->addAttributes($attributes);
return $emisor;
}
public function getReceptor(): Receptor
{
return $this->helperGetOrAdd(new Receptor());
}
public function addReceptor(array $attributes = []): Receptor
{
$receptor = $this->getReceptor();
$receptor->addAttributes($attributes);
return $receptor;
}
public function getConceptos(): Conceptos
{
return $this->helperGetOrAdd(new Conceptos());
}
public function addConcepto(array $attributes = [], array $children = []): Concepto
{
return $this->getConceptos()->addConcepto($attributes, $children);
}
public function getImpuestos(): Impuestos
{
return $this->helperGetOrAdd(new Impuestos());
}
public function addImpuestos(array $attributes = []): Impuestos
{
$impuestos = $this->getImpuestos();
$impuestos->addAttributes($attributes);
return $impuestos;
}
public function getComplemento(): Complemento
{
return $this->helperGetOrAdd(new Complemento());
}
public function addComplemento(NodeInterface $children): self
{
$this->getComplemento()->add($children);
return $this;
}
public function getAddenda(): Addenda
{
return $this->helperGetOrAdd(new Addenda());
}
public function addAddenda(NodeInterface $children): self
{
$this->getAddenda()->add($children);
return $this;
}
public function getChildrenOrder(): array
{
return [
'cfdi:CfdiRelacionados',
'cfdi:Emisor',
'cfdi:Receptor',
'cfdi:Conceptos',
'cfdi:Impuestos',
'cfdi:Complemento',
'cfdi:Addenda',
];
}
public function getFixedAttributes(): array
{
return [
'xmlns:cfdi' => 'http://www.sat.gob.mx/cfd/3',
'xmlns:xsi' => 'http://www.w3.org/2001/XMLSchema-instance',
'xsi:schemaLocation' => 'http://www.sat.gob.mx/cfd/3 http://www.sat.gob.mx/sitio_internet/cfd/3/cfdv33.xsd',
'Version' => '3.3',
];
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Elements/Cfdi33/Traits/ImpuestosTrait.php | src/CfdiUtils/Elements/Cfdi33/Traits/ImpuestosTrait.php | <?php
namespace CfdiUtils\Elements\Cfdi33\Traits;
use CfdiUtils\Elements\Cfdi33\Impuestos;
use CfdiUtils\Elements\Cfdi33\Retencion;
use CfdiUtils\Elements\Cfdi33\Traslado;
trait ImpuestosTrait
{
/*
* This method is required for all the shortcut methods included here
* The returned instance must be Impuestos or an extended class
*/
abstract public function getImpuestos(): Impuestos;
public function addTraslado(array $attributes = []): Traslado
{
return $this->getImpuestos()->getTraslados()->addTraslado($attributes);
}
public function multiTraslado(array ...$elementAttributes): self
{
$this->getImpuestos()->getTraslados()->multiTraslado(...$elementAttributes);
return $this;
}
public function addRetencion(array $attributes = []): Retencion
{
return $this->getImpuestos()->getRetenciones()->addRetencion($attributes);
}
public function multiRetencion(array ...$elementAttributes): self
{
$this->getImpuestos()->getRetenciones()->multiRetencion(...$elementAttributes);
return $this;
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Elements/Cfdi33/Traits/InformacionAduaneraTrait.php | src/CfdiUtils/Elements/Cfdi33/Traits/InformacionAduaneraTrait.php | <?php
namespace CfdiUtils\Elements\Cfdi33\Traits;
use CfdiUtils\Elements\Cfdi33\InformacionAduanera;
use CfdiUtils\Nodes\NodeInterface;
trait InformacionAduaneraTrait
{
/* This method comes from NodeInterface */
abstract public function addChild(NodeInterface $node): NodeInterface;
public function addInformacionAduanera(array $attributes = []): InformacionAduanera
{
$informacionAduanera = new InformacionAduanera($attributes);
$this->addChild($informacionAduanera);
return $informacionAduanera;
}
public function multiInformacionAduanera(array ...$elementAttributes): self
{
foreach ($elementAttributes as $attributes) {
$this->addInformacionAduanera($attributes);
}
return $this;
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Utils/RegimenCapitalRemover.php | src/CfdiUtils/Utils/RegimenCapitalRemover.php | <?php
namespace CfdiUtils\Utils;
use LogicException;
final class RegimenCapitalRemover
{
/**
* @var list<string> List of "Régimen de Capital", taken from IMSS
* @see https://altapatronalpresencial.imss.gob.mx/sapi/plantillaPatrones.do?method=initCapturaMoral
*/
private const SUFFIXES = [
'A EN P',
'AA',
'ABP',
'AC',
'AF',
'AFORE',
'AG',
'ALPR',
'APL',
'APN',
'AR DE IC DE CV DE RL',
'AR DE IC DE CV',
'AR DE IC DE RI',
'AR DE IC DE RL DE CV',
'AR DE IC DE RL',
'AR DE IC',
'AR',
'ART',
'C POR A',
'CEL',
'EPE',
'EPS',
'FA',
'FC DE RL',
'I A S',
'IAP',
'IBP',
'INSTITUCION DE ASISTENCIA SOCIAL PRIVADA',
'INSTITUCION DE BANCA MULTIPLE',
'INSTITUTO DE ASISTENCIA SOCIAL',
'L',
'MI',
'ORGANIZACIONES AUXILIARES DE CREDITO',
'P EN C',
'RI',
'RL Y CV',
'S C DE P S DE R L DE C V',
'S C P R DE R L',
'S DE CV',
'S DE I DE OL',
'S DE P DE RL',
'S DE PR DE RI',
'S DE PR DE RS',
'S DE RL ART',
'S DE RL DE CV MI',
'S DE RL DE CV',
'S DE RL DE IP DE CV',
'S DE RL DE IP',
'S DE RL MI ART',
'S DE RL MI DE CV',
'S DE RL MI',
'S DE RL',
'S DE SS DE R L',
'S DE SS DE RI',
'S DE SS',
'S EN C DE CV',
'S EN C DE RI DE CV',
'S EN C DE RI',
'S EN C DE RL DE CV',
'S EN C DE RL',
'S EN C POR A DE CV',
'S EN C POR A DE RI DE CV',
'S EN C POR A DE RI',
'S EN C POR A DE RL DE CV',
'S EN C POR A DE RL',
'S EN C POR A',
'S EN C',
'S EN CS DE CV',
'S EN NC DE CV',
'S EN NC DE RI DE CV',
'S EN NC DE RI',
'S EN NC DE RL DE CV',
'S EN NC DE RL',
'SA DE CV DE RL',
'SA DE CV S DE I DE C',
'SA DE CV SFOL',
'SA DE CV SFP',
'SA DE CV SIID PM',
'SA DE CV SIID',
'SA DE CV SIRV',
'SA DE CV SOFOM ENR',
'SA DE CV SOFOM ER',
'SA DE CV',
'SA DE RI DE CV',
'SA DE RI',
'SA DE RL DE CV',
'SA DE RL',
'SA SOFOM EN R',
'SA SOFOM ER',
'SA',
'SAB DE CV',
'SAB',
'SAPI DE CV',
'S A P I DE CV',
'SAPI DE CV,SOFOM,ENR',
'SAPI',
'SAS DE CV',
'SAS',
'SC DE C DE B Y S DE RL DE CV',
'SC DE C DE RL DE CV',
'SC DE C DE RL',
'SC DE C DE RS DE CV',
'SC DE C DE RS',
'SC DE CV DE RL',
'SC DE CV',
'SC DE P DE RL DE CV',
'SC DE P DE RL',
'SC DE P DE RS DE CV',
'SC DE P DE RS',
'SC DE RI',
'SC DE RL DE CV',
'SC DE RL DE IP Y CV',
'SC DE RL MI',
'SC DE RL',
'SC DE RS DE CV',
'SC DE RS',
'SC DE S DE RL DE CV',
'SC PBS RL',
'SC',
'SCAPRL de CV',
'SCL (LIMITADA)',
'SCL DE CV',
'SCP',
'SCP',
'SCPC DE RL DE CV',
'SCPR DE RL DE C V',
'SCS (SUPLEMENTADA)',
'SCU',
'SGC',
'SIEFORE',
'SIID',
'SIN TIPO DE SOCIEDAD',
'SL',
'SNC',
'SOCIEDAD CIVIL UNIVERSAL',
'SOCIEDAD COOPERATIVA DE RESPONSABILIDAD LIMITADA',
'SOCIEDAD COOPERATIVA',
'SOCIEDAD EN NOMBRE COLECTIVO',
'SOCIEDAD MUTUALISTA DE SEGUROS DE VIDA O DE DAÑOS',
'SOCIEDADES DE INVERSION COMUNES',
'SOCIEDADES DE INVERSION DE CAPITALES',
'SOCIEDADES DE INVERSIÓN',
'SOFOL',
'SP DE RL DE CV',
'SPA DE RL DE CV',
'SPR DE CV',
'SPR DE RI DE CV',
'SPR DE RI',
'SPR DE RL DE CV',
'SPR DE RL',
'SPR DE RS DE CV',
'SPR',
'U DE C',
'U DE E DE R L',
'U DE E',
'UE',
'USPR DE RI',
'USPR DE RL',
];
private string $regularExpression;
public function __construct(string ...$sufixes)
{
$sufixesPattern = implode('|', $sufixes);
if ('' === $sufixesPattern) {
throw new LogicException('No se han establecido sufijos para remover');
}
$this->regularExpression = '/ +(' . $sufixesPattern . ')$/i';
}
public static function createDefault(): self
{
return new self(...self::SUFFIXES);
}
public function remove(string $name): string
{
return preg_replace($this->regularExpression, '', $name);
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Utils/Format.php | src/CfdiUtils/Utils/Format.php | <?php
namespace CfdiUtils\Utils;
/**
* This class provides static methods to format the values of the attributes
*/
class Format
{
public static function number(float $value, int $decimals = 2): string
{
return number_format($value, $decimals, '.', '');
}
public static function datetime(int $timestamp): string
{
return date('Y-m-d\TH:i:s', $timestamp);
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Utils/Xml.php | src/CfdiUtils/Utils/Xml.php | <?php
namespace CfdiUtils\Utils;
use DOMDocument;
use DOMElement;
use DOMNode;
use LibXMLError;
class Xml
{
public static function documentElement(DOMDocument $document): DOMElement
{
if (! $document->documentElement instanceof DOMElement) {
throw new \UnexpectedValueException('DOM Document does not have root element');
}
return $document->documentElement;
}
public static function ownerDocument(DOMNode $node): DOMDocument
{
// $node->ownerDocument is NULL if node is a DOMDocument
if (null === $node->ownerDocument) {
if ($node instanceof DOMDocument) {
return $node;
}
/** @codeCoverageIgnore */
throw new \LogicException('node->ownerDocument is null but node is not a DOMDocument');
}
return $node->ownerDocument;
}
/**
* Creates a DOMDocument object version 1.0 encoding UTF-8
* with output formatting and not preserving white spaces
*/
public static function newDocument(): DOMDocument
{
$document = new DOMDocument('1.0', 'UTF-8');
$document->formatOutput = true;
$document->preserveWhiteSpace = false;
return $document;
}
public static function newDocumentContent(string $content): DOMDocument
{
if ('' === $content) {
throw new \UnexpectedValueException('Received xml string argument is empty');
}
$document = static::newDocument();
// this error silenced call is intentional, no need to alter libxml_use_internal_errors
if (false === @$document->loadXML($content)) {
throw new \UnexpectedValueException(
trim('Cannot create a DOM Document from xml string' . PHP_EOL . self::castLibXmlLastErrorAsString())
);
}
return $document;
}
private static function castLibXmlLastErrorAsString(): string
{
$error = libxml_get_last_error();
if (! $error instanceof LibXMLError) {
return '';
}
$types = [
LIBXML_ERR_NONE => 'None',
LIBXML_ERR_WARNING => 'Warning',
LIBXML_ERR_ERROR => 'Error',
LIBXML_ERR_FATAL => 'Fatal',
];
return sprintf(
'XML %s [L: %d, C: %d]: %s',
$types[$error->level] ?? 'Unknown',
$error->line,
$error->column,
$error->message
);
}
public static function isValidXmlName(string $name): bool
{
if ('' === $name) {
return false;
}
$pattern = '/^[:_A-Za-z'
. '\xC0-\xD6\xD8-\xF6\xF8-\x{2FF}\x{370}-\x{37D}\x{37F}-\x{1FFF}\x{200C}-\x{200D}\x{2070}-\x{218F}'
. '\x{2C00}-\x{2FEF}\x{3001}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFFD}\x{10000}-\x{EFFFF}]{1}'
. '[\-:_A-Za-z0-9'
. '\xC0-\xD6\xD8-\xF6\xF8-\x{2FF}\x{370}-\x{37D}\x{37F}-\x{1FFF}\x{200C}-\x{200D}\x{2070}-\x{218F}'
. '\x{2C00}-\x{2FEF}\x{3001}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFFD}\x{10000}-\x{EFFFF}'
. '\xB7\x{0300}-\x{036F}\x{203F}-\x{2040}]*$/u';
return 1 === preg_match($pattern, $name);
}
/**
* This is an alias of DOMDocument::createElement that will replace ampersand '&' with '&'
* @see https://www.php.net/manual/en/domdocument.createelement.php
*/
public static function createElement(DOMDocument $document, string $name, string $content = ''): DOMElement
{
return self::createDOMElement(
fn (): DOMElement|false => $document->createElement($name),
sprintf('Cannot create element with name %s', $name),
$content
);
}
/**
* This is an alias of DOMDocument::createElementNS that will replace ampersand '&' with '&'
* @see https://www.php.net/manual/en/domdocument.createelementns.php
*/
public static function createElementNS(
DOMDocument $document,
string $namespaceURI,
string $name,
string $content = '',
): DOMElement {
return self::createDOMElement(
fn (): DOMElement|false => $document->createElementNS($namespaceURI, $name),
sprintf('Cannot create element with name %s namespace %s', $name, $namespaceURI),
$content
);
}
private static function createDOMElement(\Closure $fnCreate, string $errorMessage, string $content): DOMElement
{
/** @var DOMElement|null $element */
$element = null;
$previousException = null;
try {
$element = $fnCreate();
} catch (\Throwable $creationException) {
$previousException = $creationException;
}
if (! $element instanceof DOMElement) {
throw new \LogicException($errorMessage, 0, $previousException);
}
if ('' !== $content) {
$element->appendChild(static::ownerDocument($element)->createTextNode($content));
}
return $element;
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Utils/CurrencyDecimals.php | src/CfdiUtils/Utils/CurrencyDecimals.php | <?php
namespace CfdiUtils\Utils;
class CurrencyDecimals
{
private string $currency;
private int $decimals;
public function __construct(string $currency, int $decimals)
{
if (! preg_match('/^[A-Z]{3}$/', $currency)) {
throw new \UnexpectedValueException('Property currency is not valid');
}
if ($decimals < 0) {
throw new \UnexpectedValueException('Property decimals cannot be less than zero');
}
$this->currency = $currency;
$this->decimals = $decimals;
}
public function currency(): string
{
return $this->currency;
}
public function decimals(): int
{
return $this->decimals;
}
public function round(float $value): float
{
return round($value, $this->decimals());
}
public function doesNotExceedDecimals(string $value): bool
{
// use pathinfo trick to retrieve the right part after the dot
return $this->decimalsCount($value) <= $this->decimals();
}
public static function decimalsCount(string $value): int
{
return strlen(pathinfo($value, PATHINFO_EXTENSION));
}
public static function newFromKnownCurrencies(string $currency, ?int $default = null): self
{
$decimals = static::knownCurrencyDecimals($currency);
if ($decimals < 0) {
if (null === $default) {
throw new \OutOfBoundsException('The currency %s is not known');
}
$decimals = $default;
}
return new self($currency, $decimals);
}
public static function knownCurrencyDecimals(string $currency): int
{
$map = [
'MXN' => 2,
'EUR' => 2,
'USD' => 2,
'XXX' => 0,
];
return array_key_exists($currency, $map) ? $map[$currency] : -1;
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Utils/SatNsDefinitionsMover.php | src/CfdiUtils/Utils/SatNsDefinitionsMover.php | <?php
namespace CfdiUtils\Utils;
use CfdiUtils\Nodes\NodeInterface;
use CfdiUtils\Nodes\NodeNsDefinitionsMover;
final class SatNsDefinitionsMover
{
public function move(NodeInterface $root): void
{
$nodeNsDefinitionsMover = new NodeNsDefinitionsMover();
$nodeNsDefinitionsMover->setNamespaceFilter(
fn (string $namespaceUri): bool => 'http://www.sat.gob.mx/' === (substr($namespaceUri, 0, 22) ?: '')
);
$nodeNsDefinitionsMover->process($root);
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Utils/SchemaLocations.php | src/CfdiUtils/Utils/SchemaLocations.php | <?php
namespace CfdiUtils\Utils;
use ArrayIterator;
use Countable;
use IteratorAggregate;
use Traversable;
class SchemaLocations implements Countable, IteratorAggregate
{
/** @var array<string, string> */
private array $pairs = [];
/**
* SchemaLocations constructor.
* @param array<string, string> $pairs
*/
public function __construct(array $pairs = [])
{
foreach ($pairs as $namespace => $location) {
$this->append($namespace, $location);
}
}
/**
* Create a collection of namespaces (key) and location (value)
*/
public static function fromString(string $schemaLocationValue, bool $includeLastUnpairedItem): self
{
$schemaLocations = new self();
$components = array_values(array_filter(explode(' ', $schemaLocationValue)));
$length = count($components);
for ($c = 0; $c < $length; $c = $c + 2) {
$location = $components[$c + 1] ?? '';
if ('' !== $location || $includeLastUnpairedItem) {
$schemaLocations->append($components[$c], $location);
}
}
return $schemaLocations;
}
/**
* Create a collection of namespaces (key) and location (value)
* All locations *must* end with '.xsd', If not they are considered namespaces
*/
public static function fromStingStrictXsd(string $schemaLocationValue): self
{
$schemaLocations = new self();
$components = array_values(array_filter(explode(' ', $schemaLocationValue)));
$length = count($components);
for ($c = 0; $c < $length; $c = $c + 1) {
$namespace = $components[$c];
$location = $components[$c + 1] ?? '';
if ('.xsd' === (substr($location, -4) ?: '')) {
$schemaLocations->append($namespace, $location);
$c = $c + 1; // skip ns declaration
continue;
}
$schemaLocations->append($namespace, '');
}
return $schemaLocations;
}
public function isEmpty(): bool
{
return [] === $this->pairs;
}
/**
* Return an array of pairs using namespace as key and location as value
*
* @return array<string, string>
*/
public function pairs(): array
{
return $this->pairs;
}
public function has(string $namespace): bool
{
return array_key_exists($namespace, $this->pairs);
}
/**
* Get an array with namespaces that has empty location
*
* @return string[]
*/
public function getNamespacesWithoutLocation(): array
{
return array_keys(array_filter($this->pairs, fn (string $location): bool => '' === $location));
}
public function hasAnyNamespaceWithoutLocation(): bool
{
return [] !== $this->getNamespacesWithoutLocation();
}
public function append(string $namespace, string $location): void
{
$this->pairs[$namespace] = $location;
}
public function remove(string $namespace): void
{
unset($this->pairs[$namespace]);
}
/**
* Return the collection of namespace location separated by spaces
*/
public function asString(): string
{
return implode(' ', array_filter(array_map(
function (string $namespace, string $location): string {
if ('' === $location) {
return '';
}
return $namespace . ' ' . $location;
},
array_keys($this->pairs),
$this->pairs
)));
}
/** @return Traversable<string, string> */
public function getIterator(): Traversable
{
return new ArrayIterator($this->pairs);
}
public function count(): int
{
return count($this->pairs);
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Utils/Rfc.php | src/CfdiUtils/Utils/Rfc.php | <?php
namespace CfdiUtils\Utils;
class Rfc implements \Stringable
{
public const RFC_GENERIC = 'XAXX010101000';
public const RFC_FOREIGN = 'XEXX010101000';
public const DISALLOW_GENERIC = 1;
public const DISALLOW_FOREIGN = 2;
private string $rfc;
private int $length;
/** @var string contains calculated checksum */
private string $checkSum;
private bool $checkSumMatch;
public function __construct(string $rfc, int $flags = 0)
{
$this->checkIsValid($rfc, $flags);
$this->rfc = $rfc;
$this->length = mb_strlen($rfc);
$this->checkSum = static::obtainCheckSum($rfc);
$this->checkSumMatch = ($this->checkSum === strval(substr($rfc, -1)));
}
public function rfc(): string
{
return $this->rfc;
}
public function isPerson(): bool
{
return 13 === $this->length;
}
public function isMoral(): bool
{
return 12 === $this->length;
}
public function isGeneric(): bool
{
return static::RFC_GENERIC === $this->rfc;
}
public function isForeign(): bool
{
return static::RFC_FOREIGN === $this->rfc;
}
public function checkSum(): string
{
return $this->checkSum;
}
public function checkSumMatch(): bool
{
return $this->checkSumMatch;
}
public function __toString(): string
{
return $this->rfc();
}
public static function isValid(string $value): bool
{
try {
static::checkIsValid($value);
return true;
} catch (\UnexpectedValueException) {
return false;
}
}
/**
* @throws \UnexpectedValueException when the value is generic and is not allowed by flags
* @throws \UnexpectedValueException when the value is foreign and is not allowed by flags
* @throws \UnexpectedValueException when the value does not match with the RFC format
* @throws \UnexpectedValueException when the date inside the value is not valid
* @throws \UnexpectedValueException when the last digit does not match the checksum
*/
public static function checkIsValid(string $value, int $flags = 0): void
{
if ($flags & static::DISALLOW_GENERIC && $value === static::RFC_GENERIC) {
throw new \UnexpectedValueException('No se permite el RFC genérico para público en general');
}
if ($flags & static::DISALLOW_FOREIGN && $value === static::RFC_FOREIGN) {
throw new \UnexpectedValueException('No se permite el RFC genérico para operaciones con extranjeros');
}
// validate agains a regular expression (values and length)
$regex = '/^' // desde el inicio
. '[A-ZÑ&]{3,4}' // letras y números para el nombre (3 para morales, 4 para físicas)
. '(\d{6})' // año mes y día, la validez de la fecha se comprueba después
. '[A-Z0-9]{2}[A0-9]{1}' // homoclave (letra o dígito 2 veces + A o dígito 1 vez)
. '$/u'; // hasta el final, considerar la cadena unicode
if (1 !== preg_match($regex, $value)) {
throw new \UnexpectedValueException('No coincide el formato de un RFC');
}
if (0 === static::obtainDate($value)) {
throw new \UnexpectedValueException('La fecha obtenida no es lógica');
}
}
public static function obtainCheckSum(string $rfc): string
{
// 'Ñ' translated to '#' due it is multibyte 0xC3 0xB1
$dictionary = array_flip(str_split('0123456789ABCDEFGHIJKLMN&OPQRSTUVWXYZ #', 1));
$chars = str_split(str_replace('Ñ', '#', $rfc), 1);
array_pop($chars); // remove predefined checksum
$length = count($chars);
$sum = (11 === $length) ? 481 : 0; // 481 para morales, 0 para físicas
$j = $length + 1;
foreach ($chars as $i => $char) {
$sum += ($dictionary[$char] ?? 0) * ($j - $i);
}
$digit = strval(11 - $sum % 11);
if ('11' === $digit) {
$digit = '0';
} elseif ('10' === $digit) {
$digit = 'A';
}
return $digit;
}
/**
* The date is always from the year 2000 since RFC does not provide century and 000229 is valid.
* Please, change this function on year 2100!
*/
public static function obtainDate(string $rfc): int
{
// rfc is multibyte
$begin = (12 === mb_strlen($rfc)) ? 3 : 4;
// strdate is not multibyte
$strdate = mb_substr($rfc, $begin, 6);
if (6 !== strlen($strdate)) {
return 0;
}
$parts = str_split($strdate, 2);
// year 2000 is leap year (%4 & %100 & %400)
$date = mktime(0, 0, 0, (int) $parts[1], (int) $parts[2], (int) ('20' . $parts[0]));
if (false === $date) {
/** @codeCoverageIgnore it is unlikely to enter this block */
return 0;
}
if (date('ymd', $date) !== $strdate) {
return 0;
}
return $date;
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/VersionDiscovery/DomElementContainer.php | src/CfdiUtils/VersionDiscovery/DomElementContainer.php | <?php
namespace CfdiUtils\VersionDiscovery;
use DOMElement;
class DomElementContainer implements ContainerWithAttributeInterface
{
public function __construct(private DOMElement $element)
{
}
public function getAttributeValue(string $attribute): string
{
return $this->element->getAttribute($attribute);
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/VersionDiscovery/VersionDiscoverer.php | src/CfdiUtils/VersionDiscovery/VersionDiscoverer.php | <?php
namespace CfdiUtils\VersionDiscovery;
use CfdiUtils\Nodes\NodeInterface;
use CfdiUtils\Utils\Xml;
use DOMDocument;
use DOMElement;
abstract class VersionDiscoverer
{
/**
* This method should be implemented and return array of key/value elements
* where the key is the version number
* and the value is the attribute to query
* @return array<string, string>
*/
abstract public function rules(): array;
public function discover(ContainerWithAttributeInterface $container)
{
foreach ($this->rules() as $versionNumber => $attribute) {
$currentValue = $container->getAttributeValue($attribute);
if ($versionNumber === $currentValue) {
return $versionNumber;
}
}
return '';
}
public function getFromDOMElement(DOMElement $element): string
{
return $this->discover(new DomElementContainer($element));
}
public function getFromDOMDocument(DOMDocument $document): string
{
return $this->getFromDOMElement(Xml::documentElement($document));
}
public function getFromNode(NodeInterface $node): string
{
return $this->discover(new NodeContainer($node));
}
public function getFromXmlString(string $contents): string
{
return $this->getFromDOMDocument(Xml::newDocumentContent($contents));
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/VersionDiscovery/ContainerWithAttributeInterface.php | src/CfdiUtils/VersionDiscovery/ContainerWithAttributeInterface.php | <?php
namespace CfdiUtils\VersionDiscovery;
interface ContainerWithAttributeInterface
{
public function getAttributeValue(string $attribute): string;
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/VersionDiscovery/NodeContainer.php | src/CfdiUtils/VersionDiscovery/NodeContainer.php | <?php
namespace CfdiUtils\VersionDiscovery;
use CfdiUtils\Nodes\NodeInterface;
class NodeContainer implements ContainerWithAttributeInterface
{
public function __construct(private NodeInterface $node)
{
}
public function getAttributeValue(string $attribute): string
{
return $this->node[$attribute];
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Retenciones/RetencionesCreator20.php | src/CfdiUtils/Retenciones/RetencionesCreator20.php | <?php
namespace CfdiUtils\Retenciones;
use CfdiUtils\CadenaOrigen\XsltBuilderInterface;
use CfdiUtils\CadenaOrigen\XsltBuilderPropertyInterface;
use CfdiUtils\CadenaOrigen\XsltBuilderPropertyTrait;
use CfdiUtils\Certificado\Certificado;
use CfdiUtils\Certificado\CertificadoPropertyInterface;
use CfdiUtils\Certificado\CertificadoPropertyTrait;
use CfdiUtils\Elements\Retenciones20\Retenciones;
use CfdiUtils\XmlResolver\XmlResolver;
use CfdiUtils\XmlResolver\XmlResolverPropertyInterface;
use CfdiUtils\XmlResolver\XmlResolverPropertyTrait;
class RetencionesCreator20 implements
CertificadoPropertyInterface,
XmlResolverPropertyInterface,
XsltBuilderPropertyInterface
{
use RetencionesCreatorTrait;
use CertificadoPropertyTrait;
use XmlResolverPropertyTrait;
use XsltBuilderPropertyTrait;
private Retenciones $retenciones;
public function __construct(
array $retencionesAttributes = [],
?XmlResolver $xmlResolver = null,
?XsltBuilderInterface $xsltBuilder = null,
?Certificado $certificado = null,
) {
$this->retenciones = new Retenciones();
$this->retencionesCreatorConstructor($retencionesAttributes, $certificado, $xmlResolver, $xsltBuilder);
}
public function retenciones(): Retenciones
{
/** @phpstan-var Retenciones PHPStan 1.10.13 identify retenciones as AbstractElement */
return $this->retenciones;
}
public function putCertificado(Certificado $certificado): void
{
$this->setCertificado($certificado);
$this->retenciones['NoCertificado'] = $certificado->getSerial();
$this->retenciones['Certificado'] = $certificado->getPemContentsOneLine();
// maybe put Emisor values from Certificate, as in CfdiCreatorTrait
}
public function buildCadenaDeOrigen(): string
{
return $this->buildCadenaDeOrigenFromXsltLocation(
'http://www.sat.gob.mx/esquemas/retencionpago/2/retenciones.xslt'
);
}
/** @internal This function is required by RetencionesCreatorTrait::addSello */
private function getSelloAlgorithm(): int
{
return OPENSSL_ALGO_SHA256;
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Retenciones/RetencionesCreatorTrait.php | src/CfdiUtils/Retenciones/RetencionesCreatorTrait.php | <?php
namespace CfdiUtils\Retenciones;
use CfdiUtils\CadenaOrigen\DOMBuilder;
use CfdiUtils\CadenaOrigen\XsltBuilderInterface;
use CfdiUtils\CadenaOrigen\XsltBuilderPropertyTrait;
use CfdiUtils\Certificado\Certificado;
use CfdiUtils\Certificado\CertificadoPropertyTrait;
use CfdiUtils\Elements\Common\AbstractElement;
use CfdiUtils\Nodes\XmlNodeUtils;
use CfdiUtils\PemPrivateKey\PemPrivateKey;
use CfdiUtils\Utils\SatNsDefinitionsMover;
use CfdiUtils\Validate\Asserts;
use CfdiUtils\Validate\Xml\XmlFollowSchema;
use CfdiUtils\XmlResolver\XmlResolver;
use CfdiUtils\XmlResolver\XmlResolverPropertyTrait;
/**
* @method void putCertificado(Certificado $certificado)
* @method string buildCadenaDeOrigen()
* @property AbstractElement $retenciones
*/
trait RetencionesCreatorTrait
{
use CertificadoPropertyTrait;
use XmlResolverPropertyTrait;
use XsltBuilderPropertyTrait;
private function retencionesCreatorConstructor(
array $retencionesAttributes = [],
?Certificado $certificado = null,
?XmlResolver $xmlResolver = null,
?XsltBuilderInterface $xsltBuilder = null,
): void {
$this->retenciones->addAttributes($retencionesAttributes);
$this->setXmlResolver($xmlResolver ?: new XmlResolver());
if (null !== $certificado) {
$this->putCertificado($certificado);
}
$this->setXsltBuilder($xsltBuilder ?: new DOMBuilder());
}
public function addSello(string $key, string $passPhrase = ''): void
{
// create private key
$privateKey = new PemPrivateKey($key);
if (! $privateKey->open($passPhrase)) {
throw new \RuntimeException('Cannot open the private key');
}
// check privatekey belongs to certificado
if (
$this->hasCertificado()
&& ! $privateKey->belongsTo($this->getCertificado()->getPemContents())
) {
throw new \RuntimeException('The private key does not belong to the current certificate');
}
// create sign and set into Sello attribute
$this->retenciones['Sello'] = base64_encode(
$privateKey->sign($this->buildCadenaDeOrigen(), $this->getSelloAlgorithm())
);
}
public function validate(): Asserts
{
$validator = new XmlFollowSchema();
$validator->setXmlResolver($this->getXmlResolver());
$asserts = new Asserts();
$validator->validate($this->retenciones, $asserts);
return $asserts;
}
public function asXml(): string
{
return XmlNodeUtils::nodeToXmlString($this->retenciones, true);
}
public function moveSatDefinitionsToRetenciones(): void
{
$mover = new SatNsDefinitionsMover();
$mover->move($this->retenciones);
}
private function buildCadenaDeOrigenFromXsltLocation(string $xsltLocation): string
{
if (! $this->hasXmlResolver()) {
throw new \LogicException('Cannot build the cadena de origen since there is no xml resolver');
}
if (! $this->hasXsltBuilder()) {
throw new \LogicException('Cannot build the cadena de origen since there is no xslt builder');
}
$xmlResolver = $this->getXmlResolver();
$xsltLocation = $xmlResolver->resolve($xsltLocation, $xmlResolver::TYPE_XSLT);
return $this->getXsltBuilder()->build($this->asXml(), $xsltLocation);
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Retenciones/RetencionesCreator10.php | src/CfdiUtils/Retenciones/RetencionesCreator10.php | <?php
namespace CfdiUtils\Retenciones;
use CfdiUtils\CadenaOrigen\XsltBuilderInterface;
use CfdiUtils\CadenaOrigen\XsltBuilderPropertyInterface;
use CfdiUtils\CadenaOrigen\XsltBuilderPropertyTrait;
use CfdiUtils\Certificado\Certificado;
use CfdiUtils\Certificado\CertificadoPropertyInterface;
use CfdiUtils\Certificado\CertificadoPropertyTrait;
use CfdiUtils\Elements\Retenciones10\Retenciones;
use CfdiUtils\XmlResolver\XmlResolver;
use CfdiUtils\XmlResolver\XmlResolverPropertyInterface;
use CfdiUtils\XmlResolver\XmlResolverPropertyTrait;
class RetencionesCreator10 implements
CertificadoPropertyInterface,
XmlResolverPropertyInterface,
XsltBuilderPropertyInterface
{
use RetencionesCreatorTrait;
use CertificadoPropertyTrait;
use XmlResolverPropertyTrait;
use XsltBuilderPropertyTrait;
private Retenciones $retenciones;
public function __construct(
array $retencionesAttributes = [],
?XmlResolver $xmlResolver = null,
?XsltBuilderInterface $xsltBuilder = null,
?Certificado $certificado = null,
) {
$this->retenciones = new Retenciones();
$this->retencionesCreatorConstructor($retencionesAttributes, $certificado, $xmlResolver, $xsltBuilder);
}
public function retenciones(): Retenciones
{
/** @phpstan-var Retenciones PHPStan 1.10.13 identify retenciones as AbstractElement */
return $this->retenciones;
}
public function putCertificado(Certificado $certificado): void
{
$this->setCertificado($certificado);
$this->retenciones['NumCert'] = $certificado->getSerial();
$this->retenciones['Cert'] = $certificado->getPemContentsOneLine();
}
public function buildCadenaDeOrigen(): string
{
return $this->buildCadenaDeOrigenFromXsltLocation(
'http://www.sat.gob.mx/esquemas/retencionpago/1/retenciones.xslt'
);
}
/** @internal This function is required by RetencionesCreatorTrait::addSello */
private function getSelloAlgorithm(): int
{
return OPENSSL_ALGO_SHA1;
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Retenciones/RetencionVersion.php | src/CfdiUtils/Retenciones/RetencionVersion.php | <?php
namespace CfdiUtils\Retenciones;
use CfdiUtils\VersionDiscovery\VersionDiscoverer;
/**
* This class provides static methods to retrieve the version attribute from a
* Comprobante Fiscal Digital por Internet que ampara retenciones e información de Pagos
*
* 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, 2.0 or empty string
*/
class RetencionVersion extends VersionDiscoverer
{
public function rules(): array
{
return [
'2.0' => '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/Retenciones/Retenciones.php | src/CfdiUtils/Retenciones/Retenciones.php | <?php
namespace CfdiUtils\Retenciones;
use CfdiUtils\CfdiCreateObjectException;
use CfdiUtils\Internals\XmlReaderTrait;
use DOMDocument;
use UnexpectedValueException;
/**
* This class contains minimum helpers to read CFDI Retenciones based on DOMDocument
*
* When the object is instantiated it checks that:
* implements the namespace static::RET_NAMESPACE using a prefix "retenciones"
* the root node is prefix:Retenciones
*
* This class also provides conversion to Node for easy access and manipulation,
* changes made in Node structure are not reflected into the DOMDocument,
* changes made in DOMDocument three are not reflected into the Node,
*
* Use this class as your starting point to read documents
*/
class Retenciones
{
use XmlReaderTrait;
/** @var array<string, string> Dictionary of versions and namespaces */
private const RET_SPECS = [
'2.0' => 'http://www.sat.gob.mx/esquemas/retencionpago/2',
'1.0' => 'http://www.sat.gob.mx/esquemas/retencionpago/1',
];
public function __construct(DOMDocument $document)
{
$retVersion = new RetencionVersion();
/** @var array<string, UnexpectedValueException> $exceptions */
$exceptions = [];
foreach (self::RET_SPECS as $version => $namespace) {
try {
$this->loadDocumentWithNamespace($retVersion, $document, $namespace);
return;
} catch (UnexpectedValueException $exception) {
$exceptions[$version] = $exception;
}
}
throw CfdiCreateObjectException::withVersionExceptions($exceptions);
}
/** @throws UnexpectedValueException */
private function loadDocumentWithNamespace(
RetencionVersion $retVersion,
DOMDocument $document,
string $namespace,
): void {
$rootElement = self::checkRootElement($document, $namespace, 'retenciones', 'Retenciones');
$this->version = $retVersion->getFromDOMElement($rootElement);
$this->document = clone $document;
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Nodes/Nodes.php | src/CfdiUtils/Nodes/Nodes.php | <?php
namespace CfdiUtils\Nodes;
use ArrayIterator;
use Countable;
use IteratorAggregate;
use Traversable;
/**
* @implements IteratorAggregate<int, NodeInterface>
*/
class Nodes implements Countable, IteratorAggregate
{
/** @var NodeInterface[] */
private array $nodes = [];
private NodesSorter $sorter;
/**
* Nodes constructor.
* @param NodeInterface[] $nodes
*/
public function __construct(array $nodes = [])
{
$this->sorter = new NodesSorter();
$this->importFromArray($nodes);
}
public function add(NodeInterface ...$nodes): self
{
$somethingChange = false;
foreach ($nodes as $node) {
if (! $this->exists($node)) {
$this->nodes[] = $node;
$somethingChange = true;
}
}
if ($somethingChange) {
$this->order();
}
return $this;
}
public function order(): void
{
$this->nodes = $this->sorter->sort($this->nodes);
}
/**
* It takes only the unique string names and sort using the order of appearance
* @param string[] $names
*/
public function setOrder(array $names): void
{
if ($this->sorter->setOrder($names)) {
$this->order();
}
}
/** @return string[] */
public function getOrder(): array
{
return $this->sorter->getOrder();
}
public function indexOf(NodeInterface $node): int
{
if (false === $index = array_search($node, $this->nodes, true)) {
$index = -1;
}
return (int) $index;
}
public function remove(NodeInterface $node): self
{
$index = $this->indexOf($node);
if ($index >= 0) {
unset($this->nodes[$index]);
}
return $this;
}
public function removeAll(): self
{
$this->nodes = [];
return $this;
}
public function exists(NodeInterface $node): bool
{
return $this->indexOf($node) >= 0;
}
public function first(): ?NodeInterface
{
foreach ($this->nodes as $node) {
return $node;
}
return null;
}
public function get(int $position): NodeInterface
{
$indexedNodes = array_values($this->nodes);
if (! array_key_exists($position, $indexedNodes)) {
throw new \OutOfRangeException("The index $position does not exists");
}
return $indexedNodes[$position];
}
public function firstNodeWithName(string $nodeName): ?NodeInterface
{
foreach ($this->nodes as $node) {
if ($node->name() === $nodeName) {
return $node;
}
}
return null;
}
public function getNodesByName(string $nodeName): self
{
$nodes = new self();
foreach ($this->nodes as $node) {
if ($node->name() === $nodeName) {
$nodes->add($node);
}
}
return $nodes;
}
/**
* @param NodeInterface[] $nodes
*/
public function importFromArray(array $nodes): self
{
foreach ($nodes as $index => $node) {
if (! ($node instanceof NodeInterface)) {
throw new \InvalidArgumentException("The element index $index is not a NodeInterface object");
}
}
$this->add(...$nodes);
return $this;
}
/** @return Traversable<int, NodeInterface> */
public function getIterator(): Traversable
{
return new ArrayIterator($this->nodes);
}
public function count(): int
{
return count($this->nodes);
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Nodes/NodeNsDefinitionsMover.php | src/CfdiUtils/Nodes/NodeNsDefinitionsMover.php | <?php
namespace CfdiUtils\Nodes;
use CfdiUtils\Utils\SchemaLocations;
class NodeNsDefinitionsMover
{
/** @var callable|null */
private $namespaceFilter;
public function __construct()
{
$this->setNamespaceFilter();
}
public function hasNamespaceFilter(): bool
{
return null !== $this->namespaceFilter;
}
public function getNamespaceFilter(): ?callable
{
return $this->namespaceFilter;
}
public function setNamespaceFilter(?callable $filter = null): self
{
$this->namespaceFilter = $filter;
return $this;
}
public function process(NodeInterface $root): void
{
$rootSchemaLocation = SchemaLocations::fromString($root['xsi:schemaLocation'], false);
$this->processRecursive($root->children(), $root, $rootSchemaLocation);
if (! $rootSchemaLocation->isEmpty()) {
$root['xsi:schemaLocation'] = $rootSchemaLocation->asString();
}
}
protected function processRecursive(Nodes $children, NodeInterface $root, SchemaLocations $schemaLocations): void
{
/** @var NodeInterface $child */
foreach ($children as $child) {
$this->moveXmlNs($child, $root);
$this->moveXsiSchemaLocation($child, $schemaLocations);
$this->processRecursive($child->children(), $root, $schemaLocations);
}
}
protected function moveXmlNs(NodeInterface $child, NodeInterface $root): void
{
$prefix = explode(':', $child->name(), 2)[0];
if ($child->name() === $prefix) {
return; // it does not have a prefix
}
$xmlns = 'xmlns:' . $prefix;
if (! isset($child[$xmlns])) {
return; // it does not have a definition
}
if (! $this->filterNamespace($child[$xmlns])) {
return; // it did not pass the namespace filter
}
$root->addAttributes([$xmlns => $child[$xmlns]]);
$child->addAttributes([$xmlns => null]);
}
protected function moveXsiSchemaLocation(NodeInterface $child, SchemaLocations $rootSchemaLocations): void
{
if (! isset($child['xsi:schemaLocation'])) {
return;
}
$childSchemaLocations = SchemaLocations::fromString($child['xsi:schemaLocation'], false);
foreach ($childSchemaLocations as $namespace => $location) {
if (! $this->filterNamespace($namespace)) {
continue;
}
if (! $rootSchemaLocations->has($namespace)) {
$rootSchemaLocations->append($namespace, $location);
}
}
foreach ($rootSchemaLocations as $namespace => $location) {
$childSchemaLocations->remove($namespace);
}
$child->addAttributes([
'xsi:schemaLocation' => $childSchemaLocations->isEmpty() ? null : $childSchemaLocations->asString(),
]);
}
public function filterNamespace(string $namespace): bool
{
if (! is_callable($this->namespaceFilter)) {
return true;
}
return boolval(call_user_func($this->namespaceFilter, $namespace));
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Nodes/Attributes.php | src/CfdiUtils/Nodes/Attributes.php | <?php
namespace CfdiUtils\Nodes;
use CfdiUtils\Utils\Xml;
use Traversable;
class Attributes implements \Countable, \IteratorAggregate, \ArrayAccess
{
/** @var array<string, string> */
private array $attributes = [];
public function __construct(array $attributes = [])
{
$this->importArray($attributes);
}
public function get(string $name): string
{
if (! array_key_exists($name, $this->attributes)) {
return '';
}
return $this->attributes[$name];
}
/**
* Set a value in the collection
*
* @param string|null $value If null then it will remove the value instead of setting to empty string
*/
public function set(string $name, ?string $value = null): self
{
if (null === $value) {
$this->remove($name);
return $this;
}
if (! Xml::isValidXmlName($name)) {
throw new \UnexpectedValueException(sprintf('Cannot set attribute with an invalid xml name: "%s"', $name));
}
$this->attributes[$name] = $value;
return $this;
}
public function remove(string $name): self
{
unset($this->attributes[$name]);
return $this;
}
public function removeAll(): self
{
$this->attributes = [];
return $this;
}
public function exists(string $name): bool
{
return array_key_exists($name, $this->attributes);
}
public function importArray(array $attributes): self
{
foreach ($attributes as $key => $value) {
$this->set($key, $this->castValueToString($key, $value));
}
return $this;
}
public function exportArray(): array
{
return $this->attributes;
}
/**
* @param mixed $value
*/
private function castValueToString(string $key, $value): ?string
{
if (null === $value) {
return null;
}
if (is_scalar($value)) {
return strval($value);
}
if (is_object($value) && is_callable([$value, '__toString'])) {
/**
* PHPStan false positive on cast object<Stringable> to string
* @var \Stringable $value
*/
return strval($value);
}
throw new \InvalidArgumentException(sprintf('Cannot convert value of attribute %s to string', $key));
}
/** @return Traversable<string, string> */
public function getIterator(): Traversable
{
return new \ArrayIterator($this->attributes);
}
#[\ReturnTypeWillChange]
public function offsetExists($offset)
{
return $this->exists((string) $offset);
}
#[\ReturnTypeWillChange]
public function offsetGet($offset)
{
return $this->get((string) $offset);
}
#[\ReturnTypeWillChange]
public function offsetSet($offset, $value): void
{
$offset = strval($offset);
$this->set($offset, $this->castValueToString($offset, $value));
}
#[\ReturnTypeWillChange]
public function offsetUnset($offset): void
{
$this->remove((string) $offset);
}
public function count(): int
{
return count($this->attributes);
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Nodes/XmlNodeUtils.php | src/CfdiUtils/Nodes/XmlNodeUtils.php | <?php
namespace CfdiUtils\Nodes;
use CfdiUtils\Utils\Xml;
use DOMElement;
use SimpleXMLElement;
class XmlNodeUtils
{
public static function nodeToXmlElement(NodeInterface $node): DOMElement
{
return (new XmlNodeExporter())->export($node);
}
public static function nodeToXmlString(NodeInterface $node, $withXmlHeader = false): string
{
$element = static::nodeToXmlElement($node);
if ($withXmlHeader) {
return $element->ownerDocument->saveXML();
}
return $element->ownerDocument->saveXML($element);
}
public static function nodeToSimpleXmlElement(NodeInterface $node): SimpleXMLElement
{
$element = static::nodeToXmlElement($node);
$simpleXmlElement = simplexml_import_dom($element);
if (! $simpleXmlElement instanceof SimpleXMLElement) {
throw new \InvalidArgumentException('Cannot convert to SimpleXmlElement');
}
return $simpleXmlElement;
}
public static function nodeFromXmlElement(DOMElement $element): NodeInterface
{
return (new XmlNodeImporter())->import($element);
}
public static function nodeFromXmlString(string $content): NodeInterface
{
return static::nodeFromXmlElement(Xml::documentElement(Xml::newDocumentContent($content)));
}
public static function nodeFromSimpleXmlElement(SimpleXMLElement $element): NodeInterface
{
return static::nodeFromXmlString((string) $element->asXML());
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Nodes/XmlNodeExporter.php | src/CfdiUtils/Nodes/XmlNodeExporter.php | <?php
namespace CfdiUtils\Nodes;
use CfdiUtils\Utils\Xml;
use DOMDocument;
use DOMElement;
class XmlNodeExporter
{
public function export(NodeInterface $node): DOMElement
{
$document = Xml::newDocument();
$rootElement = $this->exportRecursive($document, $node);
$document->appendChild($rootElement);
return $rootElement;
}
private function exportRecursive(DOMDocument $document, NodeInterface $node): DOMElement
{
$element = $document->createElement($node->name());
foreach ($node->attributes() as $name => $value) {
$element->setAttribute($name, $value);
}
foreach ($node->children() as $child) {
$childElement = $this->exportRecursive($document, $child);
$element->appendChild($childElement);
}
if ('' !== $node->value()) {
$element->appendChild($document->createTextNode($node->value()));
}
return $element;
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Nodes/Node.php | src/CfdiUtils/Nodes/Node.php | <?php
namespace CfdiUtils\Nodes;
use CfdiUtils\Utils\Xml;
use Traversable;
class Node implements NodeInterface
{
private string $name;
private Attributes $attributes;
/** @var Nodes|NodeInterface[] */
private Nodes $children;
/**
* Node constructor.
* @param NodeInterface[] $children
*/
public function __construct(string $name, array $attributes = [], array $children = [], private string $value = '')
{
if (! Xml::isValidXmlName($name)) {
throw new \UnexpectedValueException(sprintf('Cannot create a node with an invalid xml name: "%s"', $name));
}
$this->name = $name;
$this->attributes = new Attributes($attributes);
$this->children = new Nodes($children);
}
public function name(): string
{
return $this->name;
}
public function children(): Nodes
{
return $this->children;
}
public function addChild(NodeInterface $node): NodeInterface
{
$this->children->add($node);
return $node;
}
/**
* @return Attributes|string[]
*/
public function attributes(): Attributes
{
return $this->attributes;
}
public function clear(): void
{
$this->attributes->removeAll();
$this->children()->removeAll();
}
public function addAttributes(array $attributes): void
{
$this->attributes->importArray($attributes);
}
public function exists(string $attribute): bool
{
return $this->attributes->exists($attribute);
}
public function value(): string
{
return $this->value;
}
public function setValue(string $value): void
{
$this->value = $value;
}
/*
* Search methods
*/
public function searchAttribute(string ...$searchPath): string
{
$attribute = array_pop($searchPath);
$node = $this->searchNode(...$searchPath);
return (null !== $node) ? $node[$attribute] : '';
}
public function searchNodes(string ...$searchPath): Nodes
{
$nodes = new Nodes();
$nodeName = array_pop($searchPath);
$parent = $this->searchNode(...$searchPath);
if (null !== $parent) {
foreach ($parent->children() as $child) {
if ($child->name() === $nodeName) {
$nodes->add($child);
}
}
}
return $nodes;
}
public function searchNode(string ...$searchPath): ?NodeInterface
{
$node = $this;
foreach ($searchPath as $searchName) {
$node = $node->children()->firstNodeWithName($searchName);
if (null === $node) {
break;
}
}
return $node;
}
/*
* Array access implementation as attribute helpers
*/
#[\ReturnTypeWillChange]
public function offsetExists($offset)
{
return $this->exists(strval($offset));
}
#[\ReturnTypeWillChange]
public function offsetGet($offset)
{
return $this->attributes[$offset];
}
#[\ReturnTypeWillChange]
public function offsetSet($offset, $value): void
{
$this->attributes[$offset] = $value;
}
#[\ReturnTypeWillChange]
public function offsetUnset($offset): void
{
unset($this->attributes[$offset]);
}
/*
* other interfaces
*/
public function count(): int
{
return $this->children->count();
}
/** @return Traversable<NodeInterface> */
public function getIterator(): Traversable
{
return $this->children->getIterator();
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Nodes/NodesSorter.php | src/CfdiUtils/Nodes/NodesSorter.php | <?php
namespace CfdiUtils\Nodes;
/**
* This class is used to sort elements by name in a Nodes collection
* @internal
*/
class NodesSorter
{
/** @var array<string, int> array of key (string) value (int) representing the naming order */
private array $order = [];
private int $count = 0;
public function __construct(array $order = [])
{
$this->setOrder($order);
}
/**
* It takes only the unique string names and sort using the order of appearance
* @param string[] $names
* @return bool true if the new names list is different from previous
*/
public function setOrder(array $names): bool
{
$order = array_flip($this->parseNames($names));
if ($this->order === $order) {
return false;
}
$this->order = $order;
$this->count = count($order);
return true;
}
/**
* @return string[]
*/
public function parseNames(array $names): array
{
$isValidName = (fn ($name): bool => is_string($name) && $name);
return array_values(array_unique(array_filter($names, $isValidName)));
}
/**
* The current order list
* @return string[]
*/
public function getOrder(): array
{
return array_flip($this->order);
}
/**
* @param NodeInterface[] $nodes
* @return NodeInterface[]
*/
public function sort(array $nodes): array
{
if ($this->count > 0) {
// do not use simple usort since usort is not "stable"
// usort does not respect the previous order.
$nodes = $this->stableArraySort($nodes, [$this, 'compareNodesByName']);
}
return $nodes;
}
public function compareNodesByName(NodeInterface $a, NodeInterface $b): int
{
return $this->valueByName($a->name()) <=> $this->valueByName($b->name());
}
public function valueByName(string $name): int
{
return $this->order[$name] ?? $this->count;
}
/*
* This function is a replacement for usort that try to usort
* but if items are equal then uses the relative position as second argument
*/
private function stableArraySort(array $input, callable $function): array
{
// create the item list with the item and the index
$list = [];
foreach (array_values($input) as $i => $value) {
$item = new \stdClass();
$item->item = $value;
$item->index = $i;
$list[] = $item;
}
// perform the usort, if comparison is equal then compare the index also
usort($list, function (\stdClass $first, \stdClass $second) use ($function) {
$value = $function($first->item, $second->item);
if (0 === $value) {
$value = $first->index <=> $second->index;
}
return $value;
});
// return only the items
return array_column($list, 'item');
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Nodes/XmlNodeImporter.php | src/CfdiUtils/Nodes/XmlNodeImporter.php | <?php
namespace CfdiUtils\Nodes;
use DOMElement;
use DOMNode;
use DOMText;
class XmlNodeImporter
{
/**
* Local record for registered namespaces to avoid set the namespace declaration in every child
* @var string[]
*/
private array $registeredNamespaces = [];
public function import(DOMElement $element): NodeInterface
{
$node = new Node($element->tagName);
$node->setValue($this->extractValue($element));
if ('' !== $element->prefix) {
$this->registerNamespace($node, 'xmlns:' . $element->prefix, $element->namespaceURI);
$this->registerNamespace($node, 'xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
}
/** @var DOMNode $attribute */
foreach ($element->attributes as $attribute) {
$node[$attribute->nodeName] = $attribute->nodeValue;
}
// element is like <element namespace="uri"/>
if ($element->hasAttributeNS('http://www.w3.org/2000/xmlns/', '')) {
$node['xmlns'] = $element->getAttributeNS('http://www.w3.org/2000/xmlns/', '');
}
/** @var DOMElement $childElement */
foreach ($element->childNodes as $childElement) {
if (! $childElement instanceof DOMElement) {
continue;
}
$childNode = $this->import($childElement);
$node->children()->add($childNode);
}
return $node;
}
private function registerNamespace(Node $node, string $prefix, string $uri): void
{
if (isset($this->registeredNamespaces[$prefix])) {
return;
}
$this->registeredNamespaces[$prefix] = $uri;
$node[$prefix] = $uri;
}
private function extractValue(DOMElement $element): string
{
$values = [];
foreach ($element->childNodes as $childElement) {
if (! $childElement instanceof DOMText) {
continue;
}
$values[] = $childElement->wholeText;
}
return implode('', $values);
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Nodes/NodeInterface.php | src/CfdiUtils/Nodes/NodeInterface.php | <?php
namespace CfdiUtils\Nodes;
interface NodeInterface extends \ArrayAccess, \Countable, \IteratorAggregate
{
public function name(): string;
public function children(): Nodes;
public function addChild(self $node): self;
public function attributes(): Attributes;
public function addAttributes(array $attributes);
public function exists(string $attribute): bool;
public function value(): string;
public function setValue(string $value): void;
public function clear();
public function searchAttribute(string ...$searchPath): string;
public function searchNodes(string ...$searchPath): Nodes;
public function searchNode(string ...$searchPath): ?self;
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/PemPrivateKey/PemPrivateKey.php | src/CfdiUtils/PemPrivateKey/PemPrivateKey.php | <?php
namespace CfdiUtils\PemPrivateKey;
use CfdiUtils\OpenSSL\OpenSSL;
use CfdiUtils\OpenSSL\OpenSSLPropertyTrait;
use OpenSSLAsymmetricKey;
use UnexpectedValueException;
class PemPrivateKey
{
use OpenSSLPropertyTrait;
private string $contents;
private ?OpenSSLAsymmetricKey $privatekey = null;
/**
* Create a private key helper class based on a private key PEM formatted
* The key argument can be:
* - file location starting with 'file://'
* - file contents
*
* @throws UnexpectedValueException if the file is not PEM format
*/
public function __construct(string $key, ?OpenSSL $openSSL = null)
{
$this->setOpenSSL($openSSL ?: new OpenSSL());
try {
if (str_starts_with($key, 'file://')) {
$filename = substr($key, 7);
$contents = $this->getOpenSSL()->readPemFile($filename)->privateKey();
} else {
$contents = $this->getOpenSSL()->readPemContents($key)->privateKey();
}
if ('' === $contents) {
throw new \RuntimeException('Empty key');
}
} catch (\Throwable $exc) {
throw new UnexpectedValueException('The key is not a file or a string PEM format private key', 0, $exc);
}
$this->contents = $contents;
}
public function __destruct()
{
$this->close();
}
public function __clone()
{
$this->privatekey = null;
}
public function __sleep()
{
return ['contents'];
}
public function open(string $passPhrase): bool
{
$this->close();
$pKey = openssl_pkey_get_private($this->contents, $passPhrase);
if (false === $pKey) {
return false;
}
$this->privatekey = $pKey;
return true;
}
public function close(): void
{
$this->privatekey = null;
}
public function isOpen(): bool
{
return $this->privatekey instanceof OpenSSLAsymmetricKey;
}
private function getOpenPrivateKey(): OpenSSLAsymmetricKey
{
if (! $this->privatekey instanceof OpenSSLAsymmetricKey) {
throw new \RuntimeException('The private key is not open');
}
return $this->privatekey;
}
public function sign(string $data, int $algorithm = OPENSSL_ALGO_SHA256): string
{
if (false === openssl_sign($data, $signature, $this->getOpenPrivateKey(), $algorithm)) {
$signature = '';
}
if ('' === $signature) {
throw new \RuntimeException('Cannot create the sign data');
}
return $signature;
}
public function belongsTo(string $pemContents): bool
{
return openssl_x509_check_private_key($pemContents, $this->getOpenPrivateKey());
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/CadenaOrigen/SaxonbCliBuilder.php | src/CfdiUtils/CadenaOrigen/SaxonbCliBuilder.php | <?php
namespace CfdiUtils\CadenaOrigen;
use CfdiUtils\Internals\TemporaryFile;
use Symfony\Component\Process\Process;
class SaxonbCliBuilder extends AbstractXsltBuilder
{
private string $executablePath;
public function __construct(string $executablePath)
{
$this->setExecutablePath($executablePath);
}
public function getExecutablePath(): string
{
return $this->executablePath;
}
public function setExecutablePath(string $executablePath): void
{
if ('' === $executablePath) {
throw new \UnexpectedValueException('The executable path for SabonB cannot be empty');
}
$this->executablePath = $executablePath;
}
public function build(string $xmlContent, string $xsltLocation): string
{
$this->assertBuildArguments($xmlContent, $xsltLocation);
$executable = $this->getExecutablePath();
if (! file_exists($executable)) {
throw new XsltBuildException('The executable path for SabonB does not exists');
}
if (is_dir($executable)) {
throw new XsltBuildException('The executable path for SabonB is a directory');
}
if (! is_executable($executable)) {
throw new XsltBuildException('The executable path for SabonB is not executable');
}
$temporaryFile = TemporaryFile::create();
return $temporaryFile->runAndRemove(
function () use ($temporaryFile, $xmlContent, $xsltLocation): string {
$temporaryFile->storeContents($xmlContent);
$command = [
$this->getExecutablePath(),
'-s:' . $temporaryFile->getPath(),
'-xsl:' . $xsltLocation,
'-warnings:silent', // default recover
];
$process = new Process($command);
$exitCode = $process->run();
if (0 !== $exitCode) {
throw new XsltBuildException(
sprintf('Transformation error: %s', $process->getErrorOutput() ?: '(no output error)')
);
}
$output = trim($process->getOutput());
if ('<?xml version="1.0" encoding="UTF-8"?>' === $output) {
throw new XsltBuildException('Transformation error: XML without root element');
}
return $output;
}
);
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/CadenaOrigen/DOMBuilder.php | src/CfdiUtils/CadenaOrigen/DOMBuilder.php | <?php
namespace CfdiUtils\CadenaOrigen;
use DOMDocument;
use LibXMLError;
use XSLTProcessor;
class DOMBuilder extends AbstractXsltBuilder
{
public function build(string $xmlContent, string $xsltLocation): string
{
$this->assertBuildArguments($xmlContent, $xsltLocation);
$libxmlErrors = libxml_use_internal_errors(true);
try {
// load the xml document
$xml = new DOMDocument();
if (! $xml->loadXML($xmlContent)) {
throw $this->createLibXmlErrorOrMessage('Error while loading the xml content');
}
$xsl = new DOMDocument();
if (! $xsl->load($xsltLocation)) {
throw $this->createLibXmlErrorOrMessage('Error while loading the Xslt location');
}
return $this->transform($xml, $xsl);
} finally {
libxml_clear_errors();
libxml_use_internal_errors($libxmlErrors);
}
}
protected function transform(DOMDocument $xml, DOMDocument $xsl): string
{
$xslt = new XSLTProcessor();
if (! $xslt->importStylesheet($xsl)) {
throw $this->createLibXmlErrorOrMessage('Error while importing the style sheet from the Xslt location');
}
// this error silenced call is intentional, avoid transformation errors except when return false
/** @var string|null|false $transform */
$transform = @$xslt->transformToXml($xml);
if (null === $transform || false === $transform) {
throw $this->createLibXmlErrorOrMessage('Error while transforming the xslt content');
}
return $transform;
}
protected function createLibXmlErrorOrMessage(string $message): XsltBuildException
{
$error = libxml_get_last_error();
if (($error instanceof LibXMLError) && isset($error->message)) {
$message = $message . ': ' . $error->message;
}
return new XsltBuildException($message);
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/CadenaOrigen/CfdiDefaultLocations.php | src/CfdiUtils/CadenaOrigen/CfdiDefaultLocations.php | <?php
namespace CfdiUtils\CadenaOrigen;
class CfdiDefaultLocations
{
public const XSLT_32 = 'http://www.sat.gob.mx/sitio_internet/cfd/3/cadenaoriginal_3_2/cadenaoriginal_3_2.xslt';
public const XSLT_33 = 'http://www.sat.gob.mx/sitio_internet/cfd/3/cadenaoriginal_3_3/cadenaoriginal_3_3.xslt';
public const XSLT_40 = 'http://www.sat.gob.mx/sitio_internet/cfd/4/cadenaoriginal_4_0/cadenaoriginal_4_0.xslt';
public static function location(string $version): string
{
if ('4.0' === $version) {
return static::XSLT_40;
}
if ('3.3' === $version) {
return static::XSLT_33;
}
if ('3.2' === $version) {
return static::XSLT_32;
}
throw new \UnexpectedValueException("Cannot get the default xslt location for version '$version'");
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/CadenaOrigen/GenkgoXslBuilder.php | src/CfdiUtils/CadenaOrigen/GenkgoXslBuilder.php | <?php
namespace CfdiUtils\CadenaOrigen;
use DOMDocument;
use Genkgo\Xsl\Cache\NullCache;
use Genkgo\Xsl\Exception\TransformationException;
use Genkgo\Xsl\XsltProcessor;
class GenkgoXslBuilder extends DOMBuilder
{
public function __construct()
{
if (! class_exists(XsltProcessor::class)) {
throw new \RuntimeException('To use GenkgoXslBuilder you must install genkgo/xsl'); // @codeCoverageIgnore
}
}
protected function transform(DOMDocument $xml, DOMDocument $xsl): string
{
$xslt = new XsltProcessor(new NullCache());
$xslt->importStylesheet($xsl);
try {
$transform = $xslt->transformToXML($xml);
} catch (TransformationException $exception) {
throw new XsltBuildException('Error while transforming the xslt content', 0, $exception);
}
if (null === $transform) {
throw $this->createLibXmlErrorOrMessage('Error while transforming the xslt content');
}
return $transform;
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/CadenaOrigen/AbstractXsltBuilder.php | src/CfdiUtils/CadenaOrigen/AbstractXsltBuilder.php | <?php
namespace CfdiUtils\CadenaOrigen;
abstract class AbstractXsltBuilder implements XsltBuilderInterface
{
protected function assertBuildArguments(string $xmlContent, string $xsltLocation): string
{
if ('' === $xmlContent) {
throw new \UnexpectedValueException('The XML content to transform is empty');
}
if ('' === $xsltLocation) {
throw new \UnexpectedValueException('Xslt location was not set');
}
return '';
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/CadenaOrigen/XsltBuilderPropertyTrait.php | src/CfdiUtils/CadenaOrigen/XsltBuilderPropertyTrait.php | <?php
namespace CfdiUtils\CadenaOrigen;
trait XsltBuilderPropertyTrait
{
private ?XsltBuilderInterface $xsltBuilder = null;
public function hasXsltBuilder(): bool
{
return $this->xsltBuilder instanceof XsltBuilderInterface;
}
public function getXsltBuilder(): XsltBuilderInterface
{
if (! $this->xsltBuilder instanceof XsltBuilderInterface) {
throw new \LogicException('There is no current xsltBuilder');
}
return $this->xsltBuilder;
}
public function setXsltBuilder(?XsltBuilderInterface $xsltBuilder = null): void
{
$this->xsltBuilder = $xsltBuilder;
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/CadenaOrigen/XsltBuildException.php | src/CfdiUtils/CadenaOrigen/XsltBuildException.php | <?php
namespace CfdiUtils\CadenaOrigen;
class XsltBuildException extends \RuntimeException
{
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/CadenaOrigen/XsltBuilderPropertyInterface.php | src/CfdiUtils/CadenaOrigen/XsltBuilderPropertyInterface.php | <?php
namespace CfdiUtils\CadenaOrigen;
interface XsltBuilderPropertyInterface
{
public function hasXsltBuilder(): bool;
public function getXsltBuilder(): XsltBuilderInterface;
public function setXsltBuilder(?XsltBuilderInterface $xsltBuilder = null);
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/CadenaOrigen/XsltBuilderInterface.php | src/CfdiUtils/CadenaOrigen/XsltBuilderInterface.php | <?php
namespace CfdiUtils\CadenaOrigen;
interface XsltBuilderInterface
{
/**
* Transform XML content to a string using XSLT
*
* @throws \UnexpectedValueException if the xml content is empty
* @throws \UnexpectedValueException if the xslt location is empty
* @throws \RuntimeException on procedural errors
*/
public function build(string $xmlContent, string $xsltLocation): string;
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/OpenSSL/OpenSSLException.php | src/CfdiUtils/OpenSSL/OpenSSLException.php | <?php
namespace CfdiUtils\OpenSSL;
class OpenSSLException extends \RuntimeException
{
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/OpenSSL/OpenSSLCallerException.php | src/CfdiUtils/OpenSSL/OpenSSLCallerException.php | <?php
namespace CfdiUtils\OpenSSL;
use Throwable;
class OpenSSLCallerException extends OpenSSLException
{
public function __construct(
private CallResponse $execResult,
string $message = 'OpenSSL execution error',
int $code = 0,
?Throwable $previous = null,
) {
parent::__construct($message, $code, $previous);
}
public function getCallResponse(): CallResponse
{
return $this->execResult;
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/OpenSSL/PemContainer.php | src/CfdiUtils/OpenSSL/PemContainer.php | <?php
namespace CfdiUtils\OpenSSL;
class PemContainer
{
public function __construct(private string $certificate, private string $publicKey, private string $privateKey)
{
}
public function certificate(): string
{
return $this->certificate;
}
public function publicKey(): string
{
return $this->publicKey;
}
public function privateKey(): string
{
return $this->privateKey;
}
public function hasAny(): bool
{
return $this->hasCertificate() || $this->hasPublicKey() || $this->hasPrivateKey();
}
public function hasCertificate(): bool
{
return '' !== $this->certificate;
}
public function hasPublicKey(): bool
{
return '' !== $this->publicKey;
}
public function hasPrivateKey(): bool
{
return '' !== $this->privateKey;
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/OpenSSL/CallResponse.php | src/CfdiUtils/OpenSSL/CallResponse.php | <?php
namespace CfdiUtils\OpenSSL;
class CallResponse
{
public function __construct(
private string $commandLine,
private string $output,
private string $errors,
private int $exitStatus,
) {
}
public function commandLine(): string
{
return $this->commandLine;
}
public function output(): string
{
return $this->output;
}
public function errors(): string
{
return $this->errors;
}
public function exitStatus(): int
{
return $this->exitStatus;
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/OpenSSL/PemExtractor.php | src/CfdiUtils/OpenSSL/PemExtractor.php | <?php
namespace CfdiUtils\OpenSSL;
use CfdiUtils\Internals\NormalizeLineEndingsTrait;
class PemExtractor
{
use NormalizeLineEndingsTrait;
public function __construct(private string $contents)
{
}
public function getContents(): string
{
return $this->contents;
}
public function extractCertificate(): string
{
return $this->extractBase64('CERTIFICATE');
}
public function extractPublicKey(): string
{
return $this->extractBase64('PUBLIC KEY');
}
public function extractPrivateKey(): string
{
if ('' !== $extracted = $this->extractBase64('PRIVATE KEY')) {
return $extracted;
}
if ('' !== $extracted = $this->extractBase64('RSA PRIVATE KEY')) {
return $extracted;
}
if ('' !== $extracted = $this->extractRsaProtected()) {
return $extracted;
}
return $this->extractBase64('ENCRYPTED PRIVATE KEY');
}
protected function extractBase64(string $type): string
{
$matches = [];
$type = preg_quote($type, '/');
$pattern = '/^'
. '-----BEGIN ' . $type . '-----\r?\n'
. '([A-Za-z0-9+\/=]+\r?\n)+'
. '-----END ' . $type . '-----\r?\n?'
. '$/m';
preg_match($pattern, $this->getContents(), $matches);
return $this->normalizeLineEndings(strval($matches[0] ?? ''));
}
protected function extractRsaProtected(): string
{
$matches = [];
$pattern = '/^'
. '-----BEGIN RSA PRIVATE KEY-----\r?\n'
. 'Proc-Type: .+\r?\n'
. 'DEK-Info: .+\r?\n\r?\n'
. '([A-Za-z0-9+\/=]+\r?\n)+'
. '-----END RSA PRIVATE KEY-----\r?\n?'
. '$/m';
preg_match($pattern, $this->getContents(), $matches);
return $this->normalizeLineEndings(strval($matches[0] ?? ''));
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/OpenSSL/OpenSSL.php | src/CfdiUtils/OpenSSL/OpenSSL.php | <?php
namespace CfdiUtils\OpenSSL;
use CfdiUtils\Internals\NormalizeLineEndingsTrait;
use CfdiUtils\Internals\TemporaryFile;
class OpenSSL
{
use NormalizeLineEndingsTrait;
private Caller $caller;
public function __construct(string $opensslCommand = '')
{
$this->caller = new Caller($opensslCommand);
}
public function getOpenSSLCommand(): string
{
return $this->caller->getExecutable();
}
public function readPemFile(string $pemFile): PemContainer
{
$this->checkInputFile($pemFile);
return $this->readPemContents(strval(file_get_contents($pemFile)));
}
public function readPemContents(string $contents): PemContainer
{
$extractor = new PemExtractor($contents);
return new PemContainer(
$extractor->extractCertificate(),
$extractor->extractPublicKey(),
$extractor->extractPrivateKey()
);
}
public function derCerConvertPhp(string $derContent): string
{
return '-----BEGIN CERTIFICATE-----' . PHP_EOL
. chunk_split(base64_encode($derContent), 64, PHP_EOL)
. '-----END CERTIFICATE-----';
}
public function derCerConvert(string $derInFile, string $pemOutFile): void
{
$this->checkInputFile($derInFile);
$this->checkOutputFile($pemOutFile);
$this->caller->call(
'x509 -inform DER -in ? -outform PEM -out ?',
[$derInFile, $pemOutFile]
);
}
public function derCerConvertOut(string $derInFile): string
{
$pemOutFile = TemporaryFile::create();
return $pemOutFile->runAndRemove(
function () use ($derInFile, $pemOutFile): string {
$this->derCerConvert($derInFile, $pemOutFile);
return $this->normalizeLineEndings($pemOutFile->retriveContents());
}
);
}
public function derCerConvertInOut(string $derContents): string
{
$derInFile = TemporaryFile::create();
return $derInFile->runAndRemove(
function () use ($derInFile, $derContents): string {
$derInFile->storeContents($derContents);
return $this->derCerConvertOut($derInFile);
}
);
}
public function derKeyConvert(string $derInFile, string $inPassPhrase, string $pemOutFile): void
{
$this->checkInputFile($derInFile);
$this->checkOutputFile($pemOutFile);
$this->caller->call(
'pkcs8 -inform DER -in ? -passin env:PASSIN -out ?',
[$derInFile, $pemOutFile],
['PASSIN' => $inPassPhrase]
);
}
public function derKeyConvertOut(string $derInFile, string $inPassPhrase): string
{
$pemOutFile = TemporaryFile::create();
return $pemOutFile->runAndRemove(
function () use ($derInFile, $inPassPhrase, $pemOutFile): string {
$this->derKeyConvert($derInFile, $inPassPhrase, $pemOutFile);
return $this->normalizeLineEndings($pemOutFile->retriveContents());
}
);
}
public function derKeyProtect(
string $derInFile,
string $inPassPhrase,
string $pemOutFile,
string $outPassPhrase,
): void {
$tempfile = TemporaryFile::create();
$tempfile->runAndRemove(
function () use ($derInFile, $inPassPhrase, $tempfile, $pemOutFile, $outPassPhrase): void {
$this->derKeyConvert($derInFile, $inPassPhrase, $tempfile);
$this->pemKeyProtect($tempfile, '', $pemOutFile, $outPassPhrase);
}
);
}
public function derKeyProtectOut(string $pemInFile, string $inPassPhrase, string $outPassPhrase): string
{
$pemOutFile = TemporaryFile::create();
return $pemOutFile->runAndRemove(
function () use ($pemInFile, $inPassPhrase, $pemOutFile, $outPassPhrase): string {
$this->derKeyProtect($pemInFile, $inPassPhrase, $pemOutFile, $outPassPhrase);
return $this->normalizeLineEndings($pemOutFile->retriveContents());
}
);
}
public function pemKeyProtect(
string $pemInFile,
string $inPassPhrase,
string $pemOutFile,
string $outPassPhrase,
): void {
if ('' === $outPassPhrase) {
$this->pemKeyUnprotect($pemInFile, $inPassPhrase, $pemOutFile);
return;
}
$this->checkInputFile($pemInFile);
$this->checkOutputFile($pemOutFile);
$this->caller->call(
'rsa -in ? -passin env:PASSIN -des3 -out ? -passout env:PASSOUT',
[$pemInFile, $pemOutFile],
['PASSIN' => $inPassPhrase, 'PASSOUT' => $outPassPhrase]
);
}
public function pemKeyProtectOut(string $pemInFile, string $inPassPhrase, string $outPassPhrase): string
{
$pemOutFile = TemporaryFile::create();
return $pemOutFile->runAndRemove(
function () use ($pemInFile, $inPassPhrase, $pemOutFile, $outPassPhrase): string {
$this->pemKeyProtect($pemInFile, $inPassPhrase, $pemOutFile, $outPassPhrase);
return $this->normalizeLineEndings($pemOutFile->retriveContents());
}
);
}
public function pemKeyProtectInOut(string $pemContents, string $inPassPhrase, string $outPassPhrase): string
{
$pemInFile = TemporaryFile::create();
return $pemInFile->runAndRemove(
function () use ($pemInFile, $pemContents, $inPassPhrase, $outPassPhrase): string {
$pemInFile->storeContents($pemContents);
return $this->pemKeyProtectOut($pemInFile, $inPassPhrase, $outPassPhrase);
}
);
}
public function pemKeyUnprotect(string $pemInFile, string $inPassPhrase, string $pemOutFile): void
{
$this->checkInputFile($pemInFile);
$this->checkOutputFile($pemOutFile);
$this->caller->call(
'rsa -in ? -passin env:PASSIN -out ?',
[$pemInFile, $pemOutFile],
['PASSIN' => $inPassPhrase]
);
}
public function pemKeyUnprotectOut(string $pemInFile, string $inPassPhrase): string
{
$pemOutFile = TemporaryFile::create();
return $pemOutFile->runAndRemove(
function () use ($pemInFile, $inPassPhrase, $pemOutFile): string {
$this->pemKeyUnprotect($pemInFile, $inPassPhrase, $pemOutFile);
return $this->normalizeLineEndings($pemOutFile->retriveContents());
}
);
}
public function pemKeyUnprotectInOut(string $pemContents, string $inPassPhrase): string
{
$pemInFile = TemporaryFile::create();
return $pemInFile->runAndRemove(
function () use ($pemInFile, $pemContents, $inPassPhrase): string {
$pemInFile->storeContents($pemContents);
return $this->pemKeyUnprotectOut($pemInFile, $inPassPhrase);
}
);
}
protected function checkInputFile(string $path): void
{
// file must exists, not a directory and must contain a non-zero size
if ('' === $path) {
throw new OpenSSLException('File argument is empty');
}
if (! file_exists($path)) {
throw new OpenSSLException("File $path does not exists");
}
if (is_dir($path)) {
throw new OpenSSLException("File $path is a directory");
}
if (0 === filesize($path)) {
throw new OpenSSLException("File $path is empty");
}
}
protected function checkOutputFile(string $path): void
{
// file should not exists or exists but contain a zero size
if ('' === $path) {
throw new OpenSSLException('File argument is empty');
}
if (! file_exists($path)) {
if (! is_dir(dirname($path))) {
throw new OpenSSLException("Directory of $path does not exists");
}
return;
}
if (is_dir($path)) {
throw new OpenSSLException("File $path is a directory");
}
if (filesize($path) > 0) {
throw new OpenSSLException("File $path is not empty");
}
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/OpenSSL/OpenSSLPropertyTrait.php | src/CfdiUtils/OpenSSL/OpenSSLPropertyTrait.php | <?php
namespace CfdiUtils\OpenSSL;
trait OpenSSLPropertyTrait
{
/**
* Variable to store the instance of OpenSSL
* You must set this property on the constructor of the class that uses this property,
* otherwise getOpenSSL will fail
*
* To get this property is recommended to use getOpenSSL
* To set this property is recommended to use setOpenSSL
*
* @internal
*/
private OpenSSL $openSSL;
public function getOpenSSL(): OpenSSL
{
return $this->openSSL;
}
protected function setOpenSSL(OpenSSL $openSSL): void
{
$this->openSSL = $openSSL;
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/OpenSSL/Caller.php | src/CfdiUtils/OpenSSL/Caller.php | <?php
namespace CfdiUtils\OpenSSL;
use CfdiUtils\Internals\CommandTemplate;
use Symfony\Component\Process\Process;
use Throwable;
class Caller
{
public const DEFAULT_OPENSSL_EXECUTABLE = 'openssl';
private string $executable;
public function __construct(string $executable = '')
{
$this->executable = $executable ?: static::DEFAULT_OPENSSL_EXECUTABLE;
}
public function getExecutable(): string
{
return $this->executable;
}
public function call(string $template, array $arguments, array $environment = []): CallResponse
{
try {
// build command for process run
array_unshift($arguments, $this->getExecutable());
$command = $this->createCommandTemplate()->create('? ' . $template, $arguments);
// create Process
$process = $this->createProcess($command, $environment);
} catch (Throwable $exception) {
throw new OpenSSLException('Unable to build command', 0, $exception);
}
// execute process
try {
$execution = $process->run();
} catch (Throwable $exception) {
throw new OpenSSLException('Unable to run command', 0, $exception);
}
// build response
$callResponse = new CallResponse(
$process->getCommandLine(),
$process->getOutput(),
$process->getErrorOutput(),
$execution
);
// eval response
if (0 !== $execution) {
throw new OpenSSLCallerException($callResponse);
}
return $callResponse;
}
protected function createProcess(array $command, array $environment): Process
{
return new Process($command, null, $environment);
}
protected function createCommandTemplate(): CommandTemplate
{
return new CommandTemplate();
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Cleaner/Cleaner.php | src/CfdiUtils/Cleaner/Cleaner.php | <?php
namespace CfdiUtils\Cleaner;
use CfdiUtils\Cfdi;
use CfdiUtils\Cleaner\BeforeLoad\BeforeLoadCleanerInterface;
use CfdiUtils\Cleaner\Cleaners\SchemaLocationsXsdUrlsFixer;
use CfdiUtils\Utils\SchemaLocations;
use CfdiUtils\Utils\Xml;
use DOMAttr;
use DOMDocument;
use DOMNode;
use DOMNodeList;
use DOMXPath;
use LogicException;
use Throwable;
/**
* Class to clean CFDI and avoid bad common practices.
*
* Strictly speaking, CFDI must accomplish all XML rules, including that any other
* XML element must be isolated in its own namespace and follow their own XSD rules.
*
* The common practice (allowed by SAT) is that the CFDI is created, signed and
* some nodes are attached after sign, some of them does not follow the XML standard.
*
* This is why it's better to clear Comprobante/Addenda and remove unused namespaces
*/
class Cleaner
{
protected ?DOMDocument $dom = null;
private BeforeLoadCleanerInterface $beforeLoadCleaner;
public function __construct(string $content, ?BeforeLoadCleanerInterface $beforeLoadCleaner = null)
{
$this->beforeLoadCleaner = $beforeLoadCleaner ?? new BeforeLoad\BeforeLoadCleaner();
if ('' !== $content) {
$this->load($content);
}
}
/**
* Method to clean content and return the result
* If an error occurs, an exception is thrown
*/
public static function staticClean(string $content): string
{
$cleaner = new self($content);
$cleaner->clean();
return $cleaner->retrieveXml();
}
/**
* Check if the CFDI version is compatible to this class
*/
public static function isVersionAllowed(string $version): bool
{
return in_array($version, ['3.2', '3.3', '4.0']);
}
/**
* Check if a given namespace is allowed (must not be removed from CFDI)
*/
public static function isNameSpaceAllowed(string $namespace): bool
{
return (
'http://www.w3.org/' === (substr($namespace, 0, 18) ?: '')
|| 'http://www.sat.gob.mx/' === (substr($namespace, 0, 22) ?: '')
);
}
/**
* Apply all removals (Addenda, Non SAT Nodes and Non SAT namespaces)
*/
public function clean(): void
{
$this->removeAddenda();
$this->removeIncompleteSchemaLocations();
$this->removeNonSatNSNodes();
$this->removeNonSatNSschemaLocations();
$this->removeUnusedNamespaces();
$this->collapseComprobanteComplemento();
$this->fixKnownSchemaLocationsXsdUrls();
}
/**
* Load the string content as a CFDI
* This is exposed to reuse the current object instead of create a new instance
*
*
* @throws CleanerException when the content is not valid xml
* @throws CleanerException when the document does not use the namespace http://www.sat.gob.mx/cfd/3
* @throws CleanerException when cannot find a Comprobante version (or Version) attribute
* @throws CleanerException when the version is not compatible
*/
public function load(string $content): void
{
try {
$content = $this->beforeLoadCleaner->clean($content);
$cfdi = Cfdi::newFromString($content);
} catch (Throwable $exception) {
throw new CleanerException($exception->getMessage(), $exception->getCode(), $exception->getPrevious());
}
$version = $cfdi->getVersion();
if (! $this->isVersionAllowed($version)) {
throw new CleanerException("The CFDI version '$version' is not allowed");
}
$this->dom = $cfdi->getDocument();
}
/**
* Get the XML content of the CFDI
*/
public function retrieveXml(): string
{
return $this->dom()->saveXML();
}
/**
* Get a clone of the XML DOM Document of the CFDI
*/
public function retrieveDocument(): DOMDocument
{
return clone $this->dom();
}
/**
* Procedure to remove the Comprobante/Addenda node
*/
public function removeAddenda(): void
{
$query = '/cfdi:Comprobante/cfdi:Addenda';
$addendas = $this->xpathQuery($query);
foreach ($addendas as $addenda) {
$addenda->parentNode->removeChild($addenda);
}
}
/**
* Procedure to drop schemaLocations where second part does not end with '.xsd'
*/
public function removeIncompleteSchemaLocations(): void
{
foreach ($this->obtainXsiSchemaLocations() as $attribute) {
$attribute->nodeValue = $this->removeIncompleteSchemaLocation($attribute->nodeValue);
}
}
private function removeIncompleteSchemaLocation(string $source): string
{
$schemaLocations = SchemaLocations::fromStingStrictXsd($source);
foreach ($schemaLocations->getNamespacesWithoutLocation() as $namespace) {
$schemaLocations->remove($namespace);
}
return $schemaLocations->asString();
}
/**
* Procedure to drop schemaLocations that are not allowed
* If the schemaLocation is empty then remove the attribute
*/
public function removeNonSatNSschemaLocations(): void
{
$schemaLocations = $this->obtainXsiSchemaLocations();
foreach ($schemaLocations as $attribute) {
$this->removeNonSatNSschemaLocation($attribute);
}
}
private function removeNonSatNSschemaLocation(DOMAttr $schemaLocation): void
{
$source = $schemaLocation->nodeValue;
// load locations
$schemaLocations = SchemaLocations::fromString($source, true);
if ($schemaLocations->hasAnyNamespaceWithoutLocation()) {
throw new CleanerException(
sprintf("The schemaLocation value '%s' must have even number of URIs", $source)
);
}
// filter
foreach ($schemaLocations as $namespace => $location) {
if (! $this->isNameSpaceAllowed($namespace)) {
$schemaLocations->remove($namespace);
}
}
// apply
$modified = $schemaLocations->asString();
if ($schemaLocations->isEmpty()) { // remove node
$schemaLocation->ownerElement->removeAttributeNode($schemaLocation);
} elseif ($source !== $modified) { // replace node content and is different
$schemaLocation->nodeValue = $modified;
}
}
/**
* Procedure to remove all nodes that are not from an allowed namespace
*/
public function removeNonSatNSNodes(): void
{
$nss = $this->obtainNamespaces();
foreach ($nss as $namespace) {
if (! $this->isNameSpaceAllowed($namespace)) {
$this->removeNonSatNSNode($namespace);
}
}
}
/**
* Procedure to remove all nodes from a specific namespace
*/
private function removeNonSatNSNode(string $namespace): void
{
foreach ($this->dom()->getElementsByTagNameNS($namespace, '*') as $children) {
$children->parentNode->removeChild($children);
}
}
/**
* Procedure to remove not allowed xmlns definitions
*/
public function removeUnusedNamespaces(): void
{
$nss = [];
$dom = $this->dom();
$namespaces = $this->obtainNamespaces();
foreach ($namespaces as $namespace) {
if (! $namespace || $this->isNameSpaceAllowed($namespace)) {
continue;
}
$prefix = $dom->lookupPrefix($namespace);
$nss[$prefix] = $namespace;
}
$documentElement = Xml::documentElement($dom);
foreach ($nss as $prefix => $namespace) {
$documentElement->removeAttributeNS($namespace, $prefix);
}
}
/**
* Procedure to collapse Complemento elements from Comprobante
* Collapse will take its children and put then on the first Complemento found
*/
public function collapseComprobanteComplemento(): void
{
$comprobante = Xml::documentElement($this->dom());
$complementos = $this->xpathQuery('./cfdi:Complemento', $comprobante);
if ($complementos->length < 2) {
return; // nothing to do, there are less than 2 complemento
}
$first = null;
/** @var DOMNode $extra */
foreach ($complementos as $extra) { // iterate over all extra children
if (null === $first) {
$first = $extra;
continue;
}
$comprobante->removeChild($extra); // remove extra child from parent
while ($extra->childNodes->length > 0) { // append extra child contents into first child
/** @var DOMNode $child */
$child = $extra->childNodes->item(0);
$extra->removeChild($child);
$first->appendChild($child);
}
}
}
/**
* Procedure to fix XSD known location paths for CFDI and TFD
*/
public function fixKnownSchemaLocationsXsdUrls(): void
{
$xsiLocations = $this->obtainXsiSchemaLocations();
$schemasFixer = SchemaLocationsXsdUrlsFixer::createWithKnownSatUrls();
foreach ($xsiLocations as $attribute) {
$schemasFixer->fixSchemaLocationAttribute($attribute);
}
}
/** @return DOMNodeList<DOMAttr> */
private function obtainXsiSchemaLocations(): DOMNodeList
{
// Do not assume that prefix for http://www.w3.org/2001/XMLSchema-instance is "xsi"
$xsi = $this->dom()->lookupPrefix('http://www.w3.org/2001/XMLSchema-instance');
if (! $xsi) {
return new DOMNodeList();
}
return $this->xpathQuery("//@$xsi:schemaLocation");
}
/** @return string[] */
private function obtainNamespaces(): array
{
return array_unique(array_column(iterator_to_array($this->xpathQuery('//namespace::*')), 'nodeValue'));
}
/**
* Helper function to perform a XPath query using an element (or root element)
*/
private function xpathQuery(string $query, ?DOMNode $element = null): DOMNodeList
{
if (null === $element) {
$document = $this->dom();
$element = Xml::documentElement($document);
} else {
$document = Xml::ownerDocument($element);
}
$nodelist = (new DOMXPath($document))->query($query, $element);
if (false === $nodelist) {
$nodelist = new DOMNodeList();
}
return $nodelist;
}
private function dom(): DOMDocument
{
if (null === $this->dom) {
throw new LogicException('No document has been loaded');
}
return $this->dom;
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Cleaner/CleanerException.php | src/CfdiUtils/Cleaner/CleanerException.php | <?php
namespace CfdiUtils\Cleaner;
class CleanerException extends \RuntimeException
{
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Cleaner/Cleaners/SchemaLocationsXsdUrlsFixer.php | src/CfdiUtils/Cleaner/Cleaners/SchemaLocationsXsdUrlsFixer.php | <?php
declare(strict_types=1);
namespace CfdiUtils\Cleaner\Cleaners;
use CfdiUtils\Internals\StringUncaseReplacer;
use CfdiUtils\Utils\SchemaLocations;
use DOMAttr;
/**
* Class SchemaLocationsXsdUrlsFixer
*
* This class is an abstraction of method Cleaner::fixKnownSchemaLocationsXsdUrls
*
* @internal
*/
final class SchemaLocationsXsdUrlsFixer
{
private StringUncaseReplacer $replacer;
/**
* Create a new instance based on a map using keys as replacement and values as an array of needles
*
* @param array<string, array<string>> $replacements
*/
private function __construct(array $replacements)
{
$this->replacer = StringUncaseReplacer::create($replacements);
}
/**
* Created a new instance based on known CFDI and TFD
* It also includes the incorrect but allowed TFD 1.0 alternate urls
*/
public static function createWithKnownSatUrls(): self
{
return new self([
'http://www.sat.gob.mx/sitio_internet/cfd/4/cfdv40.xsd' => [],
'http://www.sat.gob.mx/sitio_internet/cfd/3/cfdv33.xsd' => [],
'http://www.sat.gob.mx/sitio_internet/cfd/3/cfdv32.xsd' => [],
'http://www.sat.gob.mx/sitio_internet/cfd/3/cfdv3.xsd' => [],
'http://www.sat.gob.mx/sitio_internet/cfd/2/cfdv22.xsd' => [],
'http://www.sat.gob.mx/sitio_internet/cfd/2/cfdv2.xsd' => [],
'http://www.sat.gob.mx/sitio_internet/cfd/1/cfdv1.xsd' => [],
'http://www.sat.gob.mx/sitio_internet/cfd/TimbreFiscalDigital/TimbreFiscalDigitalv11.xsd' => [],
'http://www.sat.gob.mx/sitio_internet/cfd/TimbreFiscalDigital/TimbreFiscalDigital.xsd' => [
'http://www.sat.gob.mx/sitio_internet/TimbreFiscalDigital/TimbreFiscalDigital.xsd',
],
]);
}
public function fixSchemaLocationAttribute(DOMAttr $xsiSchemaLocation): void
{
$schemas = SchemaLocations::fromString($xsiSchemaLocation->value, false);
$this->fixSchemaLocations($schemas);
$fixedValue = $schemas->asString();
if ($xsiSchemaLocation->value !== $fixedValue) {
$xsiSchemaLocation->value = $fixedValue;
}
}
public function fixSchemaLocations(SchemaLocations $schemaLocations): void
{
foreach ($schemaLocations as $ns => $url) {
$url = $this->replacer->findReplacement($url) ?: $url;
$schemaLocations->append($ns, $url);
}
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Cleaner/BeforeLoad/ChangeXmlnsSchemaLocation.php | src/CfdiUtils/Cleaner/BeforeLoad/ChangeXmlnsSchemaLocation.php | <?php
namespace CfdiUtils\Cleaner\BeforeLoad;
class ChangeXmlnsSchemaLocation implements BeforeLoadCleanerInterface
{
public function clean(string $content): string
{
return str_replace(' xmlns:schemaLocation="', ' xsi:schemaLocation="', $content);
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Cleaner/BeforeLoad/BeforeLoadCleaner.php | src/CfdiUtils/Cleaner/BeforeLoad/BeforeLoadCleaner.php | <?php
namespace CfdiUtils\Cleaner\BeforeLoad;
class BeforeLoadCleaner implements BeforeLoadCleanerInterface
{
/** @var BeforeLoadCleanerInterface[] */
private array $cleaners;
public function __construct(BeforeLoadCleanerInterface ...$cleaners)
{
if ([] === $cleaners) {
$cleaners = $this->defaultCleaners();
}
$this->cleaners = $cleaners;
}
/** @return BeforeLoadCleanerInterface[] */
public static function defaultCleaners(): array
{
return [
new ChangeXmlnsSchemaLocation(),
new RemoveDuplicatedCfdi3Namespace(),
];
}
/** @return BeforeLoadCleanerInterface[] */
public function members(): array
{
return $this->cleaners;
}
public function clean(string $content): string
{
foreach ($this->cleaners as $cleaner) {
$content = $cleaner->clean($content);
}
return $content;
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Cleaner/BeforeLoad/BeforeLoadCleanerInterface.php | src/CfdiUtils/Cleaner/BeforeLoad/BeforeLoadCleanerInterface.php | <?php
namespace CfdiUtils\Cleaner\BeforeLoad;
interface BeforeLoadCleanerInterface
{
public function clean(string $content): string;
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Cleaner/BeforeLoad/RemoveDuplicatedCfdi3Namespace.php | src/CfdiUtils/Cleaner/BeforeLoad/RemoveDuplicatedCfdi3Namespace.php | <?php
namespace CfdiUtils\Cleaner\BeforeLoad;
class RemoveDuplicatedCfdi3Namespace implements BeforeLoadCleanerInterface
{
public function clean(string $content): string
{
if (
str_contains($content, ' xmlns="http://www.sat.gob.mx/cfd/3"')
&& str_contains($content, ' xmlns:cfdi="http://www.sat.gob.mx/cfd/3"')
) {
$content = str_replace(' xmlns="http://www.sat.gob.mx/cfd/3"', '', $content);
}
return $content;
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/SumasPagos20/Decimal.php | src/CfdiUtils/SumasPagos20/Decimal.php | <?php
/** @noinspection PhpComposerExtensionStubsInspection */
namespace CfdiUtils\SumasPagos20;
use JsonSerializable;
final class Decimal implements JsonSerializable, \Stringable
{
public const SCALE = 24;
public function __construct(private string $value)
{
}
public function getValue(): string
{
return $this->value;
}
public function sum(self $other, int $scale = self::SCALE): self
{
return new self(bcadd($this->value, $other->value, $scale));
}
public function multiply(self $other, int $scale = self::SCALE): self
{
return new self(bcmul($this->value, $other->value, $scale));
}
public function divide(self $other, int $scale = self::SCALE): self
{
return new self(bcdiv($this->value, $other->value, $scale));
}
public function round(int $decimals): self
{
$exp = bcpow('10', strval($decimals + 1));
$offset = (bccomp($this->value, '0', $decimals) < 0) ? '-5' : '5';
return new self(bcdiv(bcadd(bcmul($this->value, $exp, 0), $offset), $exp, $decimals));
}
public function truncate(int $decimals): self
{
return new self(bcadd($this->value, '0', $decimals));
}
public function __toString(): string
{
return $this->value;
}
public function jsonSerialize(): string
{
return $this->value;
}
public function compareTo(self $other): int
{
return bccomp($this->value, $other->value, self::SCALE);
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/SumasPagos20/Impuestos.php | src/CfdiUtils/SumasPagos20/Impuestos.php | <?php
namespace CfdiUtils\SumasPagos20;
use JsonSerializable;
use LogicException;
final class Impuestos implements JsonSerializable
{
/** @var array<string, Impuesto> */
private array $impuestos = [];
public function __construct(Impuesto ...$impuestos)
{
foreach ($impuestos as $impuesto) {
$this->impuestos[$impuesto->getKey()] = $impuesto;
}
}
/** @param array<string, Impuesto> $impuestos */
private function withImpuestos(array $impuestos): self
{
$object = new self();
$object->impuestos = $impuestos;
return $object;
}
public function find(string $tipo, string $impuesto, string $tipoFactor = '', string $tasaCuota = ''): ?Impuesto
{
$key = Impuesto::buildKey($tipo, $impuesto, $tipoFactor, $tasaCuota);
if (! isset($this->impuestos[$key])) {
return null;
}
return $this->impuestos[$key];
}
public function get(string $tipo, string $impuesto, string $tipoFactor = '', string $tasaCuota = ''): Impuesto
{
$impuesto = $this->find($tipo, $impuesto, $tipoFactor, $tasaCuota);
if (null === $impuesto) {
throw new LogicException(sprintf(
'No se pudo encontrar el %s impuesto "%s", tipo factor "%s", tasa o cuota "%s"',
$tipo,
$impuesto,
$tipoFactor,
$tasaCuota
));
}
return $impuesto;
}
/** @return list<Impuesto> */
public function getTraslados(): array
{
return $this->filterByTipo('Traslado');
}
public function getTraslado(string $impuesto, string $tipoFactor, string $tasaCuota): Impuesto
{
return $this->get('Traslado', $impuesto, $tipoFactor, $tasaCuota);
}
/** @return list<Impuesto> */
public function getRetenciones(): array
{
return $this->filterByTipo('Retencion');
}
public function getRetencion(string $impuesto): Impuesto
{
return $this->get('Retencion', $impuesto);
}
public function aggregate(self $other): self
{
$impuestos = $this->impuestos;
foreach ($other->impuestos as $key => $impuesto) {
$impuestos[$key] = (isset($impuestos[$key])) ? $impuesto->add($impuestos[$key]) : $impuesto;
}
return $this->withImpuestos($impuestos);
}
public function truncate(int $decimals): self
{
$impuestos = $this->impuestos;
foreach ($impuestos as $key => $impuesto) {
$impuestos[$key] = $impuesto->truncate($decimals);
}
return $this->withImpuestos($impuestos);
}
public function multiply(Decimal $value): self
{
$impuestos = $this->impuestos;
foreach ($impuestos as $key => $impuesto) {
$impuestos[$key] = $impuesto->multiply($value);
}
return $this->withImpuestos($impuestos);
}
public function round(int $decimals): self
{
$impuestos = $this->impuestos;
foreach ($impuestos as $key => $impuesto) {
$impuestos[$key] = $impuesto->round($decimals);
}
return $this->withImpuestos($impuestos);
}
/** @return array<string, Impuesto> */
public function jsonSerialize(): array
{
return $this->impuestos;
}
/** @return list<Impuesto> */
private function filterByTipo(string $tipo): array
{
return array_values(array_filter(
$this->impuestos,
fn (Impuesto $impuesto): bool => $impuesto->getTipo() === $tipo
));
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/SumasPagos20/Currencies.php | src/CfdiUtils/SumasPagos20/Currencies.php | <?php
namespace CfdiUtils\SumasPagos20;
class Currencies
{
/** @var array<string, int> */
private ?array $currencyAllowedDecimals = null;
/** @param array<string, int> $currencyAllowedDecimals */
public function __construct(array $currencyAllowedDecimals)
{
foreach ($currencyAllowedDecimals as $currency => $decimals) {
$this->currencyAllowedDecimals[$currency] = min(4, max(0, $decimals));
}
}
public function get($currency): int
{
return $this->currencyAllowedDecimals[$currency] ?? 2;
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/SumasPagos20/Pagos.php | src/CfdiUtils/SumasPagos20/Pagos.php | <?php
namespace CfdiUtils\SumasPagos20;
use JsonSerializable;
class Pagos implements JsonSerializable
{
/** @var list<Pago> */
private array $pagos;
public function __construct(private Totales $totales, Pago ...$pago)
{
$this->pagos = array_values($pago);
}
public function getTotales(): Totales
{
return $this->totales;
}
/** @return list<Pago> */
public function getPagos(): array
{
return $this->pagos;
}
public function getPago(int $index): Pago
{
return $this->pagos[$index];
}
public function jsonSerialize(): array
{
return [
'totales' => $this->totales,
'pagos' => $this->pagos,
];
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/SumasPagos20/Impuesto.php | src/CfdiUtils/SumasPagos20/Impuesto.php | <?php
namespace CfdiUtils\SumasPagos20;
use JsonSerializable;
final class Impuesto implements JsonSerializable
{
public function __construct(
private string $tipo,
private string $impuesto,
private string $tipoFactor,
private string $tasaCuota,
private Decimal $base,
private Decimal $importe,
) {
}
public static function buildKey(string $tipo, string $impuesto, string $tipoFactor, string $tasaCuota): string
{
if ('Retencion' === $tipo) {
return sprintf('T:%s|I:%s', $tipo, $impuesto);
}
return sprintf('T:%s|I:%s|F:%s|C:%s', $tipo, $impuesto, $tipoFactor, $tasaCuota);
}
public function getKey(): string
{
return $this->buildKey($this->tipo, $this->impuesto, $this->tipoFactor, $this->tasaCuota);
}
public function getTipo(): string
{
return $this->tipo;
}
public function getImpuesto(): string
{
return $this->impuesto;
}
public function getTipoFactor(): string
{
return $this->tipoFactor;
}
public function getTasaCuota(): string
{
return $this->tasaCuota;
}
public function getBase(): Decimal
{
return $this->base;
}
public function getImporte(): Decimal
{
return $this->importe;
}
public function add(self $other): self
{
return new self(
$this->tipo,
$this->impuesto,
$this->tipoFactor,
$this->tasaCuota,
$this->base->sum($other->base),
$this->importe->sum($other->importe),
);
}
public function truncate(int $decimals): self
{
return new self(
$this->tipo,
$this->impuesto,
$this->tipoFactor,
$this->tasaCuota,
$this->base->truncate($decimals),
$this->importe->truncate($decimals),
);
}
public function multiply(Decimal $factor): self
{
return new self(
$this->tipo,
$this->impuesto,
$this->tipoFactor,
$this->tasaCuota,
$this->base->multiply($factor),
$this->importe->multiply($factor),
);
}
public function divide(Decimal $factor): self
{
return new self(
$this->tipo,
$this->impuesto,
$this->tipoFactor,
$this->tasaCuota,
$this->base->divide($factor),
$this->importe->divide($factor),
);
}
public function round(int $decimals): self
{
return new self(
$this->tipo,
$this->impuesto,
$this->tipoFactor,
$this->tasaCuota,
$this->base->round($decimals),
$this->importe->round($decimals),
);
}
/** @return array<string, mixed> */
public function jsonSerialize(): array
{
return [
'tipo' => $this->tipo,
'impuesto' => $this->impuesto,
'tipoFactor' => $this->tipoFactor,
'tasaCuota' => $this->tasaCuota,
'base' => $this->base,
'importe' => $this->importe,
];
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/SumasPagos20/Totales.php | src/CfdiUtils/SumasPagos20/Totales.php | <?php
namespace CfdiUtils\SumasPagos20;
use JsonSerializable;
final class Totales implements JsonSerializable
{
public function __construct(
private ?Decimal $retencionIva,
private ?Decimal $retencionIsr,
private ?Decimal $retencionIeps,
private ?Decimal $trasladoIva16Base,
private ?Decimal $trasladoIva16Importe,
private ?Decimal $trasladoIva08Base,
private ?Decimal $trasladoIva08Importe,
private ?Decimal $trasladoIva00Base,
private ?Decimal $trasladoIva00Importe,
private ?Decimal $trasladoIvaExento,
private Decimal $total,
) {
}
public function getRetencionIva(): ?Decimal
{
return $this->retencionIva;
}
public function getRetencionIsr(): ?Decimal
{
return $this->retencionIsr;
}
public function getRetencionIeps(): ?Decimal
{
return $this->retencionIeps;
}
public function getTrasladoIva16Base(): ?Decimal
{
return $this->trasladoIva16Base;
}
public function getTrasladoIva16Importe(): ?Decimal
{
return $this->trasladoIva16Importe;
}
public function getTrasladoIva08Base(): ?Decimal
{
return $this->trasladoIva08Base;
}
public function getTrasladoIva08Importe(): ?Decimal
{
return $this->trasladoIva08Importe;
}
public function getTrasladoIva00Base(): ?Decimal
{
return $this->trasladoIva00Base;
}
public function getTrasladoIva00Importe(): ?Decimal
{
return $this->trasladoIva00Importe;
}
public function getTrasladoIvaExento(): ?Decimal
{
return $this->trasladoIvaExento;
}
public function getTotal(): Decimal
{
return $this->total;
}
/** @return array<string, Decimal> */
public function jsonSerialize(): array
{
return array_filter([
'retencionIva' => $this->retencionIva,
'retencionIsr' => $this->retencionIsr,
'retencionIeps' => $this->retencionIeps,
'trasladoIva16Base' => $this->trasladoIva16Base,
'trasladoIva16Importe' => $this->trasladoIva16Importe,
'trasladoIva08Base' => $this->trasladoIva08Base,
'trasladoIva08Importe' => $this->trasladoIva08Importe,
'trasladoIva00Base' => $this->trasladoIva00Base,
'trasladoIva00Importe' => $this->trasladoIva00Importe,
'trasladoIvaExento' => $this->trasladoIvaExento,
'total' => $this->total,
]);
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/SumasPagos20/PagosWriter.php | src/CfdiUtils/SumasPagos20/PagosWriter.php | <?php
namespace CfdiUtils\SumasPagos20;
use CfdiUtils\Elements\Pagos20\Pago as ElementPago;
use CfdiUtils\Elements\Pagos20\Pagos as ElementPagos;
use CfdiUtils\Nodes\NodeInterface;
use LogicException;
final class PagosWriter
{
public function __construct(private ElementPagos $pagos)
{
}
public static function calculateAndPut(ElementPagos $complementoPagos): Pagos
{
$calculator = new Calculator();
$result = $calculator->calculate($complementoPagos);
$writer = new self($complementoPagos);
$writer->put($result);
return $result;
}
public function put(Pagos $result): void
{
$this->writeTotales($result);
$this->writePagos($result);
}
private function writeTotales(Pagos $pagoElement): void
{
$this->removeNodeIfExists($this->pagos, 'pago20:Totales');
$totales = $pagoElement->getTotales();
$this->pagos->addTotales([
'MontoTotalPagos' => $totales->getTotal(),
'TotalRetencionesIVA' => $totales->getRetencionIva(),
'TotalRetencionesISR' => $totales->getRetencionIsr(),
'TotalRetencionesIEPS' => $totales->getRetencionIeps(),
'TotalTrasladosBaseIVA16' => $totales->getTrasladoIva16Base(),
'TotalTrasladosImpuestoIVA16' => $totales->getTrasladoIva16Importe(),
'TotalTrasladosBaseIVA8' => $totales->getTrasladoIva08Base(),
'TotalTrasladosImpuestoIVA8' => $totales->getTrasladoIva08Importe(),
'TotalTrasladosBaseIVA0' => $totales->getTrasladoIva00Base(),
'TotalTrasladosImpuestoIVA0' => $totales->getTrasladoIva00Importe(),
'TotalTrasladosBaseIVAExento' => $totales->getTrasladoIvaExento(),
]);
}
private function writePagos(Pagos $pagos): void
{
foreach ($this->pagos->searchNodes('pago20:Pago') as $index => $pagoElement) {
if (! $pagoElement instanceof ElementPago) {
throw new LogicException(
sprintf('Cannot work with a pago20:Pago of class %s', $pagoElement::class)
);
}
$pagoData = $pagos->getPago($index);
$this->writePago($pagoElement, $pagoData);
}
}
public function writePago(ElementPago $pagoElement, Pago $pagoData): void
{
if (! isset($pagoElement['Monto'])) {
$pagoElement['Monto'] = $pagoData->getMontoMinimo();
}
$this->removeNodeIfExists($pagoElement, 'pago20:ImpuestosP');
$retenciones = $pagoData->getImpuestos()->getRetenciones();
if ([] !== $retenciones) {
$retencionesElement = $pagoElement->getImpuestosP()->getRetencionesP();
$retencionesElement->clear();
foreach ($retenciones as $retencion) {
$retencionesElement->addRetencionP([
'ImpuestoP' => $retencion->getImpuesto(),
'ImporteP' => $retencion->getImporte(),
]);
}
}
$traslados = $pagoData->getImpuestos()->getTraslados();
if ([] !== $traslados) {
$trasladosElement = $pagoElement->getImpuestosP()->getTrasladosP();
$trasladosElement->clear();
foreach ($traslados as $traslado) {
$trasladosElement->addTrasladoP([
'ImpuestoP' => $traslado->getImpuesto(),
'TipoFactorP' => $traslado->getTipoFactor(),
'TasaOCuotaP' => ('Exento' === $traslado->getTipoFactor()) ? null : $traslado->getTasaCuota(),
'BaseP' => $traslado->getBase(),
'ImporteP' => ('Exento' === $traslado->getTipoFactor()) ? null : $traslado->getImporte(),
]);
}
}
}
private function removeNodeIfExists(NodeInterface $node, string ...$searchPath): void
{
$elements = $node->searchNodes(...$searchPath);
foreach ($elements as $element) {
$node->children()->remove($element);
}
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/SumasPagos20/DoctoRelacionado.php | src/CfdiUtils/SumasPagos20/DoctoRelacionado.php | <?php
namespace CfdiUtils\SumasPagos20;
/**
* The amounts on this class are set in the payment currency
*/
final class DoctoRelacionado
{
public function __construct(private Decimal $impPagado, private Impuestos $impuestos)
{
}
public function getImpPagado(): Decimal
{
return $this->impPagado;
}
public function getImpuestos(): Impuestos
{
return $this->impuestos;
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/SumasPagos20/Pago.php | src/CfdiUtils/SumasPagos20/Pago.php | <?php
namespace CfdiUtils\SumasPagos20;
use JsonSerializable;
final class Pago implements JsonSerializable
{
public function __construct(
private Decimal $monto,
private Decimal $montoMinimo,
private Decimal $tipoCambioP,
private Impuestos $impuestos,
) {
}
public function getMonto(): Decimal
{
return $this->monto;
}
public function getMontoMinimo(): Decimal
{
return $this->montoMinimo;
}
public function getTipoCambioP(): Decimal
{
return $this->tipoCambioP;
}
public function getImpuestos(): Impuestos
{
return $this->impuestos;
}
/** @return array<string, mixed> */
public function jsonSerialize(): array
{
return [
'monto' => $this->monto,
'montoMinimo' => $this->montoMinimo,
'tipoCambioP' => $this->tipoCambioP,
'impuestos' => $this->impuestos,
];
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/SumasPagos20/Calculator.php | src/CfdiUtils/SumasPagos20/Calculator.php | <?php
namespace CfdiUtils\SumasPagos20;
use CfdiUtils\Nodes\NodeInterface;
use CfdiUtils\Nodes\Nodes;
class Calculator
{
private int $paymentTaxesPrecision;
private Currencies $currencies;
public function __construct(int $paymentTaxesPrecision = 6, ?Currencies $currencies = null)
{
$this->setPaymentTaxesPrecision($paymentTaxesPrecision);
$this->currencies = $currencies ?? new Currencies(['MXN' => 2, 'USD' => 2]);
}
public function getPaymentTaxesPrecision(): int
{
return $this->paymentTaxesPrecision;
}
public function setPaymentTaxesPrecision(int $paymentTaxesPrecision): void
{
$this->paymentTaxesPrecision = min(6, max(0, $paymentTaxesPrecision));
}
public function getCurrencies(): Currencies
{
return $this->currencies;
}
public function setCurrencies(Currencies $currencies): void
{
$this->currencies = $currencies;
}
public function calculate(NodeInterface $nodePagos): Pagos
{
$pagos = [];
foreach ($nodePagos->searchNodes('pago20:Pago') as $nodePago) {
$pagos[] = $this->buildPago($nodePago);
}
$totales = $this->buildTotales($pagos);
return new Pagos($totales, ...$pagos);
}
private function buildPago(NodeInterface $nodePago): Pago
{
$sumMonto = new Decimal('0');
$impuestos = new Impuestos();
foreach ($nodePago->searchNodes('pago20:DoctoRelacionado') as $nodeDoctoRelacionado) {
$doctoRelacionado = $this->buildDoctoRelacionado($nodeDoctoRelacionado);
$sumMonto = $sumMonto->sum($doctoRelacionado->getImpPagado());
$impuestos = $impuestos->aggregate($doctoRelacionado->getImpuestos());
}
$montoMinimo = $sumMonto->truncate($this->currencies->get($nodePago['MonedaP']));
$monto = (isset($nodePago['Monto'])) ? new Decimal($nodePago['Monto']) : $montoMinimo;
$impuestos = $impuestos->round($this->paymentTaxesPrecision);
$tipoCambioP = new Decimal($nodePago['TipoCambioP']);
return new Pago($monto, $montoMinimo, $tipoCambioP, $impuestos);
}
private function buildDoctoRelacionado(NodeInterface $nodeDoctoRelacionado): DoctoRelacionado
{
$equivalenciaDr = new Decimal($nodeDoctoRelacionado['EquivalenciaDR']);
$impPagado = new Decimal($nodeDoctoRelacionado['ImpPagado']);
$impPagado = $impPagado->divide($equivalenciaDr);
$traslados = $this->processImpuestosTraslados(
$equivalenciaDr,
$nodeDoctoRelacionado->searchNodes('pago20:ImpuestosDR', 'pago20:TrasladosDR', 'pago20:TrasladoDR')
);
$retenciones = $this->processImpuestosRetenciones(
$equivalenciaDr,
$nodeDoctoRelacionado->searchNodes('pago20:ImpuestosDR', 'pago20:RetencionesDR', 'pago20:RetencionDR')
);
$impuestos = new Impuestos(...$traslados, ...$retenciones);
return new DoctoRelacionado($impPagado, $impuestos);
}
/** @return list<Impuesto> */
private function processImpuestosTraslados(Decimal $equivalenciaDr, Nodes $nodeImpuestos): array
{
$impuestos = [];
foreach ($nodeImpuestos as $nodeImpuesto) {
$impuesto = new Impuesto(
'Traslado',
$nodeImpuesto['ImpuestoDR'],
$nodeImpuesto['TipoFactorDR'],
$nodeImpuesto['TasaOCuotaDR'],
new Decimal($nodeImpuesto['BaseDR']),
new Decimal($nodeImpuesto['ImporteDR'])
);
$impuesto = $impuesto->divide($equivalenciaDr);
$impuestos[] = $impuesto;
}
return $impuestos;
}
/** @return list<Impuesto> */
private function processImpuestosRetenciones(Decimal $equivalenciaDr, Nodes $nodeImpuestos): array
{
$impuestos = [];
foreach ($nodeImpuestos as $nodeImpuesto) {
$impuesto = new Impuesto(
'Retencion',
$nodeImpuesto['ImpuestoDR'],
'',
'',
new Decimal('0'),
new Decimal($nodeImpuesto['ImporteDR'])
);
$impuesto = $impuesto->divide($equivalenciaDr);
$impuestos[] = $impuesto;
}
return $impuestos;
}
/** @param Pago[] $pagos */
private function buildTotales(array $pagos): Totales
{
$total = new Decimal('0');
$impuestos = new Impuestos();
foreach ($pagos as $pago) {
$tipoCambioP = $pago->getTipoCambioP();
$impuestos = $impuestos->aggregate($pago->getImpuestos()->multiply($tipoCambioP));
$total = $total->sum($pago->getMonto()->multiply($tipoCambioP));
}
$impuestos = $impuestos->round(2); // MXN
$retencionIva = $impuestos->find('Retencion', '002');
$retencionIsr = $impuestos->find('Retencion', '001');
$retencionIeps = $impuestos->find('Retencion', '003');
$trasladoIva16 = $impuestos->find('Traslado', '002', 'Tasa', '0.160000');
$trasladoIva08 = $impuestos->find('Traslado', '002', 'Tasa', '0.080000');
$trasladoIva00 = $impuestos->find('Traslado', '002', 'Tasa', '0.000000');
$trasladoIvaEx = $impuestos->find('Traslado', '002', 'Exento');
return new Totales(
$retencionIva ? $retencionIva->getImporte() : null,
$retencionIsr ? $retencionIsr->getImporte() : null,
$retencionIeps ? $retencionIeps->getImporte() : null,
$trasladoIva16 ? $trasladoIva16->getBase() : null,
$trasladoIva16 ? $trasladoIva16->getImporte() : null,
$trasladoIva08 ? $trasladoIva08->getBase() : null,
$trasladoIva08 ? $trasladoIva08->getImporte() : null,
$trasladoIva00 ? $trasladoIva00->getBase() : null,
$trasladoIva00 ? $trasladoIva00->getImporte() : null,
$trasladoIvaEx ? $trasladoIvaEx->getBase() : null,
$total->round(2) // MXN
);
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/ConsultaCfdiSat/RequestParameters.php | src/CfdiUtils/ConsultaCfdiSat/RequestParameters.php | <?php
namespace CfdiUtils\ConsultaCfdiSat;
use CfdiUtils\Cfdi;
use UnexpectedValueException;
class RequestParameters
{
private string $version;
private float $totalFloat;
public function __construct(
string $version,
private string $rfcEmisor,
private string $rfcReceptor,
private string $total,
private string $uuid,
private string $sello = '',
) {
$this->setVersion($version);
$this->totalFloat = (float) trim(str_replace(',', '', $this->total));
}
public static function createFromCfdi(Cfdi $cfdi): self
{
$qr = $cfdi->getQuickReader();
return new self(
$qr['version'],
$qr->{'emisor'}['rfc'],
$qr->{'receptor'}['rfc'],
$qr['total'],
$qr->{'complemento'}->{'timbrefiscaldigital'}['uuid'],
$qr['sello']
);
}
public function getVersion(): string
{
return $this->version;
}
public function setVersion(string $version): void
{
if (! in_array($version, ['3.2', '3.3', '4.0'], true)) {
throw new UnexpectedValueException('The version is not allowed');
}
$this->version = $version;
}
public function getRfcEmisor(): string
{
return $this->rfcEmisor;
}
public function getRfcReceptor(): string
{
return $this->rfcReceptor;
}
public function getTotal(): string
{
return $this->total;
}
public function getTotalFloat(): float
{
return $this->totalFloat;
}
public function getUuid(): string
{
return $this->uuid;
}
public function getSello(): string
{
return $this->sello;
}
public function expression(): string
{
if ('4.0' === $this->version) {
return $this->expressionVersion40();
}
if ('3.3' === $this->version) {
return $this->expressionVersion33();
}
if ('3.2' === $this->version) {
return $this->expressionVersion32();
}
return '';
}
public function expressionVersion32(): string
{
return '?' . implode('&', [
're=' . htmlentities($this->rfcEmisor, ENT_XML1),
'rr=' . htmlentities($this->rfcReceptor, ENT_XML1),
'tt=' . str_pad(number_format($this->totalFloat, 6, '.', ''), 17, '0', STR_PAD_LEFT),
'id=' . $this->uuid,
]);
}
public function expressionVersion33(): string
{
$total = rtrim(number_format($this->totalFloat, 6, '.', ''), '0');
if (str_ends_with($total, '.')) {
$total = $total . '0'; // add trailing zero
}
return 'https://verificacfdi.facturaelectronica.sat.gob.mx/default.aspx?' . implode('&', [
'id=' . $this->uuid,
're=' . htmlentities($this->rfcEmisor, ENT_XML1),
'rr=' . htmlentities($this->rfcReceptor, ENT_XML1),
'tt=' . $total,
'fe=' . substr($this->sello, -8),
]);
}
public function expressionVersion40(): string
{
return $this->expressionVersion33();
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/ConsultaCfdiSat/StatusResponse.php | src/CfdiUtils/ConsultaCfdiSat/StatusResponse.php | <?php
namespace CfdiUtils\ConsultaCfdiSat;
class StatusResponse
{
public function __construct(
private string $code,
private string $cfdi,
private string $cancellable,
private string $cancellationStatus,
private string $validationEfos,
) {
}
/**
* Status request code, values:
* - S - Comprobante obtenido satisfactoriamente
* - N - 601: La expresión impresa proporcionada no es válida
* - N - 602: Comprobante no encontrado
*
* @see responseWasOk()
*/
public function getCode(): string
{
return $this->code;
}
/**
* Status about the CFDI, values:
* - `Vigente`: El comprobante está vigente al momento de la consulta
* - `Cancelado`: El comprobante está cancelado al momento de la consulta
* - `No Encontrado`: El comprobante no se encuentra en la base de datos del SAT
*
* @see isVigente()
* @see isNotFound()
* @see isCancelled()
*/
public function getCfdi(): string
{
return $this->cfdi;
}
/**
* Cancellable status, values:
* - `No cancelable`: No se puede cancelar, tal vez ya hay documentos relacionados.
* - `Cancelable sin aceptación`: Se puede cancelar de inmediato.
* - `Cancelable con aceptación`: Se puede cancelar, pero se va a tener que esperar respuesta.
*/
public function getCancellable(): string
{
return $this->cancellable;
}
/**
* Cancellation process status, values:
*
* - `(ninguno)`: El estado vacío es que no tiene estado de cancelación, porque no fue solicitada.
* - `Cancelado sin aceptación`: Se canceló y no fue necesaria la aceptación.
* - `En proceso`: En espera de que el receptor la autorice.
* - `Plazo vencido`: Cancelado por vencimiento de plazo en que el receptor podía denegarla.
* - `Cancelado con aceptación`: Cancelado con el consentimiento del receptor.
* - `Solicitud rechazada`: No se realizó la cancelación por rechazo.
*/
public function getCancellationStatus(): string
{
return $this->cancellationStatus;
}
/**
* Validation EFOS values:
*
* - "100": El emisor se encontró en el listado EFOS
* - "200": No se encontró en listado EFOS
*/
public function getValidationEfos(): string
{
return $this->validationEfos;
}
public function responseWasOk(): bool
{
return str_starts_with($this->code, 'S - ');
}
public function isVigente(): bool
{
return 'Vigente' === $this->cfdi;
}
public function isNotFound(): bool
{
return 'No Encontrado' === $this->cfdi;
}
public function isCancelled(): bool
{
return 'Cancelado' === $this->cfdi;
}
public function isEfosListed(): bool
{
return '100' === $this->validationEfos;
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/ConsultaCfdiSat/Config.php | src/CfdiUtils/ConsultaCfdiSat/Config.php | <?php
namespace CfdiUtils\ConsultaCfdiSat;
class Config
{
/**
* Default value of SAT web service
* @var string
*/
public const DEFAULT_SERVICE_URL = 'https://consultaqr.facturaelectronica.sat.gob.mx/ConsultaCFDIService.svc';
private string $serviceUrl;
public function __construct(
private int $timeout = 10,
private bool $verifyPeer = true,
string $serviceUrl = '',
) {
$this->serviceUrl = $serviceUrl ?: static::DEFAULT_SERVICE_URL;
}
public function getTimeout(): int
{
return $this->timeout;
}
public function shouldVerifyPeer(): bool
{
return $this->verifyPeer;
}
public function getServiceUrl(): string
{
return $this->serviceUrl;
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/ConsultaCfdiSat/WebService.php | src/CfdiUtils/ConsultaCfdiSat/WebService.php | <?php
/** @noinspection PhpComposerExtensionStubsInspection */
namespace CfdiUtils\ConsultaCfdiSat;
use RuntimeException;
use SoapClient;
use SoapVar;
use stdClass;
class WebService
{
private ?SoapClient $soapClient = null;
private Config $config;
public function __construct(?Config $config = null)
{
$this->config = $config ?: new Config();
}
public function getConfig(): Config
{
return $this->config;
}
public function getSoapClient(): SoapClient
{
if (! $this->soapClient instanceof SoapClient) {
$this->soapClient = $this->createSoapClient();
}
return $this->soapClient;
}
public function destroySoapClient(): void
{
$this->soapClient = null;
}
protected function createSoapClient(): SoapClient
{
/*
* options.location: required to build the object
*
* options.uri: required to build the object
*
* options.use: SOAP_ENCODED (default) or SOAP_LITERAL
* Both works but SOAP_LITERAL is cleaner
*
* options.style: SOAP_RPC (default) or SOAP_DOCUMENT
* SOAP_DOCUMENT removes the method name from soap body
*
*/
$config = $this->getConfig();
$soapOptions = [
'location' => $config->getServiceUrl(),
'uri' => 'http://tempuri.org/',
'style' => SOAP_RPC,
'use' => SOAP_LITERAL,
'soap_version' => SOAP_1_1,
'exceptions' => 1,
'stream_context' => stream_context_create([
'ssl' => [
'verify_peer' => $config->shouldVerifyPeer(),
],
]),
'connection_timeout' => $config->getTimeout(),
'trace' => false, // use this setting for development
];
return new SoapClient(null, $soapOptions);
}
public function request(RequestParameters $requestParameters): StatusResponse
{
return $this->requestExpression($requestParameters->expression());
}
public function requestExpression(string $expression): StatusResponse
{
$rawResponse = $this->doRequestConsulta($expression);
if (! ($rawResponse instanceof stdClass)) {
throw new RuntimeException('The consulta web service did not return any result');
}
$result = (array) $rawResponse;
if (! isset($result['CodigoEstatus'])) {
throw new RuntimeException('The consulta web service did not have expected ConsultaResult:CodigoEstatus');
}
if (! isset($result['Estado'])) {
throw new RuntimeException('The consulta web service did not have expected ConsultaResult:Estado');
}
return new StatusResponse(
$result['CodigoEstatus'],
$result['Estado'],
$result['EsCancelable'] ?? '',
$result['EstatusCancelacion'] ?? '',
$result['ValidacionEFOS'] ?? ''
);
}
/**
* This method exists to be able to mock SOAP call
*
* @internal
*/
protected function doRequestConsulta(string $expression): ?stdClass
{
$encoding = null;
return $this->getSoapClient()->__soapCall(
'Consulta',
[new SoapVar($expression, $encoding, '', '', 'expresionImpresa', 'http://tempuri.org/')],
['soapaction' => 'http://tempuri.org/IConsultaCFDIService/Consulta']
);
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/SumasConceptos/SumasConceptos.php | src/CfdiUtils/SumasConceptos/SumasConceptos.php | <?php
namespace CfdiUtils\SumasConceptos;
use CfdiUtils\Nodes\NodeInterface;
class SumasConceptos
{
private float $importes = 0.0;
private float $descuento = 0.0;
private float $total;
private float $impuestosTrasladados;
private float $impuestosRetenidos;
/**
* @var array<string, array{Impuesto:string, TipoFactor:string, TasaOCuota:string, Importe:float, Base:float}>
*/
private array $traslados = [];
/**
* @var array<string, array{Impuesto:string, TipoFactor:string, Base:float}>
*/
private array $exentos = [];
/**
* @var array<string, array{Impuesto:string, Importe:float}>
*/
private array $retenciones = [];
private float $localesImpuestosTrasladados;
private float $localesImpuestosRetenidos;
/**
* @var array<int, array{Impuesto:string, Tasa:float, Importe:float}>
*/
private array $localesTraslados = [];
/**
* @var array<int, array{Impuesto:string, Tasa:float, Importe:float}>
*/
private array $localesRetenciones = [];
private bool $foundAnyConceptWithDiscount = false;
/*
* Constructors
*/
public function __construct(NodeInterface $comprobante, private int $precision = 2)
{
$this->addComprobante($comprobante);
}
/*
* Helper functions to populate the object
*/
private function addComprobante(NodeInterface $comprobante): void
{
$conceptos = $comprobante->searchNodes('cfdi:Conceptos', 'cfdi:Concepto');
foreach ($conceptos as $concepto) {
$this->addConcepto($concepto);
}
$this->localesTraslados = $this->populateImpuestosLocales($comprobante, 'TrasladosLocales', 'Traslado');
$this->localesImpuestosTrasladados = array_sum(array_column($this->localesTraslados, 'Importe'));
$this->localesRetenciones = $this->populateImpuestosLocales($comprobante, 'RetencionesLocales', 'Retenido');
$this->localesImpuestosRetenidos = array_sum(array_column($this->localesRetenciones, 'Importe'));
$this->traslados = $this->roundImpuestosGroup($this->traslados);
$this->retenciones = $this->roundImpuestosGroup($this->retenciones);
$this->impuestosTrasladados = (float) array_sum(array_column($this->traslados, 'Importe'));
$this->impuestosRetenidos = (float) array_sum(array_column($this->retenciones, 'Importe'));
$this->impuestosTrasladados = round($this->impuestosTrasladados, $this->precision);
$this->impuestosRetenidos = round($this->impuestosRetenidos, $this->precision);
$this->importes = round($this->importes, $this->precision);
$this->descuento = round($this->descuento, $this->precision);
$this->total = round(array_sum([
$this->importes,
-$this->descuento,
$this->impuestosTrasladados,
-$this->impuestosRetenidos,
$this->localesImpuestosTrasladados,
-$this->localesImpuestosRetenidos,
]), $this->precision);
}
private function addConcepto(NodeInterface $concepto): void
{
$this->importes += (float) $concepto['Importe'];
if ($concepto->exists('Descuento')) {
$this->foundAnyConceptWithDiscount = true;
}
$this->descuento += (float) $concepto['Descuento'];
$traslados = $concepto->searchNodes('cfdi:Impuestos', 'cfdi:Traslados', 'cfdi:Traslado');
foreach ($traslados as $traslado) {
if ('Exento' === $traslado['TipoFactor']) {
$this->addExento($traslado);
} else {
$this->addTraslado($traslado);
}
}
$retenciones = $concepto->searchNodes('cfdi:Impuestos', 'cfdi:Retenciones', 'cfdi:Retencion');
foreach ($retenciones as $retencion) {
$this->addRetencion($retencion);
}
}
/**
* @return array<int, array{Impuesto:string, Tasa:float, Importe:float}>
*/
private function populateImpuestosLocales(NodeInterface $comprobante, string $plural, string $singular): array
{
$locales = $comprobante->searchNodes('cfdi:Complemento', 'implocal:ImpuestosLocales', 'implocal:' . $plural);
$list = [];
foreach ($locales as $local) {
$list[] = [
'Impuesto' => $local['ImpLoc' . $singular],
'Tasa' => (float) $local['Tasade' . $singular],
'Importe' => (float) $local['Importe'],
];
}
return $list;
}
private function roundImpuestosGroup(array $group): array
{
foreach (array_keys($group) as $key) {
$group[$key]['Importe'] = round($group[$key]['Importe'], $this->getPrecision());
if (isset($group[$key]['Base'])) {
$group[$key]['Base'] = round($group[$key]['Base'], $this->getPrecision());
}
}
return $group;
}
private function addTraslado(NodeInterface $traslado): void
{
$key = $this->impuestoKey(
$traslado['Impuesto'],
$traslado['TipoFactor'],
$traslado['TasaOCuota']
);
if (! array_key_exists($key, $this->traslados)) {
$this->traslados[$key] = [
'Impuesto' => $traslado['Impuesto'],
'TipoFactor' => $traslado['TipoFactor'],
'TasaOCuota' => $traslado['TasaOCuota'],
'Importe' => 0.0,
'Base' => 0.0,
];
}
$this->traslados[$key]['Importe'] += (float) $traslado['Importe'];
$this->traslados[$key]['Base'] += (float) $traslado['Base'];
}
private function addExento(NodeInterface $exento): void
{
$key = $this->impuestoKey($exento['Impuesto'], $exento['TipoFactor'], '');
if (! array_key_exists($key, $this->exentos)) {
$this->exentos[$key] = [
'TipoFactor' => $exento['TipoFactor'],
'Impuesto' => $exento['Impuesto'],
'Base' => 0.0,
];
}
$this->exentos[$key]['Base'] += (float) $exento['Base'];
}
private function addRetencion(NodeInterface $retencion): void
{
$key = $this->impuestoKey($retencion['Impuesto']);
if (! array_key_exists($key, $this->retenciones)) {
$this->retenciones[$key] = [
'Impuesto' => $retencion['Impuesto'],
'Importe' => 0.0,
];
}
$this->retenciones[$key]['Importe'] += (float) $retencion['Importe'];
}
public static function impuestoKey(string $impuesto, string $tipoFactor = '', string $tasaOCuota = ''): string
{
return implode(':', [$impuesto, $tipoFactor, $tasaOCuota]);
}
/*
* Getters
*/
public function getTotal(): float
{
return $this->total;
}
public function getSubTotal(): float
{
return $this->importes;
}
public function getDescuento(): float
{
return $this->descuento;
}
/**
* @return array<string, array{Impuesto:string, TipoFactor:string, TasaOCuota:string, Importe:float, Base:float}>
*/
public function getTraslados(): array
{
return $this->traslados;
}
/**
* @return array<string, array{Impuesto:string, TipoFactor:string, Base:float}>
*/
public function getExentos(): array
{
return $this->exentos;
}
/**
* @return array<string, array{Impuesto:string, Importe:float}>
*/
public function getRetenciones(): array
{
return $this->retenciones;
}
public function hasTraslados(): bool
{
return [] !== $this->traslados;
}
public function hasExentos(): bool
{
return [] !== $this->exentos;
}
public function hasRetenciones(): bool
{
return [] !== $this->retenciones;
}
public function getImpuestosTrasladados(): float
{
return $this->impuestosTrasladados;
}
public function getImpuestosRetenidos(): float
{
return $this->impuestosRetenidos;
}
public function getPrecision(): int
{
return $this->precision;
}
public function getLocalesImpuestosTrasladados(): float
{
return $this->localesImpuestosTrasladados;
}
public function getLocalesImpuestosRetenidos(): float
{
return $this->localesImpuestosRetenidos;
}
/**
* @return array<int, array{Impuesto:string, Tasa:float, Importe:float}>
*/
public function getLocalesTraslados(): array
{
return $this->localesTraslados;
}
/**
* @return array<int, array{Impuesto:string, Tasa:float, Importe:float}>
*/
public function getLocalesRetenciones(): array
{
return $this->localesRetenciones;
}
public function hasLocalesTraslados(): bool
{
return [] !== $this->localesTraslados;
}
public function hasLocalesRetenciones(): bool
{
return [] !== $this->localesRetenciones;
}
public function foundAnyConceptWithDiscount(): bool
{
return $this->foundAnyConceptWithDiscount;
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/SumasConceptos/SumasConceptosWriter.php | src/CfdiUtils/SumasConceptos/SumasConceptosWriter.php | <?php
namespace CfdiUtils\SumasConceptos;
use CfdiUtils\Elements\Cfdi33\Comprobante as Comprobante33;
use CfdiUtils\Elements\Cfdi40\Comprobante as Comprobante40;
use CfdiUtils\Nodes\NodeInterface;
use InvalidArgumentException;
class SumasConceptosWriter
{
/** @var Comprobante33|Comprobante40 */
private NodeInterface $comprobante;
private ?bool $writeImpuestoBase = null;
private ?bool $writeExentos = null;
/**
* Writer constructor.
* @param Comprobante33|Comprobante40 $comprobante
*/
public function __construct(
NodeInterface $comprobante,
private SumasConceptos $sumas,
private int $precision = 6,
) {
if ($comprobante instanceof Comprobante33) {
$this->writeImpuestoBase = false;
$this->writeExentos = false;
} elseif ($comprobante instanceof Comprobante40) {
$this->writeImpuestoBase = true;
$this->writeExentos = true;
} else {
throw new InvalidArgumentException(
'The argument $comprobante must be a Comprobante (CFDI 3.3 or CFDI 4.0) element'
);
}
$this->comprobante = $comprobante;
}
public function put(): void
{
$this->putComprobanteSumas();
$this->putImpuestosNode();
$this->putComplementoImpuestoLocalSumas();
}
private function putComprobanteSumas(): void
{
$this->comprobante['SubTotal'] = $this->format($this->sumas->getSubTotal());
$this->comprobante['Total'] = $this->format($this->sumas->getTotal());
$this->comprobante['Descuento'] = $this->format($this->sumas->getDescuento());
if (
! $this->sumas->foundAnyConceptWithDiscount()
&& ! $this->valueGreaterThanZero($this->sumas->getDescuento())
) {
unset($this->comprobante['Descuento']);
}
}
private function putImpuestosNode(): void
{
// obtain node reference
$impuestos = $this->comprobante->getImpuestos();
// if there is nothing to write then remove the children and exit
if (
! $this->sumas->hasTraslados()
&& ! $this->sumas->hasRetenciones()
&& ! ($this->writeExentos && $this->sumas->hasExentos())
) {
$this->comprobante->children()->remove($impuestos);
return;
}
// clear previous values
$impuestos->clear();
// add traslados when needed
if ($this->sumas->hasTraslados()) {
$impuestos['TotalImpuestosTrasladados'] = $this->format($this->sumas->getImpuestosTrasladados());
$impuestos->getTraslados()->multiTraslado(
...$this->getImpuestosContents($this->sumas->getTraslados(), $this->writeImpuestoBase, true)
);
}
if ($this->writeExentos && $this->sumas->hasExentos()) {
$impuestos->getTraslados()->multiTraslado(
...$this->getImpuestosContents($this->sumas->getExentos(), $this->writeImpuestoBase, false)
);
}
// add retenciones when needed
if ($this->sumas->hasRetenciones()) {
$impuestos['TotalImpuestosRetenidos'] = $this->format($this->sumas->getImpuestosRetenidos());
$impuestos->getRetenciones()->multiRetencion(
...$this->getImpuestosContents($this->sumas->getRetenciones(), false, true)
);
}
}
private function putComplementoImpuestoLocalSumas(): void
{
// search for implocal node
$impLocal = $this->comprobante->searchNode('cfdi:Complemento', 'implocal:ImpuestosLocales');
if (! $impLocal) {
return;
}
if (! $this->sumas->hasLocalesTraslados() && ! $this->sumas->hasLocalesRetenciones()) {
$complemento = $this->comprobante->getComplemento();
$complemento->children()->remove($impLocal);
if (0 === $complemento->count()) {
$this->comprobante->children()->remove($complemento);
}
return;
}
$impLocal->attributes()->set('TotaldeRetenciones', $this->format($this->sumas->getLocalesImpuestosRetenidos()));
$impLocal->attributes()->set('TotaldeTraslados', $this->format($this->sumas->getLocalesImpuestosTrasladados()));
}
private function getImpuestosContents(array $impuestos, bool $hasBase, bool $hasImporte): array
{
$return = [];
foreach ($impuestos as $impuesto) {
$impuesto['Base'] = ($hasBase) ? $this->format($impuesto['Base'] ?? 0) : null;
$impuesto['Importe'] = ($hasImporte) ? $this->format($impuesto['Importe']) : null;
$return[] = array_filter($impuesto, fn ($value): bool => null !== $value);
}
return $return;
}
private function valueGreaterThanZero(float $value): bool
{
return round($value, $this->precision) > 0;
}
public function format(float $number): string
{
return number_format($number, $this->precision, '.', '');
}
/** @return Comprobante33|Comprobante40 */
public function getComprobante(): NodeInterface
{
return $this->comprobante;
}
public function getSumasConceptos(): SumasConceptos
{
return $this->sumas;
}
public function getPrecision(): int
{
return $this->precision;
}
public function hasWriteImpuestoBase(): bool
{
return $this->writeImpuestoBase;
}
public function hasWriteExentos(): bool
{
return $this->writeExentos;
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/XmlResolver/XmlResolver.php | src/CfdiUtils/XmlResolver/XmlResolver.php | <?php
namespace CfdiUtils\XmlResolver;
use CfdiUtils\CadenaOrigen\CfdiDefaultLocations;
use CfdiUtils\Certificado\CerRetriever;
use Eclipxe\XmlResourceRetriever\Downloader\DownloaderInterface;
use Eclipxe\XmlResourceRetriever\Downloader\PhpDownloader;
use Eclipxe\XmlResourceRetriever\RetrieverInterface;
use Eclipxe\XmlResourceRetriever\XsdRetriever;
use Eclipxe\XmlResourceRetriever\XsltRetriever;
/**
* XmlResolver - Class to download xml resources from internet to local paths
*/
class XmlResolver
{
private string $localPath = '';
private DownloaderInterface $downloader;
public const TYPE_XSD = 'XSD';
public const TYPE_XSLT = 'XSLT';
public const TYPE_CER = 'CER';
/**
* XmlResolver constructor.
* @see setLocalPath
* @see setDownloaderInterface
* @param string|null $localPath values: '' => no resolve, null => use default path, anything else is the path
*/
public function __construct(?string $localPath = null, ?DownloaderInterface $downloader = null)
{
$this->setLocalPath($localPath);
$this->setDownloader($downloader);
}
public static function defaultLocalPath(): string
{
// drop 3 dirs: src/CfdiUtils/XmlResolver
return dirname(__DIR__, 3) . '/build/resources/';
}
/**
* Set the localPath to the specified value.
* If $localPath is null then the value of defaultLocalPath is used.
*
* @param string|null $localPath values: '' => no resolve, null => default path, anything else is the path
*/
public function setLocalPath(?string $localPath = null): void
{
if (null === $localPath) {
$localPath = $this->defaultLocalPath();
}
$this->localPath = $localPath;
}
/**
* Return the configured localPath.
* An empty string means that it is not configured and method resolve will return the same url as received
* @see resolve
*/
public function getLocalPath(): string
{
return $this->localPath;
}
/**
* Return when a local path has been set.
*/
public function hasLocalPath(): bool
{
return '' !== $this->localPath;
}
/**
* Set the downloader object.
* If send a NULL value the object return by defaultDownloader will be set.
*/
public function setDownloader(?DownloaderInterface $downloader = null): void
{
if (null === $downloader) {
$downloader = $this->defaultDownloader();
}
$this->downloader = $downloader;
}
public static function defaultDownloader(): DownloaderInterface
{
return new PhpDownloader();
}
public function getDownloader(): DownloaderInterface
{
return $this->downloader;
}
/**
* Resolve a resource to a local path.
* If it does not have a localPath then it will return the exact same resource
*
* @param string $resource The url
* @param string $type Allows XSD, XSLT and CER
*/
public function resolve(string $resource, string $type = ''): string
{
if (! $this->hasLocalPath()) {
return $resource;
}
if ('' === $type) {
$type = $this->obtainTypeFromUrl($resource);
} else {
$type = strtoupper($type);
}
$retriever = $this->newRetriever($type);
if (null === $retriever) {
throw new \RuntimeException("Unable to handle the resource (Type: $type) $resource");
}
$local = $retriever->buildPath($resource);
if (! file_exists($local)) {
$retriever->retrieve($resource);
}
return $local;
}
public function obtainTypeFromUrl(string $url): string
{
if ($this->isResourceExtension($url, 'xsd')) {
return static::TYPE_XSD;
}
if ($this->isResourceExtension($url, 'xslt')) {
return static::TYPE_XSLT;
}
if ($this->isResourceExtension($url, 'cer')) {
return static::TYPE_CER;
}
return '';
}
private function isResourceExtension(string $resource, string $extension): bool
{
$extension = '.' . $extension;
$length = strlen($resource);
$extLength = strlen($extension);
if ($extLength > $length) {
return false;
}
return 0 === substr_compare(strtolower($resource), $extension, $length - $extLength, $extLength);
}
/**
* Create a new retriever depending on the type parameter, only allow TYPE_XSLT and TYPE_XSD
*/
public function newRetriever(string $type): ?RetrieverInterface
{
if (! $this->hasLocalPath()) {
throw new \LogicException('Cannot create a retriever if no local path was found');
}
if (static::TYPE_XSLT === $type) {
return $this->newXsltRetriever();
}
if (static::TYPE_XSD === $type) {
return $this->newXsdRetriever();
}
if (static::TYPE_CER === $type) {
return $this->newCerRetriever();
}
return null;
}
public function newXsltRetriever(): XsltRetriever
{
return new XsltRetriever($this->getLocalPath(), $this->getDownloader());
}
public function newXsdRetriever(): XsdRetriever
{
return new XsdRetriever($this->getLocalPath(), $this->getDownloader());
}
public function newCerRetriever(): CerRetriever
{
return new CerRetriever($this->getLocalPath(), $this->getDownloader());
}
public function resolveCadenaOrigenLocation(string $version): string
{
return $this->resolve(CfdiDefaultLocations::location($version), self::TYPE_XSLT);
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/XmlResolver/XmlResolverPropertyTrait.php | src/CfdiUtils/XmlResolver/XmlResolverPropertyTrait.php | <?php
namespace CfdiUtils\XmlResolver;
trait XmlResolverPropertyTrait
{
private ?XmlResolver $xmlResolver = null;
public function hasXmlResolver(): bool
{
return $this->xmlResolver instanceof XmlResolver;
}
public function getXmlResolver(): XmlResolver
{
if (! $this->xmlResolver instanceof XmlResolver) {
throw new \LogicException('There is no current xmlResolver');
}
return $this->xmlResolver;
}
public function setXmlResolver(?XmlResolver $xmlResolver = null): void
{
$this->xmlResolver = $xmlResolver;
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/XmlResolver/XmlResolverPropertyInterface.php | src/CfdiUtils/XmlResolver/XmlResolverPropertyInterface.php | <?php
namespace CfdiUtils\XmlResolver;
interface XmlResolverPropertyInterface
{
public function hasXmlResolver(): bool;
public function getXmlResolver(): XmlResolver;
public function setXmlResolver(?XmlResolver $xmlResolver = null);
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Certificado/CertificadoPropertyTrait.php | src/CfdiUtils/Certificado/CertificadoPropertyTrait.php | <?php
namespace CfdiUtils\Certificado;
trait CertificadoPropertyTrait
{
private ?Certificado $certificado = null;
public function hasCertificado(): bool
{
return $this->certificado instanceof Certificado;
}
public function getCertificado(): Certificado
{
if (! $this->certificado instanceof Certificado) {
throw new \LogicException('There is no current certificado');
}
return $this->certificado;
}
public function setCertificado(?Certificado $certificado = null): void
{
$this->certificado = $certificado;
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Certificado/CerRetriever.php | src/CfdiUtils/Certificado/CerRetriever.php | <?php
namespace CfdiUtils\Certificado;
use Eclipxe\XmlResourceRetriever\AbstractBaseRetriever;
use Eclipxe\XmlResourceRetriever\RetrieverInterface;
class CerRetriever extends AbstractBaseRetriever implements RetrieverInterface
{
public function retrieve(string $url): string
{
$this->clearHistory();
$localFilename = $this->download($url);
$this->addToHistory($url, $localFilename);
return $localFilename;
}
protected function checkIsValidDownloadedFile(string $source, string $localpath): void
{
// check content is cer file
try {
new Certificado($localpath);
} catch (\Throwable $ex) {
unlink($localpath);
throw new \RuntimeException("The source $source is not a cer file", 0, $ex);
}
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Certificado/SatCertificateNumber.php | src/CfdiUtils/Certificado/SatCertificateNumber.php | <?php
namespace CfdiUtils\Certificado;
class SatCertificateNumber
{
private string $id;
public function __construct(string $id)
{
if (! $this->isValidCertificateNumber($id)) {
throw new \UnexpectedValueException('The certificate number is not correct');
}
$this->id = $id;
}
public function number(): string
{
return $this->id;
}
public function remoteUrl(): string
{
return sprintf(
'https://rdc.sat.gob.mx/rccf/%s/%s/%s/%s/%s/%s.cer',
substr($this->id, 0, 6),
substr($this->id, 6, 6),
substr($this->id, 12, 2),
substr($this->id, 14, 2),
substr($this->id, 16, 2),
$this->id
);
}
public static function isValidCertificateNumber(string $id): bool
{
return (bool) preg_match('/^\d{20}$/', $id);
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Certificado/SerialNumber.php | src/CfdiUtils/Certificado/SerialNumber.php | <?php
namespace CfdiUtils\Certificado;
use CfdiUtils\Internals\BaseConverter;
/**
* This class is used to load hexadecimal or decimal data as a certificate serial number.
* It have its own class because SOLID and is easy to test in this way.
* It is not intented to use in general.
*/
class SerialNumber
{
/** @var string Hexadecimal representation */
private string $hexString;
public function __construct(string $hexString)
{
$this->loadHexadecimal($hexString);
}
public function loadHexadecimal(string $hexString): void
{
if (! preg_match('/^[0-9a-f]*$/', $hexString)) {
throw new \UnexpectedValueException('The hexadecimal string contains invalid characters');
}
$this->hexString = $hexString;
}
public function loadDecimal(string $decString): void
{
if (0 === strcasecmp('0x', substr($decString, 0, 2))) {
$hexString = substr($decString, 2);
} else {
$hexString = BaseConverter::createBase36()->convert($decString, 10, 16);
}
$this->loadHexadecimal($hexString);
}
public function loadAscii(string $input): void
{
$this->loadHexadecimal($this->asciiToHex($input));
}
public function getHexadecimal(): string
{
return $this->hexString;
}
public function asAscii(): string
{
return $this->hexToAscii($this->getHexadecimal());
}
public function asDecimal(): string
{
return BaseConverter::createBase36()->convert($this->getHexadecimal(), 16, 10);
}
protected function hexToAscii(string $input): string
{
return implode('', array_map(
fn (string $value): string => chr(intval(hexdec($value))),
str_split($input, 2),
));
}
protected function asciiToHex(string $input): string
{
return implode('', array_map(
fn (string $value): string => dechex(ord($value)),
str_split($input, 1),
));
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Certificado/NodeCertificado.php | src/CfdiUtils/Certificado/NodeCertificado.php | <?php
namespace CfdiUtils\Certificado;
use CfdiUtils\Nodes\NodeInterface;
class NodeCertificado
{
public function __construct(private NodeInterface $comprobante)
{
}
/**
* Extract the certificate from Comprobante->certificado
* If the node does not exists return an empty string
* The returned string is no longer base64 encoded
*
*
* @throws \RuntimeException if the certificado attribute is not a valid base64 encoded string
*/
public function extract(): string
{
$version = $this->getVersion();
if ('3.2' === $version) {
$attr = 'certificado';
} elseif ('3.3' === $version) {
$attr = 'Certificado';
} elseif ('4.0' === $version) {
$attr = 'Certificado';
} else {
throw new \RuntimeException('Unsupported or unknown version');
}
$certificateBase64 = $this->comprobante->searchAttribute($attr);
if ('' === $certificateBase64) {
return '';
}
$certificateBin = (string) base64_decode($certificateBase64, true);
if ('' === $certificateBin) {
throw new \RuntimeException('The certificado attribute is not a valid base64 encoded string');
}
return $certificateBin;
}
public function getVersion(): string
{
if ('3.2' === $this->comprobante->searchAttribute('version')) {
return '3.2';
}
if ('3.3' === $this->comprobante->searchAttribute('Version')) {
return '3.3';
}
if ('4.0' === $this->comprobante->searchAttribute('Version')) {
return '4.0';
}
return '';
}
/**
* Extract and save the certificate into an specified location
*
* @see extract
*
*
* @throws \UnexpectedValueException if the filename to store the certificate is empty
* @throws \RuntimeException if the certificado attribute is empty
* @throws \RuntimeException if cannot write the contents of the certificate
*/
public function save(string $filename): void
{
if ('' === $filename) {
throw new \UnexpectedValueException('The filename to store the certificate is empty');
}
$certificado = $this->extract();
if ('' === $certificado) {
throw new \RuntimeException('The certificado attribute is empty');
}
try {
if (false === file_put_contents($filename, $certificado)) {
throw new \RuntimeException('file_put_contents returns FALSE');
}
} catch (\Throwable $error) {
throw new \RuntimeException("Unable to write the certificate contents into $filename", 0, $error);
}
}
/**
* Return a Certificado object from the Comprobante->Certificado attribute
* The temporary certificate is stored into a temporary folder and removed
* after the certificado is loaded. If you need to persist the certificate
* use the saveCertificado method instead
*
* @see save
*/
public function obtain(): Certificado
{
$certificado = $this->extract();
if ('' === $certificado) {
throw new \RuntimeException('The certificado attribute is empty');
}
return new Certificado(base64_encode($certificado));
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Certificado/CertificadoPropertyInterface.php | src/CfdiUtils/Certificado/CertificadoPropertyInterface.php | <?php
namespace CfdiUtils\Certificado;
interface CertificadoPropertyInterface
{
public function getCertificado(): Certificado;
public function setCertificado(Certificado $certificado);
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Certificado/Certificado.php | src/CfdiUtils/Certificado/Certificado.php | <?php
namespace CfdiUtils\Certificado;
use CfdiUtils\OpenSSL\OpenSSL;
use CfdiUtils\OpenSSL\OpenSSLPropertyTrait;
use CfdiUtils\Utils\RegimenCapitalRemover;
class Certificado
{
use OpenSSLPropertyTrait;
private string $rfc;
private string $certificateName;
private string $name;
private SerialNumber $serial;
private int $validFrom;
private int $validTo;
private string $pubkey;
private string $filename;
private string $pemContents;
private ?string $nameWithoutRegimenCapitalSuffix;
/**
* Certificado constructor.
*
* @param string $filename Allows filename or certificate contents (PEM or DER)
* @throws \UnexpectedValueException when the certificate does not exist or is not readable
* @throws \UnexpectedValueException when cannot read the certificate or is empty
* @throws \RuntimeException when cannot parse the certificate or is empty
* @throws \RuntimeException when cannot get serialNumberHex or serialNumber from certificate
*/
public function __construct(string $filename, ?OpenSSL $openSSL = null)
{
$this->setOpenSSL($openSSL ?: new OpenSSL());
$contents = $this->extractPemCertificate($filename);
// using $filename as PEM content did not retrieve any result,
// or the path actually exists (path is a valid base64 string)
// then use it as path
if ('' === $contents || realpath($filename)) {
$sourceName = 'file ' . $filename;
$this->assertFileExists($filename);
$contents = file_get_contents($filename) ?: '';
if ('' === $contents) {
throw new \UnexpectedValueException("File $filename is empty");
}
// this will take PEM contents or perform a PHP conversion from DER to PEM
$contents = $this->obtainPemCertificate($contents);
} else {
$filename = '';
$sourceName = '(contents)';
}
// get the certificate data
$data = openssl_x509_parse($contents, true);
if (! is_array($data)) {
throw new \RuntimeException("Cannot parse the certificate $sourceName");
}
// get the public key
$pubKey = $this->obtainPubKeyFromContents($contents);
// set all the values
$this->certificateName = strval($data['name'] ?? '');
$this->rfc = (string) strstr(($data['subject']['x500UniqueIdentifier'] ?? '') . ' ', ' ', true);
$this->name = strval($data['subject']['name'] ?? '');
$this->nameWithoutRegimenCapitalSuffix = null;
$serial = new SerialNumber('');
if (isset($data['serialNumberHex'])) {
$serial->loadHexadecimal($data['serialNumberHex']);
} elseif (isset($data['serialNumber'])) {
$serial->loadDecimal($data['serialNumber']);
} else {
throw new \RuntimeException("Cannot get serialNumberHex or serialNumber from certificate $sourceName");
}
$this->serial = $serial;
$this->validFrom = $data['validFrom_time_t'] ?? 0;
$this->validTo = $data['validTo_time_t'] ?? 0;
$this->pubkey = $pubKey;
$this->pemContents = $contents;
$this->filename = $filename;
}
private function extractPemCertificate(string $contents): string
{
$openssl = $this->getOpenSSL();
$decoded = @base64_decode($contents, true) ?: '';
if ('' !== $decoded && $contents === base64_encode($decoded)) { // is a one-liner certificate
$doubleEncoded = $openssl->readPemContents($decoded)->certificate();
if ('' !== $doubleEncoded) {
return $doubleEncoded;
}
// derCerConvertPhp will include PEM header and footer
$contents = $this->getOpenSSL()->derCerConvertPhp($decoded);
}
return $openssl->readPemContents($contents)->certificate();
}
private function obtainPemCertificate(string $contents): string
{
$openssl = $this->getOpenSSL();
$extracted = $openssl->readPemContents($contents)->certificate();
if ('' === $extracted) { // cannot extract, could be on DER format
$extracted = $this->getOpenSSL()->derCerConvertPhp($contents);
}
return $extracted;
}
/**
* Check if this certificate belongs to a private key
*
*
*
* @throws \UnexpectedValueException if the file does not exist or is not readable
* @throws \UnexpectedValueException if the file is not a PEM private key
* @throws \RuntimeException if the private key file cannot be opened
*/
public function belongsTo(string $pemKeyFile, string $passPhrase = ''): bool
{
$this->assertFileExists($pemKeyFile);
$openSSL = $this->getOpenSSL();
$keyContents = $openSSL->readPemContents(
// intentionally silence this error, if return false then cast it to string
strval(@file_get_contents($pemKeyFile))
)->privateKey();
if ('' === $keyContents) {
throw new \UnexpectedValueException("The file $pemKeyFile is not a PEM private key");
}
$privateKey = openssl_get_privatekey($keyContents, $passPhrase);
if (false === $privateKey) {
throw new \RuntimeException("Cannot open the private key file $pemKeyFile");
}
return openssl_x509_check_private_key($this->getPemContents(), $privateKey);
}
/**
* RFC (Registro Federal de Contribuyentes) set when certificate was created
*/
public function getRfc(): string
{
return $this->rfc;
}
/**
* Certificate name value as returned by openssl.
* In come cases (openssl version 3) it contains quoted slashes (\/)
*/
public function getCertificateName(): string
{
return $this->certificateName;
}
/**
* Name (Razón Social) set when certificate was created
*/
public function getName($trimSuffix = false): string
{
return ($trimSuffix) ? $this->getNameWithoutRegimenCapitalSuffix() : $this->name;
}
/**
* Name (Razón Social) set when certificate was created without *régimen de capital* suffix
*/
public function getNameWithoutRegimenCapitalSuffix(): string
{
if (null === $this->nameWithoutRegimenCapitalSuffix) {
$remover = RegimenCapitalRemover::createDefault();
$this->nameWithoutRegimenCapitalSuffix = $remover->remove($this->name);
}
return $this->nameWithoutRegimenCapitalSuffix;
}
/**
* Return the certificate serial number ASCII formatted, this data is in the format required by CFDI
*/
public function getSerial(): string
{
return $this->serial->asAscii();
}
public function getSerialObject(): SerialNumber
{
return clone $this->serial;
}
/**
* Timestamp since the certificate is valid
*/
public function getValidFrom(): int
{
return $this->validFrom;
}
/**
* Timestamp until the certificate is valid
*/
public function getValidTo(): int
{
return $this->validTo;
}
/**
* String representation of the public key
*/
public function getPubkey(): string
{
return $this->pubkey;
}
/**
* Place where the certificate was when loaded, it might not exist on the file system
*/
public function getFilename(): string
{
return $this->filename;
}
/**
* The contents of the certificate in PEM format
*/
public function getPemContents(): string
{
return $this->pemContents;
}
/**
* The contents of the certificate in PEM format
*/
public function getPemContentsOneLine(): string
{
return implode('', preg_grep('/^((?!-).)*$/', explode(PHP_EOL, $this->pemContents)));
}
/**
* Verify the signature of some data
*
*
*
* @throws \RuntimeException if the public key on the certificate cannot be opened
* @throws \RuntimeException if openssl report an error
*/
public function verify(string $data, string $signature, int $algorithm = OPENSSL_ALGO_SHA256): bool
{
$pubKey = openssl_get_publickey($this->getPubkey());
if (false === $pubKey) {
throw new \RuntimeException('Cannot open public key from certificate');
}
$verify = openssl_verify($data, $signature, $pubKey, $algorithm);
if (-1 === $verify) {
throw new \RuntimeException('OpenSSL Error: ' . openssl_error_string());
}
return 1 === $verify;
}
/**
* @throws \UnexpectedValueException when the file does not exist or is not readable
*/
protected function assertFileExists(string $filename): void
{
$exists = false;
$previous = null;
try {
if (preg_match('/[[:cntrl:]]/', $filename)) {
$filename = '(invalid file name)';
throw new \RuntimeException('The file name contains control characters, it might be a DER content');
}
if (file_exists($filename) && is_readable($filename) && ! is_dir($filename)) {
$exists = true;
}
} catch (\Throwable $exception) {
$previous = $exception;
}
if (! $exists) {
$exceptionMessage = sprintf('File %s does not exists or is not readable', $filename);
throw new \UnexpectedValueException($exceptionMessage, 0, $previous);
}
}
protected function obtainPubKeyFromContents(string $contents): string
{
$pubkey = openssl_get_publickey($contents);
if (false === $pubkey) {
return '';
}
$pubData = openssl_pkey_get_details($pubkey) ?: [];
return $pubData['key'] ?? '';
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Asserts.php | src/CfdiUtils/Validate/Asserts.php | <?php
namespace CfdiUtils\Validate;
use Traversable;
class Asserts implements \Countable, \IteratorAggregate
{
/** @var array<string, Assert> */
private array $asserts = [];
private bool $mustStop = false;
/**
* This will try to create a new assert or get and change an assert with the same code
* The new values are preserved, except if they are null
*/
public function put(
string $code,
?string $title = null,
?Status $status = null,
?string $explanation = null,
): Assert {
if (! $this->exists($code)) {
$assert = new Assert($code, (string) $title, $status, (string) $explanation);
$this->add($assert);
return $assert;
}
$assert = $this->get($code);
if (null !== $title) {
$assert->setTitle($title);
}
if (null !== $status) {
$assert->setStatus($status);
}
if (null !== $explanation) {
$assert->setExplanation($explanation);
}
return $assert;
}
/**
* This will try to create a new assert or get and change an assert with the same code
* The new values are preserved, except if they are null
*/
public function putStatus(string $code, ?Status $status = null, ?string $explanation = null): Assert
{
return $this->put($code, null, $status, $explanation);
}
/**
* Get and or set the flag that alerts about stop flow
* Consider this flag as: "Something was found, you must not continue"
*
* @param bool|null $newValue value of the flag, if null then will not change the flag
* @return bool the previous value of the flag
*/
public function mustStop(?bool $newValue = null): bool
{
if (null === $newValue) {
return $this->mustStop;
}
$previous = $this->mustStop;
$this->mustStop = $newValue;
return $previous;
}
public function hasStatus(Status $status): bool
{
return null !== $this->getFirstStatus($status);
}
public function hasErrors(): bool
{
return $this->hasStatus(Status::error());
}
public function hasWarnings(): bool
{
return $this->hasStatus(Status::warn());
}
public function getFirstStatus(Status $status): ?Assert
{
foreach ($this->asserts as $assert) {
if ($status->equalsTo($assert->getStatus())) {
return $assert;
}
}
return null;
}
/**
* @return Assert[]
*/
public function byStatus(Status $status): array
{
return array_filter($this->asserts, fn (Assert $item): bool => $status->equalsTo($item->getStatus()));
}
public function get(string $code): Assert
{
foreach ($this->asserts as $assert) {
if ($assert->getCode() === $code) {
return $assert;
}
}
throw new \RuntimeException("There is no assert with code $code");
}
public function exists(string $code): bool
{
return array_key_exists($code, $this->asserts);
}
/**
* @return Assert[]
*/
public function oks(): array
{
return $this->byStatus(Status::ok());
}
/**
* @return Assert[]
*/
public function errors(): array
{
return $this->byStatus(Status::error());
}
/**
* @return Assert[]
*/
public function warnings(): array
{
return $this->byStatus(Status::warn());
}
/**
* @return Assert[]
*/
public function nones(): array
{
return $this->byStatus(Status::none());
}
public function add(Assert $assert): void
{
$this->asserts[$assert->getCode()] = $assert;
}
private function indexOf(Assert $assert): string
{
$index = array_search($assert, $this->asserts, true);
return (false === $index) ? '' : $index;
}
public function remove(Assert $assert): void
{
$index = $this->indexOf($assert);
if ('' !== $index) {
unset($this->asserts[$index]);
}
}
public function removeByCode(string $index): void
{
unset($this->asserts[$index]);
}
public function removeAll(): void
{
$this->asserts = [];
}
public function import(self $asserts): void
{
foreach ($asserts as $assert) {
$this->add(clone $assert);
}
$this->mustStop($asserts->mustStop());
}
/** @return Traversable<string, Assert> */
public function getIterator(): Traversable
{
return new \ArrayIterator($this->asserts);
}
public function count(): int
{
return count($this->asserts);
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/MultiValidator.php | src/CfdiUtils/Validate/MultiValidator.php | <?php
namespace CfdiUtils\Validate;
use CfdiUtils\Nodes\NodeInterface;
use CfdiUtils\Validate\Contracts\ValidatorInterface;
use Traversable;
class MultiValidator implements ValidatorInterface, \Countable, \IteratorAggregate
{
/** @var ValidatorInterface[] */
private array $validators = [];
public function __construct(private string $version)
{
}
public function getVersion(): string
{
return $this->version;
}
public function validate(NodeInterface $comprobante, Asserts $asserts): void
{
foreach ($this->validators as $validator) {
if (! $validator->canValidateCfdiVersion($this->getVersion())) {
continue;
}
$localAsserts = new Asserts();
$validator->validate($comprobante, $localAsserts);
$asserts->import($localAsserts);
if ($localAsserts->mustStop()) {
break;
}
}
}
public function canValidateCfdiVersion(string $version): bool
{
return $this->version === $version;
}
public function hydrate(Hydrater $hydrater): void
{
foreach ($this->validators as $validator) {
$hydrater->hydrate($validator);
}
}
/*
* Collection methods
*/
public function add(ValidatorInterface $validator): void
{
$this->validators[] = $validator;
}
public function addMulti(ValidatorInterface ...$validators): void
{
foreach ($validators as $validator) {
$this->add($validator);
}
}
public function exists(ValidatorInterface $validator): bool
{
return $this->indexOf($validator) >= 0;
}
private function indexOf(ValidatorInterface $validator): int
{
$index = array_search($validator, $this->validators, true);
return (false === $index) ? -1 : (int) $index;
}
public function remove(ValidatorInterface $validator): void
{
$index = $this->indexOf($validator);
if ($index >= 0) {
unset($this->validators[$index]);
}
}
public function removeAll(): void
{
$this->validators = [];
}
/** @return Traversable<ValidatorInterface> */
public function getIterator(): Traversable
{
return new \ArrayIterator($this->validators);
}
public function count(): int
{
return count($this->validators);
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Hydrater.php | src/CfdiUtils/Validate/Hydrater.php | <?php
namespace CfdiUtils\Validate;
use CfdiUtils\CadenaOrigen\XsltBuilderPropertyInterface;
use CfdiUtils\CadenaOrigen\XsltBuilderPropertyTrait;
use CfdiUtils\Validate\Contracts\RequireXmlResolverInterface;
use CfdiUtils\Validate\Contracts\RequireXmlStringInterface;
use CfdiUtils\Validate\Contracts\RequireXsltBuilderInterface;
use CfdiUtils\Validate\Contracts\ValidatorInterface;
use CfdiUtils\Validate\Traits\XmlStringPropertyTrait;
use CfdiUtils\XmlResolver\XmlResolverPropertyInterface;
use CfdiUtils\XmlResolver\XmlResolverPropertyTrait;
class Hydrater implements XmlResolverPropertyInterface, XsltBuilderPropertyInterface
{
use XmlResolverPropertyTrait;
use XmlStringPropertyTrait;
use XsltBuilderPropertyTrait;
public function hydrate(ValidatorInterface $validator): void
{
if ($validator instanceof RequireXmlStringInterface) {
$validator->setXmlString($this->getXmlString());
}
if ($this->hasXmlResolver() && $validator instanceof RequireXmlResolverInterface) {
$validator->setXmlResolver($this->getXmlResolver());
}
if ($validator instanceof RequireXsltBuilderInterface) {
$validator->setXsltBuilder($this->getXsltBuilder());
}
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/CfdiValidatorTrait.php | src/CfdiUtils/Validate/CfdiValidatorTrait.php | <?php
namespace CfdiUtils\Validate;
use CfdiUtils\CadenaOrigen\DOMBuilder;
use CfdiUtils\CadenaOrigen\XsltBuilderInterface;
use CfdiUtils\CadenaOrigen\XsltBuilderPropertyTrait;
use CfdiUtils\Nodes\NodeInterface;
use CfdiUtils\Nodes\XmlNodeUtils;
use CfdiUtils\XmlResolver\XmlResolver;
use CfdiUtils\XmlResolver\XmlResolverPropertyTrait;
trait CfdiValidatorTrait
{
use XmlResolverPropertyTrait;
use XsltBuilderPropertyTrait;
abstract protected function createVersionedMultiValidator(): MultiValidator;
/**
* This class uses a default XmlResolver if not provided or null.
* If you really want to remove the XmlResolver then use the method setXmlResolver after construction.
*/
public function __construct(?XmlResolver $xmlResolver = null, ?XsltBuilderInterface $xsltBuilder = null)
{
$this->setXmlResolver($xmlResolver ?: new XmlResolver());
$this->setXsltBuilder($xsltBuilder ?: new DOMBuilder());
}
/**
* Validate and return the asserts from the validation process.
* This method can use a xml string and a NodeInterface,
* is your responsibility that the node is the representation of the content.
*
* @return Asserts|Assert[]
*/
public function validate(string $xmlString, NodeInterface $node): Asserts
{
if ('' === $xmlString) {
throw new \UnexpectedValueException('The xml string to validate cannot be empty');
}
$validator = $this->createVersionedMultiValidator();
$hydrater = new Hydrater();
$hydrater->setXmlString($xmlString);
$hydrater->setXmlResolver(($this->hasXmlResolver()) ? $this->getXmlResolver() : null);
$hydrater->setXsltBuilder($this->getXsltBuilder());
$validator->hydrate($hydrater);
$asserts = new Asserts();
$validator->validate($node, $asserts);
return $asserts;
}
/**
* Validate and return the asserts from the validation process based on a xml string
*
* @return Asserts|Assert[]
*/
public function validateXml(string $xmlString): Asserts
{
return $this->validate($xmlString, XmlNodeUtils::nodeFromXmlString($xmlString));
}
/**
* Validate and return the asserts from the validation process based on a node interface object
*
* @return Asserts|Assert[]
*/
public function validateNode(NodeInterface $node): Asserts
{
return $this->validate(XmlNodeUtils::nodeToXmlString($node), $node);
}
}
| php | MIT | 6786b3ee34831ef0d633302226414682a7a35aca | 2026-01-05T04:57:52.988826Z | false |
eclipxe13/CfdiUtils | https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Validate/Discoverer.php | src/CfdiUtils/Validate/Discoverer.php | <?php
namespace CfdiUtils\Validate;
use CfdiUtils\Validate\Contracts\DiscoverableCreateInterface as Discoverable;
use CfdiUtils\Validate\Contracts\ValidatorInterface;
class Discoverer
{
public function castNamespacePrefix(string $namespacePrefix): string
{
return rtrim($namespacePrefix, '\\') . '\\';
}
/**
* @return ValidatorInterface[]
*/
public function discoverInFolder(string $namespacePrefix, string $directoryPath): array
{
$discovered = [];
$filenames = glob($directoryPath . '/*.php') ?: [];
foreach ($filenames as $filename) {
$object = $this->discoverInFile($namespacePrefix, $filename);
if (null !== $object) {
$discovered[] = $object;
}
}
return $discovered;
}
public function discoverInFile(string $namespacePrefix, string $filename): ?ValidatorInterface
{
$basename = basename($filename);
$classname = $this->castNamespacePrefix($namespacePrefix) . substr($basename, 0, strlen($basename) - 4);
if (class_exists($classname) && in_array(Discoverable::class, class_implements($classname), true)) {
/** @var callable $callable */
$callable = [$classname, 'createDiscovered'];
$object = call_user_func($callable);
if ($object instanceof ValidatorInterface) {
return $object;
}
}
return null;
}
}
| 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.