repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
LibreDTE/libredte-lib | lib/FirmaElectronica.php | FirmaElectronica.sign | public function sign($data, $signature_alg = OPENSSL_ALGO_SHA1)
{
$signature = null;
if (openssl_sign($data, $signature, $this->certs['pkey'], $signature_alg)==false) {
return $this->error('No fue posible firmar los datos');
}
return base64_encode($signature);
} | php | public function sign($data, $signature_alg = OPENSSL_ALGO_SHA1)
{
$signature = null;
if (openssl_sign($data, $signature, $this->certs['pkey'], $signature_alg)==false) {
return $this->error('No fue posible firmar los datos');
}
return base64_encode($signature);
} | [
"public",
"function",
"sign",
"(",
"$",
"data",
",",
"$",
"signature_alg",
"=",
"OPENSSL_ALGO_SHA1",
")",
"{",
"$",
"signature",
"=",
"null",
";",
"if",
"(",
"openssl_sign",
"(",
"$",
"data",
",",
"$",
"signature",
",",
"$",
"this",
"->",
"certs",
"[",... | Método para realizar la firma de datos
@param data Datos que se desean firmar
@param signature_alg Algoritmo que se utilizará para firmar (por defect SHA1)
@return Firma digital de los datos en base64 o =false si no se pudo firmar
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2014-12-08 | [
"Método",
"para",
"realizar",
"la",
"firma",
"de",
"datos"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/FirmaElectronica.php#L335-L342 |
LibreDTE/libredte-lib | lib/FirmaElectronica.php | FirmaElectronica.verify | public function verify($data, $signature, $pub_key = null, $signature_alg = OPENSSL_ALGO_SHA1)
{
if ($pub_key === null)
$pub_key = $this->certs['cert'];
$pub_key = $this->normalizeCert($pub_key);
return openssl_verify($data, base64_decode($signature), $pub_key, $signature_alg) == 1 ? true : false;
} | php | public function verify($data, $signature, $pub_key = null, $signature_alg = OPENSSL_ALGO_SHA1)
{
if ($pub_key === null)
$pub_key = $this->certs['cert'];
$pub_key = $this->normalizeCert($pub_key);
return openssl_verify($data, base64_decode($signature), $pub_key, $signature_alg) == 1 ? true : false;
} | [
"public",
"function",
"verify",
"(",
"$",
"data",
",",
"$",
"signature",
",",
"$",
"pub_key",
"=",
"null",
",",
"$",
"signature_alg",
"=",
"OPENSSL_ALGO_SHA1",
")",
"{",
"if",
"(",
"$",
"pub_key",
"===",
"null",
")",
"$",
"pub_key",
"=",
"$",
"this",
... | Método que verifica la firma digital de datos
@param data Datos que se desean verificar
@param signature Firma digital de los datos en base64
@param pub_key Certificado digital, clave pública, de la firma
@param signature_alg Algoritmo que se usó para firmar (por defect SHA1)
@return =true si la firma está ok, =false si está mal o no se pudo determinar
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2014-12-08 | [
"Método",
"que",
"verifica",
"la",
"firma",
"digital",
"de",
"datos"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/FirmaElectronica.php#L354-L360 |
LibreDTE/libredte-lib | lib/FirmaElectronica.php | FirmaElectronica.signXML | public function signXML($xml, $reference = '', $tag = null, $xmlns_xsi = false)
{
// normalizar 4to parámetro que puede ser boolean o array
if (is_array($xmlns_xsi)) {
$namespace = $xmlns_xsi;
$xmlns_xsi = false;
} else {
$namespace = null;
}
// obtener objeto del XML que se va a firmar
$doc = new XML();
$doc->loadXML($xml);
if (!$doc->documentElement) {
return $this->error('No se pudo obtener el documentElement desde el XML a firmar (posible XML mal formado)');
}
// crear nodo para la firma
$Signature = $doc->importNode((new XML())->generate([
'Signature' => [
'@attributes' => $namespace ? false : [
'xmlns' => 'http://www.w3.org/2000/09/xmldsig#',
],
'SignedInfo' => [
'@attributes' => $namespace ? false : [
'xmlns' => 'http://www.w3.org/2000/09/xmldsig#',
'xmlns:xsi' => $xmlns_xsi ? 'http://www.w3.org/2001/XMLSchema-instance' : false,
],
'CanonicalizationMethod' => [
'@attributes' => [
'Algorithm' => 'http://www.w3.org/TR/2001/REC-xml-c14n-20010315',
],
],
'SignatureMethod' => [
'@attributes' => [
'Algorithm' => 'http://www.w3.org/2000/09/xmldsig#rsa-sha1',
],
],
'Reference' => [
'@attributes' => [
'URI' => $reference,
],
'Transforms' => [
'Transform' => [
'@attributes' => [
'Algorithm' => $namespace ? 'http://www.altova.com' : 'http://www.w3.org/2000/09/xmldsig#enveloped-signature',
],
],
],
'DigestMethod' => [
'@attributes' => [
'Algorithm' => 'http://www.w3.org/2000/09/xmldsig#sha1',
],
],
'DigestValue' => null,
],
],
'SignatureValue' => null,
'KeyInfo' => [
'KeyValue' => [
'RSAKeyValue' => [
'Modulus' => null,
'Exponent' => null,
],
],
'X509Data' => [
'X509Certificate' => null,
],
],
],
], $namespace)->documentElement, true);
// calcular DigestValue
if ($tag) {
$item = $doc->documentElement->getElementsByTagName($tag)->item(0);
if (!$item) {
return $this->error('No fue posible obtener el nodo con el tag '.$tag);
}
$digest = base64_encode(sha1($item->C14N(), true));
} else {
$digest = base64_encode(sha1($doc->C14N(), true));
}
$Signature->getElementsByTagName('DigestValue')->item(0)->nodeValue = $digest;
// calcular SignatureValue
$SignedInfo = $doc->saveHTML($Signature->getElementsByTagName('SignedInfo')->item(0));
$firma = $this->sign($SignedInfo);
if (!$firma)
return false;
$signature = wordwrap($firma, $this->config['wordwrap'], "\n", true);
// reemplazar valores en la firma de
$Signature->getElementsByTagName('SignatureValue')->item(0)->nodeValue = $signature;
$Signature->getElementsByTagName('Modulus')->item(0)->nodeValue = $this->getModulus();
$Signature->getElementsByTagName('Exponent')->item(0)->nodeValue = $this->getExponent();
$Signature->getElementsByTagName('X509Certificate')->item(0)->nodeValue = $this->getCertificate(true);
// agregar y entregar firma
$doc->documentElement->appendChild($Signature);
return $doc->saveXML();
} | php | public function signXML($xml, $reference = '', $tag = null, $xmlns_xsi = false)
{
// normalizar 4to parámetro que puede ser boolean o array
if (is_array($xmlns_xsi)) {
$namespace = $xmlns_xsi;
$xmlns_xsi = false;
} else {
$namespace = null;
}
// obtener objeto del XML que se va a firmar
$doc = new XML();
$doc->loadXML($xml);
if (!$doc->documentElement) {
return $this->error('No se pudo obtener el documentElement desde el XML a firmar (posible XML mal formado)');
}
// crear nodo para la firma
$Signature = $doc->importNode((new XML())->generate([
'Signature' => [
'@attributes' => $namespace ? false : [
'xmlns' => 'http://www.w3.org/2000/09/xmldsig#',
],
'SignedInfo' => [
'@attributes' => $namespace ? false : [
'xmlns' => 'http://www.w3.org/2000/09/xmldsig#',
'xmlns:xsi' => $xmlns_xsi ? 'http://www.w3.org/2001/XMLSchema-instance' : false,
],
'CanonicalizationMethod' => [
'@attributes' => [
'Algorithm' => 'http://www.w3.org/TR/2001/REC-xml-c14n-20010315',
],
],
'SignatureMethod' => [
'@attributes' => [
'Algorithm' => 'http://www.w3.org/2000/09/xmldsig#rsa-sha1',
],
],
'Reference' => [
'@attributes' => [
'URI' => $reference,
],
'Transforms' => [
'Transform' => [
'@attributes' => [
'Algorithm' => $namespace ? 'http://www.altova.com' : 'http://www.w3.org/2000/09/xmldsig#enveloped-signature',
],
],
],
'DigestMethod' => [
'@attributes' => [
'Algorithm' => 'http://www.w3.org/2000/09/xmldsig#sha1',
],
],
'DigestValue' => null,
],
],
'SignatureValue' => null,
'KeyInfo' => [
'KeyValue' => [
'RSAKeyValue' => [
'Modulus' => null,
'Exponent' => null,
],
],
'X509Data' => [
'X509Certificate' => null,
],
],
],
], $namespace)->documentElement, true);
// calcular DigestValue
if ($tag) {
$item = $doc->documentElement->getElementsByTagName($tag)->item(0);
if (!$item) {
return $this->error('No fue posible obtener el nodo con el tag '.$tag);
}
$digest = base64_encode(sha1($item->C14N(), true));
} else {
$digest = base64_encode(sha1($doc->C14N(), true));
}
$Signature->getElementsByTagName('DigestValue')->item(0)->nodeValue = $digest;
// calcular SignatureValue
$SignedInfo = $doc->saveHTML($Signature->getElementsByTagName('SignedInfo')->item(0));
$firma = $this->sign($SignedInfo);
if (!$firma)
return false;
$signature = wordwrap($firma, $this->config['wordwrap'], "\n", true);
// reemplazar valores en la firma de
$Signature->getElementsByTagName('SignatureValue')->item(0)->nodeValue = $signature;
$Signature->getElementsByTagName('Modulus')->item(0)->nodeValue = $this->getModulus();
$Signature->getElementsByTagName('Exponent')->item(0)->nodeValue = $this->getExponent();
$Signature->getElementsByTagName('X509Certificate')->item(0)->nodeValue = $this->getCertificate(true);
// agregar y entregar firma
$doc->documentElement->appendChild($Signature);
return $doc->saveXML();
} | [
"public",
"function",
"signXML",
"(",
"$",
"xml",
",",
"$",
"reference",
"=",
"''",
",",
"$",
"tag",
"=",
"null",
",",
"$",
"xmlns_xsi",
"=",
"false",
")",
"{",
"// normalizar 4to parámetro que puede ser boolean o array",
"if",
"(",
"is_array",
"(",
"$",
"xm... | Método que firma un XML utilizando RSA y SHA1
Referencia: http://www.di-mgt.com.au/xmldsig2.html
@param xml Datos XML que se desean firmar
@param reference Referencia a la que hace la firma
@return XML firmado o =false si no se pudo fimar
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2017-10-22 | [
"Método",
"que",
"firma",
"un",
"XML",
"utilizando",
"RSA",
"y",
"SHA1"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/FirmaElectronica.php#L373-L467 |
LibreDTE/libredte-lib | lib/FirmaElectronica.php | FirmaElectronica.verifyXML | public function verifyXML($xml_data, $tag = null)
{
$doc = new XML();
$doc->loadXML($xml_data);
// preparar datos que se verificarán
$SignaturesElements = $doc->documentElement->getElementsByTagName('Signature');
$Signature = $doc->documentElement->removeChild($SignaturesElements->item($SignaturesElements->length-1));
$SignedInfo = $Signature->getElementsByTagName('SignedInfo')->item(0);
$SignedInfo->setAttribute('xmlns', $Signature->getAttribute('xmlns'));
$signed_info = $doc->saveHTML($SignedInfo);
$signature = $Signature->getElementsByTagName('SignatureValue')->item(0)->nodeValue;
$pub_key = $Signature->getElementsByTagName('X509Certificate')->item(0)->nodeValue;
// verificar firma
if (!$this->verify($signed_info, $signature, $pub_key))
return false;
// verificar digest
$digest_original = $Signature->getElementsByTagName('DigestValue')->item(0)->nodeValue;
if ($tag) {
$digest_calculado = base64_encode(sha1($doc->documentElement->getElementsByTagName($tag)->item(0)->C14N(), true));
} else {
$digest_calculado = base64_encode(sha1($doc->C14N(), true));
}
return $digest_original == $digest_calculado;
} | php | public function verifyXML($xml_data, $tag = null)
{
$doc = new XML();
$doc->loadXML($xml_data);
// preparar datos que se verificarán
$SignaturesElements = $doc->documentElement->getElementsByTagName('Signature');
$Signature = $doc->documentElement->removeChild($SignaturesElements->item($SignaturesElements->length-1));
$SignedInfo = $Signature->getElementsByTagName('SignedInfo')->item(0);
$SignedInfo->setAttribute('xmlns', $Signature->getAttribute('xmlns'));
$signed_info = $doc->saveHTML($SignedInfo);
$signature = $Signature->getElementsByTagName('SignatureValue')->item(0)->nodeValue;
$pub_key = $Signature->getElementsByTagName('X509Certificate')->item(0)->nodeValue;
// verificar firma
if (!$this->verify($signed_info, $signature, $pub_key))
return false;
// verificar digest
$digest_original = $Signature->getElementsByTagName('DigestValue')->item(0)->nodeValue;
if ($tag) {
$digest_calculado = base64_encode(sha1($doc->documentElement->getElementsByTagName($tag)->item(0)->C14N(), true));
} else {
$digest_calculado = base64_encode(sha1($doc->C14N(), true));
}
return $digest_original == $digest_calculado;
} | [
"public",
"function",
"verifyXML",
"(",
"$",
"xml_data",
",",
"$",
"tag",
"=",
"null",
")",
"{",
"$",
"doc",
"=",
"new",
"XML",
"(",
")",
";",
"$",
"doc",
"->",
"loadXML",
"(",
"$",
"xml_data",
")",
";",
"// preparar datos que se verificarán",
"$",
"Si... | Método que verifica la validez de la firma de un XML utilizando RSA y SHA1
@param xml_data Archivo XML que se desea validar
@return =true si la firma del documento XML es válida o =false si no lo es
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2015-09-02 | [
"Método",
"que",
"verifica",
"la",
"validez",
"de",
"la",
"firma",
"de",
"un",
"XML",
"utilizando",
"RSA",
"y",
"SHA1"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/FirmaElectronica.php#L476-L499 |
LibreDTE/libredte-lib | lib/FirmaElectronica.php | FirmaElectronica.getFromModulusExponent | public static function getFromModulusExponent($modulus, $exponent)
{
$rsa = new \phpseclib\Crypt\RSA();
$modulus = new \phpseclib\Math\BigInteger(base64_decode($modulus), 256);
$exponent = new \phpseclib\Math\BigInteger(base64_decode($exponent), 256);
$rsa->loadKey(['n' => $modulus, 'e' => $exponent]);
$rsa->setPublicKey();
return $rsa->getPublicKey();
} | php | public static function getFromModulusExponent($modulus, $exponent)
{
$rsa = new \phpseclib\Crypt\RSA();
$modulus = new \phpseclib\Math\BigInteger(base64_decode($modulus), 256);
$exponent = new \phpseclib\Math\BigInteger(base64_decode($exponent), 256);
$rsa->loadKey(['n' => $modulus, 'e' => $exponent]);
$rsa->setPublicKey();
return $rsa->getPublicKey();
} | [
"public",
"static",
"function",
"getFromModulusExponent",
"(",
"$",
"modulus",
",",
"$",
"exponent",
")",
"{",
"$",
"rsa",
"=",
"new",
"\\",
"phpseclib",
"\\",
"Crypt",
"\\",
"RSA",
"(",
")",
";",
"$",
"modulus",
"=",
"new",
"\\",
"phpseclib",
"\\",
"M... | Método que obtiene la clave asociada al módulo y exponente entregados
@param modulus Módulo de la clave
@param exponent Exponente de la clave
@return Entrega la clave asociada al módulo y exponente
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2015-09-19 | [
"Método",
"que",
"obtiene",
"la",
"clave",
"asociada",
"al",
"módulo",
"y",
"exponente",
"entregados"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/FirmaElectronica.php#L509-L517 |
LibreDTE/libredte-lib | lib/Sii/LibroBoleta.php | LibroBoleta.agregar | public function agregar(array $detalle)
{
$this->detalles[] = array_merge([
'TpoDoc' => false,
'FolioDoc' => false,
'Anulado' => false,
'TpoServ' => 3,
'FchEmiDoc' => false,
'FchVencDoc' => false,
'PeriodoDesde' => false,
'PeriodoHasta' => false,
'CdgSIISucur' => false,
'RUTCliente' => false,
'CodIntCli' => false,
'MntExe' => false,
'MntTotal' => false,
'MntNoFact' => false,
'MntPeriodo' => false,
'SaldoAnt' => false,
'VlrPagar' => false,
'TotTicketBoleta' => false,
], $detalle);
} | php | public function agregar(array $detalle)
{
$this->detalles[] = array_merge([
'TpoDoc' => false,
'FolioDoc' => false,
'Anulado' => false,
'TpoServ' => 3,
'FchEmiDoc' => false,
'FchVencDoc' => false,
'PeriodoDesde' => false,
'PeriodoHasta' => false,
'CdgSIISucur' => false,
'RUTCliente' => false,
'CodIntCli' => false,
'MntExe' => false,
'MntTotal' => false,
'MntNoFact' => false,
'MntPeriodo' => false,
'SaldoAnt' => false,
'VlrPagar' => false,
'TotTicketBoleta' => false,
], $detalle);
} | [
"public",
"function",
"agregar",
"(",
"array",
"$",
"detalle",
")",
"{",
"$",
"this",
"->",
"detalles",
"[",
"]",
"=",
"array_merge",
"(",
"[",
"'TpoDoc'",
"=>",
"false",
",",
"'FolioDoc'",
"=>",
"false",
",",
"'Anulado'",
"=>",
"false",
",",
"'TpoServ'"... | Método que agrega un detalle al listado que se enviará
@param detalle Arreglo con los datos de la boleta que se desea agregar
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2015-12-14 | [
"Método",
"que",
"agrega",
"un",
"detalle",
"al",
"listado",
"que",
"se",
"enviará"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/LibroBoleta.php#L40-L62 |
LibreDTE/libredte-lib | lib/Sii/LibroBoleta.php | LibroBoleta.generar | public function generar()
{
// si ya se había generado se entrega directamente
if ($this->xml_data)
return $this->xml_data;
// generar XML del envío
$xmlEnvio = (new \sasco\LibreDTE\XML())->generate([
'LibroBoleta' => [
'@attributes' => [
'xmlns' => 'http://www.sii.cl/SiiDte',
'xmlns:xsi' => 'http://www.w3.org/2001/XMLSchema-instance',
'xsi:schemaLocation' => 'http://www.sii.cl/SiiDte LibroBOLETA_v10.xsd',
'version' => '1.0',
],
'EnvioLibro' => [
'@attributes' => [
'ID' => $this->id,
],
'Caratula' => $this->caratula,
'ResumenPeriodo' => $this->getResumenPeriodo(),
'Detalle' => $this->detalles,
'TmstFirma' => date('Y-m-d\TH:i:s'),
],
]
])->saveXML();
// firmar XML del envío y entregar
$this->xml_data = $this->Firma ? $this->Firma->signXML($xmlEnvio, '#'.$this->id, 'EnvioLibro', true) : $xmlEnvio;
// PARCHE! SII usa su propio namespace para la firma en las boletas ¬¬ ¡MAL!
$this->xml_data = str_replace('xmlns="http://www.w3.org/2000/09/xmldsig#"', 'xmlns="http://www.sii.cl/SiiDte"', $this->xml_data);
// entregar dato del XML
return $this->xml_data;
} | php | public function generar()
{
// si ya se había generado se entrega directamente
if ($this->xml_data)
return $this->xml_data;
// generar XML del envío
$xmlEnvio = (new \sasco\LibreDTE\XML())->generate([
'LibroBoleta' => [
'@attributes' => [
'xmlns' => 'http://www.sii.cl/SiiDte',
'xmlns:xsi' => 'http://www.w3.org/2001/XMLSchema-instance',
'xsi:schemaLocation' => 'http://www.sii.cl/SiiDte LibroBOLETA_v10.xsd',
'version' => '1.0',
],
'EnvioLibro' => [
'@attributes' => [
'ID' => $this->id,
],
'Caratula' => $this->caratula,
'ResumenPeriodo' => $this->getResumenPeriodo(),
'Detalle' => $this->detalles,
'TmstFirma' => date('Y-m-d\TH:i:s'),
],
]
])->saveXML();
// firmar XML del envío y entregar
$this->xml_data = $this->Firma ? $this->Firma->signXML($xmlEnvio, '#'.$this->id, 'EnvioLibro', true) : $xmlEnvio;
// PARCHE! SII usa su propio namespace para la firma en las boletas ¬¬ ¡MAL!
$this->xml_data = str_replace('xmlns="http://www.w3.org/2000/09/xmldsig#"', 'xmlns="http://www.sii.cl/SiiDte"', $this->xml_data);
// entregar dato del XML
return $this->xml_data;
} | [
"public",
"function",
"generar",
"(",
")",
"{",
"// si ya se había generado se entrega directamente",
"if",
"(",
"$",
"this",
"->",
"xml_data",
")",
"return",
"$",
"this",
"->",
"xml_data",
";",
"// generar XML del envío",
"$",
"xmlEnvio",
"=",
"(",
"new",
"\\",
... | Método que genera el XML del libro de boletas
@return XML con el envio del libro de boletas firmado o =false si no se pudo generar o firmar el libro
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2015-12-14 | [
"Método",
"que",
"genera",
"el",
"XML",
"del",
"libro",
"de",
"boletas"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/LibroBoleta.php#L91-L122 |
LibreDTE/libredte-lib | lib/Sii/LibroBoleta.php | LibroBoleta.getResumenPeriodo | private function getResumenPeriodo()
{
$resumen = [];
foreach ($this->detalles as &$d) {
// si el tipo de boleta no está en el resumen se crea
if (!isset($resumen[$d['TpoDoc']])) {
$resumen[$d['TpoDoc']] = [
'TpoDoc' => $d['TpoDoc'],
'TotAnulado' => false,
'TotalesServicio' => [],
];
}
// si no existe el tipo de servicio se agrega
if (!isset($resumen[$d['TpoDoc']]['TotalesServicio'][$d['TpoServ']])) {
$resumen[$d['TpoDoc']]['TotalesServicio'][$d['TpoServ']] = [
'TpoServ' => $d['TpoServ'],
'PeriodoDevengado' => false,
'TotDoc' => false,
'TotMntExe' => false,
'TotMntNeto' => 0,
'TasaIVA' => 0,
'TotMntIVA' => 0,
'TotMntTotal' => false,
'TotMntNoFact' => false,
'TotMntPeriodo' => false,
'TotSaldoAnt' => false,
'TotVlrPagar' => false,
'TotTicket' => false,
];
}
// agregar detalle al resumen
if (empty($d['Anulado'])) {
// contabilizar documento
$resumen[$d['TpoDoc']]['TotalesServicio'][$d['TpoServ']]['TotDoc'] += 1;
// ir sumando valores
$vals = ['MntExe'=>'TotMntExe', 'MntTotal'=>'TotMntTotal', 'MntNoFact'=>'TotMntNoFact', 'MntPeriodo'=>'TotMntPeriodo', 'SaldoAnt'=>'TotSaldoAnt', 'VlrPagar'=>'TotVlrPagar', 'TotTicketBoleta'=>'TotTicket'];
foreach ($vals as $ori => $des) {
if ($d[$ori]) {
$resumen[$d['TpoDoc']]['TotalesServicio'][$d['TpoServ']][$des] += $d[$ori];
}
}
// determinar neto e iva
$tasa = \sasco\LibreDTE\Sii::getIVA();
$neto = round(($d['MntTotal'] - $d['MntExe']) / (1 + $tasa/100));
if ($neto) {
$resumen[$d['TpoDoc']]['TotalesServicio'][$d['TpoServ']]['TotMntNeto'] += $neto;
$resumen[$d['TpoDoc']]['TotalesServicio'][$d['TpoServ']]['TasaIVA'] = $tasa;
// WARNING: problema por aproximaciones al calcular el NETO e IVA a partir del BRUTO
//$resumen[$d['TpoDoc']]['TotalesServicio'][$d['TpoServ']]['TotMntIVA'] = round($resumen[$d['TpoDoc']]['TotalesServicio'][$d['TpoServ']]['TotMntNeto'] * ($tasa/100));
$resumen[$d['TpoDoc']]['TotalesServicio'][$d['TpoServ']]['TotMntIVA'] = $resumen[$d['TpoDoc']]['TotalesServicio'][$d['TpoServ']]['TotMntTotal'] - $resumen[$d['TpoDoc']]['TotalesServicio'][$d['TpoServ']]['TotMntExe'] - $resumen[$d['TpoDoc']]['TotalesServicio'][$d['TpoServ']]['TotMntNeto'];
}
}
// documento anulado
else if ($d['Anulado']=='A') {
$resumen[$d['TpoDoc']]['TotAnulado'] += 1;
}
}
// armar resumen verdadero
$ResumenPeriodo = ['TotalesPeriodo'=>[]];
foreach ($resumen as $r) {
$ResumenPeriodo['TotalesPeriodo'][] = $r;
}
// entregar resumen
return $ResumenPeriodo;
} | php | private function getResumenPeriodo()
{
$resumen = [];
foreach ($this->detalles as &$d) {
// si el tipo de boleta no está en el resumen se crea
if (!isset($resumen[$d['TpoDoc']])) {
$resumen[$d['TpoDoc']] = [
'TpoDoc' => $d['TpoDoc'],
'TotAnulado' => false,
'TotalesServicio' => [],
];
}
// si no existe el tipo de servicio se agrega
if (!isset($resumen[$d['TpoDoc']]['TotalesServicio'][$d['TpoServ']])) {
$resumen[$d['TpoDoc']]['TotalesServicio'][$d['TpoServ']] = [
'TpoServ' => $d['TpoServ'],
'PeriodoDevengado' => false,
'TotDoc' => false,
'TotMntExe' => false,
'TotMntNeto' => 0,
'TasaIVA' => 0,
'TotMntIVA' => 0,
'TotMntTotal' => false,
'TotMntNoFact' => false,
'TotMntPeriodo' => false,
'TotSaldoAnt' => false,
'TotVlrPagar' => false,
'TotTicket' => false,
];
}
// agregar detalle al resumen
if (empty($d['Anulado'])) {
// contabilizar documento
$resumen[$d['TpoDoc']]['TotalesServicio'][$d['TpoServ']]['TotDoc'] += 1;
// ir sumando valores
$vals = ['MntExe'=>'TotMntExe', 'MntTotal'=>'TotMntTotal', 'MntNoFact'=>'TotMntNoFact', 'MntPeriodo'=>'TotMntPeriodo', 'SaldoAnt'=>'TotSaldoAnt', 'VlrPagar'=>'TotVlrPagar', 'TotTicketBoleta'=>'TotTicket'];
foreach ($vals as $ori => $des) {
if ($d[$ori]) {
$resumen[$d['TpoDoc']]['TotalesServicio'][$d['TpoServ']][$des] += $d[$ori];
}
}
// determinar neto e iva
$tasa = \sasco\LibreDTE\Sii::getIVA();
$neto = round(($d['MntTotal'] - $d['MntExe']) / (1 + $tasa/100));
if ($neto) {
$resumen[$d['TpoDoc']]['TotalesServicio'][$d['TpoServ']]['TotMntNeto'] += $neto;
$resumen[$d['TpoDoc']]['TotalesServicio'][$d['TpoServ']]['TasaIVA'] = $tasa;
// WARNING: problema por aproximaciones al calcular el NETO e IVA a partir del BRUTO
//$resumen[$d['TpoDoc']]['TotalesServicio'][$d['TpoServ']]['TotMntIVA'] = round($resumen[$d['TpoDoc']]['TotalesServicio'][$d['TpoServ']]['TotMntNeto'] * ($tasa/100));
$resumen[$d['TpoDoc']]['TotalesServicio'][$d['TpoServ']]['TotMntIVA'] = $resumen[$d['TpoDoc']]['TotalesServicio'][$d['TpoServ']]['TotMntTotal'] - $resumen[$d['TpoDoc']]['TotalesServicio'][$d['TpoServ']]['TotMntExe'] - $resumen[$d['TpoDoc']]['TotalesServicio'][$d['TpoServ']]['TotMntNeto'];
}
}
// documento anulado
else if ($d['Anulado']=='A') {
$resumen[$d['TpoDoc']]['TotAnulado'] += 1;
}
}
// armar resumen verdadero
$ResumenPeriodo = ['TotalesPeriodo'=>[]];
foreach ($resumen as $r) {
$ResumenPeriodo['TotalesPeriodo'][] = $r;
}
// entregar resumen
return $ResumenPeriodo;
} | [
"private",
"function",
"getResumenPeriodo",
"(",
")",
"{",
"$",
"resumen",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"detalles",
"as",
"&",
"$",
"d",
")",
"{",
"// si el tipo de boleta no está en el resumen se crea",
"if",
"(",
"!",
"isset",
"("... | Método que obtiene los datos para generar los tags TotalesPeriodo
@return Arreglo con los datos para generar los tags TotalesPeriodo
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2016-02-17 | [
"Método",
"que",
"obtiene",
"los",
"datos",
"para",
"generar",
"los",
"tags",
"TotalesPeriodo"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/LibroBoleta.php#L130-L194 |
LibreDTE/libredte-lib | lib/Sii/Folios.php | Folios.check | public function check()
{
// validar firma del SII sobre los folios
$firma = $this->getFirma();
$idk = $this->getIDK();
if ($firma === false || $idk === false) {
return false;
}
$pub_key = \sasco\LibreDTE\Sii::cert($idk);
if ($pub_key === false || openssl_verify($this->xml->getFlattened('/AUTORIZACION/CAF/DA'), base64_decode($firma), $pub_key)!==1) {
\sasco\LibreDTE\Log::write(
\sasco\LibreDTE\Estado::FOLIOS_ERROR_FIRMA,
\sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::FOLIOS_ERROR_FIRMA)
);
return false;
}
// validar clave privada y pública proporcionada por el SII
$private_key = $this->getPrivateKey();
if (!$private_key) {
return false;
}
$plain = md5(date('U'));
if (!openssl_private_encrypt($plain, $crypt, $private_key)) {
\sasco\LibreDTE\Log::write(
\sasco\LibreDTE\Estado::FOLIOS_ERROR_ENCRIPTAR,
\sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::FOLIOS_ERROR_ENCRIPTAR)
);
return false;
}
$public_key = $this->getPublicKey();
if (!$public_key) {
return false;
}
if (!openssl_public_decrypt($crypt, $plain_firmado, $public_key)) {
\sasco\LibreDTE\Log::write(
\sasco\LibreDTE\Estado::FOLIOS_ERROR_DESENCRIPTAR,
\sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::FOLIOS_ERROR_DESENCRIPTAR)
);
return false;
}
return $plain === $plain_firmado;
} | php | public function check()
{
// validar firma del SII sobre los folios
$firma = $this->getFirma();
$idk = $this->getIDK();
if ($firma === false || $idk === false) {
return false;
}
$pub_key = \sasco\LibreDTE\Sii::cert($idk);
if ($pub_key === false || openssl_verify($this->xml->getFlattened('/AUTORIZACION/CAF/DA'), base64_decode($firma), $pub_key)!==1) {
\sasco\LibreDTE\Log::write(
\sasco\LibreDTE\Estado::FOLIOS_ERROR_FIRMA,
\sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::FOLIOS_ERROR_FIRMA)
);
return false;
}
// validar clave privada y pública proporcionada por el SII
$private_key = $this->getPrivateKey();
if (!$private_key) {
return false;
}
$plain = md5(date('U'));
if (!openssl_private_encrypt($plain, $crypt, $private_key)) {
\sasco\LibreDTE\Log::write(
\sasco\LibreDTE\Estado::FOLIOS_ERROR_ENCRIPTAR,
\sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::FOLIOS_ERROR_ENCRIPTAR)
);
return false;
}
$public_key = $this->getPublicKey();
if (!$public_key) {
return false;
}
if (!openssl_public_decrypt($crypt, $plain_firmado, $public_key)) {
\sasco\LibreDTE\Log::write(
\sasco\LibreDTE\Estado::FOLIOS_ERROR_DESENCRIPTAR,
\sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::FOLIOS_ERROR_DESENCRIPTAR)
);
return false;
}
return $plain === $plain_firmado;
} | [
"public",
"function",
"check",
"(",
")",
"{",
"// validar firma del SII sobre los folios",
"$",
"firma",
"=",
"$",
"this",
"->",
"getFirma",
"(",
")",
";",
"$",
"idk",
"=",
"$",
"this",
"->",
"getIDK",
"(",
")",
";",
"if",
"(",
"$",
"firma",
"===",
"fa... | Método que verifica el código de autorización de folios
@return bool =true si está ok el XML cargado
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2018-03-20 | [
"Método",
"que",
"verifica",
"el",
"código",
"de",
"autorización",
"de",
"folios"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Folios.php#L61-L102 |
LibreDTE/libredte-lib | lib/Sii/Folios.php | Folios.getCaf | public function getCaf()
{
if (!$this->xml) {
return false;
}
$CAF = $this->xml->getElementsByTagName('CAF')->item(0);
return $CAF ? $CAF : false;
} | php | public function getCaf()
{
if (!$this->xml) {
return false;
}
$CAF = $this->xml->getElementsByTagName('CAF')->item(0);
return $CAF ? $CAF : false;
} | [
"public",
"function",
"getCaf",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"xml",
")",
"{",
"return",
"false",
";",
"}",
"$",
"CAF",
"=",
"$",
"this",
"->",
"xml",
"->",
"getElementsByTagName",
"(",
"'CAF'",
")",
"->",
"item",
"(",
"0",
")... | Método que entrega el nodo CAF
@return DomElement
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2015-10-30 | [
"Método",
"que",
"entrega",
"el",
"nodo",
"CAF"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Folios.php#L110-L117 |
LibreDTE/libredte-lib | lib/Sii/Folios.php | Folios.getEmisor | public function getEmisor()
{
if (!$this->xml) {
return false;
}
$RE = $this->xml->getElementsByTagName('RE')->item(0);
return $RE ? $RE->nodeValue : false;
} | php | public function getEmisor()
{
if (!$this->xml) {
return false;
}
$RE = $this->xml->getElementsByTagName('RE')->item(0);
return $RE ? $RE->nodeValue : false;
} | [
"public",
"function",
"getEmisor",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"xml",
")",
"{",
"return",
"false",
";",
"}",
"$",
"RE",
"=",
"$",
"this",
"->",
"xml",
"->",
"getElementsByTagName",
"(",
"'RE'",
")",
"->",
"item",
"(",
"0",
"... | Método que entrega el RUT de a quién se está autorizando el CAF
@return string RUT del emisor del CAF
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2015-10-30 | [
"Método",
"que",
"entrega",
"el",
"RUT",
"de",
"a",
"quién",
"se",
"está",
"autorizando",
"el",
"CAF"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Folios.php#L125-L132 |
LibreDTE/libredte-lib | lib/Sii/Folios.php | Folios.getDesde | public function getDesde()
{
if (!$this->xml) {
return false;
}
$D = $this->xml->getElementsByTagName('D')->item(0);
return $D ? (int)$D->nodeValue : false;
} | php | public function getDesde()
{
if (!$this->xml) {
return false;
}
$D = $this->xml->getElementsByTagName('D')->item(0);
return $D ? (int)$D->nodeValue : false;
} | [
"public",
"function",
"getDesde",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"xml",
")",
"{",
"return",
"false",
";",
"}",
"$",
"D",
"=",
"$",
"this",
"->",
"xml",
"->",
"getElementsByTagName",
"(",
"'D'",
")",
"->",
"item",
"(",
"0",
")",... | Método que entrega el primer folio autorizado en el CAF
@return int Número del primer folio
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2015-10-30 | [
"Método",
"que",
"entrega",
"el",
"primer",
"folio",
"autorizado",
"en",
"el",
"CAF"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Folios.php#L140-L147 |
LibreDTE/libredte-lib | lib/Sii/Folios.php | Folios.getHasta | public function getHasta()
{
if (!$this->xml) {
return false;
}
$H = $this->xml->getElementsByTagName('H')->item(0);
return $H ? (int)$H->nodeValue : false;
} | php | public function getHasta()
{
if (!$this->xml) {
return false;
}
$H = $this->xml->getElementsByTagName('H')->item(0);
return $H ? (int)$H->nodeValue : false;
} | [
"public",
"function",
"getHasta",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"xml",
")",
"{",
"return",
"false",
";",
"}",
"$",
"H",
"=",
"$",
"this",
"->",
"xml",
"->",
"getElementsByTagName",
"(",
"'H'",
")",
"->",
"item",
"(",
"0",
")",... | Método que entrega el últimmo folio autorizado en el CAF
@return int Número del último folio
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2015-10-30 | [
"Método",
"que",
"entrega",
"el",
"últimmo",
"folio",
"autorizado",
"en",
"el",
"CAF"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Folios.php#L155-L162 |
LibreDTE/libredte-lib | lib/Sii/Folios.php | Folios.getFirma | private function getFirma()
{
if (!$this->xml) {
return false;
}
$FRMA = $this->xml->getElementsByTagName('FRMA')->item(0);
return $FRMA ? $FRMA->nodeValue : false;
} | php | private function getFirma()
{
if (!$this->xml) {
return false;
}
$FRMA = $this->xml->getElementsByTagName('FRMA')->item(0);
return $FRMA ? $FRMA->nodeValue : false;
} | [
"private",
"function",
"getFirma",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"xml",
")",
"{",
"return",
"false",
";",
"}",
"$",
"FRMA",
"=",
"$",
"this",
"->",
"xml",
"->",
"getElementsByTagName",
"(",
"'FRMA'",
")",
"->",
"item",
"(",
"0",... | Método que entrega la firma del SII sobre el nodo DA
@return string Firma en base64
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2015-10-30 | [
"Método",
"que",
"entrega",
"la",
"firma",
"del",
"SII",
"sobre",
"el",
"nodo",
"DA"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Folios.php#L170-L177 |
LibreDTE/libredte-lib | lib/Sii/Folios.php | Folios.getIDK | private function getIDK()
{
if (!$this->xml) {
return false;
}
$IDK = $this->xml->getElementsByTagName('IDK')->item(0);
return $IDK ? (int)$IDK->nodeValue : false;
} | php | private function getIDK()
{
if (!$this->xml) {
return false;
}
$IDK = $this->xml->getElementsByTagName('IDK')->item(0);
return $IDK ? (int)$IDK->nodeValue : false;
} | [
"private",
"function",
"getIDK",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"xml",
")",
"{",
"return",
"false",
";",
"}",
"$",
"IDK",
"=",
"$",
"this",
"->",
"xml",
"->",
"getElementsByTagName",
"(",
"'IDK'",
")",
"->",
"item",
"(",
"0",
"... | Método que entrega el IDK (serial number) de la clave pública del SII
utilizada para firmar el CAF
@return int Serial number
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2015-10-30 | [
"Método",
"que",
"entrega",
"el",
"IDK",
"(",
"serial",
"number",
")",
"de",
"la",
"clave",
"pública",
"del",
"SII",
"utilizada",
"para",
"firmar",
"el",
"CAF"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Folios.php#L186-L193 |
LibreDTE/libredte-lib | lib/Sii/Folios.php | Folios.getPrivateKey | public function getPrivateKey()
{
if (!$this->xml) {
return false;
}
$RSASK = $this->xml->getElementsByTagName('RSASK')->item(0);
return $RSASK ? $RSASK->nodeValue : false;
} | php | public function getPrivateKey()
{
if (!$this->xml) {
return false;
}
$RSASK = $this->xml->getElementsByTagName('RSASK')->item(0);
return $RSASK ? $RSASK->nodeValue : false;
} | [
"public",
"function",
"getPrivateKey",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"xml",
")",
"{",
"return",
"false",
";",
"}",
"$",
"RSASK",
"=",
"$",
"this",
"->",
"xml",
"->",
"getElementsByTagName",
"(",
"'RSASK'",
")",
"->",
"item",
"(",
... | Método que entrega la clave privada proporcionada por el SII para el CAF
@return string Clave privada en base64
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2015-10-30 | [
"Método",
"que",
"entrega",
"la",
"clave",
"privada",
"proporcionada",
"por",
"el",
"SII",
"para",
"el",
"CAF"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Folios.php#L201-L208 |
LibreDTE/libredte-lib | lib/Sii/Folios.php | Folios.getPublicKey | public function getPublicKey()
{
if (!$this->xml) {
return false;
}
$RSAPUBK = $this->xml->getElementsByTagName('RSAPUBK')->item(0);
return $RSAPUBK ? $RSAPUBK->nodeValue : false;
} | php | public function getPublicKey()
{
if (!$this->xml) {
return false;
}
$RSAPUBK = $this->xml->getElementsByTagName('RSAPUBK')->item(0);
return $RSAPUBK ? $RSAPUBK->nodeValue : false;
} | [
"public",
"function",
"getPublicKey",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"xml",
")",
"{",
"return",
"false",
";",
"}",
"$",
"RSAPUBK",
"=",
"$",
"this",
"->",
"xml",
"->",
"getElementsByTagName",
"(",
"'RSAPUBK'",
")",
"->",
"item",
"(... | Método que entrega la clave pública proporcionada por el SII para el CAF
@return string Clave pública en base64
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2015-10-30 | [
"Método",
"que",
"entrega",
"la",
"clave",
"pública",
"proporcionada",
"por",
"el",
"SII",
"para",
"el",
"CAF"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Folios.php#L216-L223 |
LibreDTE/libredte-lib | lib/Sii/Folios.php | Folios.getTipo | public function getTipo()
{
if (!$this->xml) {
return false;
}
$TD = $this->xml->getElementsByTagName('TD')->item(0);
return $TD ? (int)$TD->nodeValue : false;
} | php | public function getTipo()
{
if (!$this->xml) {
return false;
}
$TD = $this->xml->getElementsByTagName('TD')->item(0);
return $TD ? (int)$TD->nodeValue : false;
} | [
"public",
"function",
"getTipo",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"xml",
")",
"{",
"return",
"false",
";",
"}",
"$",
"TD",
"=",
"$",
"this",
"->",
"xml",
"->",
"getElementsByTagName",
"(",
"'TD'",
")",
"->",
"item",
"(",
"0",
")"... | Método que entrega el tipo de DTE para el cual se emitió el CAF
@return int Código de tipo de DTE
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2015-10-30 | [
"Método",
"que",
"entrega",
"el",
"tipo",
"de",
"DTE",
"para",
"el",
"cual",
"se",
"emitió",
"el",
"CAF"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Folios.php#L231-L238 |
LibreDTE/libredte-lib | lib/Sii/Folios.php | Folios.getFechaAutorizacion | public function getFechaAutorizacion()
{
if (!$this->xml) {
return false;
}
$FA = $this->xml->getElementsByTagName('FA')->item(0);
return $FA ? $FA->nodeValue : false;
} | php | public function getFechaAutorizacion()
{
if (!$this->xml) {
return false;
}
$FA = $this->xml->getElementsByTagName('FA')->item(0);
return $FA ? $FA->nodeValue : false;
} | [
"public",
"function",
"getFechaAutorizacion",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"xml",
")",
"{",
"return",
"false",
";",
"}",
"$",
"FA",
"=",
"$",
"this",
"->",
"xml",
"->",
"getElementsByTagName",
"(",
"'FA'",
")",
"->",
"item",
"(",... | Método que entrega la fecha de autorización con la que se emitió el CAF
@return string Fecha de autorización del CAF
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2017-07-19 | [
"Método",
"que",
"entrega",
"la",
"fecha",
"de",
"autorización",
"con",
"la",
"que",
"se",
"emitió",
"el",
"CAF"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Folios.php#L246-L253 |
LibreDTE/libredte-lib | lib/Sii/Folios.php | Folios.vigente | public function vigente()
{
if (!in_array($this->getTipo(), [33, 43, 46, 56, 61])) {
return true;
}
$fecha_autorizacion = $this->getFechaAutorizacion();
$hoy = date('Y-m-d');
if ($fecha_autorizacion < '2018-07-01' and $hoy > '2018-12-31') {
return false;
}
$vigencia = $fecha_autorizacion >= '2018-07-01' ? 6 : 18;
$d1 = new \DateTime($fecha_autorizacion);
$d2 = new \DateTime($hoy);
$meses = $d1->diff($d2)->m + ($d1->diff($d2)->y*12);
return $meses <= $vigencia;
} | php | public function vigente()
{
if (!in_array($this->getTipo(), [33, 43, 46, 56, 61])) {
return true;
}
$fecha_autorizacion = $this->getFechaAutorizacion();
$hoy = date('Y-m-d');
if ($fecha_autorizacion < '2018-07-01' and $hoy > '2018-12-31') {
return false;
}
$vigencia = $fecha_autorizacion >= '2018-07-01' ? 6 : 18;
$d1 = new \DateTime($fecha_autorizacion);
$d2 = new \DateTime($hoy);
$meses = $d1->diff($d2)->m + ($d1->diff($d2)->y*12);
return $meses <= $vigencia;
} | [
"public",
"function",
"vigente",
"(",
")",
"{",
"if",
"(",
"!",
"in_array",
"(",
"$",
"this",
"->",
"getTipo",
"(",
")",
",",
"[",
"33",
",",
"43",
",",
"46",
",",
"56",
",",
"61",
"]",
")",
")",
"{",
"return",
"true",
";",
"}",
"$",
"fecha_a... | Método que indica si el CAF está o no vigente
@return bool =true si el CAF está vigente, =false si no está vigente
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2018-12-21 | [
"Método",
"que",
"indica",
"si",
"el",
"CAF",
"está",
"o",
"no",
"vigente"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Folios.php#L273-L288 |
LibreDTE/libredte-lib | bin/libredte_pdf.php | generar_pdf.args_check | public function args_check()
{
// archivo
if (!$this->args['xml'] or !is_readable($this->args['xml'])) {
$this->error('Debe especificar archivo XML de entrada válido');
}
// directorio de salida
if (!$this->args['dir'] or (!is_dir($this->args['dir']) and !mkdir($this->args['dir']))) {
$this->error('Debe especificar directorio válido para dejar los archivos PDF generados');
}
} | php | public function args_check()
{
// archivo
if (!$this->args['xml'] or !is_readable($this->args['xml'])) {
$this->error('Debe especificar archivo XML de entrada válido');
}
// directorio de salida
if (!$this->args['dir'] or (!is_dir($this->args['dir']) and !mkdir($this->args['dir']))) {
$this->error('Debe especificar directorio válido para dejar los archivos PDF generados');
}
} | [
"public",
"function",
"args_check",
"(",
")",
"{",
"// archivo",
"if",
"(",
"!",
"$",
"this",
"->",
"args",
"[",
"'xml'",
"]",
"or",
"!",
"is_readable",
"(",
"$",
"this",
"->",
"args",
"[",
"'xml'",
"]",
")",
")",
"{",
"$",
"this",
"->",
"error",
... | Método que valida los argumentos pasados al comando
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2015-12-15 | [
"Método",
"que",
"valida",
"los",
"argumentos",
"pasados",
"al",
"comando"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/bin/libredte_pdf.php#L69-L79 |
LibreDTE/libredte-lib | bin/libredte_pdf.php | generar_pdf.main | public function main()
{
// cargar XML y extraer arreglo con datos de carátula y DTEs
$EnvioDte = new \sasco\LibreDTE\Sii\EnvioDte();
$EnvioDte->loadXML(file_get_contents($this->args['xml']));
$Caratula = $EnvioDte->getCaratula();
$Documentos = $EnvioDte->getDocumentos();
// procesar cada DTEs e ir creando los archivos PDF
foreach ($Documentos as $DTE) {
if (!$DTE->getDatos())
$this->error('No se pudieron obtener los datos de uno de los DTE del XML');
$this->out('Generando PDF para DTE '.$DTE->getID());
$pdf = new \sasco\LibreDTE\Sii\Dte\PDF\Dte($this->args['papel']);
$pdf->setFooterText();
if ($this->args['logo'])
$pdf->setLogo($this->args['logo']);
$pdf->setResolucion(['FchResol'=>$Caratula['FchResol'], 'NroResol'=>$Caratula['NroResol']]);
$pdf->setWebVerificacion($this->args['web']);
$pdf->agregar($DTE->getDatos(), $DTE->getTED());
if (isset($this->args['cedible'])) {
$pdf->setCedible(true);
$pdf->agregar($DTE->getDatos(), $DTE->getTED());
}
$pdf->Output($this->args['dir'].'/dte_'.$Caratula['RutEmisor'].'_'.$DTE->getID().'.pdf', 'F');
}
return 0;
} | php | public function main()
{
// cargar XML y extraer arreglo con datos de carátula y DTEs
$EnvioDte = new \sasco\LibreDTE\Sii\EnvioDte();
$EnvioDte->loadXML(file_get_contents($this->args['xml']));
$Caratula = $EnvioDte->getCaratula();
$Documentos = $EnvioDte->getDocumentos();
// procesar cada DTEs e ir creando los archivos PDF
foreach ($Documentos as $DTE) {
if (!$DTE->getDatos())
$this->error('No se pudieron obtener los datos de uno de los DTE del XML');
$this->out('Generando PDF para DTE '.$DTE->getID());
$pdf = new \sasco\LibreDTE\Sii\Dte\PDF\Dte($this->args['papel']);
$pdf->setFooterText();
if ($this->args['logo'])
$pdf->setLogo($this->args['logo']);
$pdf->setResolucion(['FchResol'=>$Caratula['FchResol'], 'NroResol'=>$Caratula['NroResol']]);
$pdf->setWebVerificacion($this->args['web']);
$pdf->agregar($DTE->getDatos(), $DTE->getTED());
if (isset($this->args['cedible'])) {
$pdf->setCedible(true);
$pdf->agregar($DTE->getDatos(), $DTE->getTED());
}
$pdf->Output($this->args['dir'].'/dte_'.$Caratula['RutEmisor'].'_'.$DTE->getID().'.pdf', 'F');
}
return 0;
} | [
"public",
"function",
"main",
"(",
")",
"{",
"// cargar XML y extraer arreglo con datos de carátula y DTEs",
"$",
"EnvioDte",
"=",
"new",
"\\",
"sasco",
"\\",
"LibreDTE",
"\\",
"Sii",
"\\",
"EnvioDte",
"(",
")",
";",
"$",
"EnvioDte",
"->",
"loadXML",
"(",
"file_... | Método principal del comando
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2015-12-15 | [
"Método",
"principal",
"del",
"comando"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/bin/libredte_pdf.php#L86-L112 |
LibreDTE/libredte-lib | lib/Sii/Base/Documento.php | Documento.schemaValidate | public function schemaValidate()
{
if (!$this->xml_data) {
\sasco\LibreDTE\Log::write(
\sasco\LibreDTE\Estado::DOCUMENTO_FALTA_XML,
\sasco\LibreDTE\Estado::get(
\sasco\LibreDTE\Estado::DOCUMENTO_FALTA_XML,
substr(get_class($this), strrpos(get_class($this), '\\')+1)
)
);
return null;
}
$this->xml = new \sasco\LibreDTE\XML();
$this->xml->loadXML($this->xml_data);
$schema = $this->xml->getSchema();
if (!$schema) {
$tag = array_keys($this->toArray())[0];
if (isset($this->schemas[$tag])) {
$schema = $this->schemas[$tag];
}
}
if ($schema) {
$xsd = dirname(dirname(dirname(dirname(__FILE__)))).'/schemas/'.$schema;
}
if (!$schema or !is_readable($xsd)) {
\sasco\LibreDTE\Log::write(
\sasco\LibreDTE\Estado::DOCUMENTO_FALTA_SCHEMA,
\sasco\LibreDTE\Estado::get(
\sasco\LibreDTE\Estado::DOCUMENTO_FALTA_SCHEMA
)
);
return null;
}
$result = $this->xml->schemaValidate($xsd);
if (!$result) {
\sasco\LibreDTE\Log::write(
\sasco\LibreDTE\Estado::DOCUMENTO_ERROR_SCHEMA,
\sasco\LibreDTE\Estado::get(
\sasco\LibreDTE\Estado::DOCUMENTO_ERROR_SCHEMA,
substr(get_class($this), strrpos(get_class($this), '\\')+1),
implode("\n", $this->xml->getErrors())
)
);
}
return $result;
} | php | public function schemaValidate()
{
if (!$this->xml_data) {
\sasco\LibreDTE\Log::write(
\sasco\LibreDTE\Estado::DOCUMENTO_FALTA_XML,
\sasco\LibreDTE\Estado::get(
\sasco\LibreDTE\Estado::DOCUMENTO_FALTA_XML,
substr(get_class($this), strrpos(get_class($this), '\\')+1)
)
);
return null;
}
$this->xml = new \sasco\LibreDTE\XML();
$this->xml->loadXML($this->xml_data);
$schema = $this->xml->getSchema();
if (!$schema) {
$tag = array_keys($this->toArray())[0];
if (isset($this->schemas[$tag])) {
$schema = $this->schemas[$tag];
}
}
if ($schema) {
$xsd = dirname(dirname(dirname(dirname(__FILE__)))).'/schemas/'.$schema;
}
if (!$schema or !is_readable($xsd)) {
\sasco\LibreDTE\Log::write(
\sasco\LibreDTE\Estado::DOCUMENTO_FALTA_SCHEMA,
\sasco\LibreDTE\Estado::get(
\sasco\LibreDTE\Estado::DOCUMENTO_FALTA_SCHEMA
)
);
return null;
}
$result = $this->xml->schemaValidate($xsd);
if (!$result) {
\sasco\LibreDTE\Log::write(
\sasco\LibreDTE\Estado::DOCUMENTO_ERROR_SCHEMA,
\sasco\LibreDTE\Estado::get(
\sasco\LibreDTE\Estado::DOCUMENTO_ERROR_SCHEMA,
substr(get_class($this), strrpos(get_class($this), '\\')+1),
implode("\n", $this->xml->getErrors())
)
);
}
return $result;
} | [
"public",
"function",
"schemaValidate",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"xml_data",
")",
"{",
"\\",
"sasco",
"\\",
"LibreDTE",
"\\",
"Log",
"::",
"write",
"(",
"\\",
"sasco",
"\\",
"LibreDTE",
"\\",
"Estado",
"::",
"DOCUMENTO_FALTA_XML"... | Método que valida el XML del documento
@return =true si el schema del documento del envío es válido, =null si no se pudo determinar
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2016-08-05 | [
"Método",
"que",
"valida",
"el",
"XML",
"del",
"documento"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Base/Documento.php#L88-L133 |
LibreDTE/libredte-lib | lib/Sii/Base/Documento.php | Documento.loadXML | public function loadXML($xml_data)
{
$this->xml_data = $xml_data;
$this->xml = new \sasco\LibreDTE\XML();
if (!$this->xml->loadXML($this->xml_data)) {
return false;
}
$this->toArray();
return $this->xml;
} | php | public function loadXML($xml_data)
{
$this->xml_data = $xml_data;
$this->xml = new \sasco\LibreDTE\XML();
if (!$this->xml->loadXML($this->xml_data)) {
return false;
}
$this->toArray();
return $this->xml;
} | [
"public",
"function",
"loadXML",
"(",
"$",
"xml_data",
")",
"{",
"$",
"this",
"->",
"xml_data",
"=",
"$",
"xml_data",
";",
"$",
"this",
"->",
"xml",
"=",
"new",
"\\",
"sasco",
"\\",
"LibreDTE",
"\\",
"XML",
"(",
")",
";",
"if",
"(",
"!",
"$",
"th... | Método que carga un XML y asigna el objeto XML correspondiente para poder
obtener los datos del mismo a través de un arreglo
@return Objeto XML
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2016-06-29 | [
"Método",
"que",
"carga",
"un",
"XML",
"y",
"asigna",
"el",
"objeto",
"XML",
"correspondiente",
"para",
"poder",
"obtener",
"los",
"datos",
"del",
"mismo",
"a",
"través",
"de",
"un",
"arreglo"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Base/Documento.php#L153-L162 |
LibreDTE/libredte-lib | lib/Sii/Base/Documento.php | Documento.toArray | public function toArray()
{
if (!$this->xml and $this->xml_data) {
$this->loadXML($this->xml_data);
}
if (!$this->xml) {
return false;
}
if (!$this->arreglo) {
$this->arreglo = $this->xml->toArray();
}
return $this->arreglo;
} | php | public function toArray()
{
if (!$this->xml and $this->xml_data) {
$this->loadXML($this->xml_data);
}
if (!$this->xml) {
return false;
}
if (!$this->arreglo) {
$this->arreglo = $this->xml->toArray();
}
return $this->arreglo;
} | [
"public",
"function",
"toArray",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"xml",
"and",
"$",
"this",
"->",
"xml_data",
")",
"{",
"$",
"this",
"->",
"loadXML",
"(",
"$",
"this",
"->",
"xml_data",
")",
";",
"}",
"if",
"(",
"!",
"$",
"thi... | Método que entrega un arreglo con los datos del documento XML
@return Arreglo con datos del documento XML
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2018-12-20 | [
"Método",
"que",
"entrega",
"un",
"arreglo",
"con",
"los",
"datos",
"del",
"documento",
"XML"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Base/Documento.php#L170-L182 |
LibreDTE/libredte-lib | bin/libredte_set2json.php | set_prueba_json.main | public function main()
{
$json = \sasco\LibreDTE\Sii\Certificacion\SetPruebas::getJSON(
file_get_contents($this->args['set'])
);
if (!empty($this->args['json']))
file_put_contents($this->args['json'], $json);
else
echo $json;
return 0;
} | php | public function main()
{
$json = \sasco\LibreDTE\Sii\Certificacion\SetPruebas::getJSON(
file_get_contents($this->args['set'])
);
if (!empty($this->args['json']))
file_put_contents($this->args['json'], $json);
else
echo $json;
return 0;
} | [
"public",
"function",
"main",
"(",
")",
"{",
"$",
"json",
"=",
"\\",
"sasco",
"\\",
"LibreDTE",
"\\",
"Sii",
"\\",
"Certificacion",
"\\",
"SetPruebas",
"::",
"getJSON",
"(",
"file_get_contents",
"(",
"$",
"this",
"->",
"args",
"[",
"'set'",
"]",
")",
"... | Método principal del comando
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2015-12-18 | [
"Método",
"principal",
"del",
"comando"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/bin/libredte_set2json.php#L67-L77 |
LibreDTE/libredte-lib | lib/Estado.php | Estado.get | public static function get($codigo, $args = null)
{
// si no hay glosa asociada al código se entrega el mismo código
if (!isset(self::$glosas[(int)$codigo]))
return (int)$codigo;
// si los argumentos no son un arreglo se obtiene arreglo a partir
// de los argumentos pasados a la función
if (!is_array($args))
$args = array_slice(func_get_args(), 1);
// entregar glosa
return vsprintf(I18n::translate(self::$glosas[(int)$codigo], 'estados'), $args);
} | php | public static function get($codigo, $args = null)
{
// si no hay glosa asociada al código se entrega el mismo código
if (!isset(self::$glosas[(int)$codigo]))
return (int)$codigo;
// si los argumentos no son un arreglo se obtiene arreglo a partir
// de los argumentos pasados a la función
if (!is_array($args))
$args = array_slice(func_get_args(), 1);
// entregar glosa
return vsprintf(I18n::translate(self::$glosas[(int)$codigo], 'estados'), $args);
} | [
"public",
"static",
"function",
"get",
"(",
"$",
"codigo",
",",
"$",
"args",
"=",
"null",
")",
"{",
"// si no hay glosa asociada al código se entrega el mismo código",
"if",
"(",
"!",
"isset",
"(",
"self",
"::",
"$",
"glosas",
"[",
"(",
"int",
")",
"$",
"cod... | Método que recupera la glosa del estado
@param codigo Código del error que se desea recuperar
@param args Argumentos que se usarán para reemplazar "máscaras" en glosa
@return Glosa del estado si existe o bien el mismo código del estado si no hay glosa
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2015-09-24 | [
"Método",
"que",
"recupera",
"la",
"glosa",
"del",
"estado"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Estado.php#L176-L187 |
LibreDTE/libredte-lib | lib/Sii/Factoring/DteCedido.php | DteCedido.firmar | public function firmar(\sasco\LibreDTE\FirmaElectronica $Firma)
{
$xml = $Firma->signXML($this->xml, '#LibreDTE_DTECedido', 'DocumentoDTECedido');
if (!$xml) {
\sasco\LibreDTE\Log::write(
\sasco\LibreDTE\Estado::DTE_ERROR_FIRMA,
\sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::DTE_ERROR_FIRMA, '#LibreDTE_DTECedido')
);
return false;
}
$this->xml = $xml;
return true;
} | php | public function firmar(\sasco\LibreDTE\FirmaElectronica $Firma)
{
$xml = $Firma->signXML($this->xml, '#LibreDTE_DTECedido', 'DocumentoDTECedido');
if (!$xml) {
\sasco\LibreDTE\Log::write(
\sasco\LibreDTE\Estado::DTE_ERROR_FIRMA,
\sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::DTE_ERROR_FIRMA, '#LibreDTE_DTECedido')
);
return false;
}
$this->xml = $xml;
return true;
} | [
"public",
"function",
"firmar",
"(",
"\\",
"sasco",
"\\",
"LibreDTE",
"\\",
"FirmaElectronica",
"$",
"Firma",
")",
"{",
"$",
"xml",
"=",
"$",
"Firma",
"->",
"signXML",
"(",
"$",
"this",
"->",
"xml",
",",
"'#LibreDTE_DTECedido'",
",",
"'DocumentoDTECedido'",
... | Método que realiza la firma del DTE cedido
@param Firma objeto que representa la Firma Electrónca
@return =true si el DTE pudo ser fimado o =false si no se pudo firmar
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2016-12-10 | [
"Método",
"que",
"realiza",
"la",
"firma",
"del",
"DTE",
"cedido"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Factoring/DteCedido.php#L76-L88 |
LibreDTE/libredte-lib | lib/Sii/LibroGuia.php | LibroGuia.agregar | public function agregar(array $detalle, $normalizar = true)
{
if ($normalizar)
$this->normalizarDetalle($detalle);
$this->detalles[] = $detalle;
return true;
} | php | public function agregar(array $detalle, $normalizar = true)
{
if ($normalizar)
$this->normalizarDetalle($detalle);
$this->detalles[] = $detalle;
return true;
} | [
"public",
"function",
"agregar",
"(",
"array",
"$",
"detalle",
",",
"$",
"normalizar",
"=",
"true",
")",
"{",
"if",
"(",
"$",
"normalizar",
")",
"$",
"this",
"->",
"normalizarDetalle",
"(",
"$",
"detalle",
")",
";",
"$",
"this",
"->",
"detalles",
"[",
... | Método que agrega un detalle al listado que se enviará
@param detalle Arreglo con el resumen del DTE que se desea agregar
@return =true si se pudo agregar el detalle o =false si no se agregó por exceder el límite del libro
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2015-10-02 | [
"Método",
"que",
"agrega",
"un",
"detalle",
"al",
"listado",
"que",
"se",
"enviará"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/LibroGuia.php#L41-L47 |
LibreDTE/libredte-lib | lib/Sii/LibroGuia.php | LibroGuia.normalizarDetalle | private function normalizarDetalle(array &$detalle)
{
// agregar nodos (esto para mantener orden del XML)
$detalle = array_merge([
'Folio' => false,
'Anulado' => false,
'Operacion' => false,
'TpoOper' => false,
'FchDoc' => date('Y-m-d'),
'RUTDoc' => false,
'RznSoc' => false,
'MntNeto' => false,
'TasaImp' => 0,
'IVA' => 0,
'MntTotal' => false,
'MntModificado' => false,
'TpoDocRef' => false,
'FolioDocRef' => false,
'FchDocRef' => false,
], $detalle);
// acortar razon social
if ($detalle['RznSoc']) {
$detalle['RznSoc'] = mb_substr($detalle['RznSoc'], 0, 50);
}
// calcular valores que no se hayan entregado
if (!$detalle['IVA'] and $detalle['TasaImp'] and $detalle['MntNeto']) {
$detalle['IVA'] = round($detalle['MntNeto'] * ($detalle['TasaImp']/100));
}
// calcular monto total si no se especificó
if ($detalle['MntTotal']===false) {
$detalle['MntTotal'] = $detalle['MntNeto'] + $detalle['IVA'];
}
} | php | private function normalizarDetalle(array &$detalle)
{
// agregar nodos (esto para mantener orden del XML)
$detalle = array_merge([
'Folio' => false,
'Anulado' => false,
'Operacion' => false,
'TpoOper' => false,
'FchDoc' => date('Y-m-d'),
'RUTDoc' => false,
'RznSoc' => false,
'MntNeto' => false,
'TasaImp' => 0,
'IVA' => 0,
'MntTotal' => false,
'MntModificado' => false,
'TpoDocRef' => false,
'FolioDocRef' => false,
'FchDocRef' => false,
], $detalle);
// acortar razon social
if ($detalle['RznSoc']) {
$detalle['RznSoc'] = mb_substr($detalle['RznSoc'], 0, 50);
}
// calcular valores que no se hayan entregado
if (!$detalle['IVA'] and $detalle['TasaImp'] and $detalle['MntNeto']) {
$detalle['IVA'] = round($detalle['MntNeto'] * ($detalle['TasaImp']/100));
}
// calcular monto total si no se especificó
if ($detalle['MntTotal']===false) {
$detalle['MntTotal'] = $detalle['MntNeto'] + $detalle['IVA'];
}
} | [
"private",
"function",
"normalizarDetalle",
"(",
"array",
"&",
"$",
"detalle",
")",
"{",
"// agregar nodos (esto para mantener orden del XML)",
"$",
"detalle",
"=",
"array_merge",
"(",
"[",
"'Folio'",
"=>",
"false",
",",
"'Anulado'",
"=>",
"false",
",",
"'Operacion'... | Método que normaliza un detalle del libro de guías
@param detalle Arreglo con el resumen del DTE que se desea agregar
@return Arreglo con el detalle normalizado
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2017-07-24 | [
"Método",
"que",
"normaliza",
"un",
"detalle",
"del",
"libro",
"de",
"guías"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/LibroGuia.php#L56-L88 |
LibreDTE/libredte-lib | lib/Sii/LibroGuia.php | LibroGuia.agregarCSV | public function agregarCSV($archivo, $separador = ';')
{
$data = \sasco\LibreDTE\CSV::read($archivo);
$n_data = count($data);
$detalles = [];
for ($i=1; $i<$n_data; $i++) {
// detalle genérico
$detalle = [
'Folio' => $data[$i][0],
'Anulado' => !empty($data[$i][1]) ? $data[$i][1] : false,
'Operacion' => !empty($data[$i][2]) ? $data[$i][2] : false,
'TpoOper' => !empty($data[$i][3]) ? $data[$i][3] : false,
'FchDoc' => !empty($data[$i][4]) ? $data[$i][4] : date('Y-m-d'),
'RUTDoc' => !empty($data[$i][5]) ? $data[$i][5] : false,
'RznSoc' => !empty($data[$i][6]) ? mb_substr($data[$i][6], 0, 50) : false,
'MntNeto' => !empty($data[$i][7]) ? $data[$i][7] : false,
'TasaImp' => !empty($data[$i][8]) ? $data[$i][8] : 0,
'IVA' => !empty($data[$i][9]) ? $data[$i][9] : 0,
'MntTotal' => !empty($data[$i][10]) ? $data[$i][10] : false,
'MntModificado' => !empty($data[$i][11]) ? $data[$i][11] : false,
'TpoDocRef' => !empty($data[$i][12]) ? $data[$i][12] : false,
'FolioDocRef' => !empty($data[$i][13]) ? $data[$i][13] : false,
'FchDocRef' => !empty($data[$i][14]) ? $data[$i][14] : false,
];
// agregar a los detalles
$this->agregar($detalle);
}
} | php | public function agregarCSV($archivo, $separador = ';')
{
$data = \sasco\LibreDTE\CSV::read($archivo);
$n_data = count($data);
$detalles = [];
for ($i=1; $i<$n_data; $i++) {
// detalle genérico
$detalle = [
'Folio' => $data[$i][0],
'Anulado' => !empty($data[$i][1]) ? $data[$i][1] : false,
'Operacion' => !empty($data[$i][2]) ? $data[$i][2] : false,
'TpoOper' => !empty($data[$i][3]) ? $data[$i][3] : false,
'FchDoc' => !empty($data[$i][4]) ? $data[$i][4] : date('Y-m-d'),
'RUTDoc' => !empty($data[$i][5]) ? $data[$i][5] : false,
'RznSoc' => !empty($data[$i][6]) ? mb_substr($data[$i][6], 0, 50) : false,
'MntNeto' => !empty($data[$i][7]) ? $data[$i][7] : false,
'TasaImp' => !empty($data[$i][8]) ? $data[$i][8] : 0,
'IVA' => !empty($data[$i][9]) ? $data[$i][9] : 0,
'MntTotal' => !empty($data[$i][10]) ? $data[$i][10] : false,
'MntModificado' => !empty($data[$i][11]) ? $data[$i][11] : false,
'TpoDocRef' => !empty($data[$i][12]) ? $data[$i][12] : false,
'FolioDocRef' => !empty($data[$i][13]) ? $data[$i][13] : false,
'FchDocRef' => !empty($data[$i][14]) ? $data[$i][14] : false,
];
// agregar a los detalles
$this->agregar($detalle);
}
} | [
"public",
"function",
"agregarCSV",
"(",
"$",
"archivo",
",",
"$",
"separador",
"=",
"';'",
")",
"{",
"$",
"data",
"=",
"\\",
"sasco",
"\\",
"LibreDTE",
"\\",
"CSV",
"::",
"read",
"(",
"$",
"archivo",
")",
";",
"$",
"n_data",
"=",
"count",
"(",
"$"... | Método que agrega el detalle del libro de guías a partir de un archivo
CSV.
@param archivo Ruta al archivo que se desea cargar
@param separador Separador de campos del archivo CSV
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2017-07-24 | [
"Método",
"que",
"agrega",
"el",
"detalle",
"del",
"libro",
"de",
"guías",
"a",
"partir",
"de",
"un",
"archivo",
"CSV",
"."
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/LibroGuia.php#L98-L125 |
LibreDTE/libredte-lib | lib/Sii/LibroGuia.php | LibroGuia.getResumenPeriodo | private function getResumenPeriodo()
{
$ResumenPeriodo = [
'TotFolAnulado' => false,
'TotGuiaAnulada' => false,
'TotGuiaVenta' => 0,
'TotMntGuiaVta' => 0,
'TotTraslado' => false,
];
foreach ($this->detalles as &$d) {
// se contabiliza si la guía está anulada
if ($d['Anulado']==1 or $d['Anulado']==2) {
if ($d['Anulado']==1) {
$ResumenPeriodo['TotFolAnulado'] = (int)$ResumenPeriodo['TotFolAnulado'] + 1;
} else {
$ResumenPeriodo['TotGuiaAnulada'] = (int)$ResumenPeriodo['TotGuiaAnulada'] + 1;
}
}
// si no está anulado
else {
// si es de venta
if ($d['TpoOper']==1) {
$ResumenPeriodo['TotGuiaVenta'] = (int)$ResumenPeriodo['TotGuiaVenta'] + 1;
$ResumenPeriodo['TotMntGuiaVta'] = (int)$ResumenPeriodo['TotMntGuiaVta'] + $d['MntTotal'];
}
// si no es de venta
else {
if ($ResumenPeriodo['TotTraslado']===false) {
$ResumenPeriodo['TotTraslado'] = [];
}
if (!isset($ResumenPeriodo['TotTraslado'][$d['TpoOper']])) {
$ResumenPeriodo['TotTraslado'][$d['TpoOper']] = [
'TpoTraslado' => $d['TpoOper'],
'CantGuia' => 0,
'MntGuia' => 0,
];
}
$ResumenPeriodo['TotTraslado'][$d['TpoOper']]['CantGuia']++;
$ResumenPeriodo['TotTraslado'][$d['TpoOper']]['MntGuia'] += $d['MntTotal'];
}
}
}
return $ResumenPeriodo;
} | php | private function getResumenPeriodo()
{
$ResumenPeriodo = [
'TotFolAnulado' => false,
'TotGuiaAnulada' => false,
'TotGuiaVenta' => 0,
'TotMntGuiaVta' => 0,
'TotTraslado' => false,
];
foreach ($this->detalles as &$d) {
// se contabiliza si la guía está anulada
if ($d['Anulado']==1 or $d['Anulado']==2) {
if ($d['Anulado']==1) {
$ResumenPeriodo['TotFolAnulado'] = (int)$ResumenPeriodo['TotFolAnulado'] + 1;
} else {
$ResumenPeriodo['TotGuiaAnulada'] = (int)$ResumenPeriodo['TotGuiaAnulada'] + 1;
}
}
// si no está anulado
else {
// si es de venta
if ($d['TpoOper']==1) {
$ResumenPeriodo['TotGuiaVenta'] = (int)$ResumenPeriodo['TotGuiaVenta'] + 1;
$ResumenPeriodo['TotMntGuiaVta'] = (int)$ResumenPeriodo['TotMntGuiaVta'] + $d['MntTotal'];
}
// si no es de venta
else {
if ($ResumenPeriodo['TotTraslado']===false) {
$ResumenPeriodo['TotTraslado'] = [];
}
if (!isset($ResumenPeriodo['TotTraslado'][$d['TpoOper']])) {
$ResumenPeriodo['TotTraslado'][$d['TpoOper']] = [
'TpoTraslado' => $d['TpoOper'],
'CantGuia' => 0,
'MntGuia' => 0,
];
}
$ResumenPeriodo['TotTraslado'][$d['TpoOper']]['CantGuia']++;
$ResumenPeriodo['TotTraslado'][$d['TpoOper']]['MntGuia'] += $d['MntTotal'];
}
}
}
return $ResumenPeriodo;
} | [
"private",
"function",
"getResumenPeriodo",
"(",
")",
"{",
"$",
"ResumenPeriodo",
"=",
"[",
"'TotFolAnulado'",
"=>",
"false",
",",
"'TotGuiaAnulada'",
"=>",
"false",
",",
"'TotGuiaVenta'",
"=>",
"0",
",",
"'TotMntGuiaVta'",
"=>",
"0",
",",
"'TotTraslado'",
"=>",... | Método que obtiene los datos para generar los tags TotalesPeriodo
@return Arreglo con los datos para generar los tags TotalesPeriodo
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2015-10-02 | [
"Método",
"que",
"obtiene",
"los",
"datos",
"para",
"generar",
"los",
"tags",
"TotalesPeriodo"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/LibroGuia.php#L193-L236 |
LibreDTE/libredte-lib | lib/Sii/RespuestaEnvio.php | RespuestaEnvio.agregarRespuestaEnvio | public function agregarRespuestaEnvio(array $datos)
{
if (isset($this->respuesta_documentos[0]))
return false;
if (isset($this->respuesta_envios[$this->config['respuesta_envios_max']-1]))
return false;
$this->respuesta_envios[] = array_merge([
'NmbEnvio' => false,
'FchRecep' => date('Y-m-d\TH:i:s'),
'CodEnvio' => 0,
'EnvioDTEID' => false,
'Digest' => false,
'RutEmisor' => false,
'RutReceptor' => false,
'EstadoRecepEnv' => false,
'RecepEnvGlosa' => false,
'NroDTE' => false,
'RecepcionDTE' => false,
], $datos);
return true;
} | php | public function agregarRespuestaEnvio(array $datos)
{
if (isset($this->respuesta_documentos[0]))
return false;
if (isset($this->respuesta_envios[$this->config['respuesta_envios_max']-1]))
return false;
$this->respuesta_envios[] = array_merge([
'NmbEnvio' => false,
'FchRecep' => date('Y-m-d\TH:i:s'),
'CodEnvio' => 0,
'EnvioDTEID' => false,
'Digest' => false,
'RutEmisor' => false,
'RutReceptor' => false,
'EstadoRecepEnv' => false,
'RecepEnvGlosa' => false,
'NroDTE' => false,
'RecepcionDTE' => false,
], $datos);
return true;
} | [
"public",
"function",
"agregarRespuestaEnvio",
"(",
"array",
"$",
"datos",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"respuesta_documentos",
"[",
"0",
"]",
")",
")",
"return",
"false",
";",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"respu... | Método que agrega una respuesta de envío
@param datos Arreglo con los datos de la respuesta
@return =true si se pudo agregar la respuesta o =false si no se agregó por exceder el límite o bien ya existía al menos una respuesta de documento
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2015-09-07 | [
"Método",
"que",
"agrega",
"una",
"respuesta",
"de",
"envío"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/RespuestaEnvio.php#L74-L94 |
LibreDTE/libredte-lib | lib/Sii/RespuestaEnvio.php | RespuestaEnvio.agregarRespuestaDocumento | public function agregarRespuestaDocumento(array $datos)
{
if (isset($this->respuesta_envios[0]))
return false;
if (isset($this->respuesta_documentos[$this->config['respuesta_documentos_max']-1]))
return false;
$this->respuesta_documentos[] = array_merge([
'TipoDTE' => false,
'Folio' => false,
'FchEmis' => false,
'RUTEmisor' => false,
'RUTRecep' => false,
'MntTotal' => false,
'CodEnvio' => false,
'EstadoDTE' => false,
'EstadoDTEGlosa' => false,
'CodRchDsc' => false,
], $datos);
return true;
} | php | public function agregarRespuestaDocumento(array $datos)
{
if (isset($this->respuesta_envios[0]))
return false;
if (isset($this->respuesta_documentos[$this->config['respuesta_documentos_max']-1]))
return false;
$this->respuesta_documentos[] = array_merge([
'TipoDTE' => false,
'Folio' => false,
'FchEmis' => false,
'RUTEmisor' => false,
'RUTRecep' => false,
'MntTotal' => false,
'CodEnvio' => false,
'EstadoDTE' => false,
'EstadoDTEGlosa' => false,
'CodRchDsc' => false,
], $datos);
return true;
} | [
"public",
"function",
"agregarRespuestaDocumento",
"(",
"array",
"$",
"datos",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"respuesta_envios",
"[",
"0",
"]",
")",
")",
"return",
"false",
";",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"respu... | Método que agrega una respuesta de documento
@param datos Arreglo con los datos de la respuesta
@return =true si se pudo agregar la respuesta o =false si no se agregó por exceder el límite o bien ya existía al menos una respuesta de envío
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2015-09-08 | [
"Método",
"que",
"agrega",
"una",
"respuesta",
"de",
"documento"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/RespuestaEnvio.php#L103-L122 |
LibreDTE/libredte-lib | lib/Sii/RespuestaEnvio.php | RespuestaEnvio.setCaratula | public function setCaratula(array $caratula)
{
$this->caratula = array_merge([
'@attributes' => [
'version' => '1.0'
],
'RutResponde' => false,
'RutRecibe' => false,
'IdRespuesta' => 0,
'NroDetalles' => isset($this->respuesta_envios[0]) ? count($this->respuesta_envios) : count($this->respuesta_documentos),
'NmbContacto' => false,
'FonoContacto' => false,
'MailContacto' => false,
'TmstFirmaResp' => date('Y-m-d\TH:i:s'),
], $caratula);
if ($this->caratula['NmbContacto']) {
$this->caratula['NmbContacto'] = mb_substr($this->caratula['NmbContacto'], 0, 40);
}
$this->id = 'ResultadoEnvio';
} | php | public function setCaratula(array $caratula)
{
$this->caratula = array_merge([
'@attributes' => [
'version' => '1.0'
],
'RutResponde' => false,
'RutRecibe' => false,
'IdRespuesta' => 0,
'NroDetalles' => isset($this->respuesta_envios[0]) ? count($this->respuesta_envios) : count($this->respuesta_documentos),
'NmbContacto' => false,
'FonoContacto' => false,
'MailContacto' => false,
'TmstFirmaResp' => date('Y-m-d\TH:i:s'),
], $caratula);
if ($this->caratula['NmbContacto']) {
$this->caratula['NmbContacto'] = mb_substr($this->caratula['NmbContacto'], 0, 40);
}
$this->id = 'ResultadoEnvio';
} | [
"public",
"function",
"setCaratula",
"(",
"array",
"$",
"caratula",
")",
"{",
"$",
"this",
"->",
"caratula",
"=",
"array_merge",
"(",
"[",
"'@attributes'",
"=>",
"[",
"'version'",
"=>",
"'1.0'",
"]",
",",
"'RutResponde'",
"=>",
"false",
",",
"'RutRecibe'",
... | Método para asignar la caratula
@param caratula Arreglo con datos de la respuesta
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2018-01-23 | [
"Método",
"para",
"asignar",
"la",
"caratula"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/RespuestaEnvio.php#L130-L149 |
LibreDTE/libredte-lib | lib/Sii/RespuestaEnvio.php | RespuestaEnvio.generar | public function generar()
{
// si ya se había generado se entrega directamente
if ($this->xml_data)
return $this->xml_data;
// si no hay respuestas para generar entregar falso
if (!isset($this->respuesta_envios[0]) and !isset($this->respuesta_documentos[0])) {
\sasco\LibreDTE\Log::write(
\sasco\LibreDTE\Estado::RESPUESTAENVIO_FALTA_RESPUESTA,
\sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::RESPUESTAENVIO_FALTA_RESPUESTA)
);
return false;
}
// si no hay carátula error
if (!$this->caratula) {
\sasco\LibreDTE\Log::write(
\sasco\LibreDTE\Estado::RESPUESTAENVIO_FALTA_CARATULA,
\sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::RESPUESTAENVIO_FALTA_CARATULA)
);
return false;
}
// crear arreglo de lo que se enviará
$arreglo = [
'RespuestaDTE' => [
'@attributes' => [
'xmlns' => 'http://www.sii.cl/SiiDte',
'xmlns:xsi' => 'http://www.w3.org/2001/XMLSchema-instance',
'xsi:schemaLocation' => 'http://www.sii.cl/SiiDte RespuestaEnvioDTE_v10.xsd',
'version' => '1.0',
],
'Resultado' => [
'@attributes' => [
'ID' => 'LibreDTE_ResultadoEnvio'
],
'Caratula' => $this->caratula,
]
]
];
if (isset($this->respuesta_envios[0])) {
$arreglo['RespuestaDTE']['Resultado']['RecepcionEnvio'] = $this->respuesta_envios;
} else {
$arreglo['RespuestaDTE']['Resultado']['ResultadoDTE'] = $this->respuesta_documentos;
}
// generar XML del envío
$xmlEnvio = (new \sasco\LibreDTE\XML())->generate($arreglo)->saveXML();
// firmar XML del envío y entregar
$this->xml_data = $this->Firma ? $this->Firma->signXML($xmlEnvio, '#LibreDTE_ResultadoEnvio', 'Resultado', true) : $xmlEnvio;
return $this->xml_data;
} | php | public function generar()
{
// si ya se había generado se entrega directamente
if ($this->xml_data)
return $this->xml_data;
// si no hay respuestas para generar entregar falso
if (!isset($this->respuesta_envios[0]) and !isset($this->respuesta_documentos[0])) {
\sasco\LibreDTE\Log::write(
\sasco\LibreDTE\Estado::RESPUESTAENVIO_FALTA_RESPUESTA,
\sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::RESPUESTAENVIO_FALTA_RESPUESTA)
);
return false;
}
// si no hay carátula error
if (!$this->caratula) {
\sasco\LibreDTE\Log::write(
\sasco\LibreDTE\Estado::RESPUESTAENVIO_FALTA_CARATULA,
\sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::RESPUESTAENVIO_FALTA_CARATULA)
);
return false;
}
// crear arreglo de lo que se enviará
$arreglo = [
'RespuestaDTE' => [
'@attributes' => [
'xmlns' => 'http://www.sii.cl/SiiDte',
'xmlns:xsi' => 'http://www.w3.org/2001/XMLSchema-instance',
'xsi:schemaLocation' => 'http://www.sii.cl/SiiDte RespuestaEnvioDTE_v10.xsd',
'version' => '1.0',
],
'Resultado' => [
'@attributes' => [
'ID' => 'LibreDTE_ResultadoEnvio'
],
'Caratula' => $this->caratula,
]
]
];
if (isset($this->respuesta_envios[0])) {
$arreglo['RespuestaDTE']['Resultado']['RecepcionEnvio'] = $this->respuesta_envios;
} else {
$arreglo['RespuestaDTE']['Resultado']['ResultadoDTE'] = $this->respuesta_documentos;
}
// generar XML del envío
$xmlEnvio = (new \sasco\LibreDTE\XML())->generate($arreglo)->saveXML();
// firmar XML del envío y entregar
$this->xml_data = $this->Firma ? $this->Firma->signXML($xmlEnvio, '#LibreDTE_ResultadoEnvio', 'Resultado', true) : $xmlEnvio;
return $this->xml_data;
} | [
"public",
"function",
"generar",
"(",
")",
"{",
"// si ya se había generado se entrega directamente",
"if",
"(",
"$",
"this",
"->",
"xml_data",
")",
"return",
"$",
"this",
"->",
"xml_data",
";",
"// si no hay respuestas para generar entregar falso",
"if",
"(",
"!",
"i... | Método que genera el XML para el envío de la respuesta al SII
@param caratula Arreglo con la carátula de la respuesta
@param Firma Objeto con la firma electrónica
@return XML con la respuesta firmada o =false si no se pudo generar o firmar la respuesta
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2016-08-06 | [
"Método",
"que",
"genera",
"el",
"XML",
"para",
"el",
"envío",
"de",
"la",
"respuesta",
"al",
"SII"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/RespuestaEnvio.php#L159-L207 |
LibreDTE/libredte-lib | lib/Sii/RespuestaEnvio.php | RespuestaEnvio.getRecepciones | public function getRecepciones()
{
if (!$this->esRecepcionEnvio())
return false;
// si no hay respustas se deben crear
if (!$this->respuesta_envios) {
// si no está creado el arrelgo con los datos error
if (!$this->arreglo) {
return false;
}
// procesa rsólo si hay recepciones
if (isset($this->arreglo['RespuestaDTE']['Resultado']['RecepcionEnvio']['RecepcionDTE'])) {
// crear repuestas a partir del arreglo
$Recepciones = $this->arreglo['RespuestaDTE']['Resultado']['RecepcionEnvio']['RecepcionDTE'];
if (!isset($Recepciones[0]))
$Recepciones = [$Recepciones];
foreach ($Recepciones as $Recepcion) {
$this->respuesta_envios[] = $Recepcion;
}
}
}
// entregar recibos
return $this->respuesta_envios;
} | php | public function getRecepciones()
{
if (!$this->esRecepcionEnvio())
return false;
// si no hay respustas se deben crear
if (!$this->respuesta_envios) {
// si no está creado el arrelgo con los datos error
if (!$this->arreglo) {
return false;
}
// procesa rsólo si hay recepciones
if (isset($this->arreglo['RespuestaDTE']['Resultado']['RecepcionEnvio']['RecepcionDTE'])) {
// crear repuestas a partir del arreglo
$Recepciones = $this->arreglo['RespuestaDTE']['Resultado']['RecepcionEnvio']['RecepcionDTE'];
if (!isset($Recepciones[0]))
$Recepciones = [$Recepciones];
foreach ($Recepciones as $Recepcion) {
$this->respuesta_envios[] = $Recepcion;
}
}
}
// entregar recibos
return $this->respuesta_envios;
} | [
"public",
"function",
"getRecepciones",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"esRecepcionEnvio",
"(",
")",
")",
"return",
"false",
";",
"// si no hay respustas se deben crear",
"if",
"(",
"!",
"$",
"this",
"->",
"respuesta_envios",
")",
"{",
"//... | Método que entrega un arreglo con los resultados de recepciones del XML
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2016-08-09 | [
"Método",
"que",
"entrega",
"un",
"arreglo",
"con",
"los",
"resultados",
"de",
"recepciones",
"del",
"XML"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/RespuestaEnvio.php#L234-L257 |
LibreDTE/libredte-lib | lib/Sii/RespuestaEnvio.php | RespuestaEnvio.getResultados | public function getResultados()
{
if (!$this->esResultadoDTE())
return false;
// si no hay respustas se deben crear
if (!$this->respuesta_documentos) {
// si no está creado el arrelgo con los datos error
if (!$this->arreglo) {
return false;
}
// crear repuestas a partir del arreglo
$Resultados = $this->arreglo['RespuestaDTE']['Resultado']['ResultadoDTE'];
if (!isset($Resultados[0]))
$Resultados = [$Resultados];
foreach ($Resultados as $Resultado) {
$this->respuesta_documentos[] = $Resultado;
}
}
// entregar recibos
return $this->respuesta_documentos;
} | php | public function getResultados()
{
if (!$this->esResultadoDTE())
return false;
// si no hay respustas se deben crear
if (!$this->respuesta_documentos) {
// si no está creado el arrelgo con los datos error
if (!$this->arreglo) {
return false;
}
// crear repuestas a partir del arreglo
$Resultados = $this->arreglo['RespuestaDTE']['Resultado']['ResultadoDTE'];
if (!isset($Resultados[0]))
$Resultados = [$Resultados];
foreach ($Resultados as $Resultado) {
$this->respuesta_documentos[] = $Resultado;
}
}
// entregar recibos
return $this->respuesta_documentos;
} | [
"public",
"function",
"getResultados",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"esResultadoDTE",
"(",
")",
")",
"return",
"false",
";",
"// si no hay respustas se deben crear",
"if",
"(",
"!",
"$",
"this",
"->",
"respuesta_documentos",
")",
"{",
"/... | Método que entrega un arreglo con los resultados de DTE del XML
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2015-12-23 | [
"Método",
"que",
"entrega",
"un",
"arreglo",
"con",
"los",
"resultados",
"de",
"DTE",
"del",
"XML"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/RespuestaEnvio.php#L264-L284 |
LibreDTE/libredte-lib | lib/Sii/Dte.php | Dte.loadXML | private function loadXML($xml)
{
if (!empty($xml)) {
$this->xml = new \sasco\LibreDTE\XML();
if (!$this->xml->loadXML($xml) or !$this->schemaValidate()) {
\sasco\LibreDTE\Log::write(
\sasco\LibreDTE\Estado::DTE_ERROR_LOADXML,
\sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::DTE_ERROR_LOADXML)
);
return false;
}
$TipoDTE = $this->xml->getElementsByTagName('TipoDTE')->item(0);
if (!$TipoDTE) {
return false;
}
$this->tipo = $TipoDTE->nodeValue;
$this->tipo_general = $this->getTipoGeneral($this->tipo);
if (!$this->tipo_general) {
return false;
}
$Folio = $this->xml->getElementsByTagName('Folio')->item(0);
if (!$Folio) {
return false;
}
$this->folio = $Folio->nodeValue;
if (isset($this->getDatos()['@attributes'])) {
$this->id = $this->getDatos()['@attributes']['ID'];
} else {
$this->id = 'LibreDTE_T'.$this->tipo.'F'.$this->folio;
}
return true;
}
return false;
} | php | private function loadXML($xml)
{
if (!empty($xml)) {
$this->xml = new \sasco\LibreDTE\XML();
if (!$this->xml->loadXML($xml) or !$this->schemaValidate()) {
\sasco\LibreDTE\Log::write(
\sasco\LibreDTE\Estado::DTE_ERROR_LOADXML,
\sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::DTE_ERROR_LOADXML)
);
return false;
}
$TipoDTE = $this->xml->getElementsByTagName('TipoDTE')->item(0);
if (!$TipoDTE) {
return false;
}
$this->tipo = $TipoDTE->nodeValue;
$this->tipo_general = $this->getTipoGeneral($this->tipo);
if (!$this->tipo_general) {
return false;
}
$Folio = $this->xml->getElementsByTagName('Folio')->item(0);
if (!$Folio) {
return false;
}
$this->folio = $Folio->nodeValue;
if (isset($this->getDatos()['@attributes'])) {
$this->id = $this->getDatos()['@attributes']['ID'];
} else {
$this->id = 'LibreDTE_T'.$this->tipo.'F'.$this->folio;
}
return true;
}
return false;
} | [
"private",
"function",
"loadXML",
"(",
"$",
"xml",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"xml",
")",
")",
"{",
"$",
"this",
"->",
"xml",
"=",
"new",
"\\",
"sasco",
"\\",
"LibreDTE",
"\\",
"XML",
"(",
")",
";",
"if",
"(",
"!",
"$",
"thi... | Método que carga el DTE ya armado desde un archivo XML
@param xml String con los datos completos del XML del DTE
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2016-09-01 | [
"Método",
"que",
"carga",
"el",
"DTE",
"ya",
"armado",
"desde",
"un",
"archivo",
"XML"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Dte.php#L73-L106 |
LibreDTE/libredte-lib | lib/Sii/Dte.php | Dte.setDatos | private function setDatos(array $datos, $normalizar = true)
{
if (!empty($datos)) {
$this->tipo = $datos['Encabezado']['IdDoc']['TipoDTE'];
$this->folio = $datos['Encabezado']['IdDoc']['Folio'];
$this->id = 'LibreDTE_T'.$this->tipo.'F'.$this->folio;
if ($normalizar) {
$this->normalizar($datos);
$method = 'normalizar_'.$this->tipo;
if (method_exists($this, $method))
$this->$method($datos);
$this->normalizar_final($datos);
}
$this->tipo_general = $this->getTipoGeneral($this->tipo);
$this->xml = (new \sasco\LibreDTE\XML())->generate([
'DTE' => [
'@attributes' => [
'version' => '1.0',
],
$this->tipo_general => [
'@attributes' => [
'ID' => $this->id
],
]
]
]);
$parent = $this->xml->getElementsByTagName($this->tipo_general)->item(0);
$this->xml->generate($datos + ['TED' => null], null, $parent);
$this->datos = $datos;
if ($normalizar and !$this->verificarDatos()) {
return false;
}
return $this->schemaValidate();
}
return false;
} | php | private function setDatos(array $datos, $normalizar = true)
{
if (!empty($datos)) {
$this->tipo = $datos['Encabezado']['IdDoc']['TipoDTE'];
$this->folio = $datos['Encabezado']['IdDoc']['Folio'];
$this->id = 'LibreDTE_T'.$this->tipo.'F'.$this->folio;
if ($normalizar) {
$this->normalizar($datos);
$method = 'normalizar_'.$this->tipo;
if (method_exists($this, $method))
$this->$method($datos);
$this->normalizar_final($datos);
}
$this->tipo_general = $this->getTipoGeneral($this->tipo);
$this->xml = (new \sasco\LibreDTE\XML())->generate([
'DTE' => [
'@attributes' => [
'version' => '1.0',
],
$this->tipo_general => [
'@attributes' => [
'ID' => $this->id
],
]
]
]);
$parent = $this->xml->getElementsByTagName($this->tipo_general)->item(0);
$this->xml->generate($datos + ['TED' => null], null, $parent);
$this->datos = $datos;
if ($normalizar and !$this->verificarDatos()) {
return false;
}
return $this->schemaValidate();
}
return false;
} | [
"private",
"function",
"setDatos",
"(",
"array",
"$",
"datos",
",",
"$",
"normalizar",
"=",
"true",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"datos",
")",
")",
"{",
"$",
"this",
"->",
"tipo",
"=",
"$",
"datos",
"[",
"'Encabezado'",
"]",
"[",
... | Método que asigna los datos del DTE
@param datos Arreglo con los datos del DTE que se quire generar
@param normalizar Si se pasa un arreglo permitirá indicar si el mismo se debe o no normalizar
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2017-10-22 | [
"Método",
"que",
"asigna",
"los",
"datos",
"del",
"DTE"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Dte.php#L115-L150 |
LibreDTE/libredte-lib | lib/Sii/Dte.php | Dte.getDatos | public function getDatos()
{
if (!$this->datos) {
$datos = $this->xml->toArray();
if (!isset($datos['DTE'][$this->tipo_general])) {
\sasco\LibreDTE\Log::write(
\sasco\LibreDTE\Estado::DTE_ERROR_GETDATOS,
\sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::DTE_ERROR_GETDATOS)
);
return false;
}
$this->datos = $datos['DTE'][$this->tipo_general];
if (isset($datos['DTE']['Signature'])) {
$this->Signature = $datos['DTE']['Signature'];
}
}
return $this->datos;
} | php | public function getDatos()
{
if (!$this->datos) {
$datos = $this->xml->toArray();
if (!isset($datos['DTE'][$this->tipo_general])) {
\sasco\LibreDTE\Log::write(
\sasco\LibreDTE\Estado::DTE_ERROR_GETDATOS,
\sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::DTE_ERROR_GETDATOS)
);
return false;
}
$this->datos = $datos['DTE'][$this->tipo_general];
if (isset($datos['DTE']['Signature'])) {
$this->Signature = $datos['DTE']['Signature'];
}
}
return $this->datos;
} | [
"public",
"function",
"getDatos",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"datos",
")",
"{",
"$",
"datos",
"=",
"$",
"this",
"->",
"xml",
"->",
"toArray",
"(",
")",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"datos",
"[",
"'DTE'",
"]",
... | Método que entrega el arreglo con los datos del DTE.
Si el DTE fue creado a partir de un arreglo serán los datos normalizados,
en cambio si se creó a partir de un XML serán todos los nodos del
documento sin cambios.
@return Arreglo con datos del DTE
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2016-07-04 | [
"Método",
"que",
"entrega",
"el",
"arreglo",
"con",
"los",
"datos",
"del",
"DTE",
".",
"Si",
"el",
"DTE",
"fue",
"creado",
"a",
"partir",
"de",
"un",
"arreglo",
"serán",
"los",
"datos",
"normalizados",
"en",
"cambio",
"si",
"se",
"creó",
"a",
"partir",
... | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Dte.php#L161-L178 |
LibreDTE/libredte-lib | lib/Sii/Dte.php | Dte.getID | public function getID($estandar = false)
{
return $estandar ? ('T'.$this->tipo.'F'.$this->folio) : $this->id;
} | php | public function getID($estandar = false)
{
return $estandar ? ('T'.$this->tipo.'F'.$this->folio) : $this->id;
} | [
"public",
"function",
"getID",
"(",
"$",
"estandar",
"=",
"false",
")",
"{",
"return",
"$",
"estandar",
"?",
"(",
"'T'",
".",
"$",
"this",
"->",
"tipo",
".",
"'F'",
".",
"$",
"this",
"->",
"folio",
")",
":",
"$",
"this",
"->",
"id",
";",
"}"
] | Método que entrega el ID del documento
@return String con el ID del DTE
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2016-08-17 | [
"Método",
"que",
"entrega",
"el",
"ID",
"del",
"documento"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Dte.php#L213-L216 |
LibreDTE/libredte-lib | lib/Sii/Dte.php | Dte.getTipoGeneral | private function getTipoGeneral($dte)
{
foreach ($this->tipos as $tipo => $codigos)
if (in_array($dte, $codigos))
return $tipo;
\sasco\LibreDTE\Log::write(
\sasco\LibreDTE\Estado::DTE_ERROR_TIPO,
\sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::DTE_ERROR_TIPO, $dte)
);
return false;
} | php | private function getTipoGeneral($dte)
{
foreach ($this->tipos as $tipo => $codigos)
if (in_array($dte, $codigos))
return $tipo;
\sasco\LibreDTE\Log::write(
\sasco\LibreDTE\Estado::DTE_ERROR_TIPO,
\sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::DTE_ERROR_TIPO, $dte)
);
return false;
} | [
"private",
"function",
"getTipoGeneral",
"(",
"$",
"dte",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"tipos",
"as",
"$",
"tipo",
"=>",
"$",
"codigos",
")",
"if",
"(",
"in_array",
"(",
"$",
"dte",
",",
"$",
"codigos",
")",
")",
"return",
"$",
"tip... | Método que entrega el tipo general de documento, de acuerdo a
$this->tipos
@param dte Tipo númerico de DTE, ejemplo: 33 (factura electrónica)
@return String con el tipo general: Documento, Liquidacion o Exportaciones
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2015-09-17 | [
"Método",
"que",
"entrega",
"el",
"tipo",
"general",
"de",
"documento",
"de",
"acuerdo",
"a",
"$this",
"-",
">",
"tipos"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Dte.php#L226-L236 |
LibreDTE/libredte-lib | lib/Sii/Dte.php | Dte.getEmisor | public function getEmisor()
{
$nodo = $this->xml->xpath('/DTE/'.$this->tipo_general.'/Encabezado/Emisor/RUTEmisor')->item(0);
if ($nodo)
return $nodo->nodeValue;
if (!$this->getDatos())
return false;
return $this->datos['Encabezado']['Emisor']['RUTEmisor'];
} | php | public function getEmisor()
{
$nodo = $this->xml->xpath('/DTE/'.$this->tipo_general.'/Encabezado/Emisor/RUTEmisor')->item(0);
if ($nodo)
return $nodo->nodeValue;
if (!$this->getDatos())
return false;
return $this->datos['Encabezado']['Emisor']['RUTEmisor'];
} | [
"public",
"function",
"getEmisor",
"(",
")",
"{",
"$",
"nodo",
"=",
"$",
"this",
"->",
"xml",
"->",
"xpath",
"(",
"'/DTE/'",
".",
"$",
"this",
"->",
"tipo_general",
".",
"'/Encabezado/Emisor/RUTEmisor'",
")",
"->",
"item",
"(",
"0",
")",
";",
"if",
"("... | Método que entrega rut del emisor del DTE
@return RUT del emiro
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2015-09-07 | [
"Método",
"que",
"entrega",
"rut",
"del",
"emisor",
"del",
"DTE"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Dte.php#L266-L274 |
LibreDTE/libredte-lib | lib/Sii/Dte.php | Dte.getReferencias | public function getReferencias()
{
if (!$this->getDatos()) {
return false;
}
$referencias = !empty($this->datos['Referencia']) ? $this->datos['Referencia'] : false;
if (!$referencias) {
return [];
}
if (!isset($referencias[0])) {
$referencias = [$referencias];
}
return $referencias;
} | php | public function getReferencias()
{
if (!$this->getDatos()) {
return false;
}
$referencias = !empty($this->datos['Referencia']) ? $this->datos['Referencia'] : false;
if (!$referencias) {
return [];
}
if (!isset($referencias[0])) {
$referencias = [$referencias];
}
return $referencias;
} | [
"public",
"function",
"getReferencias",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"getDatos",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"$",
"referencias",
"=",
"!",
"empty",
"(",
"$",
"this",
"->",
"datos",
"[",
"'Referencia'",
"]",
... | Método que entrega las referencias del DTE si existen
@return Arreglo con las referencias
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2017-11-17 | [
"Método",
"que",
"entrega",
"las",
"referencias",
"del",
"DTE",
"si",
"existen"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Dte.php#L346-L359 |
LibreDTE/libredte-lib | lib/Sii/Dte.php | Dte.getTED | public function getTED()
{
/*$xml = new \sasco\LibreDTE\XML();
$xml->loadXML($this->xml->getElementsByTagName('TED')->item(0)->getElementsByTagName('DD')->item(0)->C14N());
$xml->documentElement->removeAttributeNS('http://www.w3.org/2001/XMLSchema-instance', 'xsi');
$xml->documentElement->removeAttributeNS('http://www.sii.cl/SiiDte', '');
$FRMT = $this->xml->getElementsByTagName('TED')->item(0)->getElementsByTagName('FRMT')->item(0)->nodeValue;
$pub_key = '';
if (openssl_verify($xml->getFlattened('/'), base64_decode($FRMT), $pub_key, OPENSSL_ALGO_SHA1)!==1);
return false;*/
$xml = new \sasco\LibreDTE\XML();
$TED = $this->xml->getElementsByTagName('TED')->item(0);
if (!$TED)
return '<TED/>';
$xml->loadXML($TED->C14N());
$xml->documentElement->removeAttributeNS('http://www.w3.org/2001/XMLSchema-instance', 'xsi');
$xml->documentElement->removeAttributeNS('http://www.sii.cl/SiiDte', '');
$TED = $xml->getFlattened('/');
return mb_detect_encoding($TED, ['UTF-8', 'ISO-8859-1']) != 'ISO-8859-1' ? utf8_decode($TED) : $TED;
} | php | public function getTED()
{
/*$xml = new \sasco\LibreDTE\XML();
$xml->loadXML($this->xml->getElementsByTagName('TED')->item(0)->getElementsByTagName('DD')->item(0)->C14N());
$xml->documentElement->removeAttributeNS('http://www.w3.org/2001/XMLSchema-instance', 'xsi');
$xml->documentElement->removeAttributeNS('http://www.sii.cl/SiiDte', '');
$FRMT = $this->xml->getElementsByTagName('TED')->item(0)->getElementsByTagName('FRMT')->item(0)->nodeValue;
$pub_key = '';
if (openssl_verify($xml->getFlattened('/'), base64_decode($FRMT), $pub_key, OPENSSL_ALGO_SHA1)!==1);
return false;*/
$xml = new \sasco\LibreDTE\XML();
$TED = $this->xml->getElementsByTagName('TED')->item(0);
if (!$TED)
return '<TED/>';
$xml->loadXML($TED->C14N());
$xml->documentElement->removeAttributeNS('http://www.w3.org/2001/XMLSchema-instance', 'xsi');
$xml->documentElement->removeAttributeNS('http://www.sii.cl/SiiDte', '');
$TED = $xml->getFlattened('/');
return mb_detect_encoding($TED, ['UTF-8', 'ISO-8859-1']) != 'ISO-8859-1' ? utf8_decode($TED) : $TED;
} | [
"public",
"function",
"getTED",
"(",
")",
"{",
"/*$xml = new \\sasco\\LibreDTE\\XML();\n $xml->loadXML($this->xml->getElementsByTagName('TED')->item(0)->getElementsByTagName('DD')->item(0)->C14N());\n $xml->documentElement->removeAttributeNS('http://www.w3.org/2001/XMLSchema-instance', 'xs... | Método que entrega el string XML del tag TED
@return String XML con tag TED
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2016-08-03 | [
"Método",
"que",
"entrega",
"el",
"string",
"XML",
"del",
"tag",
"TED"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Dte.php#L367-L386 |
LibreDTE/libredte-lib | lib/Sii/Dte.php | Dte.getCertificacion | public function getCertificacion()
{
$datos = $this->getDatos();
$idk = !empty($datos['TED']['DD']['CAF']['DA']['IDK']) ? (int)$datos['TED']['DD']['CAF']['DA']['IDK'] : null;
return $idk ? $idk === 100 : null;
} | php | public function getCertificacion()
{
$datos = $this->getDatos();
$idk = !empty($datos['TED']['DD']['CAF']['DA']['IDK']) ? (int)$datos['TED']['DD']['CAF']['DA']['IDK'] : null;
return $idk ? $idk === 100 : null;
} | [
"public",
"function",
"getCertificacion",
"(",
")",
"{",
"$",
"datos",
"=",
"$",
"this",
"->",
"getDatos",
"(",
")",
";",
"$",
"idk",
"=",
"!",
"empty",
"(",
"$",
"datos",
"[",
"'TED'",
"]",
"[",
"'DD'",
"]",
"[",
"'CAF'",
"]",
"[",
"'DA'",
"]",
... | Método que indica si el DTE es de certificación o no
@return =true si el DTE es de certificación, =null si no se pudo determinar
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2016-06-15 | [
"Método",
"que",
"indica",
"si",
"el",
"DTE",
"es",
"de",
"certificación",
"o",
"no"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Dte.php#L394-L399 |
LibreDTE/libredte-lib | lib/Sii/Dte.php | Dte.timbrar | public function timbrar(Folios $Folios)
{
// verificar que el folio que se está usando para el DTE esté dentro
// del rango de folios autorizados que se usarán para timbrar
// Esta validación NO verifica si el folio ya fue usado, sólo si está
// dentro del CAF que se está usando
$folio = $this->xml->xpath('/DTE/'.$this->tipo_general.'/Encabezado/IdDoc/Folio')->item(0)->nodeValue;
if ($folio<$Folios->getDesde() or $folio>$Folios->getHasta()) {
\sasco\LibreDTE\Log::write(
\sasco\LibreDTE\Estado::DTE_ERROR_RANGO_FOLIO,
\sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::DTE_ERROR_RANGO_FOLIO, $this->getID())
);
return false;
}
// verificar que existan datos para el timbre
if (!$this->xml->xpath('/DTE/'.$this->tipo_general.'/Encabezado/IdDoc/FchEmis')->item(0)) {
\sasco\LibreDTE\Log::write(
\sasco\LibreDTE\Estado::DTE_FALTA_FCHEMIS,
\sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::DTE_FALTA_FCHEMIS, $this->getID())
);
\sasco\LibreDTE\Log::write('Falta FchEmis del DTE '.$this->getID());
return false;
}
if (!$this->xml->xpath('/DTE/'.$this->tipo_general.'/Encabezado/Totales/MntTotal')->item(0)) {
\sasco\LibreDTE\Log::write(
\sasco\LibreDTE\Estado::DTE_FALTA_MNTTOTAL,
\sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::DTE_FALTA_MNTTOTAL, $this->getID())
);
return false;
}
// timbrar
$RR = $this->xml->xpath('/DTE/'.$this->tipo_general.'/Encabezado/Receptor/RUTRecep')->item(0)->nodeValue;
$RSR_nodo = $this->xml->xpath('/DTE/'.$this->tipo_general.'/Encabezado/Receptor/RznSocRecep');
$RSR = $RSR_nodo->length ? trim(mb_substr($RSR_nodo->item(0)->nodeValue, 0, 40)) : $RR;
$TED = new \sasco\LibreDTE\XML();
$TED->generate([
'TED' => [
'@attributes' => [
'version' => '1.0',
],
'DD' => [
'RE' => $this->xml->xpath('/DTE/'.$this->tipo_general.'/Encabezado/Emisor/RUTEmisor')->item(0)->nodeValue,
'TD' => $this->xml->xpath('/DTE/'.$this->tipo_general.'/Encabezado/IdDoc/TipoDTE')->item(0)->nodeValue,
'F' => $folio,
'FE' => $this->xml->xpath('/DTE/'.$this->tipo_general.'/Encabezado/IdDoc/FchEmis')->item(0)->nodeValue,
'RR' => $this->xml->xpath('/DTE/'.$this->tipo_general.'/Encabezado/Receptor/RUTRecep')->item(0)->nodeValue,
'RSR' => $RSR,
'MNT' => $this->xml->xpath('/DTE/'.$this->tipo_general.'/Encabezado/Totales/MntTotal')->item(0)->nodeValue,
'IT1' => trim(mb_substr($this->xml->xpath('/DTE/'.$this->tipo_general.'/Detalle')->item(0)->getElementsByTagName('NmbItem')->item(0)->nodeValue, 0, 40)),
'CAF' => $Folios->getCaf(),
'TSTED' => $this->timestamp,
],
'FRMT' => [
'@attributes' => [
'algoritmo' => 'SHA1withRSA'
],
],
]
]);
$DD = $TED->getFlattened('/TED/DD');
if (openssl_sign($DD, $timbre, $Folios->getPrivateKey(), OPENSSL_ALGO_SHA1)==false) {
\sasco\LibreDTE\Log::write(
\sasco\LibreDTE\Estado::DTE_ERROR_TIMBRE,
\sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::DTE_ERROR_TIMBRE, $this->getID())
);
return false;
}
$TED->getElementsByTagName('FRMT')->item(0)->nodeValue = base64_encode($timbre);
$xml = str_replace('<TED/>', trim(str_replace('<?xml version="1.0" encoding="ISO-8859-1"?>', '', $TED->saveXML())), $this->saveXML());
if (!$this->loadXML($xml)) {
\sasco\LibreDTE\Log::write(
\sasco\LibreDTE\Estado::DTE_ERROR_TIMBRE,
\sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::DTE_ERROR_TIMBRE, $this->getID())
);
return false;
}
return true;
} | php | public function timbrar(Folios $Folios)
{
// verificar que el folio que se está usando para el DTE esté dentro
// del rango de folios autorizados que se usarán para timbrar
// Esta validación NO verifica si el folio ya fue usado, sólo si está
// dentro del CAF que se está usando
$folio = $this->xml->xpath('/DTE/'.$this->tipo_general.'/Encabezado/IdDoc/Folio')->item(0)->nodeValue;
if ($folio<$Folios->getDesde() or $folio>$Folios->getHasta()) {
\sasco\LibreDTE\Log::write(
\sasco\LibreDTE\Estado::DTE_ERROR_RANGO_FOLIO,
\sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::DTE_ERROR_RANGO_FOLIO, $this->getID())
);
return false;
}
// verificar que existan datos para el timbre
if (!$this->xml->xpath('/DTE/'.$this->tipo_general.'/Encabezado/IdDoc/FchEmis')->item(0)) {
\sasco\LibreDTE\Log::write(
\sasco\LibreDTE\Estado::DTE_FALTA_FCHEMIS,
\sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::DTE_FALTA_FCHEMIS, $this->getID())
);
\sasco\LibreDTE\Log::write('Falta FchEmis del DTE '.$this->getID());
return false;
}
if (!$this->xml->xpath('/DTE/'.$this->tipo_general.'/Encabezado/Totales/MntTotal')->item(0)) {
\sasco\LibreDTE\Log::write(
\sasco\LibreDTE\Estado::DTE_FALTA_MNTTOTAL,
\sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::DTE_FALTA_MNTTOTAL, $this->getID())
);
return false;
}
// timbrar
$RR = $this->xml->xpath('/DTE/'.$this->tipo_general.'/Encabezado/Receptor/RUTRecep')->item(0)->nodeValue;
$RSR_nodo = $this->xml->xpath('/DTE/'.$this->tipo_general.'/Encabezado/Receptor/RznSocRecep');
$RSR = $RSR_nodo->length ? trim(mb_substr($RSR_nodo->item(0)->nodeValue, 0, 40)) : $RR;
$TED = new \sasco\LibreDTE\XML();
$TED->generate([
'TED' => [
'@attributes' => [
'version' => '1.0',
],
'DD' => [
'RE' => $this->xml->xpath('/DTE/'.$this->tipo_general.'/Encabezado/Emisor/RUTEmisor')->item(0)->nodeValue,
'TD' => $this->xml->xpath('/DTE/'.$this->tipo_general.'/Encabezado/IdDoc/TipoDTE')->item(0)->nodeValue,
'F' => $folio,
'FE' => $this->xml->xpath('/DTE/'.$this->tipo_general.'/Encabezado/IdDoc/FchEmis')->item(0)->nodeValue,
'RR' => $this->xml->xpath('/DTE/'.$this->tipo_general.'/Encabezado/Receptor/RUTRecep')->item(0)->nodeValue,
'RSR' => $RSR,
'MNT' => $this->xml->xpath('/DTE/'.$this->tipo_general.'/Encabezado/Totales/MntTotal')->item(0)->nodeValue,
'IT1' => trim(mb_substr($this->xml->xpath('/DTE/'.$this->tipo_general.'/Detalle')->item(0)->getElementsByTagName('NmbItem')->item(0)->nodeValue, 0, 40)),
'CAF' => $Folios->getCaf(),
'TSTED' => $this->timestamp,
],
'FRMT' => [
'@attributes' => [
'algoritmo' => 'SHA1withRSA'
],
],
]
]);
$DD = $TED->getFlattened('/TED/DD');
if (openssl_sign($DD, $timbre, $Folios->getPrivateKey(), OPENSSL_ALGO_SHA1)==false) {
\sasco\LibreDTE\Log::write(
\sasco\LibreDTE\Estado::DTE_ERROR_TIMBRE,
\sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::DTE_ERROR_TIMBRE, $this->getID())
);
return false;
}
$TED->getElementsByTagName('FRMT')->item(0)->nodeValue = base64_encode($timbre);
$xml = str_replace('<TED/>', trim(str_replace('<?xml version="1.0" encoding="ISO-8859-1"?>', '', $TED->saveXML())), $this->saveXML());
if (!$this->loadXML($xml)) {
\sasco\LibreDTE\Log::write(
\sasco\LibreDTE\Estado::DTE_ERROR_TIMBRE,
\sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::DTE_ERROR_TIMBRE, $this->getID())
);
return false;
}
return true;
} | [
"public",
"function",
"timbrar",
"(",
"Folios",
"$",
"Folios",
")",
"{",
"// verificar que el folio que se está usando para el DTE esté dentro",
"// del rango de folios autorizados que se usarán para timbrar",
"// Esta validación NO verifica si el folio ya fue usado, sólo si está",
"// dentr... | Método que realiza el timbrado del DTE
@param Folios Objeto de los Folios con los que se desea timbrar
@return =true si se pudo timbrar o =false en caso de error
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2016-09-01 | [
"Método",
"que",
"realiza",
"el",
"timbrado",
"del",
"DTE"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Dte.php#L408-L485 |
LibreDTE/libredte-lib | lib/Sii/Dte.php | Dte.firmar | public function firmar(\sasco\LibreDTE\FirmaElectronica $Firma)
{
$parent = $this->xml->getElementsByTagName($this->tipo_general)->item(0);
$this->xml->generate(['TmstFirma'=>$this->timestamp], null, $parent);
$xml = $Firma->signXML($this->xml->saveXML(), '#'.$this->id, $this->tipo_general);
if (!$xml) {
\sasco\LibreDTE\Log::write(
\sasco\LibreDTE\Estado::DTE_ERROR_FIRMA,
\sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::DTE_ERROR_FIRMA, $this->getID())
);
return false;
}
$this->loadXML($xml);
return true;
} | php | public function firmar(\sasco\LibreDTE\FirmaElectronica $Firma)
{
$parent = $this->xml->getElementsByTagName($this->tipo_general)->item(0);
$this->xml->generate(['TmstFirma'=>$this->timestamp], null, $parent);
$xml = $Firma->signXML($this->xml->saveXML(), '#'.$this->id, $this->tipo_general);
if (!$xml) {
\sasco\LibreDTE\Log::write(
\sasco\LibreDTE\Estado::DTE_ERROR_FIRMA,
\sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::DTE_ERROR_FIRMA, $this->getID())
);
return false;
}
$this->loadXML($xml);
return true;
} | [
"public",
"function",
"firmar",
"(",
"\\",
"sasco",
"\\",
"LibreDTE",
"\\",
"FirmaElectronica",
"$",
"Firma",
")",
"{",
"$",
"parent",
"=",
"$",
"this",
"->",
"xml",
"->",
"getElementsByTagName",
"(",
"$",
"this",
"->",
"tipo_general",
")",
"->",
"item",
... | Método que realiza la firma del DTE
@param Firma objeto que representa la Firma Electrónca
@return =true si el DTE pudo ser fimado o =false si no se pudo firmar
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2017-10-22 | [
"Método",
"que",
"realiza",
"la",
"firma",
"del",
"DTE"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Dte.php#L494-L508 |
LibreDTE/libredte-lib | lib/Sii/Dte.php | Dte.getResumen | public function getResumen()
{
$this->getDatos();
// generar resumen
$resumen = [
'TpoDoc' => (int)$this->datos['Encabezado']['IdDoc']['TipoDTE'],
'NroDoc' => (int)$this->datos['Encabezado']['IdDoc']['Folio'],
'TasaImp' => 0,
'FchDoc' => $this->datos['Encabezado']['IdDoc']['FchEmis'],
'CdgSIISucur' => !empty($this->datos['Encabezado']['Emisor']['CdgSIISucur']) ? $this->datos['Encabezado']['Emisor']['CdgSIISucur'] : false,
'RUTDoc' => $this->datos['Encabezado']['Receptor']['RUTRecep'],
'RznSoc' => isset($this->datos['Encabezado']['Receptor']['RznSocRecep']) ? $this->datos['Encabezado']['Receptor']['RznSocRecep'] : false,
'MntExe' => false,
'MntNeto' => false,
'MntIVA' => 0,
'MntTotal' => 0,
];
// obtener montos si es que existen en el documento
$montos = ['TasaImp'=>'TasaIVA', 'MntExe'=>'MntExe', 'MntNeto'=>'MntNeto', 'MntIVA'=>'IVA', 'MntTotal'=>'MntTotal'];
foreach ($montos as $dest => $orig) {
if (!empty($this->datos['Encabezado']['Totales'][$orig])) {
$resumen[$dest] = !$this->esExportacion() ? round($this->datos['Encabezado']['Totales'][$orig]) : $this->datos['Encabezado']['Totales'][$orig];
}
}
// si es una boleta se calculan los datos para el resumen
if ($this->esBoleta()) {
if (!$resumen['TasaImp']) {
$resumen['TasaImp'] = \sasco\LibreDTE\Sii::getIVA();
}
$resumen['MntExe'] = (int)$resumen['MntExe'];
if (!$resumen['MntNeto']) {
list($resumen['MntNeto'], $resumen['MntIVA']) = $this->calcularNetoIVA($resumen['MntTotal']-$resumen['MntExe'], $resumen['TasaImp']);
}
}
// entregar resumen
return $resumen;
} | php | public function getResumen()
{
$this->getDatos();
// generar resumen
$resumen = [
'TpoDoc' => (int)$this->datos['Encabezado']['IdDoc']['TipoDTE'],
'NroDoc' => (int)$this->datos['Encabezado']['IdDoc']['Folio'],
'TasaImp' => 0,
'FchDoc' => $this->datos['Encabezado']['IdDoc']['FchEmis'],
'CdgSIISucur' => !empty($this->datos['Encabezado']['Emisor']['CdgSIISucur']) ? $this->datos['Encabezado']['Emisor']['CdgSIISucur'] : false,
'RUTDoc' => $this->datos['Encabezado']['Receptor']['RUTRecep'],
'RznSoc' => isset($this->datos['Encabezado']['Receptor']['RznSocRecep']) ? $this->datos['Encabezado']['Receptor']['RznSocRecep'] : false,
'MntExe' => false,
'MntNeto' => false,
'MntIVA' => 0,
'MntTotal' => 0,
];
// obtener montos si es que existen en el documento
$montos = ['TasaImp'=>'TasaIVA', 'MntExe'=>'MntExe', 'MntNeto'=>'MntNeto', 'MntIVA'=>'IVA', 'MntTotal'=>'MntTotal'];
foreach ($montos as $dest => $orig) {
if (!empty($this->datos['Encabezado']['Totales'][$orig])) {
$resumen[$dest] = !$this->esExportacion() ? round($this->datos['Encabezado']['Totales'][$orig]) : $this->datos['Encabezado']['Totales'][$orig];
}
}
// si es una boleta se calculan los datos para el resumen
if ($this->esBoleta()) {
if (!$resumen['TasaImp']) {
$resumen['TasaImp'] = \sasco\LibreDTE\Sii::getIVA();
}
$resumen['MntExe'] = (int)$resumen['MntExe'];
if (!$resumen['MntNeto']) {
list($resumen['MntNeto'], $resumen['MntIVA']) = $this->calcularNetoIVA($resumen['MntTotal']-$resumen['MntExe'], $resumen['TasaImp']);
}
}
// entregar resumen
return $resumen;
} | [
"public",
"function",
"getResumen",
"(",
")",
"{",
"$",
"this",
"->",
"getDatos",
"(",
")",
";",
"// generar resumen",
"$",
"resumen",
"=",
"[",
"'TpoDoc'",
"=>",
"(",
"int",
")",
"$",
"this",
"->",
"datos",
"[",
"'Encabezado'",
"]",
"[",
"'IdDoc'",
"]... | Método que genera un arreglo con el resumen del documento. Este resumen
puede servir, por ejemplo, para generar los detalles de los IECV
@return Arreglo con el resumen del DTE
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2016-07-15 | [
"Método",
"que",
"genera",
"un",
"arreglo",
"con",
"el",
"resumen",
"del",
"documento",
".",
"Este",
"resumen",
"puede",
"servir",
"por",
"ejemplo",
"para",
"generar",
"los",
"detalles",
"de",
"los",
"IECV"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Dte.php#L528-L564 |
LibreDTE/libredte-lib | lib/Sii/Dte.php | Dte.calcularNetoIVA | private function calcularNetoIVA($total, $tasa = null)
{
if ($tasa === 0 or $tasa === false)
return [0, 0];
if ($tasa === null)
$tasa = \sasco\LibreDTE\Sii::getIVA();
// WARNING: el IVA obtenido puede no ser el NETO*(TASA/100)
// se calcula el monto neto y luego se obtiene el IVA haciendo la resta
// entre el total y el neto, ya que hay casos de borde como:
// - BRUTO: 680 => NETO: 571 e IVA: 108 => TOTAL: 679
// - BRUTO: 86710 => NETO: 72866 e IVA: 13845 => TOTAL: 86711
$neto = round($total / (1+($tasa/100)));
$iva = $total - $neto;
return [$neto, $iva];
} | php | private function calcularNetoIVA($total, $tasa = null)
{
if ($tasa === 0 or $tasa === false)
return [0, 0];
if ($tasa === null)
$tasa = \sasco\LibreDTE\Sii::getIVA();
// WARNING: el IVA obtenido puede no ser el NETO*(TASA/100)
// se calcula el monto neto y luego se obtiene el IVA haciendo la resta
// entre el total y el neto, ya que hay casos de borde como:
// - BRUTO: 680 => NETO: 571 e IVA: 108 => TOTAL: 679
// - BRUTO: 86710 => NETO: 72866 e IVA: 13845 => TOTAL: 86711
$neto = round($total / (1+($tasa/100)));
$iva = $total - $neto;
return [$neto, $iva];
} | [
"private",
"function",
"calcularNetoIVA",
"(",
"$",
"total",
",",
"$",
"tasa",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"tasa",
"===",
"0",
"or",
"$",
"tasa",
"===",
"false",
")",
"return",
"[",
"0",
",",
"0",
"]",
";",
"if",
"(",
"$",
"tasa",
"=... | Método que permite obtener el monto neto y el IVA de ese neto a partir de
un monto total
@param total neto + iva
@param tasa Tasa del IVA
@return Arreglo con el neto y el iva
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2016-04-05 | [
"Método",
"que",
"permite",
"obtener",
"el",
"monto",
"neto",
"y",
"el",
"IVA",
"de",
"ese",
"neto",
"a",
"partir",
"de",
"un",
"monto",
"total"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Dte.php#L575-L589 |
LibreDTE/libredte-lib | lib/Sii/Dte.php | Dte.normalizar | private function normalizar(array &$datos)
{
// completar con nodos por defecto
$datos = \sasco\LibreDTE\Arreglo::mergeRecursiveDistinct([
'Encabezado' => [
'IdDoc' => [
'TipoDTE' => false,
'Folio' => false,
'FchEmis' => date('Y-m-d'),
'IndNoRebaja' => false,
'TipoDespacho' => false,
'IndTraslado' => false,
'TpoImpresion' => false,
'IndServicio' => $this->esBoleta() ? 3 : false,
'MntBruto' => false,
'TpoTranCompra' => false,
'TpoTranVenta' => false,
'FmaPago' => false,
'FmaPagExp' => false,
'MntCancel' => false,
'SaldoInsol' => false,
'FchCancel' => false,
'MntPagos' => false,
'PeriodoDesde' => false,
'PeriodoHasta' => false,
'MedioPago' => false,
'TpoCtaPago' => false,
'NumCtaPago' => false,
'BcoPago' => false,
'TermPagoCdg' => false,
'TermPagoGlosa' => false,
'TermPagoDias' => false,
'FchVenc' => false,
],
'Emisor' => [
'RUTEmisor' => false,
'RznSoc' => false,
'GiroEmis' => false,
'Telefono' => false,
'CorreoEmisor' => false,
'Acteco' => false,
'Sucursal' => false,
'CdgSIISucur' => false,
'DirOrigen' => false,
'CmnaOrigen' => false,
'CiudadOrigen' => false,
'CdgVendedor' => false,
],
'Receptor' => [
'RUTRecep' => false,
'CdgIntRecep' => false,
'RznSocRecep' => false,
'Extranjero' => false,
'GiroRecep' => false,
'Contacto' => false,
'CorreoRecep' => false,
'DirRecep' => false,
'CmnaRecep' => false,
'CiudadRecep' => false,
'DirPostal' => false,
'CmnaPostal' => false,
'CiudadPostal' => false,
],
'Totales' => [
'TpoMoneda' => false,
],
],
'Detalle' => false,
'SubTotInfo' => false,
'DscRcgGlobal' => false,
'Referencia' => false,
'Comisiones' => false,
], $datos);
// corregir algunos datos que podrían venir malos para no caer por schema
$datos['Encabezado']['Emisor']['RUTEmisor'] = strtoupper(trim(str_replace('.', '', $datos['Encabezado']['Emisor']['RUTEmisor'])));
$datos['Encabezado']['Receptor']['RUTRecep'] = strtoupper(trim(str_replace('.', '', $datos['Encabezado']['Receptor']['RUTRecep'])));
$datos['Encabezado']['Receptor']['RznSocRecep'] = mb_substr($datos['Encabezado']['Receptor']['RznSocRecep'], 0, 100);
if (!empty($datos['Encabezado']['Receptor']['GiroRecep'])) {
$datos['Encabezado']['Receptor']['GiroRecep'] = mb_substr($datos['Encabezado']['Receptor']['GiroRecep'], 0, 40);
}
if (!empty($datos['Encabezado']['Receptor']['Contacto'])) {
$datos['Encabezado']['Receptor']['Contacto'] = mb_substr($datos['Encabezado']['Receptor']['Contacto'], 0, 80);
}
if (!empty($datos['Encabezado']['Receptor']['CorreoRecep'])) {
$datos['Encabezado']['Receptor']['CorreoRecep'] = mb_substr($datos['Encabezado']['Receptor']['CorreoRecep'], 0, 80);
}
if (!empty($datos['Encabezado']['Receptor']['DirRecep'])) {
$datos['Encabezado']['Receptor']['DirRecep'] = mb_substr($datos['Encabezado']['Receptor']['DirRecep'], 0, 70);
}
if (!empty($datos['Encabezado']['Receptor']['CmnaRecep'])) {
$datos['Encabezado']['Receptor']['CmnaRecep'] = mb_substr($datos['Encabezado']['Receptor']['CmnaRecep'], 0, 20);
}
if (!empty($datos['Encabezado']['Emisor']['Acteco'])) {
if (strlen((string)$datos['Encabezado']['Emisor']['Acteco'])==5) {
$datos['Encabezado']['Emisor']['Acteco'] = '0'.$datos['Encabezado']['Emisor']['Acteco'];
}
}
// si existe descuento o recargo global se normalizan
if (!empty($datos['DscRcgGlobal'])) {
if (!isset($datos['DscRcgGlobal'][0]))
$datos['DscRcgGlobal'] = [$datos['DscRcgGlobal']];
$NroLinDR = 1;
foreach ($datos['DscRcgGlobal'] as &$dr) {
$dr = array_merge([
'NroLinDR' => $NroLinDR++,
], $dr);
}
}
// si existe una o más referencias se normalizan
if (!empty($datos['Referencia'])) {
if (!isset($datos['Referencia'][0])) {
$datos['Referencia'] = [$datos['Referencia']];
}
$NroLinRef = 1;
foreach ($datos['Referencia'] as &$r) {
$r = array_merge([
'NroLinRef' => $NroLinRef++,
'TpoDocRef' => false,
'IndGlobal' => false,
'FolioRef' => false,
'RUTOtr' => false,
'FchRef' => date('Y-m-d'),
'CodRef' => false,
'RazonRef' => false,
], $r);
}
}
// verificar que exista TpoTranVenta
if (!in_array($datos['Encabezado']['IdDoc']['TipoDTE'], [39, 41, 110, 111, 112]) and empty($datos['Encabezado']['IdDoc']['TpoTranVenta'])) {
$datos['Encabezado']['IdDoc']['TpoTranVenta'] = 1; // ventas del giro
}
} | php | private function normalizar(array &$datos)
{
// completar con nodos por defecto
$datos = \sasco\LibreDTE\Arreglo::mergeRecursiveDistinct([
'Encabezado' => [
'IdDoc' => [
'TipoDTE' => false,
'Folio' => false,
'FchEmis' => date('Y-m-d'),
'IndNoRebaja' => false,
'TipoDespacho' => false,
'IndTraslado' => false,
'TpoImpresion' => false,
'IndServicio' => $this->esBoleta() ? 3 : false,
'MntBruto' => false,
'TpoTranCompra' => false,
'TpoTranVenta' => false,
'FmaPago' => false,
'FmaPagExp' => false,
'MntCancel' => false,
'SaldoInsol' => false,
'FchCancel' => false,
'MntPagos' => false,
'PeriodoDesde' => false,
'PeriodoHasta' => false,
'MedioPago' => false,
'TpoCtaPago' => false,
'NumCtaPago' => false,
'BcoPago' => false,
'TermPagoCdg' => false,
'TermPagoGlosa' => false,
'TermPagoDias' => false,
'FchVenc' => false,
],
'Emisor' => [
'RUTEmisor' => false,
'RznSoc' => false,
'GiroEmis' => false,
'Telefono' => false,
'CorreoEmisor' => false,
'Acteco' => false,
'Sucursal' => false,
'CdgSIISucur' => false,
'DirOrigen' => false,
'CmnaOrigen' => false,
'CiudadOrigen' => false,
'CdgVendedor' => false,
],
'Receptor' => [
'RUTRecep' => false,
'CdgIntRecep' => false,
'RznSocRecep' => false,
'Extranjero' => false,
'GiroRecep' => false,
'Contacto' => false,
'CorreoRecep' => false,
'DirRecep' => false,
'CmnaRecep' => false,
'CiudadRecep' => false,
'DirPostal' => false,
'CmnaPostal' => false,
'CiudadPostal' => false,
],
'Totales' => [
'TpoMoneda' => false,
],
],
'Detalle' => false,
'SubTotInfo' => false,
'DscRcgGlobal' => false,
'Referencia' => false,
'Comisiones' => false,
], $datos);
// corregir algunos datos que podrían venir malos para no caer por schema
$datos['Encabezado']['Emisor']['RUTEmisor'] = strtoupper(trim(str_replace('.', '', $datos['Encabezado']['Emisor']['RUTEmisor'])));
$datos['Encabezado']['Receptor']['RUTRecep'] = strtoupper(trim(str_replace('.', '', $datos['Encabezado']['Receptor']['RUTRecep'])));
$datos['Encabezado']['Receptor']['RznSocRecep'] = mb_substr($datos['Encabezado']['Receptor']['RznSocRecep'], 0, 100);
if (!empty($datos['Encabezado']['Receptor']['GiroRecep'])) {
$datos['Encabezado']['Receptor']['GiroRecep'] = mb_substr($datos['Encabezado']['Receptor']['GiroRecep'], 0, 40);
}
if (!empty($datos['Encabezado']['Receptor']['Contacto'])) {
$datos['Encabezado']['Receptor']['Contacto'] = mb_substr($datos['Encabezado']['Receptor']['Contacto'], 0, 80);
}
if (!empty($datos['Encabezado']['Receptor']['CorreoRecep'])) {
$datos['Encabezado']['Receptor']['CorreoRecep'] = mb_substr($datos['Encabezado']['Receptor']['CorreoRecep'], 0, 80);
}
if (!empty($datos['Encabezado']['Receptor']['DirRecep'])) {
$datos['Encabezado']['Receptor']['DirRecep'] = mb_substr($datos['Encabezado']['Receptor']['DirRecep'], 0, 70);
}
if (!empty($datos['Encabezado']['Receptor']['CmnaRecep'])) {
$datos['Encabezado']['Receptor']['CmnaRecep'] = mb_substr($datos['Encabezado']['Receptor']['CmnaRecep'], 0, 20);
}
if (!empty($datos['Encabezado']['Emisor']['Acteco'])) {
if (strlen((string)$datos['Encabezado']['Emisor']['Acteco'])==5) {
$datos['Encabezado']['Emisor']['Acteco'] = '0'.$datos['Encabezado']['Emisor']['Acteco'];
}
}
// si existe descuento o recargo global se normalizan
if (!empty($datos['DscRcgGlobal'])) {
if (!isset($datos['DscRcgGlobal'][0]))
$datos['DscRcgGlobal'] = [$datos['DscRcgGlobal']];
$NroLinDR = 1;
foreach ($datos['DscRcgGlobal'] as &$dr) {
$dr = array_merge([
'NroLinDR' => $NroLinDR++,
], $dr);
}
}
// si existe una o más referencias se normalizan
if (!empty($datos['Referencia'])) {
if (!isset($datos['Referencia'][0])) {
$datos['Referencia'] = [$datos['Referencia']];
}
$NroLinRef = 1;
foreach ($datos['Referencia'] as &$r) {
$r = array_merge([
'NroLinRef' => $NroLinRef++,
'TpoDocRef' => false,
'IndGlobal' => false,
'FolioRef' => false,
'RUTOtr' => false,
'FchRef' => date('Y-m-d'),
'CodRef' => false,
'RazonRef' => false,
], $r);
}
}
// verificar que exista TpoTranVenta
if (!in_array($datos['Encabezado']['IdDoc']['TipoDTE'], [39, 41, 110, 111, 112]) and empty($datos['Encabezado']['IdDoc']['TpoTranVenta'])) {
$datos['Encabezado']['IdDoc']['TpoTranVenta'] = 1; // ventas del giro
}
} | [
"private",
"function",
"normalizar",
"(",
"array",
"&",
"$",
"datos",
")",
"{",
"// completar con nodos por defecto",
"$",
"datos",
"=",
"\\",
"sasco",
"\\",
"LibreDTE",
"\\",
"Arreglo",
"::",
"mergeRecursiveDistinct",
"(",
"[",
"'Encabezado'",
"=>",
"[",
"'IdDo... | Método que normaliza los datos de un documento tributario electrónico
@param datos Arreglo con los datos del documento que se desean normalizar
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2018-06-25 | [
"Método",
"que",
"normaliza",
"los",
"datos",
"de",
"un",
"documento",
"tributario",
"electrónico"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Dte.php#L597-L728 |
LibreDTE/libredte-lib | lib/Sii/Dte.php | Dte.normalizar_final | private function normalizar_final(array &$datos)
{
// normalizar montos de pagos programados
if (is_array($datos['Encabezado']['IdDoc']['MntPagos'])) {
$montos = 0;
if (!isset($datos['Encabezado']['IdDoc']['MntPagos'][0])) {
$datos['Encabezado']['IdDoc']['MntPagos'] = [$datos['Encabezado']['IdDoc']['MntPagos']];
}
foreach ($datos['Encabezado']['IdDoc']['MntPagos'] as &$MntPagos) {
$MntPagos = array_merge([
'FchPago' => null,
'MntPago' => null,
'GlosaPagos' => false,
], $MntPagos);
if ($MntPagos['MntPago']===null) {
$MntPagos['MntPago'] = $datos['Encabezado']['Totales']['MntTotal'];
}
}
}
// si existe OtraMoneda se verifican los tipos de cambio y totales
if (!empty($datos['Encabezado']['OtraMoneda'])) {
if (!isset($datos['Encabezado']['OtraMoneda'][0])) {
$datos['Encabezado']['OtraMoneda'] = [$datos['Encabezado']['OtraMoneda']];
}
foreach ($datos['Encabezado']['OtraMoneda'] as &$OtraMoneda) {
// colocar campos por defecto
$OtraMoneda = array_merge([
'TpoMoneda' => false,
'TpoCambio' => false,
'MntNetoOtrMnda' => false,
'MntExeOtrMnda' => false,
'MntFaeCarneOtrMnda' => false,
'MntMargComOtrMnda' => false,
'IVAOtrMnda' => false,
'ImpRetOtrMnda' => false,
'IVANoRetOtrMnda' => false,
'MntTotOtrMnda' => false,
], $OtraMoneda);
// si no hay tipo de cambio no seguir
if (!isset($OtraMoneda['TpoCambio'])) {
continue;
}
// buscar si los valores están asignados, si no lo están asignar
// usando el tipo de cambio que existe para la moneda
foreach (['MntNeto', 'MntExe', 'IVA', 'IVANoRet'] as $monto) {
if (empty($OtraMoneda[$monto.'OtrMnda']) and !empty($datos['Encabezado']['Totales'][$monto])) {
$OtraMoneda[$monto.'OtrMnda'] = round($datos['Encabezado']['Totales'][$monto] * $OtraMoneda['TpoCambio'], 4);
}
}
// calcular MntFaeCarneOtrMnda, MntMargComOtrMnda, ImpRetOtrMnda
if (empty($OtraMoneda['MntFaeCarneOtrMnda'])) {
$OtraMoneda['MntFaeCarneOtrMnda'] = false; // TODO
}
if (empty($OtraMoneda['MntMargComOtrMnda'])) {
$OtraMoneda['MntMargComOtrMnda'] = false; // TODO
}
if (empty($OtraMoneda['ImpRetOtrMnda'])) {
$OtraMoneda['ImpRetOtrMnda'] = false; // TODO
}
// calcular monto total
if (empty($OtraMoneda['MntTotOtrMnda'])) {
$OtraMoneda['MntTotOtrMnda'] = 0;
$cols = ['MntNetoOtrMnda', 'MntExeOtrMnda', 'MntFaeCarneOtrMnda', 'MntMargComOtrMnda', 'IVAOtrMnda', 'IVANoRetOtrMnda'];
foreach ($cols as $monto) {
if (!empty($OtraMoneda[$monto])) {
$OtraMoneda['MntTotOtrMnda'] += $OtraMoneda[$monto];
}
}
// agregar total de impuesto retenido otra moneda
if (!empty($OtraMoneda['ImpRetOtrMnda'])) {
// TODO
}
// aproximar el total si es en pesos chilenos
if ($OtraMoneda['TpoMoneda']=='PESO CL') {
$OtraMoneda['MntTotOtrMnda'] = round($OtraMoneda['MntTotOtrMnda']);
}
}
// si el tipo de cambio es 0, se quita
if ($OtraMoneda['TpoCambio']==0) {
$OtraMoneda['TpoCambio'] = false;
}
}
}
} | php | private function normalizar_final(array &$datos)
{
// normalizar montos de pagos programados
if (is_array($datos['Encabezado']['IdDoc']['MntPagos'])) {
$montos = 0;
if (!isset($datos['Encabezado']['IdDoc']['MntPagos'][0])) {
$datos['Encabezado']['IdDoc']['MntPagos'] = [$datos['Encabezado']['IdDoc']['MntPagos']];
}
foreach ($datos['Encabezado']['IdDoc']['MntPagos'] as &$MntPagos) {
$MntPagos = array_merge([
'FchPago' => null,
'MntPago' => null,
'GlosaPagos' => false,
], $MntPagos);
if ($MntPagos['MntPago']===null) {
$MntPagos['MntPago'] = $datos['Encabezado']['Totales']['MntTotal'];
}
}
}
// si existe OtraMoneda se verifican los tipos de cambio y totales
if (!empty($datos['Encabezado']['OtraMoneda'])) {
if (!isset($datos['Encabezado']['OtraMoneda'][0])) {
$datos['Encabezado']['OtraMoneda'] = [$datos['Encabezado']['OtraMoneda']];
}
foreach ($datos['Encabezado']['OtraMoneda'] as &$OtraMoneda) {
// colocar campos por defecto
$OtraMoneda = array_merge([
'TpoMoneda' => false,
'TpoCambio' => false,
'MntNetoOtrMnda' => false,
'MntExeOtrMnda' => false,
'MntFaeCarneOtrMnda' => false,
'MntMargComOtrMnda' => false,
'IVAOtrMnda' => false,
'ImpRetOtrMnda' => false,
'IVANoRetOtrMnda' => false,
'MntTotOtrMnda' => false,
], $OtraMoneda);
// si no hay tipo de cambio no seguir
if (!isset($OtraMoneda['TpoCambio'])) {
continue;
}
// buscar si los valores están asignados, si no lo están asignar
// usando el tipo de cambio que existe para la moneda
foreach (['MntNeto', 'MntExe', 'IVA', 'IVANoRet'] as $monto) {
if (empty($OtraMoneda[$monto.'OtrMnda']) and !empty($datos['Encabezado']['Totales'][$monto])) {
$OtraMoneda[$monto.'OtrMnda'] = round($datos['Encabezado']['Totales'][$monto] * $OtraMoneda['TpoCambio'], 4);
}
}
// calcular MntFaeCarneOtrMnda, MntMargComOtrMnda, ImpRetOtrMnda
if (empty($OtraMoneda['MntFaeCarneOtrMnda'])) {
$OtraMoneda['MntFaeCarneOtrMnda'] = false; // TODO
}
if (empty($OtraMoneda['MntMargComOtrMnda'])) {
$OtraMoneda['MntMargComOtrMnda'] = false; // TODO
}
if (empty($OtraMoneda['ImpRetOtrMnda'])) {
$OtraMoneda['ImpRetOtrMnda'] = false; // TODO
}
// calcular monto total
if (empty($OtraMoneda['MntTotOtrMnda'])) {
$OtraMoneda['MntTotOtrMnda'] = 0;
$cols = ['MntNetoOtrMnda', 'MntExeOtrMnda', 'MntFaeCarneOtrMnda', 'MntMargComOtrMnda', 'IVAOtrMnda', 'IVANoRetOtrMnda'];
foreach ($cols as $monto) {
if (!empty($OtraMoneda[$monto])) {
$OtraMoneda['MntTotOtrMnda'] += $OtraMoneda[$monto];
}
}
// agregar total de impuesto retenido otra moneda
if (!empty($OtraMoneda['ImpRetOtrMnda'])) {
// TODO
}
// aproximar el total si es en pesos chilenos
if ($OtraMoneda['TpoMoneda']=='PESO CL') {
$OtraMoneda['MntTotOtrMnda'] = round($OtraMoneda['MntTotOtrMnda']);
}
}
// si el tipo de cambio es 0, se quita
if ($OtraMoneda['TpoCambio']==0) {
$OtraMoneda['TpoCambio'] = false;
}
}
}
} | [
"private",
"function",
"normalizar_final",
"(",
"array",
"&",
"$",
"datos",
")",
"{",
"// normalizar montos de pagos programados",
"if",
"(",
"is_array",
"(",
"$",
"datos",
"[",
"'Encabezado'",
"]",
"[",
"'IdDoc'",
"]",
"[",
"'MntPagos'",
"]",
")",
")",
"{",
... | Método que realiza la normalización final de los datos de un documento
tributario electrónico. Esto se aplica todos los documentos una vez que
ya se aplicaron las normalizaciones por tipo
@param datos Arreglo con los datos del documento que se desean normalizar
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2017-09-23 | [
"Método",
"que",
"realiza",
"la",
"normalización",
"final",
"de",
"los",
"datos",
"de",
"un",
"documento",
"tributario",
"electrónico",
".",
"Esto",
"se",
"aplica",
"todos",
"los",
"documentos",
"una",
"vez",
"que",
"ya",
"se",
"aplicaron",
"las",
"normalizaci... | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Dte.php#L738-L821 |
LibreDTE/libredte-lib | lib/Sii/Dte.php | Dte.normalizar_33 | private function normalizar_33(array &$datos)
{
// completar con nodos por defecto
$datos = \sasco\LibreDTE\Arreglo::mergeRecursiveDistinct([
'Encabezado' => [
'IdDoc' => false,
'Emisor' => false,
'RUTMandante' => false,
'Receptor' => false,
'RUTSolicita' => false,
'Transporte' => false,
'Totales' => [
'MntNeto' => 0,
'MntExe' => false,
'TasaIVA' => \sasco\LibreDTE\Sii::getIVA(),
'IVA' => 0,
'ImptoReten' => false,
'CredEC' => false,
'MntTotal' => 0,
],
'OtraMoneda' => false,
],
], $datos);
// normalizar datos
$this->normalizar_detalle($datos);
$this->normalizar_aplicar_descuentos_recargos($datos);
$this->normalizar_impuesto_retenido($datos);
$this->normalizar_agregar_IVA_MntTotal($datos);
$this->normalizar_transporte($datos);
} | php | private function normalizar_33(array &$datos)
{
// completar con nodos por defecto
$datos = \sasco\LibreDTE\Arreglo::mergeRecursiveDistinct([
'Encabezado' => [
'IdDoc' => false,
'Emisor' => false,
'RUTMandante' => false,
'Receptor' => false,
'RUTSolicita' => false,
'Transporte' => false,
'Totales' => [
'MntNeto' => 0,
'MntExe' => false,
'TasaIVA' => \sasco\LibreDTE\Sii::getIVA(),
'IVA' => 0,
'ImptoReten' => false,
'CredEC' => false,
'MntTotal' => 0,
],
'OtraMoneda' => false,
],
], $datos);
// normalizar datos
$this->normalizar_detalle($datos);
$this->normalizar_aplicar_descuentos_recargos($datos);
$this->normalizar_impuesto_retenido($datos);
$this->normalizar_agregar_IVA_MntTotal($datos);
$this->normalizar_transporte($datos);
} | [
"private",
"function",
"normalizar_33",
"(",
"array",
"&",
"$",
"datos",
")",
"{",
"// completar con nodos por defecto",
"$",
"datos",
"=",
"\\",
"sasco",
"\\",
"LibreDTE",
"\\",
"Arreglo",
"::",
"mergeRecursiveDistinct",
"(",
"[",
"'Encabezado'",
"=>",
"[",
"'I... | Método que normaliza los datos de una factura electrónica
@param datos Arreglo con los datos del documento que se desean normalizar
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2017-09-01 | [
"Método",
"que",
"normaliza",
"los",
"datos",
"de",
"una",
"factura",
"electrónica"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Dte.php#L829-L858 |
LibreDTE/libredte-lib | lib/Sii/Dte.php | Dte.normalizar_34 | private function normalizar_34(array &$datos)
{
// completar con nodos por defecto
$datos = \sasco\LibreDTE\Arreglo::mergeRecursiveDistinct([
'Encabezado' => [
'IdDoc' => false,
'Emisor' => false,
'Receptor' => false,
'RUTSolicita' => false,
'Totales' => [
'MntExe' => false,
'MntTotal' => 0,
]
],
], $datos);
// normalizar datos
$this->normalizar_detalle($datos);
$this->normalizar_aplicar_descuentos_recargos($datos);
$this->normalizar_agregar_IVA_MntTotal($datos);
} | php | private function normalizar_34(array &$datos)
{
// completar con nodos por defecto
$datos = \sasco\LibreDTE\Arreglo::mergeRecursiveDistinct([
'Encabezado' => [
'IdDoc' => false,
'Emisor' => false,
'Receptor' => false,
'RUTSolicita' => false,
'Totales' => [
'MntExe' => false,
'MntTotal' => 0,
]
],
], $datos);
// normalizar datos
$this->normalizar_detalle($datos);
$this->normalizar_aplicar_descuentos_recargos($datos);
$this->normalizar_agregar_IVA_MntTotal($datos);
} | [
"private",
"function",
"normalizar_34",
"(",
"array",
"&",
"$",
"datos",
")",
"{",
"// completar con nodos por defecto",
"$",
"datos",
"=",
"\\",
"sasco",
"\\",
"LibreDTE",
"\\",
"Arreglo",
"::",
"mergeRecursiveDistinct",
"(",
"[",
"'Encabezado'",
"=>",
"[",
"'I... | Método que normaliza los datos de una factura exenta electrónica
@param datos Arreglo con los datos del documento que se desean normalizar
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2017-02-23 | [
"Método",
"que",
"normaliza",
"los",
"datos",
"de",
"una",
"factura",
"exenta",
"electrónica"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Dte.php#L866-L885 |
LibreDTE/libredte-lib | lib/Sii/Dte.php | Dte.normalizar_39 | private function normalizar_39(array &$datos)
{
// completar con nodos por defecto
$datos = \sasco\LibreDTE\Arreglo::mergeRecursiveDistinct([
'Encabezado' => [
'IdDoc' => false,
'Emisor' => [
'RUTEmisor' => false,
'RznSocEmisor' => false,
'GiroEmisor' => false,
],
'Receptor' => false,
'Totales' => [
'MntExe' => false,
'MntTotal' => 0,
]
],
], $datos);
// normalizar datos
$this->normalizar_boletas($datos);
$this->normalizar_detalle($datos);
$this->normalizar_aplicar_descuentos_recargos($datos);
$this->normalizar_agregar_IVA_MntTotal($datos);
} | php | private function normalizar_39(array &$datos)
{
// completar con nodos por defecto
$datos = \sasco\LibreDTE\Arreglo::mergeRecursiveDistinct([
'Encabezado' => [
'IdDoc' => false,
'Emisor' => [
'RUTEmisor' => false,
'RznSocEmisor' => false,
'GiroEmisor' => false,
],
'Receptor' => false,
'Totales' => [
'MntExe' => false,
'MntTotal' => 0,
]
],
], $datos);
// normalizar datos
$this->normalizar_boletas($datos);
$this->normalizar_detalle($datos);
$this->normalizar_aplicar_descuentos_recargos($datos);
$this->normalizar_agregar_IVA_MntTotal($datos);
} | [
"private",
"function",
"normalizar_39",
"(",
"array",
"&",
"$",
"datos",
")",
"{",
"// completar con nodos por defecto",
"$",
"datos",
"=",
"\\",
"sasco",
"\\",
"LibreDTE",
"\\",
"Arreglo",
"::",
"mergeRecursiveDistinct",
"(",
"[",
"'Encabezado'",
"=>",
"[",
"'I... | Método que normaliza los datos de una boleta electrónica
@param datos Arreglo con los datos del documento que se desean normalizar
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2016-03-14 | [
"Método",
"que",
"normaliza",
"los",
"datos",
"de",
"una",
"boleta",
"electrónica"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Dte.php#L893-L916 |
LibreDTE/libredte-lib | lib/Sii/Dte.php | Dte.normalizar_52 | private function normalizar_52(array &$datos)
{
// completar con nodos por defecto
$datos = \sasco\LibreDTE\Arreglo::mergeRecursiveDistinct([
'Encabezado' => [
'IdDoc' => false,
'Emisor' => false,
'Receptor' => false,
'RUTSolicita' => false,
'Transporte' => false,
'Totales' => [
'MntNeto' => 0,
'MntExe' => false,
'TasaIVA' => \sasco\LibreDTE\Sii::getIVA(),
'IVA' => 0,
'ImptoReten' => false,
'CredEC' => false,
'MntTotal' => 0,
]
],
], $datos);
// si es traslado interno se copia el emisor en el receptor sólo si el
// receptor no está definido o bien si el receptor tiene RUT diferente
// al emisor
if ($datos['Encabezado']['IdDoc']['IndTraslado']==5) {
if (!$datos['Encabezado']['Receptor'] or $datos['Encabezado']['Receptor']['RUTRecep']!=$datos['Encabezado']['Emisor']['RUTEmisor']) {
$datos['Encabezado']['Receptor'] = [];
$cols = [
'RUTEmisor'=>'RUTRecep',
'RznSoc'=>'RznSocRecep',
'GiroEmis'=>'GiroRecep',
'Telefono'=>'Contacto',
'CorreoEmisor'=>'CorreoRecep',
'DirOrigen'=>'DirRecep',
'CmnaOrigen'=>'CmnaRecep',
];
foreach ($cols as $emisor => $receptor) {
if (!empty($datos['Encabezado']['Emisor'][$emisor])) {
$datos['Encabezado']['Receptor'][$receptor] = $datos['Encabezado']['Emisor'][$emisor];
}
}
if (!empty($datos['Encabezado']['Receptor']['GiroRecep'])) {
$datos['Encabezado']['Receptor']['GiroRecep'] = mb_substr($datos['Encabezado']['Receptor']['GiroRecep'], 0, 40);
}
}
}
// normalizar datos
$this->normalizar_detalle($datos);
$this->normalizar_aplicar_descuentos_recargos($datos);
$this->normalizar_impuesto_retenido($datos);
$this->normalizar_agregar_IVA_MntTotal($datos);
$this->normalizar_transporte($datos);
} | php | private function normalizar_52(array &$datos)
{
// completar con nodos por defecto
$datos = \sasco\LibreDTE\Arreglo::mergeRecursiveDistinct([
'Encabezado' => [
'IdDoc' => false,
'Emisor' => false,
'Receptor' => false,
'RUTSolicita' => false,
'Transporte' => false,
'Totales' => [
'MntNeto' => 0,
'MntExe' => false,
'TasaIVA' => \sasco\LibreDTE\Sii::getIVA(),
'IVA' => 0,
'ImptoReten' => false,
'CredEC' => false,
'MntTotal' => 0,
]
],
], $datos);
// si es traslado interno se copia el emisor en el receptor sólo si el
// receptor no está definido o bien si el receptor tiene RUT diferente
// al emisor
if ($datos['Encabezado']['IdDoc']['IndTraslado']==5) {
if (!$datos['Encabezado']['Receptor'] or $datos['Encabezado']['Receptor']['RUTRecep']!=$datos['Encabezado']['Emisor']['RUTEmisor']) {
$datos['Encabezado']['Receptor'] = [];
$cols = [
'RUTEmisor'=>'RUTRecep',
'RznSoc'=>'RznSocRecep',
'GiroEmis'=>'GiroRecep',
'Telefono'=>'Contacto',
'CorreoEmisor'=>'CorreoRecep',
'DirOrigen'=>'DirRecep',
'CmnaOrigen'=>'CmnaRecep',
];
foreach ($cols as $emisor => $receptor) {
if (!empty($datos['Encabezado']['Emisor'][$emisor])) {
$datos['Encabezado']['Receptor'][$receptor] = $datos['Encabezado']['Emisor'][$emisor];
}
}
if (!empty($datos['Encabezado']['Receptor']['GiroRecep'])) {
$datos['Encabezado']['Receptor']['GiroRecep'] = mb_substr($datos['Encabezado']['Receptor']['GiroRecep'], 0, 40);
}
}
}
// normalizar datos
$this->normalizar_detalle($datos);
$this->normalizar_aplicar_descuentos_recargos($datos);
$this->normalizar_impuesto_retenido($datos);
$this->normalizar_agregar_IVA_MntTotal($datos);
$this->normalizar_transporte($datos);
} | [
"private",
"function",
"normalizar_52",
"(",
"array",
"&",
"$",
"datos",
")",
"{",
"// completar con nodos por defecto",
"$",
"datos",
"=",
"\\",
"sasco",
"\\",
"LibreDTE",
"\\",
"Arreglo",
"::",
"mergeRecursiveDistinct",
"(",
"[",
"'Encabezado'",
"=>",
"[",
"'I... | Método que normaliza los datos de una guía de despacho electrónica
@param datos Arreglo con los datos del documento que se desean normalizar
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2017-09-01 | [
"Método",
"que",
"normaliza",
"los",
"datos",
"de",
"una",
"guía",
"de",
"despacho",
"electrónica"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Dte.php#L988-L1040 |
LibreDTE/libredte-lib | lib/Sii/Dte.php | Dte.normalizar_110 | private function normalizar_110(array &$datos)
{
// completar con nodos por defecto
$datos = \sasco\LibreDTE\Arreglo::mergeRecursiveDistinct([
'Encabezado' => [
'IdDoc' => false,
'Emisor' => false,
'Receptor' => false,
'Transporte' => [
'Patente' => false,
'RUTTrans' => false,
'Chofer' => false,
'DirDest' => false,
'CmnaDest' => false,
'CiudadDest' => false,
'Aduana' => [
'CodModVenta' => false,
'CodClauVenta' => false,
'TotClauVenta' => false,
'CodViaTransp' => false,
'NombreTransp' => false,
'RUTCiaTransp' => false,
'NomCiaTransp' => false,
'IdAdicTransp' => false,
'Booking' => false,
'Operador' => false,
'CodPtoEmbarque' => false,
'IdAdicPtoEmb' => false,
'CodPtoDesemb' => false,
'IdAdicPtoDesemb' => false,
'Tara' => false,
'CodUnidMedTara' => false,
'PesoBruto' => false,
'CodUnidPesoBruto' => false,
'PesoNeto' => false,
'CodUnidPesoNeto' => false,
'TotItems' => false,
'TotBultos' => false,
'TipoBultos' => false,
'MntFlete' => false,
'MntSeguro' => false,
'CodPaisRecep' => false,
'CodPaisDestin' => false,
],
],
'Totales' => [
'TpoMoneda' => null,
'MntExe' => 0,
'MntTotal' => 0,
]
],
], $datos);
// normalizar datos
$this->normalizar_detalle($datos);
$this->normalizar_aplicar_descuentos_recargos($datos);
$this->normalizar_impuesto_retenido($datos);
$this->normalizar_agregar_IVA_MntTotal($datos);
$this->normalizar_exportacion($datos);
} | php | private function normalizar_110(array &$datos)
{
// completar con nodos por defecto
$datos = \sasco\LibreDTE\Arreglo::mergeRecursiveDistinct([
'Encabezado' => [
'IdDoc' => false,
'Emisor' => false,
'Receptor' => false,
'Transporte' => [
'Patente' => false,
'RUTTrans' => false,
'Chofer' => false,
'DirDest' => false,
'CmnaDest' => false,
'CiudadDest' => false,
'Aduana' => [
'CodModVenta' => false,
'CodClauVenta' => false,
'TotClauVenta' => false,
'CodViaTransp' => false,
'NombreTransp' => false,
'RUTCiaTransp' => false,
'NomCiaTransp' => false,
'IdAdicTransp' => false,
'Booking' => false,
'Operador' => false,
'CodPtoEmbarque' => false,
'IdAdicPtoEmb' => false,
'CodPtoDesemb' => false,
'IdAdicPtoDesemb' => false,
'Tara' => false,
'CodUnidMedTara' => false,
'PesoBruto' => false,
'CodUnidPesoBruto' => false,
'PesoNeto' => false,
'CodUnidPesoNeto' => false,
'TotItems' => false,
'TotBultos' => false,
'TipoBultos' => false,
'MntFlete' => false,
'MntSeguro' => false,
'CodPaisRecep' => false,
'CodPaisDestin' => false,
],
],
'Totales' => [
'TpoMoneda' => null,
'MntExe' => 0,
'MntTotal' => 0,
]
],
], $datos);
// normalizar datos
$this->normalizar_detalle($datos);
$this->normalizar_aplicar_descuentos_recargos($datos);
$this->normalizar_impuesto_retenido($datos);
$this->normalizar_agregar_IVA_MntTotal($datos);
$this->normalizar_exportacion($datos);
} | [
"private",
"function",
"normalizar_110",
"(",
"array",
"&",
"$",
"datos",
")",
"{",
"// completar con nodos por defecto",
"$",
"datos",
"=",
"\\",
"sasco",
"\\",
"LibreDTE",
"\\",
"Arreglo",
"::",
"mergeRecursiveDistinct",
"(",
"[",
"'Encabezado'",
"=>",
"[",
"'... | Método que normaliza los datos de una factura electrónica de exportación
@param datos Arreglo con los datos del documento que se desean normalizar
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2016-04-05 | [
"Método",
"que",
"normaliza",
"los",
"datos",
"de",
"una",
"factura",
"electrónica",
"de",
"exportación"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Dte.php#L1124-L1182 |
LibreDTE/libredte-lib | lib/Sii/Dte.php | Dte.normalizar_exportacion | public function normalizar_exportacion(array &$datos)
{
// agregar modalidad de venta por defecto si no existe
if (empty($datos['Encabezado']['Transporte']['Aduana']['CodModVenta']) and (!isset($datos['Encabezado']['IdDoc']['IndServicio']) or !in_array($datos['Encabezado']['IdDoc']['IndServicio'], [3, 4, 5]))) {
$datos['Encabezado']['Transporte']['Aduana']['CodModVenta'] = 1;
}
// quitar campos que no son parte del documento de exportacion
$datos['Encabezado']['Receptor']['CmnaRecep'] = false;
// colocar forma de pago de exportación
if (!empty($datos['Encabezado']['IdDoc']['FmaPago'])) {
$formas = [3 => 21];
if (isset($formas[$datos['Encabezado']['IdDoc']['FmaPago']])) {
$datos['Encabezado']['IdDoc']['FmaPagExp'] = $formas[$datos['Encabezado']['IdDoc']['FmaPago']];
}
$datos['Encabezado']['IdDoc']['FmaPago'] = false;
}
// si es entrega gratuita se coloca el tipo de cambio en CLP en 0 para que total sea 0
if (!empty($datos['Encabezado']['IdDoc']['FmaPagExp']) and $datos['Encabezado']['IdDoc']['FmaPagExp']==21 and !empty($datos['Encabezado']['OtraMoneda'])) {
if (!isset($datos['Encabezado']['OtraMoneda'][0])) {
$datos['Encabezado']['OtraMoneda'] = [$datos['Encabezado']['OtraMoneda']];
}
foreach ($datos['Encabezado']['OtraMoneda'] as &$OtraMoneda) {
if ($OtraMoneda['TpoMoneda']=='PESO CL') {
$OtraMoneda['TpoCambio'] = 0;
}
}
}
} | php | public function normalizar_exportacion(array &$datos)
{
// agregar modalidad de venta por defecto si no existe
if (empty($datos['Encabezado']['Transporte']['Aduana']['CodModVenta']) and (!isset($datos['Encabezado']['IdDoc']['IndServicio']) or !in_array($datos['Encabezado']['IdDoc']['IndServicio'], [3, 4, 5]))) {
$datos['Encabezado']['Transporte']['Aduana']['CodModVenta'] = 1;
}
// quitar campos que no son parte del documento de exportacion
$datos['Encabezado']['Receptor']['CmnaRecep'] = false;
// colocar forma de pago de exportación
if (!empty($datos['Encabezado']['IdDoc']['FmaPago'])) {
$formas = [3 => 21];
if (isset($formas[$datos['Encabezado']['IdDoc']['FmaPago']])) {
$datos['Encabezado']['IdDoc']['FmaPagExp'] = $formas[$datos['Encabezado']['IdDoc']['FmaPago']];
}
$datos['Encabezado']['IdDoc']['FmaPago'] = false;
}
// si es entrega gratuita se coloca el tipo de cambio en CLP en 0 para que total sea 0
if (!empty($datos['Encabezado']['IdDoc']['FmaPagExp']) and $datos['Encabezado']['IdDoc']['FmaPagExp']==21 and !empty($datos['Encabezado']['OtraMoneda'])) {
if (!isset($datos['Encabezado']['OtraMoneda'][0])) {
$datos['Encabezado']['OtraMoneda'] = [$datos['Encabezado']['OtraMoneda']];
}
foreach ($datos['Encabezado']['OtraMoneda'] as &$OtraMoneda) {
if ($OtraMoneda['TpoMoneda']=='PESO CL') {
$OtraMoneda['TpoCambio'] = 0;
}
}
}
} | [
"public",
"function",
"normalizar_exportacion",
"(",
"array",
"&",
"$",
"datos",
")",
"{",
"// agregar modalidad de venta por defecto si no existe",
"if",
"(",
"empty",
"(",
"$",
"datos",
"[",
"'Encabezado'",
"]",
"[",
"'Transporte'",
"]",
"[",
"'Aduana'",
"]",
"[... | Método que normaliza los datos de exportacion de un documento
@param datos Arreglo con los datos del documento que se desean normalizar
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2017-10-15 | [
"Método",
"que",
"normaliza",
"los",
"datos",
"de",
"exportacion",
"de",
"un",
"documento"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Dte.php#L1322-L1349 |
LibreDTE/libredte-lib | lib/Sii/Dte.php | Dte.normalizar_detalle | private function normalizar_detalle(array &$datos)
{
if (!isset($datos['Detalle'][0]))
$datos['Detalle'] = [$datos['Detalle']];
$item = 1;
foreach ($datos['Detalle'] as &$d) {
$d = array_merge([
'NroLinDet' => $item++,
'CdgItem' => false,
'IndExe' => false,
'Retenedor' => false,
'NmbItem' => false,
'DscItem' => false,
'QtyRef' => false,
'UnmdRef' => false,
'PrcRef' => false,
'QtyItem' => false,
'Subcantidad' => false,
'FchElabor' => false,
'FchVencim' => false,
'UnmdItem' => false,
'PrcItem' => false,
'DescuentoPct' => false,
'DescuentoMonto' => false,
'RecargoPct' => false,
'RecargoMonto' => false,
'CodImpAdic' => false,
'MontoItem' => false,
], $d);
// corregir datos
$d['NmbItem'] = mb_substr($d['NmbItem'], 0, 80);
if (!empty($d['DscItem'])) {
$d['DscItem'] = mb_substr($d['DscItem'], 0, 1000);
}
// normalizar
if ($this->esExportacion()) {
$d['IndExe'] = 1;
}
if (is_array($d['CdgItem'])) {
$d['CdgItem'] = array_merge([
'TpoCodigo' => false,
'VlrCodigo' => false,
], $d['CdgItem']);
if ($d['Retenedor']===false and $d['CdgItem']['TpoCodigo']=='CPCS') {
$d['Retenedor'] = true;
}
}
if ($d['Retenedor']!==false) {
if (!is_array($d['Retenedor'])) {
$d['Retenedor'] = ['IndAgente'=>'R'];
}
$d['Retenedor'] = array_merge([
'IndAgente' => 'R',
'MntBaseFaena' => false,
'MntMargComer' => false,
'PrcConsFinal' => false,
], $d['Retenedor']);
}
if ($d['CdgItem']!==false and !is_array($d['CdgItem'])) {
$d['CdgItem'] = [
'TpoCodigo' => empty($d['Retenedor']['IndAgente']) ? 'INT1' : 'CPCS',
'VlrCodigo' => $d['CdgItem'],
];
}
if ($d['PrcItem']) {
if (!$d['QtyItem'])
$d['QtyItem'] = 1;
if (empty($d['MontoItem'])) {
$d['MontoItem'] = $this->round(
$d['QtyItem'] * $d['PrcItem'],
$datos['Encabezado']['Totales']['TpoMoneda']
);
// aplicar descuento
if ($d['DescuentoPct']) {
$d['DescuentoMonto'] = round($d['MontoItem'] * (float)$d['DescuentoPct']/100);
}
$d['MontoItem'] -= $d['DescuentoMonto'];
// aplicar recargo
if ($d['RecargoPct']) {
$d['RecargoMonto'] = round($d['MontoItem'] * (float)$d['RecargoPct']/100);
}
$d['MontoItem'] += $d['RecargoMonto'];
// aproximar monto del item
$d['MontoItem'] = $this->round(
$d['MontoItem'], $datos['Encabezado']['Totales']['TpoMoneda']
);
}
} else if (empty($d['MontoItem'])) {
$d['MontoItem'] = 0;
}
// sumar valor del monto a MntNeto o MntExe según corresponda
if ($d['MontoItem']) {
// si no es boleta
if (!$this->esBoleta()) {
if ((!isset($datos['Encabezado']['Totales']['MntNeto']) or $datos['Encabezado']['Totales']['MntNeto']===false) and isset($datos['Encabezado']['Totales']['MntExe'])) {
$datos['Encabezado']['Totales']['MntExe'] += $d['MontoItem'];
} else {
if (!empty($d['IndExe'])) {
if ($d['IndExe']==1) {
$datos['Encabezado']['Totales']['MntExe'] += $d['MontoItem'];
}
} else {
$datos['Encabezado']['Totales']['MntNeto'] += $d['MontoItem'];
}
}
}
// si es boleta
else {
// si es exento
if (!empty($d['IndExe'])) {
if ($d['IndExe']==1) {
$datos['Encabezado']['Totales']['MntExe'] += $d['MontoItem'];
}
}
// agregar al monto total
$datos['Encabezado']['Totales']['MntTotal'] += $d['MontoItem'];
}
}
}
} | php | private function normalizar_detalle(array &$datos)
{
if (!isset($datos['Detalle'][0]))
$datos['Detalle'] = [$datos['Detalle']];
$item = 1;
foreach ($datos['Detalle'] as &$d) {
$d = array_merge([
'NroLinDet' => $item++,
'CdgItem' => false,
'IndExe' => false,
'Retenedor' => false,
'NmbItem' => false,
'DscItem' => false,
'QtyRef' => false,
'UnmdRef' => false,
'PrcRef' => false,
'QtyItem' => false,
'Subcantidad' => false,
'FchElabor' => false,
'FchVencim' => false,
'UnmdItem' => false,
'PrcItem' => false,
'DescuentoPct' => false,
'DescuentoMonto' => false,
'RecargoPct' => false,
'RecargoMonto' => false,
'CodImpAdic' => false,
'MontoItem' => false,
], $d);
// corregir datos
$d['NmbItem'] = mb_substr($d['NmbItem'], 0, 80);
if (!empty($d['DscItem'])) {
$d['DscItem'] = mb_substr($d['DscItem'], 0, 1000);
}
// normalizar
if ($this->esExportacion()) {
$d['IndExe'] = 1;
}
if (is_array($d['CdgItem'])) {
$d['CdgItem'] = array_merge([
'TpoCodigo' => false,
'VlrCodigo' => false,
], $d['CdgItem']);
if ($d['Retenedor']===false and $d['CdgItem']['TpoCodigo']=='CPCS') {
$d['Retenedor'] = true;
}
}
if ($d['Retenedor']!==false) {
if (!is_array($d['Retenedor'])) {
$d['Retenedor'] = ['IndAgente'=>'R'];
}
$d['Retenedor'] = array_merge([
'IndAgente' => 'R',
'MntBaseFaena' => false,
'MntMargComer' => false,
'PrcConsFinal' => false,
], $d['Retenedor']);
}
if ($d['CdgItem']!==false and !is_array($d['CdgItem'])) {
$d['CdgItem'] = [
'TpoCodigo' => empty($d['Retenedor']['IndAgente']) ? 'INT1' : 'CPCS',
'VlrCodigo' => $d['CdgItem'],
];
}
if ($d['PrcItem']) {
if (!$d['QtyItem'])
$d['QtyItem'] = 1;
if (empty($d['MontoItem'])) {
$d['MontoItem'] = $this->round(
$d['QtyItem'] * $d['PrcItem'],
$datos['Encabezado']['Totales']['TpoMoneda']
);
// aplicar descuento
if ($d['DescuentoPct']) {
$d['DescuentoMonto'] = round($d['MontoItem'] * (float)$d['DescuentoPct']/100);
}
$d['MontoItem'] -= $d['DescuentoMonto'];
// aplicar recargo
if ($d['RecargoPct']) {
$d['RecargoMonto'] = round($d['MontoItem'] * (float)$d['RecargoPct']/100);
}
$d['MontoItem'] += $d['RecargoMonto'];
// aproximar monto del item
$d['MontoItem'] = $this->round(
$d['MontoItem'], $datos['Encabezado']['Totales']['TpoMoneda']
);
}
} else if (empty($d['MontoItem'])) {
$d['MontoItem'] = 0;
}
// sumar valor del monto a MntNeto o MntExe según corresponda
if ($d['MontoItem']) {
// si no es boleta
if (!$this->esBoleta()) {
if ((!isset($datos['Encabezado']['Totales']['MntNeto']) or $datos['Encabezado']['Totales']['MntNeto']===false) and isset($datos['Encabezado']['Totales']['MntExe'])) {
$datos['Encabezado']['Totales']['MntExe'] += $d['MontoItem'];
} else {
if (!empty($d['IndExe'])) {
if ($d['IndExe']==1) {
$datos['Encabezado']['Totales']['MntExe'] += $d['MontoItem'];
}
} else {
$datos['Encabezado']['Totales']['MntNeto'] += $d['MontoItem'];
}
}
}
// si es boleta
else {
// si es exento
if (!empty($d['IndExe'])) {
if ($d['IndExe']==1) {
$datos['Encabezado']['Totales']['MntExe'] += $d['MontoItem'];
}
}
// agregar al monto total
$datos['Encabezado']['Totales']['MntTotal'] += $d['MontoItem'];
}
}
}
} | [
"private",
"function",
"normalizar_detalle",
"(",
"array",
"&",
"$",
"datos",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"datos",
"[",
"'Detalle'",
"]",
"[",
"0",
"]",
")",
")",
"$",
"datos",
"[",
"'Detalle'",
"]",
"=",
"[",
"$",
"datos",
"[",
... | Método que normaliza los detalles del documento
@param datos Arreglo con los datos del documento que se desean normalizar
@warning Revisar como se aplican descuentos y recargos, ¿debería ser un porcentaje del monto original?
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2017-07-24 | [
"Método",
"que",
"normaliza",
"los",
"detalles",
"del",
"documento"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Dte.php#L1358-L1477 |
LibreDTE/libredte-lib | lib/Sii/Dte.php | Dte.normalizar_aplicar_descuentos_recargos | private function normalizar_aplicar_descuentos_recargos(array &$datos)
{
if (!empty($datos['DscRcgGlobal'])) {
if (!isset($datos['DscRcgGlobal'][0]))
$datos['DscRcgGlobal'] = [$datos['DscRcgGlobal']];
foreach ($datos['DscRcgGlobal'] as &$dr) {
$dr = array_merge([
'NroLinDR' => false,
'TpoMov' => false,
'GlosaDR' => false,
'TpoValor' => false,
'ValorDR' => false,
'ValorDROtrMnda' => false,
'IndExeDR' => false,
], $dr);
if ($this->esExportacion()) {
$dr['IndExeDR'] = 1;
}
// determinar a que aplicar el descuento/recargo
if (!isset($dr['IndExeDR']) or $dr['IndExeDR']===false) {
$monto = $this->getTipo()==39 ? 'MntTotal' : 'MntNeto';
} else if ($dr['IndExeDR']==1) {
$monto = 'MntExe';
} else if ($dr['IndExeDR']==2) {
$monto = 'MontoNF';
}
// si no hay monto al que aplicar el descuento se omite
if (empty($datos['Encabezado']['Totales'][$monto])) {
continue;
}
// calcular valor del descuento o recargo
if ($dr['TpoValor']=='$') {
$dr['ValorDR'] = $this->round($dr['ValorDR'], $datos['Encabezado']['Totales']['TpoMoneda'], 2);
}
$valor =
$dr['TpoValor']=='%'
? $this->round(($dr['ValorDR']/100)*$datos['Encabezado']['Totales'][$monto], $datos['Encabezado']['Totales']['TpoMoneda'])
: $dr['ValorDR']
;
// aplicar descuento
if ($dr['TpoMov']=='D') {
$datos['Encabezado']['Totales'][$monto] -= $valor;
}
// aplicar recargo
else if ($dr['TpoMov']=='R') {
$datos['Encabezado']['Totales'][$monto] += $valor;
}
$datos['Encabezado']['Totales'][$monto] = $this->round(
$datos['Encabezado']['Totales'][$monto],
$datos['Encabezado']['Totales']['TpoMoneda']
);
// si el descuento global se aplica a una boleta exenta se copia el valor exento al total
if ($this->getTipo()==41 and isset($dr['IndExeDR']) and $dr['IndExeDR']==1) {
$datos['Encabezado']['Totales']['MntTotal'] = $datos['Encabezado']['Totales']['MntExe'];
}
}
}
} | php | private function normalizar_aplicar_descuentos_recargos(array &$datos)
{
if (!empty($datos['DscRcgGlobal'])) {
if (!isset($datos['DscRcgGlobal'][0]))
$datos['DscRcgGlobal'] = [$datos['DscRcgGlobal']];
foreach ($datos['DscRcgGlobal'] as &$dr) {
$dr = array_merge([
'NroLinDR' => false,
'TpoMov' => false,
'GlosaDR' => false,
'TpoValor' => false,
'ValorDR' => false,
'ValorDROtrMnda' => false,
'IndExeDR' => false,
], $dr);
if ($this->esExportacion()) {
$dr['IndExeDR'] = 1;
}
// determinar a que aplicar el descuento/recargo
if (!isset($dr['IndExeDR']) or $dr['IndExeDR']===false) {
$monto = $this->getTipo()==39 ? 'MntTotal' : 'MntNeto';
} else if ($dr['IndExeDR']==1) {
$monto = 'MntExe';
} else if ($dr['IndExeDR']==2) {
$monto = 'MontoNF';
}
// si no hay monto al que aplicar el descuento se omite
if (empty($datos['Encabezado']['Totales'][$monto])) {
continue;
}
// calcular valor del descuento o recargo
if ($dr['TpoValor']=='$') {
$dr['ValorDR'] = $this->round($dr['ValorDR'], $datos['Encabezado']['Totales']['TpoMoneda'], 2);
}
$valor =
$dr['TpoValor']=='%'
? $this->round(($dr['ValorDR']/100)*$datos['Encabezado']['Totales'][$monto], $datos['Encabezado']['Totales']['TpoMoneda'])
: $dr['ValorDR']
;
// aplicar descuento
if ($dr['TpoMov']=='D') {
$datos['Encabezado']['Totales'][$monto] -= $valor;
}
// aplicar recargo
else if ($dr['TpoMov']=='R') {
$datos['Encabezado']['Totales'][$monto] += $valor;
}
$datos['Encabezado']['Totales'][$monto] = $this->round(
$datos['Encabezado']['Totales'][$monto],
$datos['Encabezado']['Totales']['TpoMoneda']
);
// si el descuento global se aplica a una boleta exenta se copia el valor exento al total
if ($this->getTipo()==41 and isset($dr['IndExeDR']) and $dr['IndExeDR']==1) {
$datos['Encabezado']['Totales']['MntTotal'] = $datos['Encabezado']['Totales']['MntExe'];
}
}
}
} | [
"private",
"function",
"normalizar_aplicar_descuentos_recargos",
"(",
"array",
"&",
"$",
"datos",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"datos",
"[",
"'DscRcgGlobal'",
"]",
")",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"datos",
"[",
"'DscRcgGl... | Método que aplica los descuentos y recargos generales respectivos a los
montos que correspondan según e indicador del descuento o recargo
@param datos Arreglo con los datos del documento que se desean normalizar
@warning Boleta afecta con algún item exento el descuento se podría estar aplicando mal
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2017-09-06 | [
"Método",
"que",
"aplica",
"los",
"descuentos",
"y",
"recargos",
"generales",
"respectivos",
"a",
"los",
"montos",
"que",
"correspondan",
"según",
"e",
"indicador",
"del",
"descuento",
"o",
"recargo"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Dte.php#L1487-L1544 |
LibreDTE/libredte-lib | lib/Sii/Dte.php | Dte.normalizar_impuesto_retenido | private function normalizar_impuesto_retenido(array &$datos)
{
// copiar montos
$montos = [];
foreach ($datos['Detalle'] as &$d) {
if (!empty($d['CodImpAdic'])) {
if (!isset($montos[$d['CodImpAdic']]))
$montos[$d['CodImpAdic']] = 0;
$montos[$d['CodImpAdic']] += $d['MontoItem'];
}
}
// si hay montos y no hay total para impuesto retenido se arma
if (!empty($montos)) {
if (!is_array($datos['Encabezado']['Totales']['ImptoReten'])) {
$datos['Encabezado']['Totales']['ImptoReten'] = [];
} else if (!isset($datos['Encabezado']['Totales']['ImptoReten'][0])) {
$datos['Encabezado']['Totales']['ImptoReten'] = [$datos['Encabezado']['Totales']['ImptoReten']];
}
}
// armar impuesto adicional o retención en los totales
foreach ($montos as $codigo => $neto) {
// buscar si existe el impuesto en los totales
$i = 0;
foreach ($datos['Encabezado']['Totales']['ImptoReten'] as &$ImptoReten) {
if ($ImptoReten['TipoImp']==$codigo) {
break;
}
$i++;
}
// si no existe se crea
if (!isset($datos['Encabezado']['Totales']['ImptoReten'][$i])) {
$datos['Encabezado']['Totales']['ImptoReten'][] = [
'TipoImp' => $codigo
];
}
// se normaliza
$datos['Encabezado']['Totales']['ImptoReten'][$i] = array_merge([
'TipoImp' => $codigo,
'TasaImp' => ImpuestosAdicionales::getTasa($codigo),
'MontoImp' => null,
], $datos['Encabezado']['Totales']['ImptoReten'][$i]);
// si el monto no existe se asigna
if ($datos['Encabezado']['Totales']['ImptoReten'][$i]['MontoImp']===null) {
$datos['Encabezado']['Totales']['ImptoReten'][$i]['MontoImp'] = round(
$neto * $datos['Encabezado']['Totales']['ImptoReten'][$i]['TasaImp']/100
);
}
}
// quitar los codigos que no existen en el detalle
if (isset($datos['Encabezado']['Totales']['ImptoReten']) and is_array($datos['Encabezado']['Totales']['ImptoReten'])) {
$codigos = array_keys($montos);
$n_impuestos = count($datos['Encabezado']['Totales']['ImptoReten']);
for ($i=0; $i<$n_impuestos; $i++) {
if (!in_array($datos['Encabezado']['Totales']['ImptoReten'][$i]['TipoImp'], $codigos)) {
unset($datos['Encabezado']['Totales']['ImptoReten'][$i]);
}
}
sort($datos['Encabezado']['Totales']['ImptoReten']);
}
} | php | private function normalizar_impuesto_retenido(array &$datos)
{
// copiar montos
$montos = [];
foreach ($datos['Detalle'] as &$d) {
if (!empty($d['CodImpAdic'])) {
if (!isset($montos[$d['CodImpAdic']]))
$montos[$d['CodImpAdic']] = 0;
$montos[$d['CodImpAdic']] += $d['MontoItem'];
}
}
// si hay montos y no hay total para impuesto retenido se arma
if (!empty($montos)) {
if (!is_array($datos['Encabezado']['Totales']['ImptoReten'])) {
$datos['Encabezado']['Totales']['ImptoReten'] = [];
} else if (!isset($datos['Encabezado']['Totales']['ImptoReten'][0])) {
$datos['Encabezado']['Totales']['ImptoReten'] = [$datos['Encabezado']['Totales']['ImptoReten']];
}
}
// armar impuesto adicional o retención en los totales
foreach ($montos as $codigo => $neto) {
// buscar si existe el impuesto en los totales
$i = 0;
foreach ($datos['Encabezado']['Totales']['ImptoReten'] as &$ImptoReten) {
if ($ImptoReten['TipoImp']==$codigo) {
break;
}
$i++;
}
// si no existe se crea
if (!isset($datos['Encabezado']['Totales']['ImptoReten'][$i])) {
$datos['Encabezado']['Totales']['ImptoReten'][] = [
'TipoImp' => $codigo
];
}
// se normaliza
$datos['Encabezado']['Totales']['ImptoReten'][$i] = array_merge([
'TipoImp' => $codigo,
'TasaImp' => ImpuestosAdicionales::getTasa($codigo),
'MontoImp' => null,
], $datos['Encabezado']['Totales']['ImptoReten'][$i]);
// si el monto no existe se asigna
if ($datos['Encabezado']['Totales']['ImptoReten'][$i]['MontoImp']===null) {
$datos['Encabezado']['Totales']['ImptoReten'][$i]['MontoImp'] = round(
$neto * $datos['Encabezado']['Totales']['ImptoReten'][$i]['TasaImp']/100
);
}
}
// quitar los codigos que no existen en el detalle
if (isset($datos['Encabezado']['Totales']['ImptoReten']) and is_array($datos['Encabezado']['Totales']['ImptoReten'])) {
$codigos = array_keys($montos);
$n_impuestos = count($datos['Encabezado']['Totales']['ImptoReten']);
for ($i=0; $i<$n_impuestos; $i++) {
if (!in_array($datos['Encabezado']['Totales']['ImptoReten'][$i]['TipoImp'], $codigos)) {
unset($datos['Encabezado']['Totales']['ImptoReten'][$i]);
}
}
sort($datos['Encabezado']['Totales']['ImptoReten']);
}
} | [
"private",
"function",
"normalizar_impuesto_retenido",
"(",
"array",
"&",
"$",
"datos",
")",
"{",
"// copiar montos",
"$",
"montos",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"datos",
"[",
"'Detalle'",
"]",
"as",
"&",
"$",
"d",
")",
"{",
"if",
"(",
"!",... | Método que calcula los montos de impuestos adicionales o retenciones
@param datos Arreglo con los datos del documento que se desean normalizar
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2016-04-05 | [
"Método",
"que",
"calcula",
"los",
"montos",
"de",
"impuestos",
"adicionales",
"o",
"retenciones"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Dte.php#L1552-L1611 |
LibreDTE/libredte-lib | lib/Sii/Dte.php | Dte.normalizar_agregar_IVA_MntTotal | private function normalizar_agregar_IVA_MntTotal(array &$datos)
{
// agregar IVA y monto total
if (!empty($datos['Encabezado']['Totales']['MntNeto'])) {
if ($datos['Encabezado']['IdDoc']['MntBruto']==1) {
list($datos['Encabezado']['Totales']['MntNeto'], $datos['Encabezado']['Totales']['IVA']) = $this->calcularNetoIVA(
$datos['Encabezado']['Totales']['MntNeto'],
$datos['Encabezado']['Totales']['TasaIVA']
);
} else {
if (empty($datos['Encabezado']['Totales']['IVA']) and !empty($datos['Encabezado']['Totales']['TasaIVA'])) {
$datos['Encabezado']['Totales']['IVA'] = round(
$datos['Encabezado']['Totales']['MntNeto']*($datos['Encabezado']['Totales']['TasaIVA']/100)
);
}
}
if (empty($datos['Encabezado']['Totales']['MntTotal'])) {
$datos['Encabezado']['Totales']['MntTotal'] = $datos['Encabezado']['Totales']['MntNeto'];
if (!empty($datos['Encabezado']['Totales']['IVA']))
$datos['Encabezado']['Totales']['MntTotal'] += $datos['Encabezado']['Totales']['IVA'];
if (!empty($datos['Encabezado']['Totales']['MntExe']))
$datos['Encabezado']['Totales']['MntTotal'] += $datos['Encabezado']['Totales']['MntExe'];
}
} else {
if (!$datos['Encabezado']['Totales']['MntTotal'] and !empty($datos['Encabezado']['Totales']['MntExe'])) {
$datos['Encabezado']['Totales']['MntTotal'] = $datos['Encabezado']['Totales']['MntExe'];
}
}
// si hay impuesto retenido o adicional se contabiliza en el total
if (!empty($datos['Encabezado']['Totales']['ImptoReten'])) {
foreach ($datos['Encabezado']['Totales']['ImptoReten'] as &$ImptoReten) {
// si es retención se resta al total y se traspasaa IVA no retenido
// en caso que corresponda
if (ImpuestosAdicionales::getTipo($ImptoReten['TipoImp'])=='R') {
$datos['Encabezado']['Totales']['MntTotal'] -= $ImptoReten['MontoImp'];
if ($ImptoReten['MontoImp']!=$datos['Encabezado']['Totales']['IVA']) {
$datos['Encabezado']['Totales']['IVANoRet'] = $datos['Encabezado']['Totales']['IVA'] - $ImptoReten['MontoImp'];
}
}
// si es adicional se suma al total
else if (ImpuestosAdicionales::getTipo($ImptoReten['TipoImp'])=='A' and isset($ImptoReten['MontoImp'])) {
$datos['Encabezado']['Totales']['MntTotal'] += $ImptoReten['MontoImp'];
}
}
}
// si hay impuesto de crédito a constructoras del 65% se descuenta del total
if (!empty($datos['Encabezado']['Totales']['CredEC'])) {
if ($datos['Encabezado']['Totales']['CredEC']===true)
$datos['Encabezado']['Totales']['CredEC'] = round($datos['Encabezado']['Totales']['IVA'] * 0.65); // TODO: mover a constante o método
$datos['Encabezado']['Totales']['MntTotal'] -= $datos['Encabezado']['Totales']['CredEC'];
}
} | php | private function normalizar_agregar_IVA_MntTotal(array &$datos)
{
// agregar IVA y monto total
if (!empty($datos['Encabezado']['Totales']['MntNeto'])) {
if ($datos['Encabezado']['IdDoc']['MntBruto']==1) {
list($datos['Encabezado']['Totales']['MntNeto'], $datos['Encabezado']['Totales']['IVA']) = $this->calcularNetoIVA(
$datos['Encabezado']['Totales']['MntNeto'],
$datos['Encabezado']['Totales']['TasaIVA']
);
} else {
if (empty($datos['Encabezado']['Totales']['IVA']) and !empty($datos['Encabezado']['Totales']['TasaIVA'])) {
$datos['Encabezado']['Totales']['IVA'] = round(
$datos['Encabezado']['Totales']['MntNeto']*($datos['Encabezado']['Totales']['TasaIVA']/100)
);
}
}
if (empty($datos['Encabezado']['Totales']['MntTotal'])) {
$datos['Encabezado']['Totales']['MntTotal'] = $datos['Encabezado']['Totales']['MntNeto'];
if (!empty($datos['Encabezado']['Totales']['IVA']))
$datos['Encabezado']['Totales']['MntTotal'] += $datos['Encabezado']['Totales']['IVA'];
if (!empty($datos['Encabezado']['Totales']['MntExe']))
$datos['Encabezado']['Totales']['MntTotal'] += $datos['Encabezado']['Totales']['MntExe'];
}
} else {
if (!$datos['Encabezado']['Totales']['MntTotal'] and !empty($datos['Encabezado']['Totales']['MntExe'])) {
$datos['Encabezado']['Totales']['MntTotal'] = $datos['Encabezado']['Totales']['MntExe'];
}
}
// si hay impuesto retenido o adicional se contabiliza en el total
if (!empty($datos['Encabezado']['Totales']['ImptoReten'])) {
foreach ($datos['Encabezado']['Totales']['ImptoReten'] as &$ImptoReten) {
// si es retención se resta al total y se traspasaa IVA no retenido
// en caso que corresponda
if (ImpuestosAdicionales::getTipo($ImptoReten['TipoImp'])=='R') {
$datos['Encabezado']['Totales']['MntTotal'] -= $ImptoReten['MontoImp'];
if ($ImptoReten['MontoImp']!=$datos['Encabezado']['Totales']['IVA']) {
$datos['Encabezado']['Totales']['IVANoRet'] = $datos['Encabezado']['Totales']['IVA'] - $ImptoReten['MontoImp'];
}
}
// si es adicional se suma al total
else if (ImpuestosAdicionales::getTipo($ImptoReten['TipoImp'])=='A' and isset($ImptoReten['MontoImp'])) {
$datos['Encabezado']['Totales']['MntTotal'] += $ImptoReten['MontoImp'];
}
}
}
// si hay impuesto de crédito a constructoras del 65% se descuenta del total
if (!empty($datos['Encabezado']['Totales']['CredEC'])) {
if ($datos['Encabezado']['Totales']['CredEC']===true)
$datos['Encabezado']['Totales']['CredEC'] = round($datos['Encabezado']['Totales']['IVA'] * 0.65); // TODO: mover a constante o método
$datos['Encabezado']['Totales']['MntTotal'] -= $datos['Encabezado']['Totales']['CredEC'];
}
} | [
"private",
"function",
"normalizar_agregar_IVA_MntTotal",
"(",
"array",
"&",
"$",
"datos",
")",
"{",
"// agregar IVA y monto total",
"if",
"(",
"!",
"empty",
"(",
"$",
"datos",
"[",
"'Encabezado'",
"]",
"[",
"'Totales'",
"]",
"[",
"'MntNeto'",
"]",
")",
")",
... | Método que calcula el monto del IVA y el monto total del documento a
partir del monto neto y la tasa de IVA si es que existe
@param datos Arreglo con los datos del documento que se desean normalizar
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2016-04-05 | [
"Método",
"que",
"calcula",
"el",
"monto",
"del",
"IVA",
"y",
"el",
"monto",
"total",
"del",
"documento",
"a",
"partir",
"del",
"monto",
"neto",
"y",
"la",
"tasa",
"de",
"IVA",
"si",
"es",
"que",
"existe"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Dte.php#L1620-L1671 |
LibreDTE/libredte-lib | lib/Sii/Dte.php | Dte.normalizar_transporte | private function normalizar_transporte(array &$datos)
{
if (!empty($datos['Encabezado']['Transporte'])) {
$datos['Encabezado']['Transporte'] = array_merge([
'Patente' => false,
'RUTTrans' => false,
'Chofer' => false,
'DirDest' => false,
'CmnaDest' => false,
'CiudadDest' => false,
'Aduana' => false,
], $datos['Encabezado']['Transporte']);
}
} | php | private function normalizar_transporte(array &$datos)
{
if (!empty($datos['Encabezado']['Transporte'])) {
$datos['Encabezado']['Transporte'] = array_merge([
'Patente' => false,
'RUTTrans' => false,
'Chofer' => false,
'DirDest' => false,
'CmnaDest' => false,
'CiudadDest' => false,
'Aduana' => false,
], $datos['Encabezado']['Transporte']);
}
} | [
"private",
"function",
"normalizar_transporte",
"(",
"array",
"&",
"$",
"datos",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"datos",
"[",
"'Encabezado'",
"]",
"[",
"'Transporte'",
"]",
")",
")",
"{",
"$",
"datos",
"[",
"'Encabezado'",
"]",
"[",
"'Tra... | Método que normaliza los datos de transporte
@param datos Arreglo con los datos del documento que se desean normalizar
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2017-09-01 | [
"Método",
"que",
"normaliza",
"los",
"datos",
"de",
"transporte"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Dte.php#L1679-L1692 |
LibreDTE/libredte-lib | lib/Sii/Dte.php | Dte.normalizar_boletas | private function normalizar_boletas(array &$datos)
{
// cambiar tags de DTE a boleta si se pasaron
if ($datos['Encabezado']['Emisor']['RznSoc']) {
$datos['Encabezado']['Emisor']['RznSocEmisor'] = $datos['Encabezado']['Emisor']['RznSoc'];
$datos['Encabezado']['Emisor']['RznSoc'] = false;
}
if ($datos['Encabezado']['Emisor']['GiroEmis']) {
$datos['Encabezado']['Emisor']['GiroEmisor'] = $datos['Encabezado']['Emisor']['GiroEmis'];
$datos['Encabezado']['Emisor']['GiroEmis'] = false;
}
$datos['Encabezado']['Emisor']['Acteco'] = false;
$datos['Encabezado']['Emisor']['Telefono'] = false;
$datos['Encabezado']['Emisor']['CorreoEmisor'] = false;
$datos['Encabezado']['Emisor']['CdgVendedor'] = false;
$datos['Encabezado']['Receptor']['GiroRecep'] = false;
if (!empty($datos['Encabezado']['Receptor']['CorreoRecep'])) {
$datos['Referencia'][] = [
'NroLinRef' => !empty($datos['Referencia']) ? (count($datos['Referencia'])+1) : 1,
'RazonRef' => mb_substr('Email receptor: '.$datos['Encabezado']['Receptor']['CorreoRecep'], 0, 90),
];
}
$datos['Encabezado']['Receptor']['CorreoRecep'] = false;
// quitar otros tags que no son parte de las boletas
$datos['Encabezado']['IdDoc']['FmaPago'] = false;
$datos['Encabezado']['IdDoc']['FchCancel'] = false;
$datos['Encabezado']['IdDoc']['MedioPago'] = false;
$datos['Encabezado']['IdDoc']['TpoCtaPago'] = false;
$datos['Encabezado']['IdDoc']['NumCtaPago'] = false;
$datos['Encabezado']['IdDoc']['BcoPago'] = false;
$datos['Encabezado']['IdDoc']['TermPagoGlosa'] = false;
$datos['Encabezado']['RUTSolicita'] = false;
$datos['Encabezado']['IdDoc']['TpoTranCompra'] = false;
$datos['Encabezado']['IdDoc']['TpoTranVenta'] = false;
// si es boleta no nominativa se deja sólo el RUT en el campo del receptor
/*if ($datos['Encabezado']['Receptor']['RUTRecep']=='66666666-6') {
$datos['Encabezado']['Receptor'] = ['RUTRecep'=>'66666666-6'];
}*/
// ajustar las referencias si existen
if (!empty($datos['Referencia'])) {
if (!isset($datos['Referencia'][0])) {
$datos['Referencia'] = [$datos['Referencia']];
}
foreach ($datos['Referencia'] as &$r) {
foreach (['TpoDocRef', 'FolioRef', 'FchRef'] as $c) {
if (isset($r[$c])) {
unset($r[$c]);
}
}
}
}
} | php | private function normalizar_boletas(array &$datos)
{
// cambiar tags de DTE a boleta si se pasaron
if ($datos['Encabezado']['Emisor']['RznSoc']) {
$datos['Encabezado']['Emisor']['RznSocEmisor'] = $datos['Encabezado']['Emisor']['RznSoc'];
$datos['Encabezado']['Emisor']['RznSoc'] = false;
}
if ($datos['Encabezado']['Emisor']['GiroEmis']) {
$datos['Encabezado']['Emisor']['GiroEmisor'] = $datos['Encabezado']['Emisor']['GiroEmis'];
$datos['Encabezado']['Emisor']['GiroEmis'] = false;
}
$datos['Encabezado']['Emisor']['Acteco'] = false;
$datos['Encabezado']['Emisor']['Telefono'] = false;
$datos['Encabezado']['Emisor']['CorreoEmisor'] = false;
$datos['Encabezado']['Emisor']['CdgVendedor'] = false;
$datos['Encabezado']['Receptor']['GiroRecep'] = false;
if (!empty($datos['Encabezado']['Receptor']['CorreoRecep'])) {
$datos['Referencia'][] = [
'NroLinRef' => !empty($datos['Referencia']) ? (count($datos['Referencia'])+1) : 1,
'RazonRef' => mb_substr('Email receptor: '.$datos['Encabezado']['Receptor']['CorreoRecep'], 0, 90),
];
}
$datos['Encabezado']['Receptor']['CorreoRecep'] = false;
// quitar otros tags que no son parte de las boletas
$datos['Encabezado']['IdDoc']['FmaPago'] = false;
$datos['Encabezado']['IdDoc']['FchCancel'] = false;
$datos['Encabezado']['IdDoc']['MedioPago'] = false;
$datos['Encabezado']['IdDoc']['TpoCtaPago'] = false;
$datos['Encabezado']['IdDoc']['NumCtaPago'] = false;
$datos['Encabezado']['IdDoc']['BcoPago'] = false;
$datos['Encabezado']['IdDoc']['TermPagoGlosa'] = false;
$datos['Encabezado']['RUTSolicita'] = false;
$datos['Encabezado']['IdDoc']['TpoTranCompra'] = false;
$datos['Encabezado']['IdDoc']['TpoTranVenta'] = false;
// si es boleta no nominativa se deja sólo el RUT en el campo del receptor
/*if ($datos['Encabezado']['Receptor']['RUTRecep']=='66666666-6') {
$datos['Encabezado']['Receptor'] = ['RUTRecep'=>'66666666-6'];
}*/
// ajustar las referencias si existen
if (!empty($datos['Referencia'])) {
if (!isset($datos['Referencia'][0])) {
$datos['Referencia'] = [$datos['Referencia']];
}
foreach ($datos['Referencia'] as &$r) {
foreach (['TpoDocRef', 'FolioRef', 'FchRef'] as $c) {
if (isset($r[$c])) {
unset($r[$c]);
}
}
}
}
} | [
"private",
"function",
"normalizar_boletas",
"(",
"array",
"&",
"$",
"datos",
")",
"{",
"// cambiar tags de DTE a boleta si se pasaron",
"if",
"(",
"$",
"datos",
"[",
"'Encabezado'",
"]",
"[",
"'Emisor'",
"]",
"[",
"'RznSoc'",
"]",
")",
"{",
"$",
"datos",
"[",... | Método que normaliza las boletas electrónicas, dte 39 y 41
@param datos Arreglo con los datos del documento que se desean normalizar
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2018-06-15 | [
"Método",
"que",
"normaliza",
"las",
"boletas",
"electrónicas",
"dte",
"39",
"y",
"41"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Dte.php#L1700-L1751 |
LibreDTE/libredte-lib | lib/Sii/Dte.php | Dte.round | private function round($valor, $moneda = false, $decimal = 4)
{
return (!$moneda or $moneda=='PESO CL') ? (int)round($valor) : (float)round($valor, $decimal);
} | php | private function round($valor, $moneda = false, $decimal = 4)
{
return (!$moneda or $moneda=='PESO CL') ? (int)round($valor) : (float)round($valor, $decimal);
} | [
"private",
"function",
"round",
"(",
"$",
"valor",
",",
"$",
"moneda",
"=",
"false",
",",
"$",
"decimal",
"=",
"4",
")",
"{",
"return",
"(",
"!",
"$",
"moneda",
"or",
"$",
"moneda",
"==",
"'PESO CL'",
")",
"?",
"(",
"int",
")",
"round",
"(",
"$",... | Método que redondea valores. Si los montos son en pesos chilenos se
redondea, si no se mantienen todos los decimales
@param valor Valor que se desea redondear
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2016-04-05 | [
"Método",
"que",
"redondea",
"valores",
".",
"Si",
"los",
"montos",
"son",
"en",
"pesos",
"chilenos",
"se",
"redondea",
"si",
"no",
"se",
"mantienen",
"todos",
"los",
"decimales"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Dte.php#L1760-L1763 |
LibreDTE/libredte-lib | lib/Sii/Dte.php | Dte.getEstadoValidacion | public function getEstadoValidacion(array $datos = null)
{
/*if (!$this->checkFirma())
return 1;*/
if (is_array($datos)) {
if (isset($datos['RUTEmisor']) and $this->getEmisor()!=$datos['RUTEmisor'])
return 2;
if (isset($datos['RUTRecep']) and $this->getReceptor()!=$datos['RUTRecep'])
return 3;
}
return 0;
} | php | public function getEstadoValidacion(array $datos = null)
{
/*if (!$this->checkFirma())
return 1;*/
if (is_array($datos)) {
if (isset($datos['RUTEmisor']) and $this->getEmisor()!=$datos['RUTEmisor'])
return 2;
if (isset($datos['RUTRecep']) and $this->getReceptor()!=$datos['RUTRecep'])
return 3;
}
return 0;
} | [
"public",
"function",
"getEstadoValidacion",
"(",
"array",
"$",
"datos",
"=",
"null",
")",
"{",
"/*if (!$this->checkFirma())\n return 1;*/",
"if",
"(",
"is_array",
"(",
"$",
"datos",
")",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"datos",
"[",
"'RUTEm... | Método que determina el estado de validación sobre el DTE, se verifica:
- Firma del DTE
- RUT del emisor (si se pasó uno para comparar)
- RUT del receptor (si se pasó uno para comparar)
@return Código del estado de la validación
@warning No se está validando la firma
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2015-09-08 | [
"Método",
"que",
"determina",
"el",
"estado",
"de",
"validación",
"sobre",
"el",
"DTE",
"se",
"verifica",
":",
"-",
"Firma",
"del",
"DTE",
"-",
"RUT",
"del",
"emisor",
"(",
"si",
"se",
"pasó",
"uno",
"para",
"comparar",
")",
"-",
"RUT",
"del",
"recepto... | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Dte.php#L1775-L1786 |
LibreDTE/libredte-lib | lib/Sii/Dte.php | Dte.checkFirma | public function checkFirma()
{
if (!$this->xml)
return null;
// obtener firma
$Signature = $this->xml->documentElement->getElementsByTagName('Signature')->item(0);
// preparar documento a validar
$D = $this->xml->documentElement->getElementsByTagName('Documento')->item(0);
$Documento = new \sasco\LibreDTE\XML();
$Documento->loadXML($D->C14N());
$Documento->documentElement->removeAttributeNS('http://www.w3.org/2001/XMLSchema-instance', 'xsi');
$Documento->documentElement->removeAttributeNS('http://www.sii.cl/SiiDte', '');
$SignedInfo = new \sasco\LibreDTE\XML();
$SignedInfo->loadXML($Signature->getElementsByTagName('SignedInfo')->item(0)->C14N());
$SignedInfo->documentElement->removeAttributeNS('http://www.w3.org/2001/XMLSchema-instance', 'xsi');
$DigestValue = $Signature->getElementsByTagName('DigestValue')->item(0)->nodeValue;
$SignatureValue = $Signature->getElementsByTagName('SignatureValue')->item(0)->nodeValue;
$X509Certificate = $Signature->getElementsByTagName('X509Certificate')->item(0)->nodeValue;
$X509Certificate = '-----BEGIN CERTIFICATE-----'."\n".wordwrap(trim($X509Certificate), 64, "\n", true)."\n".'-----END CERTIFICATE----- ';
$valid = openssl_verify($SignedInfo->C14N(), base64_decode($SignatureValue), $X509Certificate) === 1 ? true : false;
return $valid;
//return $valid and $DigestValue===base64_encode(sha1($Documento->C14N(), true));
} | php | public function checkFirma()
{
if (!$this->xml)
return null;
// obtener firma
$Signature = $this->xml->documentElement->getElementsByTagName('Signature')->item(0);
// preparar documento a validar
$D = $this->xml->documentElement->getElementsByTagName('Documento')->item(0);
$Documento = new \sasco\LibreDTE\XML();
$Documento->loadXML($D->C14N());
$Documento->documentElement->removeAttributeNS('http://www.w3.org/2001/XMLSchema-instance', 'xsi');
$Documento->documentElement->removeAttributeNS('http://www.sii.cl/SiiDte', '');
$SignedInfo = new \sasco\LibreDTE\XML();
$SignedInfo->loadXML($Signature->getElementsByTagName('SignedInfo')->item(0)->C14N());
$SignedInfo->documentElement->removeAttributeNS('http://www.w3.org/2001/XMLSchema-instance', 'xsi');
$DigestValue = $Signature->getElementsByTagName('DigestValue')->item(0)->nodeValue;
$SignatureValue = $Signature->getElementsByTagName('SignatureValue')->item(0)->nodeValue;
$X509Certificate = $Signature->getElementsByTagName('X509Certificate')->item(0)->nodeValue;
$X509Certificate = '-----BEGIN CERTIFICATE-----'."\n".wordwrap(trim($X509Certificate), 64, "\n", true)."\n".'-----END CERTIFICATE----- ';
$valid = openssl_verify($SignedInfo->C14N(), base64_decode($SignatureValue), $X509Certificate) === 1 ? true : false;
return $valid;
//return $valid and $DigestValue===base64_encode(sha1($Documento->C14N(), true));
} | [
"public",
"function",
"checkFirma",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"xml",
")",
"return",
"null",
";",
"// obtener firma",
"$",
"Signature",
"=",
"$",
"this",
"->",
"xml",
"->",
"documentElement",
"->",
"getElementsByTagName",
"(",
"'Sign... | Método que indica si la firma del DTE es o no válida
@return =true si la firma del DTE es válida, =null si no se pudo determinar
@warning No se está verificando el valor del DigestValue del documento (sólo la firma de ese DigestValue)
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2015-09-08 | [
"Método",
"que",
"indica",
"si",
"la",
"firma",
"del",
"DTE",
"es",
"o",
"no",
"válida"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Dte.php#L1795-L1817 |
LibreDTE/libredte-lib | lib/Sii/Dte.php | Dte.verificarDatos | public function verificarDatos()
{
if (class_exists('\sasco\LibreDTE\Sii\Dte\VerificadorDatos')) {
if (!\sasco\LibreDTE\Sii\Dte\VerificadorDatos::check($this->getDatos())) {
return false;
}
}
return true;
} | php | public function verificarDatos()
{
if (class_exists('\sasco\LibreDTE\Sii\Dte\VerificadorDatos')) {
if (!\sasco\LibreDTE\Sii\Dte\VerificadorDatos::check($this->getDatos())) {
return false;
}
}
return true;
} | [
"public",
"function",
"verificarDatos",
"(",
")",
"{",
"if",
"(",
"class_exists",
"(",
"'\\sasco\\LibreDTE\\Sii\\Dte\\VerificadorDatos'",
")",
")",
"{",
"if",
"(",
"!",
"\\",
"sasco",
"\\",
"LibreDTE",
"\\",
"Sii",
"\\",
"Dte",
"\\",
"VerificadorDatos",
"::",
... | Método que valida los datos del DTE
@return =true si no hay errores de validación, =false si se encontraron errores al validar
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2018-11-04 | [
"Método",
"que",
"valida",
"los",
"datos",
"del",
"DTE"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Dte.php#L1869-L1877 |
LibreDTE/libredte-lib | lib/Sii/Dte.php | Dte.getEstado | public function getEstado(\sasco\LibreDTE\FirmaElectronica $Firma)
{
// solicitar token
$token = \sasco\LibreDTE\Sii\Autenticacion::getToken($Firma);
if (!$token)
return false;
// consultar estado dte
$run = $Firma->getID();
if ($run===false)
return false;
list($RutConsultante, $DvConsultante) = explode('-', $run);
list($RutCompania, $DvCompania) = explode('-', $this->getEmisor());
list($RutReceptor, $DvReceptor) = explode('-', $this->getReceptor());
list($Y, $m, $d) = explode('-', $this->getFechaEmision());
$xml = \sasco\LibreDTE\Sii::request('QueryEstDte', 'getEstDte', [
'RutConsultante' => $RutConsultante,
'DvConsultante' => $DvConsultante,
'RutCompania' => $RutCompania,
'DvCompania' => $DvCompania,
'RutReceptor' => $RutReceptor,
'DvReceptor' => $DvReceptor,
'TipoDte' => $this->getTipo(),
'FolioDte' => $this->getFolio(),
'FechaEmisionDte' => $d.$m.$Y,
'MontoDte' => $this->getMontoTotal(),
'token' => $token,
]);
// si el estado se pudo recuperar se muestra
if ($xml===false)
return false;
// entregar estado
return (array)$xml->xpath('/SII:RESPUESTA/SII:RESP_HDR')[0];
} | php | public function getEstado(\sasco\LibreDTE\FirmaElectronica $Firma)
{
// solicitar token
$token = \sasco\LibreDTE\Sii\Autenticacion::getToken($Firma);
if (!$token)
return false;
// consultar estado dte
$run = $Firma->getID();
if ($run===false)
return false;
list($RutConsultante, $DvConsultante) = explode('-', $run);
list($RutCompania, $DvCompania) = explode('-', $this->getEmisor());
list($RutReceptor, $DvReceptor) = explode('-', $this->getReceptor());
list($Y, $m, $d) = explode('-', $this->getFechaEmision());
$xml = \sasco\LibreDTE\Sii::request('QueryEstDte', 'getEstDte', [
'RutConsultante' => $RutConsultante,
'DvConsultante' => $DvConsultante,
'RutCompania' => $RutCompania,
'DvCompania' => $DvCompania,
'RutReceptor' => $RutReceptor,
'DvReceptor' => $DvReceptor,
'TipoDte' => $this->getTipo(),
'FolioDte' => $this->getFolio(),
'FechaEmisionDte' => $d.$m.$Y,
'MontoDte' => $this->getMontoTotal(),
'token' => $token,
]);
// si el estado se pudo recuperar se muestra
if ($xml===false)
return false;
// entregar estado
return (array)$xml->xpath('/SII:RESPUESTA/SII:RESP_HDR')[0];
} | [
"public",
"function",
"getEstado",
"(",
"\\",
"sasco",
"\\",
"LibreDTE",
"\\",
"FirmaElectronica",
"$",
"Firma",
")",
"{",
"// solicitar token",
"$",
"token",
"=",
"\\",
"sasco",
"\\",
"LibreDTE",
"\\",
"Sii",
"\\",
"Autenticacion",
"::",
"getToken",
"(",
"$... | Método que obtiene el estado del DTE
@param Firma objeto que representa la Firma Electrónca
@return Arreglo con el estado del DTE
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2015-10-24 | [
"Método",
"que",
"obtiene",
"el",
"estado",
"del",
"DTE"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Dte.php#L1886-L1918 |
LibreDTE/libredte-lib | lib/Sii/Dte.php | Dte.getEstadoAvanzado | public function getEstadoAvanzado(\sasco\LibreDTE\FirmaElectronica $Firma)
{
// solicitar token
$token = \sasco\LibreDTE\Sii\Autenticacion::getToken($Firma);
if (!$token)
return false;
// consultar estado dte
list($RutEmpresa, $DvEmpresa) = explode('-', $this->getEmisor());
list($RutReceptor, $DvReceptor) = explode('-', $this->getReceptor());
list($Y, $m, $d) = explode('-', $this->getFechaEmision());
$xml = \sasco\LibreDTE\Sii::request('QueryEstDteAv', 'getEstDteAv', [
'RutEmpresa' => $RutEmpresa,
'DvEmpresa' => $DvEmpresa,
'RutReceptor' => $RutReceptor,
'DvReceptor' => $DvReceptor,
'TipoDte' => $this->getTipo(),
'FolioDte' => $this->getFolio(),
'FechaEmisionDte' => $d.'-'.$m.'-'.$Y,
'MontoDte' => $this->getMontoTotal(),
'FirmaDte' => str_replace("\n", '', $this->getFirma()['SignatureValue']),
'token' => $token,
]);
// si el estado se pudo recuperar se muestra
if ($xml===false)
return false;
// entregar estado
return (array)$xml->xpath('/SII:RESPUESTA/SII:RESP_BODY')[0];
} | php | public function getEstadoAvanzado(\sasco\LibreDTE\FirmaElectronica $Firma)
{
// solicitar token
$token = \sasco\LibreDTE\Sii\Autenticacion::getToken($Firma);
if (!$token)
return false;
// consultar estado dte
list($RutEmpresa, $DvEmpresa) = explode('-', $this->getEmisor());
list($RutReceptor, $DvReceptor) = explode('-', $this->getReceptor());
list($Y, $m, $d) = explode('-', $this->getFechaEmision());
$xml = \sasco\LibreDTE\Sii::request('QueryEstDteAv', 'getEstDteAv', [
'RutEmpresa' => $RutEmpresa,
'DvEmpresa' => $DvEmpresa,
'RutReceptor' => $RutReceptor,
'DvReceptor' => $DvReceptor,
'TipoDte' => $this->getTipo(),
'FolioDte' => $this->getFolio(),
'FechaEmisionDte' => $d.'-'.$m.'-'.$Y,
'MontoDte' => $this->getMontoTotal(),
'FirmaDte' => str_replace("\n", '', $this->getFirma()['SignatureValue']),
'token' => $token,
]);
// si el estado se pudo recuperar se muestra
if ($xml===false)
return false;
// entregar estado
return (array)$xml->xpath('/SII:RESPUESTA/SII:RESP_BODY')[0];
} | [
"public",
"function",
"getEstadoAvanzado",
"(",
"\\",
"sasco",
"\\",
"LibreDTE",
"\\",
"FirmaElectronica",
"$",
"Firma",
")",
"{",
"// solicitar token",
"$",
"token",
"=",
"\\",
"sasco",
"\\",
"LibreDTE",
"\\",
"Sii",
"\\",
"Autenticacion",
"::",
"getToken",
"... | Método que obtiene el estado avanzado del DTE
@param Firma objeto que representa la Firma Electrónca
@return Arreglo con el estado del DTE
@todo Corregir warning y también definir que se retornará (sobre todo en caso de error)
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2016-08-05 | [
"Método",
"que",
"obtiene",
"el",
"estado",
"avanzado",
"del",
"DTE"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Dte.php#L1928-L1955 |
LibreDTE/libredte-lib | lib/Sii/Dte.php | Dte.getUltimaAccionRCV | public function getUltimaAccionRCV(\sasco\LibreDTE\FirmaElectronica $Firma)
{
list($emisor_rut, $emisor_dv) = explode('-', $this->getEmisor());
$RCV = new \sasco\LibreDTE\Sii\RegistroCompraVenta($Firma);
try {
$eventos = $RCV->listarEventosHistDoc($emisor_rut, $emisor_dv, $this->getTipo(), $this->getFolio());
return $eventos ? $eventos[count($eventos)-1] : null;
} catch (\Exception $e) {
return null;
}
} | php | public function getUltimaAccionRCV(\sasco\LibreDTE\FirmaElectronica $Firma)
{
list($emisor_rut, $emisor_dv) = explode('-', $this->getEmisor());
$RCV = new \sasco\LibreDTE\Sii\RegistroCompraVenta($Firma);
try {
$eventos = $RCV->listarEventosHistDoc($emisor_rut, $emisor_dv, $this->getTipo(), $this->getFolio());
return $eventos ? $eventos[count($eventos)-1] : null;
} catch (\Exception $e) {
return null;
}
} | [
"public",
"function",
"getUltimaAccionRCV",
"(",
"\\",
"sasco",
"\\",
"LibreDTE",
"\\",
"FirmaElectronica",
"$",
"Firma",
")",
"{",
"list",
"(",
"$",
"emisor_rut",
",",
"$",
"emisor_dv",
")",
"=",
"explode",
"(",
"'-'",
",",
"$",
"this",
"->",
"getEmisor",... | Método que entrega la última acción registrada para el DTE en el registro de compra y venta
@return Arreglo con los datos de la última acción
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2017-08-29 | [
"Método",
"que",
"entrega",
"la",
"última",
"acción",
"registrada",
"para",
"el",
"DTE",
"en",
"el",
"registro",
"de",
"compra",
"y",
"venta"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Dte.php#L1963-L1973 |
LibreDTE/libredte-lib | lib/Sii/Dte/Formatos/XML.php | XML.toArray | public static function toArray($data)
{
$XML = new \sasco\LibreDTE\XML();
if (!$XML->loadXML($data)) {
throw new \Exception('Ocurrió un problema al cargar el XML');
}
$datos = $XML->toArray();
if (!isset($datos['DTE'])) {
throw new \Exception('El nodo raíz del string XML debe ser el tag DTE');
}
if (isset($datos['DTE']['Documento']))
$dte = $datos['DTE']['Documento'];
else if (isset($datos['DTE']['Exportaciones']))
$dte = $datos['DTE']['Exportaciones'];
else if (isset($datos['DTE']['Liquidacion']))
$dte = $datos['DTE']['Liquidacion'];
unset($dte['@attributes']);
return $dte;
} | php | public static function toArray($data)
{
$XML = new \sasco\LibreDTE\XML();
if (!$XML->loadXML($data)) {
throw new \Exception('Ocurrió un problema al cargar el XML');
}
$datos = $XML->toArray();
if (!isset($datos['DTE'])) {
throw new \Exception('El nodo raíz del string XML debe ser el tag DTE');
}
if (isset($datos['DTE']['Documento']))
$dte = $datos['DTE']['Documento'];
else if (isset($datos['DTE']['Exportaciones']))
$dte = $datos['DTE']['Exportaciones'];
else if (isset($datos['DTE']['Liquidacion']))
$dte = $datos['DTE']['Liquidacion'];
unset($dte['@attributes']);
return $dte;
} | [
"public",
"static",
"function",
"toArray",
"(",
"$",
"data",
")",
"{",
"$",
"XML",
"=",
"new",
"\\",
"sasco",
"\\",
"LibreDTE",
"\\",
"XML",
"(",
")",
";",
"if",
"(",
"!",
"$",
"XML",
"->",
"loadXML",
"(",
"$",
"data",
")",
")",
"{",
"throw",
"... | Método que recibe los datos y los entrega como un arreglo PHP en el
formato del DTE que usa LibreDTE
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2016-09-12 | [
"Método",
"que",
"recibe",
"los",
"datos",
"y",
"los",
"entrega",
"como",
"un",
"arreglo",
"PHP",
"en",
"el",
"formato",
"del",
"DTE",
"que",
"usa",
"LibreDTE"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Dte/Formatos/XML.php#L40-L58 |
LibreDTE/libredte-lib | lib/Sii/Factoring/Aec.php | Aec.setCaratula | public function setCaratula(array $caratula = [])
{
$this->caratula = array_merge([
'@attributes' => [
'version' => '1.0'
],
'RutCedente' => isset($this->cesiones[0]) ? $this->cesiones[0]->getCedente()['RUT'] : false,
'RutCesionario' => isset($this->cesiones[0]) ? $this->cesiones[0]->getCesionario()['RUT'] : false,
'NmbContacto' => isset($this->cesiones[0]) ? $this->cesiones[0]->getCedente()['RUTAutorizado']['Nombre'] : false,
'FonoContacto' => false,
'MailContacto' => isset($this->cesiones[0]) ? $this->cesiones[0]->getCedente()['eMail'] : false,
'TmstFirmaEnvio' => date('Y-m-d\TH:i:s'),
], $caratula);
} | php | public function setCaratula(array $caratula = [])
{
$this->caratula = array_merge([
'@attributes' => [
'version' => '1.0'
],
'RutCedente' => isset($this->cesiones[0]) ? $this->cesiones[0]->getCedente()['RUT'] : false,
'RutCesionario' => isset($this->cesiones[0]) ? $this->cesiones[0]->getCesionario()['RUT'] : false,
'NmbContacto' => isset($this->cesiones[0]) ? $this->cesiones[0]->getCedente()['RUTAutorizado']['Nombre'] : false,
'FonoContacto' => false,
'MailContacto' => isset($this->cesiones[0]) ? $this->cesiones[0]->getCedente()['eMail'] : false,
'TmstFirmaEnvio' => date('Y-m-d\TH:i:s'),
], $caratula);
} | [
"public",
"function",
"setCaratula",
"(",
"array",
"$",
"caratula",
"=",
"[",
"]",
")",
"{",
"$",
"this",
"->",
"caratula",
"=",
"array_merge",
"(",
"[",
"'@attributes'",
"=>",
"[",
"'version'",
"=>",
"'1.0'",
"]",
",",
"'RutCedente'",
"=>",
"isset",
"("... | Método para asignar la carátula. Opcional, si no se usa se sacan los datos
del documento de Cesion
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2016-12-10 | [
"Método",
"para",
"asignar",
"la",
"carátula",
".",
"Opcional",
"si",
"no",
"se",
"usa",
"se",
"sacan",
"los",
"datos",
"del",
"documento",
"de",
"Cesion"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Factoring/Aec.php#L66-L79 |
LibreDTE/libredte-lib | lib/Sii/Factoring/Aec.php | Aec.generar | public function generar()
{
if (!isset($this->cedido) or !isset($this->cesiones[0]))
return false;
if (!isset($this->caratula))
$this->setCaratula();
// genear XML del envío
$xmlEnvio = (new \sasco\LibreDTE\XML())->generate([
'AEC' => [
'@attributes' => [
'xmlns' => 'http://www.sii.cl/SiiDte',
'xmlns:xsi' => 'http://www.w3.org/2001/XMLSchema-instance',
'xsi:schemaLocation' => 'http://www.sii.cl/SiiDte AEC_v10.xsd',
'version' => '1.0'
],
'DocumentoAEC' => [
'@attributes' => [
'ID' => 'LibreDTE_AEC'
],
'Caratula' => $this->caratula,
'Cesiones' => [
'DTECedido' => null,
'Cesion' => null,
]
]
]
])->saveXML();
// agregar XML de DTE cedido y cesión
$cedido_xml = trim(str_replace(['<?xml version="1.0" encoding="ISO-8859-1"?>', '<?xml version="1.0"?>'], '', $this->cedido->saveXML()));
$cesion_xml = '';
foreach ($this->cesiones as $cesion) {
$cesion_xml .= trim(str_replace(['<?xml version="1.0" encoding="ISO-8859-1"?>', '<?xml version="1.0"?>'], '', $cesion->saveXML()))."\n";
}
$xmlEnvio = str_replace(
['<DTECedido/>', '<Cesion/>'],
[$cedido_xml, $cesion_xml],
$xmlEnvio
);
// firmar XML del envío y entregar
$this->xml_data = $this->Firma->signXML($xmlEnvio, '#LibreDTE_AEC', 'DocumentoAEC', true);
return $this->xml_data;
} | php | public function generar()
{
if (!isset($this->cedido) or !isset($this->cesiones[0]))
return false;
if (!isset($this->caratula))
$this->setCaratula();
// genear XML del envío
$xmlEnvio = (new \sasco\LibreDTE\XML())->generate([
'AEC' => [
'@attributes' => [
'xmlns' => 'http://www.sii.cl/SiiDte',
'xmlns:xsi' => 'http://www.w3.org/2001/XMLSchema-instance',
'xsi:schemaLocation' => 'http://www.sii.cl/SiiDte AEC_v10.xsd',
'version' => '1.0'
],
'DocumentoAEC' => [
'@attributes' => [
'ID' => 'LibreDTE_AEC'
],
'Caratula' => $this->caratula,
'Cesiones' => [
'DTECedido' => null,
'Cesion' => null,
]
]
]
])->saveXML();
// agregar XML de DTE cedido y cesión
$cedido_xml = trim(str_replace(['<?xml version="1.0" encoding="ISO-8859-1"?>', '<?xml version="1.0"?>'], '', $this->cedido->saveXML()));
$cesion_xml = '';
foreach ($this->cesiones as $cesion) {
$cesion_xml .= trim(str_replace(['<?xml version="1.0" encoding="ISO-8859-1"?>', '<?xml version="1.0"?>'], '', $cesion->saveXML()))."\n";
}
$xmlEnvio = str_replace(
['<DTECedido/>', '<Cesion/>'],
[$cedido_xml, $cesion_xml],
$xmlEnvio
);
// firmar XML del envío y entregar
$this->xml_data = $this->Firma->signXML($xmlEnvio, '#LibreDTE_AEC', 'DocumentoAEC', true);
return $this->xml_data;
} | [
"public",
"function",
"generar",
"(",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"cedido",
")",
"or",
"!",
"isset",
"(",
"$",
"this",
"->",
"cesiones",
"[",
"0",
"]",
")",
")",
"return",
"false",
";",
"if",
"(",
"!",
"isset",
"(... | Método que genera el XML del AEC
@return XML AEC con DTE y Cesion
@author Adonias Vasquez (adonias.vasquez[at]epys.cl)
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2016-12-10 | [
"Método",
"que",
"genera",
"el",
"XML",
"del",
"AEC"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Factoring/Aec.php#L88-L129 |
LibreDTE/libredte-lib | lib/Sii/Factoring/Aec.php | Aec.enviar | public function enviar()
{
// generar XML que se enviará
if (!$this->xml_data)
$this->xml_data = $this->generar();
if (!$this->xml_data) {
\sasco\LibreDTE\Log::write(
\sasco\LibreDTE\Estado::DOCUMENTO_ERROR_GENERAR_XML,
\sasco\LibreDTE\Estado::get(
\sasco\LibreDTE\Estado::DOCUMENTO_ERROR_GENERAR_XML,
substr(get_class($this), strrpos(get_class($this), '\\')+1)
)
);
return false;
}
// validar schema del documento antes de enviar
if (!$this->schemaValidate())
return false;
// solicitar token
$token = \sasco\LibreDTE\Sii\Autenticacion::getToken($this->Firma);
if (!$token)
return false;
// enviar AEC
$email = $this->caratula['MailContacto'];
$emisor = $this->caratula['RutCedente'];
$result = $this->enviarRTC($email, $emisor, $this->xml_data, $token, 10);
if ($result===false)
return false;
if (!is_numeric((string)$result->TRACKID))
return false;
return (int)(string)$result->TRACKID;
} | php | public function enviar()
{
// generar XML que se enviará
if (!$this->xml_data)
$this->xml_data = $this->generar();
if (!$this->xml_data) {
\sasco\LibreDTE\Log::write(
\sasco\LibreDTE\Estado::DOCUMENTO_ERROR_GENERAR_XML,
\sasco\LibreDTE\Estado::get(
\sasco\LibreDTE\Estado::DOCUMENTO_ERROR_GENERAR_XML,
substr(get_class($this), strrpos(get_class($this), '\\')+1)
)
);
return false;
}
// validar schema del documento antes de enviar
if (!$this->schemaValidate())
return false;
// solicitar token
$token = \sasco\LibreDTE\Sii\Autenticacion::getToken($this->Firma);
if (!$token)
return false;
// enviar AEC
$email = $this->caratula['MailContacto'];
$emisor = $this->caratula['RutCedente'];
$result = $this->enviarRTC($email, $emisor, $this->xml_data, $token, 10);
if ($result===false)
return false;
if (!is_numeric((string)$result->TRACKID))
return false;
return (int)(string)$result->TRACKID;
} | [
"public",
"function",
"enviar",
"(",
")",
"{",
"// generar XML que se enviará",
"if",
"(",
"!",
"$",
"this",
"->",
"xml_data",
")",
"$",
"this",
"->",
"xml_data",
"=",
"$",
"this",
"->",
"generar",
"(",
")",
";",
"if",
"(",
"!",
"$",
"this",
"->",
"x... | Método que realiza el envío del AEC al SII
@return Track ID del envío o =false si hubo algún problema al enviar el documento
@author Adonias Vasquez (adonias.vasquez[at]epys.cl)
@version 2016-12-10 | [
"Método",
"que",
"realiza",
"el",
"envío",
"del",
"AEC",
"al",
"SII"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Factoring/Aec.php#L137-L168 |
LibreDTE/libredte-lib | lib/Sii/Factoring/Aec.php | Aec.enviarRTC | private function enviarRTC($email, $empresa, $dte, $token, $retry = null)
{
// definir datos que se usarán en el envío
list($rutCompany, $dvCompany) = explode('-', str_replace('.', '', $empresa));
if (strpos($dte, '<?xml') === false) {
$dte = '<?xml version="1.0" encoding="ISO-8859-1"?>' . "\n" . $dte;
}
do {
$file = sys_get_temp_dir() . '/aec_' . md5(microtime() . $token . $dte) . '.xml';
} while (file_exists($file));
file_put_contents($file, $dte);
$data = [
'emailNotif' => $email,
'rutCompany' => $rutCompany,
'dvCompany' => $dvCompany,
'archivo' => curl_file_create(
$file,
'application/xml',
basename($file)
),
];
// crear sesión curl con sus opciones
$curl = curl_init();
$header = [
'User-Agent: Mozilla/4.0 (compatible; PROG 1.0; LibreDTE)',
'Referer: https://libredte.cl',
'Cookie: TOKEN='.$token,
];
$url = 'https://'.\sasco\LibreDTE\Sii::getServidor().'.sii.cl/cgi_rtc/RTC/RTCAnotEnvio.cgi';
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
// si no se debe verificar el SSL se asigna opción a curl, además si
// se está en el ambiente de producción y no se verifica SSL se
// generará una entrada en el log
if (!\sasco\LibreDTE\Sii::getVerificarSSL()) {
if (\sasco\LibreDTE\Sii::getAmbiente()==\sasco\LibreDTE\Sii::PRODUCCION) {
\sasco\LibreDTE\Log::write(
\sasco\LibreDTE\Estado::ENVIO_SSL_SIN_VERIFICAR,
\sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::ENVIO_SSL_SIN_VERIFICAR),
LOG_WARNING
);
}
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
}
// enviar XML al SII
for ($i = 0; $i < $retry; $i++) {
$response = curl_exec($curl);
if ($response and $response != 'Error 500')
break;
}
unlink($file);
// verificar respuesta del envío y entregar error en caso que haya uno
if (!$response or $response == 'Error 500') {
if (!$response)
\sasco\LibreDTE\Log::write(\sasco\LibreDTE\Estado::ENVIO_ERROR_CURL, \sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::ENVIO_ERROR_CURL, curl_error($curl)));
if ($response == 'Error 500')
\sasco\LibreDTE\Log::write(\sasco\LibreDTE\Estado::ENVIO_ERROR_500, \sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::ENVIO_ERROR_500));
return false;
}
// cerrar sesión curl
curl_close($curl);
// crear XML con la respuesta y retornar
try {
$xml = new \SimpleXMLElement($response, LIBXML_COMPACT);
} catch (Exception $e) {
\sasco\LibreDTE\Log::write(\sasco\LibreDTE\Estado::ENVIO_ERROR_XML, \sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::ENVIO_ERROR_XML, $e->getMessage()));
return false;
}
/*
* 0 Envío recibido OK.
* 1 Rut usuario autenticado no tiene permiso para enviar en empresa Cedente.
* 2 Error en tamaño del archivo enviado.
* 4 Faltan parámetros de entrada.
* 5 Error de autenticación, TOKEN inválido, no existe o está expirado.
* 6 Empresa no es DTE.
* 9 Error Interno.
* 10 Error Interno
*/
$error = [
1 => 'Rut usuario autenticado no tiene permiso para enviar en empresa Cedente',
2 => 'Error en tamaño del archivo enviado',
4 => 'Faltan parámetros de entrada',
5 => 'Error de autenticación, TOKEN inválido, no existe o está expirado',
6 => 'Empresa no es DTE',
9 => 'Error Interno',
10 => 'Error Interno'
];
if ($xml->STATUS != 0) {
\sasco\LibreDTE\Log::write(
$xml->STATUS,
$error[(int)$xml->STATUS]
);
}
return $xml;
} | php | private function enviarRTC($email, $empresa, $dte, $token, $retry = null)
{
// definir datos que se usarán en el envío
list($rutCompany, $dvCompany) = explode('-', str_replace('.', '', $empresa));
if (strpos($dte, '<?xml') === false) {
$dte = '<?xml version="1.0" encoding="ISO-8859-1"?>' . "\n" . $dte;
}
do {
$file = sys_get_temp_dir() . '/aec_' . md5(microtime() . $token . $dte) . '.xml';
} while (file_exists($file));
file_put_contents($file, $dte);
$data = [
'emailNotif' => $email,
'rutCompany' => $rutCompany,
'dvCompany' => $dvCompany,
'archivo' => curl_file_create(
$file,
'application/xml',
basename($file)
),
];
// crear sesión curl con sus opciones
$curl = curl_init();
$header = [
'User-Agent: Mozilla/4.0 (compatible; PROG 1.0; LibreDTE)',
'Referer: https://libredte.cl',
'Cookie: TOKEN='.$token,
];
$url = 'https://'.\sasco\LibreDTE\Sii::getServidor().'.sii.cl/cgi_rtc/RTC/RTCAnotEnvio.cgi';
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
// si no se debe verificar el SSL se asigna opción a curl, además si
// se está en el ambiente de producción y no se verifica SSL se
// generará una entrada en el log
if (!\sasco\LibreDTE\Sii::getVerificarSSL()) {
if (\sasco\LibreDTE\Sii::getAmbiente()==\sasco\LibreDTE\Sii::PRODUCCION) {
\sasco\LibreDTE\Log::write(
\sasco\LibreDTE\Estado::ENVIO_SSL_SIN_VERIFICAR,
\sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::ENVIO_SSL_SIN_VERIFICAR),
LOG_WARNING
);
}
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
}
// enviar XML al SII
for ($i = 0; $i < $retry; $i++) {
$response = curl_exec($curl);
if ($response and $response != 'Error 500')
break;
}
unlink($file);
// verificar respuesta del envío y entregar error en caso que haya uno
if (!$response or $response == 'Error 500') {
if (!$response)
\sasco\LibreDTE\Log::write(\sasco\LibreDTE\Estado::ENVIO_ERROR_CURL, \sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::ENVIO_ERROR_CURL, curl_error($curl)));
if ($response == 'Error 500')
\sasco\LibreDTE\Log::write(\sasco\LibreDTE\Estado::ENVIO_ERROR_500, \sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::ENVIO_ERROR_500));
return false;
}
// cerrar sesión curl
curl_close($curl);
// crear XML con la respuesta y retornar
try {
$xml = new \SimpleXMLElement($response, LIBXML_COMPACT);
} catch (Exception $e) {
\sasco\LibreDTE\Log::write(\sasco\LibreDTE\Estado::ENVIO_ERROR_XML, \sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::ENVIO_ERROR_XML, $e->getMessage()));
return false;
}
/*
* 0 Envío recibido OK.
* 1 Rut usuario autenticado no tiene permiso para enviar en empresa Cedente.
* 2 Error en tamaño del archivo enviado.
* 4 Faltan parámetros de entrada.
* 5 Error de autenticación, TOKEN inválido, no existe o está expirado.
* 6 Empresa no es DTE.
* 9 Error Interno.
* 10 Error Interno
*/
$error = [
1 => 'Rut usuario autenticado no tiene permiso para enviar en empresa Cedente',
2 => 'Error en tamaño del archivo enviado',
4 => 'Faltan parámetros de entrada',
5 => 'Error de autenticación, TOKEN inválido, no existe o está expirado',
6 => 'Empresa no es DTE',
9 => 'Error Interno',
10 => 'Error Interno'
];
if ($xml->STATUS != 0) {
\sasco\LibreDTE\Log::write(
$xml->STATUS,
$error[(int)$xml->STATUS]
);
}
return $xml;
} | [
"private",
"function",
"enviarRTC",
"(",
"$",
"email",
",",
"$",
"empresa",
",",
"$",
"dte",
",",
"$",
"token",
",",
"$",
"retry",
"=",
"null",
")",
"{",
"// definir datos que se usarán en el envío",
"list",
"(",
"$",
"rutCompany",
",",
"$",
"dvCompany",
"... | Método que realiza el envío de un AEC al SII
Referencia: https://palena.sii.cl/cgi_rtc/RTC/RTCDocum.cgi?2
@param email del usuario que envía el AEC
@param empresa RUT de la empresa emisora del AEC
@param dte Documento XML con el DTE que se desea enviar a SII
@param token Token de autenticación automática ante el SII
@param retry Intentos que se realizarán como máximo para obtener respuesta
@return Respuesta XML desde SII o bien null si no se pudo obtener respuesta
@author Adonias Vasquez (adonias.vasquez[at]epys.cl)
@author Esteban De La Fuente Rubio (esteban[sasco.cl])
@version 2017-05-11 | [
"Método",
"que",
"realiza",
"el",
"envío",
"de",
"un",
"AEC",
"al",
"SII",
"Referencia",
":",
"https",
":",
"//",
"palena",
".",
"sii",
".",
"cl",
"/",
"cgi_rtc",
"/",
"RTC",
"/",
"RTCDocum",
".",
"cgi?2"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Factoring/Aec.php#L183-L280 |
php-http/guzzle6-adapter | src/Promise.php | Promise.wait | public function wait($unwrap = true)
{
$this->promise->wait(false);
if ($unwrap) {
if (self::REJECTED == $this->getState()) {
throw $this->exception;
}
return $this->response;
}
} | php | public function wait($unwrap = true)
{
$this->promise->wait(false);
if ($unwrap) {
if (self::REJECTED == $this->getState()) {
throw $this->exception;
}
return $this->response;
}
} | [
"public",
"function",
"wait",
"(",
"$",
"unwrap",
"=",
"true",
")",
"{",
"$",
"this",
"->",
"promise",
"->",
"wait",
"(",
"false",
")",
";",
"if",
"(",
"$",
"unwrap",
")",
"{",
"if",
"(",
"self",
"::",
"REJECTED",
"==",
"$",
"this",
"->",
"getSta... | {@inheritdoc} | [
"{"
] | train | https://github.com/php-http/guzzle6-adapter/blob/4b491b78e1b24ca941e6ca925f48a63e6a2d9a45/src/Promise.php#L96-L107 |
php-http/guzzle6-adapter | src/Promise.php | Promise.handleException | private function handleException(GuzzleExceptions\GuzzleException $exception, RequestInterface $request)
{
if ($exception instanceof GuzzleExceptions\SeekException) {
return new HttplugException\RequestException($exception->getMessage(), $request, $exception);
}
if ($exception instanceof GuzzleExceptions\ConnectException) {
return new HttplugException\NetworkException($exception->getMessage(), $exception->getRequest(), $exception);
}
if ($exception instanceof GuzzleExceptions\RequestException) {
// Make sure we have a response for the HttpException
if ($exception->hasResponse()) {
return new HttplugException\HttpException(
$exception->getMessage(),
$exception->getRequest(),
$exception->getResponse(),
$exception
);
}
return new HttplugException\RequestException($exception->getMessage(), $exception->getRequest(), $exception);
}
return new HttplugException\TransferException($exception->getMessage(), 0, $exception);
} | php | private function handleException(GuzzleExceptions\GuzzleException $exception, RequestInterface $request)
{
if ($exception instanceof GuzzleExceptions\SeekException) {
return new HttplugException\RequestException($exception->getMessage(), $request, $exception);
}
if ($exception instanceof GuzzleExceptions\ConnectException) {
return new HttplugException\NetworkException($exception->getMessage(), $exception->getRequest(), $exception);
}
if ($exception instanceof GuzzleExceptions\RequestException) {
// Make sure we have a response for the HttpException
if ($exception->hasResponse()) {
return new HttplugException\HttpException(
$exception->getMessage(),
$exception->getRequest(),
$exception->getResponse(),
$exception
);
}
return new HttplugException\RequestException($exception->getMessage(), $exception->getRequest(), $exception);
}
return new HttplugException\TransferException($exception->getMessage(), 0, $exception);
} | [
"private",
"function",
"handleException",
"(",
"GuzzleExceptions",
"\\",
"GuzzleException",
"$",
"exception",
",",
"RequestInterface",
"$",
"request",
")",
"{",
"if",
"(",
"$",
"exception",
"instanceof",
"GuzzleExceptions",
"\\",
"SeekException",
")",
"{",
"return",... | Converts a Guzzle exception into an Httplug exception.
@param GuzzleExceptions\GuzzleException $exception
@param RequestInterface $request
@return HttplugException | [
"Converts",
"a",
"Guzzle",
"exception",
"into",
"an",
"Httplug",
"exception",
"."
] | train | https://github.com/php-http/guzzle6-adapter/blob/4b491b78e1b24ca941e6ca925f48a63e6a2d9a45/src/Promise.php#L117-L142 |
php-http/guzzle6-adapter | src/Client.php | Client.sendAsyncRequest | public function sendAsyncRequest(RequestInterface $request)
{
$promise = $this->client->sendAsync($request);
return new Promise($promise, $request);
} | php | public function sendAsyncRequest(RequestInterface $request)
{
$promise = $this->client->sendAsync($request);
return new Promise($promise, $request);
} | [
"public",
"function",
"sendAsyncRequest",
"(",
"RequestInterface",
"$",
"request",
")",
"{",
"$",
"promise",
"=",
"$",
"this",
"->",
"client",
"->",
"sendAsync",
"(",
"$",
"request",
")",
";",
"return",
"new",
"Promise",
"(",
"$",
"promise",
",",
"$",
"r... | {@inheritdoc} | [
"{"
] | train | https://github.com/php-http/guzzle6-adapter/blob/4b491b78e1b24ca941e6ca925f48a63e6a2d9a45/src/Client.php#L63-L68 |
php-http/guzzle6-adapter | src/Client.php | Client.buildClient | private static function buildClient(array $config = []): GuzzleClient
{
$handlerStack = new HandlerStack(\GuzzleHttp\choose_handler());
$handlerStack->push(Middleware::prepareBody(), 'prepare_body');
$config = array_merge(['handler' => $handlerStack], $config);
return new GuzzleClient($config);
} | php | private static function buildClient(array $config = []): GuzzleClient
{
$handlerStack = new HandlerStack(\GuzzleHttp\choose_handler());
$handlerStack->push(Middleware::prepareBody(), 'prepare_body');
$config = array_merge(['handler' => $handlerStack], $config);
return new GuzzleClient($config);
} | [
"private",
"static",
"function",
"buildClient",
"(",
"array",
"$",
"config",
"=",
"[",
"]",
")",
":",
"GuzzleClient",
"{",
"$",
"handlerStack",
"=",
"new",
"HandlerStack",
"(",
"\\",
"GuzzleHttp",
"\\",
"choose_handler",
"(",
")",
")",
";",
"$",
"handlerSt... | Build the Guzzle client instance. | [
"Build",
"the",
"Guzzle",
"client",
"instance",
"."
] | train | https://github.com/php-http/guzzle6-adapter/blob/4b491b78e1b24ca941e6ca925f48a63e6a2d9a45/src/Client.php#L73-L80 |
cocur/background-process | src/BackgroundProcess.php | BackgroundProcess.run | public function run($outputFile = '/dev/null', $append = false)
{
if($this->command === null) {
return;
}
switch ($this->getOS()) {
case self::OS_WINDOWS:
shell_exec(sprintf('%s &', $this->command, $outputFile));
break;
case self::OS_NIX:
$this->pid = (int)shell_exec(sprintf('%s %s %s 2>&1 & echo $!', $this->command, ($append) ? '>>' : '>', $outputFile));
break;
default:
throw new RuntimeException(sprintf(
'Could not execute command "%s" because operating system "%s" is not supported by '.
'Cocur\BackgroundProcess.',
$this->command,
PHP_OS
));
}
} | php | public function run($outputFile = '/dev/null', $append = false)
{
if($this->command === null) {
return;
}
switch ($this->getOS()) {
case self::OS_WINDOWS:
shell_exec(sprintf('%s &', $this->command, $outputFile));
break;
case self::OS_NIX:
$this->pid = (int)shell_exec(sprintf('%s %s %s 2>&1 & echo $!', $this->command, ($append) ? '>>' : '>', $outputFile));
break;
default:
throw new RuntimeException(sprintf(
'Could not execute command "%s" because operating system "%s" is not supported by '.
'Cocur\BackgroundProcess.',
$this->command,
PHP_OS
));
}
} | [
"public",
"function",
"run",
"(",
"$",
"outputFile",
"=",
"'/dev/null'",
",",
"$",
"append",
"=",
"false",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"command",
"===",
"null",
")",
"{",
"return",
";",
"}",
"switch",
"(",
"$",
"this",
"->",
"getOS",
"(... | Runs the command in a background process.
@param string $outputFile File to write the output of the process to; defaults to /dev/null
currently $outputFile has no effect when used in conjunction with a Windows server
@param bool $append - set to true if output should be appended to $outputfile | [
"Runs",
"the",
"command",
"in",
"a",
"background",
"process",
"."
] | train | https://github.com/cocur/background-process/blob/9ae2902922f02ec5544d723756758eb7304c6869/src/BackgroundProcess.php#L63-L84 |
cocur/background-process | src/BackgroundProcess.php | BackgroundProcess.isRunning | public function isRunning()
{
$this->checkSupportingOS('Cocur\BackgroundProcess can only check if a process is running on *nix-based '.
'systems, such as Unix, Linux or Mac OS X. You are running "%s".');
try {
$result = shell_exec(sprintf('ps %d 2>&1', $this->pid));
if (count(preg_split("/\n/", $result)) > 2 && !preg_match('/ERROR: Process ID out of range/', $result)) {
return true;
}
} catch (Exception $e) {
}
return false;
} | php | public function isRunning()
{
$this->checkSupportingOS('Cocur\BackgroundProcess can only check if a process is running on *nix-based '.
'systems, such as Unix, Linux or Mac OS X. You are running "%s".');
try {
$result = shell_exec(sprintf('ps %d 2>&1', $this->pid));
if (count(preg_split("/\n/", $result)) > 2 && !preg_match('/ERROR: Process ID out of range/', $result)) {
return true;
}
} catch (Exception $e) {
}
return false;
} | [
"public",
"function",
"isRunning",
"(",
")",
"{",
"$",
"this",
"->",
"checkSupportingOS",
"(",
"'Cocur\\BackgroundProcess can only check if a process is running on *nix-based '",
".",
"'systems, such as Unix, Linux or Mac OS X. You are running \"%s\".'",
")",
";",
"try",
"{",
"$"... | Returns if the process is currently running.
@return bool TRUE if the process is running, FALSE if not. | [
"Returns",
"if",
"the",
"process",
"is",
"currently",
"running",
"."
] | train | https://github.com/cocur/background-process/blob/9ae2902922f02ec5544d723756758eb7304c6869/src/BackgroundProcess.php#L91-L105 |
cocur/background-process | src/BackgroundProcess.php | BackgroundProcess.stop | public function stop()
{
$this->checkSupportingOS('Cocur\BackgroundProcess can only stop a process on *nix-based systems, such as '.
'Unix, Linux or Mac OS X. You are running "%s".');
try {
$result = shell_exec(sprintf('kill %d 2>&1', $this->pid));
if (!preg_match('/No such process/', $result)) {
return true;
}
} catch (Exception $e) {
}
return false;
} | php | public function stop()
{
$this->checkSupportingOS('Cocur\BackgroundProcess can only stop a process on *nix-based systems, such as '.
'Unix, Linux or Mac OS X. You are running "%s".');
try {
$result = shell_exec(sprintf('kill %d 2>&1', $this->pid));
if (!preg_match('/No such process/', $result)) {
return true;
}
} catch (Exception $e) {
}
return false;
} | [
"public",
"function",
"stop",
"(",
")",
"{",
"$",
"this",
"->",
"checkSupportingOS",
"(",
"'Cocur\\BackgroundProcess can only stop a process on *nix-based systems, such as '",
".",
"'Unix, Linux or Mac OS X. You are running \"%s\".'",
")",
";",
"try",
"{",
"$",
"result",
"=",... | Stops the process.
@return bool `true` if the processes was stopped, `false` otherwise. | [
"Stops",
"the",
"process",
"."
] | train | https://github.com/cocur/background-process/blob/9ae2902922f02ec5544d723756758eb7304c6869/src/BackgroundProcess.php#L112-L126 |
cocur/background-process | src/BackgroundProcess.php | BackgroundProcess.checkSupportingOS | protected function checkSupportingOS($message)
{
if ($this->getOS() !== self::OS_NIX) {
throw new RuntimeException(sprintf($message, PHP_OS));
}
} | php | protected function checkSupportingOS($message)
{
if ($this->getOS() !== self::OS_NIX) {
throw new RuntimeException(sprintf($message, PHP_OS));
}
} | [
"protected",
"function",
"checkSupportingOS",
"(",
"$",
"message",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"getOS",
"(",
")",
"!==",
"self",
"::",
"OS_NIX",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"sprintf",
"(",
"$",
"message",
",",
"PHP_OS",... | @param string $message Exception message if the OS is not supported
@throws RuntimeException if the operating system is not supported by Cocur\BackgroundProcess
@codeCoverageIgnore | [
"@param",
"string",
"$message",
"Exception",
"message",
"if",
"the",
"OS",
"is",
"not",
"supported"
] | train | https://github.com/cocur/background-process/blob/9ae2902922f02ec5544d723756758eb7304c6869/src/BackgroundProcess.php#L174-L179 |
doctrine/data-fixtures | lib/Doctrine/Common/DataFixtures/ReferenceRepository.php | ReferenceRepository.getIdentifier | protected function getIdentifier($reference, $uow)
{
// In case Reference is not yet managed in UnitOfWork
if ( ! $this->hasIdentifier($reference)) {
$class = $this->manager->getClassMetadata(get_class($reference));
return $class->getIdentifierValues($reference);
}
// Dealing with ORM UnitOfWork
if (method_exists($uow, 'getEntityIdentifier')) {
return $uow->getEntityIdentifier($reference);
}
// PHPCR ODM UnitOfWork
if ($this->manager instanceof PhpcrDocumentManager) {
return $uow->getDocumentId($reference);
}
// ODM UnitOfWork
return $uow->getDocumentIdentifier($reference);
} | php | protected function getIdentifier($reference, $uow)
{
// In case Reference is not yet managed in UnitOfWork
if ( ! $this->hasIdentifier($reference)) {
$class = $this->manager->getClassMetadata(get_class($reference));
return $class->getIdentifierValues($reference);
}
// Dealing with ORM UnitOfWork
if (method_exists($uow, 'getEntityIdentifier')) {
return $uow->getEntityIdentifier($reference);
}
// PHPCR ODM UnitOfWork
if ($this->manager instanceof PhpcrDocumentManager) {
return $uow->getDocumentId($reference);
}
// ODM UnitOfWork
return $uow->getDocumentIdentifier($reference);
} | [
"protected",
"function",
"getIdentifier",
"(",
"$",
"reference",
",",
"$",
"uow",
")",
"{",
"// In case Reference is not yet managed in UnitOfWork",
"if",
"(",
"!",
"$",
"this",
"->",
"hasIdentifier",
"(",
"$",
"reference",
")",
")",
"{",
"$",
"class",
"=",
"$... | Get identifier for a unit of work
@param object $reference Reference object
@param object $uow Unit of work
@return array | [
"Get",
"identifier",
"for",
"a",
"unit",
"of",
"work"
] | train | https://github.com/doctrine/data-fixtures/blob/71592a19ec7c6122e3a1df6b18dc4d15097d895f/lib/Doctrine/Common/DataFixtures/ReferenceRepository.php#L54-L75 |
doctrine/data-fixtures | lib/Doctrine/Common/DataFixtures/ReferenceRepository.php | ReferenceRepository.setReference | public function setReference($name, $reference)
{
$this->references[$name] = $reference;
if ($this->hasIdentifier($reference)) {
// in case if reference is set after flush, store its identity
$uow = $this->manager->getUnitOfWork();
$this->identities[$name] = $this->getIdentifier($reference, $uow);
}
} | php | public function setReference($name, $reference)
{
$this->references[$name] = $reference;
if ($this->hasIdentifier($reference)) {
// in case if reference is set after flush, store its identity
$uow = $this->manager->getUnitOfWork();
$this->identities[$name] = $this->getIdentifier($reference, $uow);
}
} | [
"public",
"function",
"setReference",
"(",
"$",
"name",
",",
"$",
"reference",
")",
"{",
"$",
"this",
"->",
"references",
"[",
"$",
"name",
"]",
"=",
"$",
"reference",
";",
"if",
"(",
"$",
"this",
"->",
"hasIdentifier",
"(",
"$",
"reference",
")",
")... | Set the reference entry identified by $name
and referenced to $reference. If $name
already is set, it overrides it
@param string $name
@param object $reference | [
"Set",
"the",
"reference",
"entry",
"identified",
"by",
"$name",
"and",
"referenced",
"to",
"$reference",
".",
"If",
"$name",
"already",
"is",
"set",
"it",
"overrides",
"it"
] | train | https://github.com/doctrine/data-fixtures/blob/71592a19ec7c6122e3a1df6b18dc4d15097d895f/lib/Doctrine/Common/DataFixtures/ReferenceRepository.php#L85-L94 |
doctrine/data-fixtures | lib/Doctrine/Common/DataFixtures/ReferenceRepository.php | ReferenceRepository.addReference | public function addReference($name, $object)
{
if (isset($this->references[$name])) {
throw new \BadMethodCallException("Reference to: ({$name}) already exists, use method setReference in order to override it");
}
$this->setReference($name, $object);
} | php | public function addReference($name, $object)
{
if (isset($this->references[$name])) {
throw new \BadMethodCallException("Reference to: ({$name}) already exists, use method setReference in order to override it");
}
$this->setReference($name, $object);
} | [
"public",
"function",
"addReference",
"(",
"$",
"name",
",",
"$",
"object",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"references",
"[",
"$",
"name",
"]",
")",
")",
"{",
"throw",
"new",
"\\",
"BadMethodCallException",
"(",
"\"Reference to: ({... | Set the reference entry identified by $name
and referenced to managed $object. $name must
not be set yet
Notice: in case if identifier is generated after
the record is inserted, be sure tu use this method
after $object is flushed
@param string $name
@param object $object - managed object
@throws \BadMethodCallException - if repository already has
a reference by $name
@return void | [
"Set",
"the",
"reference",
"entry",
"identified",
"by",
"$name",
"and",
"referenced",
"to",
"managed",
"$object",
".",
"$name",
"must",
"not",
"be",
"set",
"yet"
] | train | https://github.com/doctrine/data-fixtures/blob/71592a19ec7c6122e3a1df6b18dc4d15097d895f/lib/Doctrine/Common/DataFixtures/ReferenceRepository.php#L122-L128 |
doctrine/data-fixtures | lib/Doctrine/Common/DataFixtures/ReferenceRepository.php | ReferenceRepository.getReference | public function getReference($name)
{
if (!$this->hasReference($name)) {
throw new \OutOfBoundsException("Reference to: ({$name}) does not exist");
}
$reference = $this->references[$name];
$meta = $this->manager->getClassMetadata(get_class($reference));
if (!$this->manager->contains($reference) && isset($this->identities[$name])) {
$reference = $this->manager->getReference(
$meta->name,
$this->identities[$name]
);
$this->references[$name] = $reference; // already in identity map
}
return $reference;
} | php | public function getReference($name)
{
if (!$this->hasReference($name)) {
throw new \OutOfBoundsException("Reference to: ({$name}) does not exist");
}
$reference = $this->references[$name];
$meta = $this->manager->getClassMetadata(get_class($reference));
if (!$this->manager->contains($reference) && isset($this->identities[$name])) {
$reference = $this->manager->getReference(
$meta->name,
$this->identities[$name]
);
$this->references[$name] = $reference; // already in identity map
}
return $reference;
} | [
"public",
"function",
"getReference",
"(",
"$",
"name",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"hasReference",
"(",
"$",
"name",
")",
")",
"{",
"throw",
"new",
"\\",
"OutOfBoundsException",
"(",
"\"Reference to: ({$name}) does not exist\"",
")",
";",
"... | Loads an object using stored reference
named by $name
@param string $name
@throws \OutOfBoundsException - if repository does not exist
@return object | [
"Loads",
"an",
"object",
"using",
"stored",
"reference",
"named",
"by",
"$name"
] | train | https://github.com/doctrine/data-fixtures/blob/71592a19ec7c6122e3a1df6b18dc4d15097d895f/lib/Doctrine/Common/DataFixtures/ReferenceRepository.php#L138-L156 |
doctrine/data-fixtures | lib/Doctrine/Common/DataFixtures/ReferenceRepository.php | ReferenceRepository.hasIdentifier | private function hasIdentifier($reference)
{
// in case if reference is set after flush, store its identity
$uow = $this->manager->getUnitOfWork();
if ($this->manager instanceof PhpcrDocumentManager) {
return $uow->contains($reference);
} else {
return $uow->isInIdentityMap($reference);
}
} | php | private function hasIdentifier($reference)
{
// in case if reference is set after flush, store its identity
$uow = $this->manager->getUnitOfWork();
if ($this->manager instanceof PhpcrDocumentManager) {
return $uow->contains($reference);
} else {
return $uow->isInIdentityMap($reference);
}
} | [
"private",
"function",
"hasIdentifier",
"(",
"$",
"reference",
")",
"{",
"// in case if reference is set after flush, store its identity",
"$",
"uow",
"=",
"$",
"this",
"->",
"manager",
"->",
"getUnitOfWork",
"(",
")",
";",
"if",
"(",
"$",
"this",
"->",
"manager",... | Checks if object has identifier already in unit of work.
@param $reference
@return bool | [
"Checks",
"if",
"object",
"has",
"identifier",
"already",
"in",
"unit",
"of",
"work",
"."
] | train | https://github.com/doctrine/data-fixtures/blob/71592a19ec7c6122e3a1df6b18dc4d15097d895f/lib/Doctrine/Common/DataFixtures/ReferenceRepository.php#L229-L239 |
doctrine/data-fixtures | lib/Doctrine/Common/DataFixtures/Executor/AbstractExecutor.php | AbstractExecutor.load | public function load(ObjectManager $manager, FixtureInterface $fixture)
{
if ($this->logger) {
$prefix = '';
if ($fixture instanceof OrderedFixtureInterface) {
$prefix = sprintf('[%d] ',$fixture->getOrder());
}
$this->log('loading ' . $prefix . get_class($fixture));
}
// additionally pass the instance of reference repository to shared fixtures
if ($fixture instanceof SharedFixtureInterface) {
$fixture->setReferenceRepository($this->referenceRepository);
}
$fixture->load($manager);
$manager->clear();
} | php | public function load(ObjectManager $manager, FixtureInterface $fixture)
{
if ($this->logger) {
$prefix = '';
if ($fixture instanceof OrderedFixtureInterface) {
$prefix = sprintf('[%d] ',$fixture->getOrder());
}
$this->log('loading ' . $prefix . get_class($fixture));
}
// additionally pass the instance of reference repository to shared fixtures
if ($fixture instanceof SharedFixtureInterface) {
$fixture->setReferenceRepository($this->referenceRepository);
}
$fixture->load($manager);
$manager->clear();
} | [
"public",
"function",
"load",
"(",
"ObjectManager",
"$",
"manager",
",",
"FixtureInterface",
"$",
"fixture",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"logger",
")",
"{",
"$",
"prefix",
"=",
"''",
";",
"if",
"(",
"$",
"fixture",
"instanceof",
"OrderedFixtu... | Load a fixture with the given persistence manager.
@param ObjectManager $manager
@param FixtureInterface $fixture | [
"Load",
"a",
"fixture",
"with",
"the",
"given",
"persistence",
"manager",
"."
] | train | https://github.com/doctrine/data-fixtures/blob/71592a19ec7c6122e3a1df6b18dc4d15097d895f/lib/Doctrine/Common/DataFixtures/Executor/AbstractExecutor.php#L103-L118 |
doctrine/data-fixtures | lib/Doctrine/Common/DataFixtures/Executor/AbstractExecutor.php | AbstractExecutor.purge | public function purge()
{
if ($this->purger === null) {
throw new \Exception('Doctrine\Common\DataFixtures\Purger\PurgerInterface instance is required if you want to purge the database before loading your data fixtures.');
}
if ($this->logger) {
$this->log('purging database');
}
$this->purger->purge();
} | php | public function purge()
{
if ($this->purger === null) {
throw new \Exception('Doctrine\Common\DataFixtures\Purger\PurgerInterface instance is required if you want to purge the database before loading your data fixtures.');
}
if ($this->logger) {
$this->log('purging database');
}
$this->purger->purge();
} | [
"public",
"function",
"purge",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"purger",
"===",
"null",
")",
"{",
"throw",
"new",
"\\",
"Exception",
"(",
"'Doctrine\\Common\\DataFixtures\\Purger\\PurgerInterface instance is required if you want to purge the database before loa... | Purges the database before loading.
@throws \Exception if the purger is not defined | [
"Purges",
"the",
"database",
"before",
"loading",
"."
] | train | https://github.com/doctrine/data-fixtures/blob/71592a19ec7c6122e3a1df6b18dc4d15097d895f/lib/Doctrine/Common/DataFixtures/Executor/AbstractExecutor.php#L125-L134 |
doctrine/data-fixtures | lib/Doctrine/Common/DataFixtures/Loader.php | Loader.loadFromFile | public function loadFromFile($fileName)
{
if (!is_readable($fileName)) {
throw new \InvalidArgumentException(sprintf('"%s" does not exist or is not readable', $fileName));
}
$iterator = new \ArrayIterator([new \SplFileInfo($fileName)]);
return $this->loadFromIterator($iterator);
} | php | public function loadFromFile($fileName)
{
if (!is_readable($fileName)) {
throw new \InvalidArgumentException(sprintf('"%s" does not exist or is not readable', $fileName));
}
$iterator = new \ArrayIterator([new \SplFileInfo($fileName)]);
return $this->loadFromIterator($iterator);
} | [
"public",
"function",
"loadFromFile",
"(",
"$",
"fileName",
")",
"{",
"if",
"(",
"!",
"is_readable",
"(",
"$",
"fileName",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'\"%s\" does not exist or is not readable'",
",",
"$... | Find fixtures classes in a given file and load them.
@param string $fileName File to find fixture classes in.
@return array $fixtures Array of loaded fixture object instances. | [
"Find",
"fixtures",
"classes",
"in",
"a",
"given",
"file",
"and",
"load",
"them",
"."
] | train | https://github.com/doctrine/data-fixtures/blob/71592a19ec7c6122e3a1df6b18dc4d15097d895f/lib/Doctrine/Common/DataFixtures/Loader.php#L74-L82 |
doctrine/data-fixtures | lib/Doctrine/Common/DataFixtures/Loader.php | Loader.getFixture | public function getFixture($className)
{
if (!isset($this->fixtures[$className])) {
throw new \InvalidArgumentException(sprintf(
'"%s" is not a registered fixture',
$className
));
}
return $this->fixtures[$className];
} | php | public function getFixture($className)
{
if (!isset($this->fixtures[$className])) {
throw new \InvalidArgumentException(sprintf(
'"%s" is not a registered fixture',
$className
));
}
return $this->fixtures[$className];
} | [
"public",
"function",
"getFixture",
"(",
"$",
"className",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"fixtures",
"[",
"$",
"className",
"]",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'\"%s\" i... | Get a specific fixture instance
@param string $className
@return FixtureInterface | [
"Get",
"a",
"specific",
"fixture",
"instance"
] | train | https://github.com/doctrine/data-fixtures/blob/71592a19ec7c6122e3a1df6b18dc4d15097d895f/lib/Doctrine/Common/DataFixtures/Loader.php#L102-L112 |
doctrine/data-fixtures | lib/Doctrine/Common/DataFixtures/Loader.php | Loader.addFixture | public function addFixture(FixtureInterface $fixture)
{
$fixtureClass = get_class($fixture);
if (!isset($this->fixtures[$fixtureClass])) {
if ($fixture instanceof OrderedFixtureInterface && $fixture instanceof DependentFixtureInterface) {
throw new \InvalidArgumentException(sprintf('Class "%s" can\'t implement "%s" and "%s" at the same time.',
get_class($fixture),
'OrderedFixtureInterface',
'DependentFixtureInterface'));
}
$this->fixtures[$fixtureClass] = $fixture;
if ($fixture instanceof OrderedFixtureInterface) {
$this->orderFixturesByNumber = true;
} elseif ($fixture instanceof DependentFixtureInterface) {
$this->orderFixturesByDependencies = true;
foreach($fixture->getDependencies() as $class) {
if (class_exists($class)) {
$this->addFixture($this->createFixture($class));
}
}
}
}
} | php | public function addFixture(FixtureInterface $fixture)
{
$fixtureClass = get_class($fixture);
if (!isset($this->fixtures[$fixtureClass])) {
if ($fixture instanceof OrderedFixtureInterface && $fixture instanceof DependentFixtureInterface) {
throw new \InvalidArgumentException(sprintf('Class "%s" can\'t implement "%s" and "%s" at the same time.',
get_class($fixture),
'OrderedFixtureInterface',
'DependentFixtureInterface'));
}
$this->fixtures[$fixtureClass] = $fixture;
if ($fixture instanceof OrderedFixtureInterface) {
$this->orderFixturesByNumber = true;
} elseif ($fixture instanceof DependentFixtureInterface) {
$this->orderFixturesByDependencies = true;
foreach($fixture->getDependencies() as $class) {
if (class_exists($class)) {
$this->addFixture($this->createFixture($class));
}
}
}
}
} | [
"public",
"function",
"addFixture",
"(",
"FixtureInterface",
"$",
"fixture",
")",
"{",
"$",
"fixtureClass",
"=",
"get_class",
"(",
"$",
"fixture",
")",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"fixtures",
"[",
"$",
"fixtureClass",
"]",
")",
... | Add a fixture object instance to the loader.
@param FixtureInterface $fixture | [
"Add",
"a",
"fixture",
"object",
"instance",
"to",
"the",
"loader",
"."
] | train | https://github.com/doctrine/data-fixtures/blob/71592a19ec7c6122e3a1df6b18dc4d15097d895f/lib/Doctrine/Common/DataFixtures/Loader.php#L119-L144 |
doctrine/data-fixtures | lib/Doctrine/Common/DataFixtures/Loader.php | Loader.getFixtures | public function getFixtures()
{
$this->orderedFixtures = [];
if ($this->orderFixturesByNumber) {
$this->orderFixturesByNumber();
}
if ($this->orderFixturesByDependencies) {
$this->orderFixturesByDependencies();
}
if (!$this->orderFixturesByNumber && !$this->orderFixturesByDependencies) {
$this->orderedFixtures = $this->fixtures;
}
return $this->orderedFixtures;
} | php | public function getFixtures()
{
$this->orderedFixtures = [];
if ($this->orderFixturesByNumber) {
$this->orderFixturesByNumber();
}
if ($this->orderFixturesByDependencies) {
$this->orderFixturesByDependencies();
}
if (!$this->orderFixturesByNumber && !$this->orderFixturesByDependencies) {
$this->orderedFixtures = $this->fixtures;
}
return $this->orderedFixtures;
} | [
"public",
"function",
"getFixtures",
"(",
")",
"{",
"$",
"this",
"->",
"orderedFixtures",
"=",
"[",
"]",
";",
"if",
"(",
"$",
"this",
"->",
"orderFixturesByNumber",
")",
"{",
"$",
"this",
"->",
"orderFixturesByNumber",
"(",
")",
";",
"}",
"if",
"(",
"$... | Returns the array of data fixtures to execute.
@return array $fixtures | [
"Returns",
"the",
"array",
"of",
"data",
"fixtures",
"to",
"execute",
"."
] | train | https://github.com/doctrine/data-fixtures/blob/71592a19ec7c6122e3a1df6b18dc4d15097d895f/lib/Doctrine/Common/DataFixtures/Loader.php#L151-L168 |
doctrine/data-fixtures | lib/Doctrine/Common/DataFixtures/Loader.php | Loader.orderFixturesByDependencies | private function orderFixturesByDependencies()
{
$sequenceForClasses = [];
// If fixtures were already ordered by number then we need
// to remove classes which are not instances of OrderedFixtureInterface
// in case fixtures implementing DependentFixtureInterface exist.
// This is because, in that case, the method orderFixturesByDependencies
// will handle all fixtures which are not instances of
// OrderedFixtureInterface
if ($this->orderFixturesByNumber) {
$count = count($this->orderedFixtures);
for ($i = 0 ; $i < $count ; ++$i) {
if (!($this->orderedFixtures[$i] instanceof OrderedFixtureInterface)) {
unset($this->orderedFixtures[$i]);
}
}
}
// First we determine which classes has dependencies and which don't
foreach ($this->fixtures as $fixture) {
$fixtureClass = get_class($fixture);
if ($fixture instanceof OrderedFixtureInterface) {
continue;
} elseif ($fixture instanceof DependentFixtureInterface) {
$dependenciesClasses = $fixture->getDependencies();
$this->validateDependencies($dependenciesClasses);
if (!is_array($dependenciesClasses) || empty($dependenciesClasses)) {
throw new \InvalidArgumentException(sprintf('Method "%s" in class "%s" must return an array of classes which are dependencies for the fixture, and it must be NOT empty.', 'getDependencies', $fixtureClass));
}
if (in_array($fixtureClass, $dependenciesClasses)) {
throw new \InvalidArgumentException(sprintf('Class "%s" can\'t have itself as a dependency', $fixtureClass));
}
// We mark this class as unsequenced
$sequenceForClasses[$fixtureClass] = -1;
} else {
// This class has no dependencies, so we assign 0
$sequenceForClasses[$fixtureClass] = 0;
}
}
// Now we order fixtures by sequence
$sequence = 1;
$lastCount = -1;
while (($count = count($unsequencedClasses = $this->getUnsequencedClasses($sequenceForClasses))) > 0 && $count !== $lastCount) {
foreach ($unsequencedClasses as $key => $class) {
$fixture = $this->fixtures[$class];
$dependencies = $fixture->getDependencies();
$unsequencedDependencies = $this->getUnsequencedClasses($sequenceForClasses, $dependencies);
if (count($unsequencedDependencies) === 0) {
$sequenceForClasses[$class] = $sequence++;
}
}
$lastCount = $count;
}
$orderedFixtures = [];
// If there're fixtures unsequenced left and they couldn't be sequenced,
// it means we have a circular reference
if ($count > 0) {
$msg = 'Classes "%s" have produced a CircularReferenceException. ';
$msg .= 'An example of this problem would be the following: Class C has class B as its dependency. ';
$msg .= 'Then, class B has class A has its dependency. Finally, class A has class C as its dependency. ';
$msg .= 'This case would produce a CircularReferenceException.';
throw new CircularReferenceException(sprintf($msg, implode(',', $unsequencedClasses)));
} else {
// We order the classes by sequence
asort($sequenceForClasses);
foreach ($sequenceForClasses as $class => $sequence) {
// If fixtures were ordered
$orderedFixtures[] = $this->fixtures[$class];
}
}
$this->orderedFixtures = array_merge($this->orderedFixtures, $orderedFixtures);
} | php | private function orderFixturesByDependencies()
{
$sequenceForClasses = [];
// If fixtures were already ordered by number then we need
// to remove classes which are not instances of OrderedFixtureInterface
// in case fixtures implementing DependentFixtureInterface exist.
// This is because, in that case, the method orderFixturesByDependencies
// will handle all fixtures which are not instances of
// OrderedFixtureInterface
if ($this->orderFixturesByNumber) {
$count = count($this->orderedFixtures);
for ($i = 0 ; $i < $count ; ++$i) {
if (!($this->orderedFixtures[$i] instanceof OrderedFixtureInterface)) {
unset($this->orderedFixtures[$i]);
}
}
}
// First we determine which classes has dependencies and which don't
foreach ($this->fixtures as $fixture) {
$fixtureClass = get_class($fixture);
if ($fixture instanceof OrderedFixtureInterface) {
continue;
} elseif ($fixture instanceof DependentFixtureInterface) {
$dependenciesClasses = $fixture->getDependencies();
$this->validateDependencies($dependenciesClasses);
if (!is_array($dependenciesClasses) || empty($dependenciesClasses)) {
throw new \InvalidArgumentException(sprintf('Method "%s" in class "%s" must return an array of classes which are dependencies for the fixture, and it must be NOT empty.', 'getDependencies', $fixtureClass));
}
if (in_array($fixtureClass, $dependenciesClasses)) {
throw new \InvalidArgumentException(sprintf('Class "%s" can\'t have itself as a dependency', $fixtureClass));
}
// We mark this class as unsequenced
$sequenceForClasses[$fixtureClass] = -1;
} else {
// This class has no dependencies, so we assign 0
$sequenceForClasses[$fixtureClass] = 0;
}
}
// Now we order fixtures by sequence
$sequence = 1;
$lastCount = -1;
while (($count = count($unsequencedClasses = $this->getUnsequencedClasses($sequenceForClasses))) > 0 && $count !== $lastCount) {
foreach ($unsequencedClasses as $key => $class) {
$fixture = $this->fixtures[$class];
$dependencies = $fixture->getDependencies();
$unsequencedDependencies = $this->getUnsequencedClasses($sequenceForClasses, $dependencies);
if (count($unsequencedDependencies) === 0) {
$sequenceForClasses[$class] = $sequence++;
}
}
$lastCount = $count;
}
$orderedFixtures = [];
// If there're fixtures unsequenced left and they couldn't be sequenced,
// it means we have a circular reference
if ($count > 0) {
$msg = 'Classes "%s" have produced a CircularReferenceException. ';
$msg .= 'An example of this problem would be the following: Class C has class B as its dependency. ';
$msg .= 'Then, class B has class A has its dependency. Finally, class A has class C as its dependency. ';
$msg .= 'This case would produce a CircularReferenceException.';
throw new CircularReferenceException(sprintf($msg, implode(',', $unsequencedClasses)));
} else {
// We order the classes by sequence
asort($sequenceForClasses);
foreach ($sequenceForClasses as $class => $sequence) {
// If fixtures were ordered
$orderedFixtures[] = $this->fixtures[$class];
}
}
$this->orderedFixtures = array_merge($this->orderedFixtures, $orderedFixtures);
} | [
"private",
"function",
"orderFixturesByDependencies",
"(",
")",
"{",
"$",
"sequenceForClasses",
"=",
"[",
"]",
";",
"// If fixtures were already ordered by number then we need ",
"// to remove classes which are not instances of OrderedFixtureInterface",
"// in case fixtures implementing ... | Orders fixtures by dependencies
@return void | [
"Orders",
"fixtures",
"by",
"dependencies"
] | train | https://github.com/doctrine/data-fixtures/blob/71592a19ec7c6122e3a1df6b18dc4d15097d895f/lib/Doctrine/Common/DataFixtures/Loader.php#L226-L313 |
doctrine/data-fixtures | lib/Doctrine/Common/DataFixtures/Sorter/TopologicalSorter.php | TopologicalSorter.addDependency | public function addDependency($fromHash, $toHash)
{
$definition = $this->nodeList[$fromHash];
$definition->dependencyList[] = $toHash;
} | php | public function addDependency($fromHash, $toHash)
{
$definition = $this->nodeList[$fromHash];
$definition->dependencyList[] = $toHash;
} | [
"public",
"function",
"addDependency",
"(",
"$",
"fromHash",
",",
"$",
"toHash",
")",
"{",
"$",
"definition",
"=",
"$",
"this",
"->",
"nodeList",
"[",
"$",
"fromHash",
"]",
";",
"$",
"definition",
"->",
"dependencyList",
"[",
"]",
"=",
"$",
"toHash",
"... | Adds a new dependency (edge) to the graph using their hashes.
@param string $fromHash
@param string $toHash
@return void | [
"Adds",
"a",
"new",
"dependency",
"(",
"edge",
")",
"to",
"the",
"graph",
"using",
"their",
"hashes",
"."
] | train | https://github.com/doctrine/data-fixtures/blob/71592a19ec7c6122e3a1df6b18dc4d15097d895f/lib/Doctrine/Common/DataFixtures/Sorter/TopologicalSorter.php#L88-L93 |
doctrine/data-fixtures | lib/Doctrine/Common/DataFixtures/Sorter/TopologicalSorter.php | TopologicalSorter.sort | public function sort()
{
foreach ($this->nodeList as $definition) {
if ($definition->state !== Vertex::NOT_VISITED) {
continue;
}
$this->visit($definition);
}
$sortedList = $this->sortedNodeList;
$this->nodeList = [];
$this->sortedNodeList = [];
return $sortedList;
} | php | public function sort()
{
foreach ($this->nodeList as $definition) {
if ($definition->state !== Vertex::NOT_VISITED) {
continue;
}
$this->visit($definition);
}
$sortedList = $this->sortedNodeList;
$this->nodeList = [];
$this->sortedNodeList = [];
return $sortedList;
} | [
"public",
"function",
"sort",
"(",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"nodeList",
"as",
"$",
"definition",
")",
"{",
"if",
"(",
"$",
"definition",
"->",
"state",
"!==",
"Vertex",
"::",
"NOT_VISITED",
")",
"{",
"continue",
";",
"}",
"$",
"th... | Return a valid order list of all current nodes.
The desired topological sorting is the postorder of these searches.
Note: Highly performance-sensitive method.
@throws \RuntimeException
@throws CircularReferenceException
@return array | [
"Return",
"a",
"valid",
"order",
"list",
"of",
"all",
"current",
"nodes",
".",
"The",
"desired",
"topological",
"sorting",
"is",
"the",
"postorder",
"of",
"these",
"searches",
"."
] | train | https://github.com/doctrine/data-fixtures/blob/71592a19ec7c6122e3a1df6b18dc4d15097d895f/lib/Doctrine/Common/DataFixtures/Sorter/TopologicalSorter.php#L106-L122 |
doctrine/data-fixtures | lib/Doctrine/Common/DataFixtures/Sorter/TopologicalSorter.php | TopologicalSorter.visit | private function visit(Vertex $definition)
{
$definition->state = Vertex::IN_PROGRESS;
foreach ($definition->dependencyList as $dependency) {
if ( ! isset($this->nodeList[$dependency])) {
throw new \RuntimeException(sprintf(
'Fixture "%s" has a dependency of fixture "%s", but it not listed to be loaded.',
get_class($definition->value),
$dependency
));
}
$childDefinition = $this->nodeList[$dependency];
// allow self referencing classes
if ($definition === $childDefinition) {
continue;
}
switch ($childDefinition->state) {
case Vertex::VISITED:
break;
case Vertex::IN_PROGRESS:
if ( ! $this->allowCyclicDependencies) {
throw new CircularReferenceException(
sprintf(
'Graph contains cyclic dependency between the classes "%s" and'
.' "%s". An example of this problem would be the following: '
.'Class C has class B as its dependency. Then, class B has class A has its dependency. '
.'Finally, class A has class C as its dependency.',
$definition->value->getName(),
$childDefinition->value->getName()
)
);
}
break;
case Vertex::NOT_VISITED:
$this->visit($childDefinition);
}
}
$definition->state = Vertex::VISITED;
$this->sortedNodeList[] = $definition->value;
} | php | private function visit(Vertex $definition)
{
$definition->state = Vertex::IN_PROGRESS;
foreach ($definition->dependencyList as $dependency) {
if ( ! isset($this->nodeList[$dependency])) {
throw new \RuntimeException(sprintf(
'Fixture "%s" has a dependency of fixture "%s", but it not listed to be loaded.',
get_class($definition->value),
$dependency
));
}
$childDefinition = $this->nodeList[$dependency];
// allow self referencing classes
if ($definition === $childDefinition) {
continue;
}
switch ($childDefinition->state) {
case Vertex::VISITED:
break;
case Vertex::IN_PROGRESS:
if ( ! $this->allowCyclicDependencies) {
throw new CircularReferenceException(
sprintf(
'Graph contains cyclic dependency between the classes "%s" and'
.' "%s". An example of this problem would be the following: '
.'Class C has class B as its dependency. Then, class B has class A has its dependency. '
.'Finally, class A has class C as its dependency.',
$definition->value->getName(),
$childDefinition->value->getName()
)
);
}
break;
case Vertex::NOT_VISITED:
$this->visit($childDefinition);
}
}
$definition->state = Vertex::VISITED;
$this->sortedNodeList[] = $definition->value;
} | [
"private",
"function",
"visit",
"(",
"Vertex",
"$",
"definition",
")",
"{",
"$",
"definition",
"->",
"state",
"=",
"Vertex",
"::",
"IN_PROGRESS",
";",
"foreach",
"(",
"$",
"definition",
"->",
"dependencyList",
"as",
"$",
"dependency",
")",
"{",
"if",
"(",
... | Visit a given node definition for reordering.
Note: Highly performance-sensitive method.
@throws \RuntimeException
@throws CircularReferenceException
@param Vertex $definition | [
"Visit",
"a",
"given",
"node",
"definition",
"for",
"reordering",
"."
] | train | https://github.com/doctrine/data-fixtures/blob/71592a19ec7c6122e3a1df6b18dc4d15097d895f/lib/Doctrine/Common/DataFixtures/Sorter/TopologicalSorter.php#L134-L179 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.