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 |
|---|---|---|---|---|---|---|---|---|---|---|
mpratt/Embera | Lib/Embera/Oembed.php | Oembed.lookup | protected function lookup($url)
{
$response = $this->http->fetch($url);
$json = json_decode($response, true);
if ($json) {
return array_merge(array('embera_using_fake' => 0), $json);
}
return array();
} | php | protected function lookup($url)
{
$response = $this->http->fetch($url);
$json = json_decode($response, true);
if ($json) {
return array_merge(array('embera_using_fake' => 0), $json);
}
return array();
} | [
"protected",
"function",
"lookup",
"(",
"$",
"url",
")",
"{",
"$",
"response",
"=",
"$",
"this",
"->",
"http",
"->",
"fetch",
"(",
"$",
"url",
")",
";",
"$",
"json",
"=",
"json_decode",
"(",
"$",
"response",
",",
"true",
")",
";",
"if",
"(",
"$",... | Executes a http request to the given url and
returns an associative array with the fetched data.
@param string $url
@return array
@throws Exception From the Http object only if there is no way
to perform the request or if the response from
the server is empty/invalid. | [
"Executes",
"a",
"http",
"request",
"to",
"the",
"given",
"url",
"and",
"returns",
"an",
"associative",
"array",
"with",
"the",
"fetched",
"data",
"."
] | train | https://github.com/mpratt/Embera/blob/84df7a11426c017f1aae493a5994babddffac571/Lib/Embera/Oembed.php#L67-L77 |
mpratt/Embera | Lib/Embera/Oembed.php | Oembed.constructUrl | protected function constructUrl($apiUrl, array $params = array())
{
return $apiUrl . ((strpos($apiUrl, '?') === false) ? '?' : '&') . http_build_query(array_filter($params));
} | php | protected function constructUrl($apiUrl, array $params = array())
{
return $apiUrl . ((strpos($apiUrl, '?') === false) ? '?' : '&') . http_build_query(array_filter($params));
} | [
"protected",
"function",
"constructUrl",
"(",
"$",
"apiUrl",
",",
"array",
"$",
"params",
"=",
"array",
"(",
")",
")",
"{",
"return",
"$",
"apiUrl",
".",
"(",
"(",
"strpos",
"(",
"$",
"apiUrl",
",",
"'?'",
")",
"===",
"false",
")",
"?",
"'?'",
":",... | Builds a valid Oembed query string based on the given parameters,
Since this method uses the http_build_query function, there is no
need to pass urlencoded parameters, http_build_query already does
this for us.
@param string $apiUrl The Url to the Oembed Api
@param array $params Parameters for the query string
@return string | [
"Builds",
"a",
"valid",
"Oembed",
"query",
"string",
"based",
"on",
"the",
"given",
"parameters",
"Since",
"this",
"method",
"uses",
"the",
"http_build_query",
"function",
"there",
"is",
"no",
"need",
"to",
"pass",
"urlencoded",
"parameters",
"http_build_query",
... | train | https://github.com/mpratt/Embera/blob/84df7a11426c017f1aae493a5994babddffac571/Lib/Embera/Oembed.php#L89-L92 |
mpratt/Embera | Lib/Embera/Providers/AmCharts.php | AmCharts.fakeResponse | public function fakeResponse()
{
preg_match('~amcharts\.com/([^ /]+)~i', $this->url, $matches);
$url = 'http://live.amcharts.com/' . $matches['1'];
return array(
'type' => 'rich',
'provider_name' => 'amCharts',
'provider_url' => 'http://www.amcharts.com/',
'thumbnail_url' => 'http://generated.amcharts.com/' . substr($matches['1'], 0, 2) . '/' . $matches['1'] . '-full.png',
'thumbnail_width' => 404,
'thumbnail_height' => 300,
'canonical' => $url . '/',
'html' => '<iframe width="{width}" height="{height}" src="' . $url . '/embed/" frameborder="0"></iframe>',
);
} | php | public function fakeResponse()
{
preg_match('~amcharts\.com/([^ /]+)~i', $this->url, $matches);
$url = 'http://live.amcharts.com/' . $matches['1'];
return array(
'type' => 'rich',
'provider_name' => 'amCharts',
'provider_url' => 'http://www.amcharts.com/',
'thumbnail_url' => 'http://generated.amcharts.com/' . substr($matches['1'], 0, 2) . '/' . $matches['1'] . '-full.png',
'thumbnail_width' => 404,
'thumbnail_height' => 300,
'canonical' => $url . '/',
'html' => '<iframe width="{width}" height="{height}" src="' . $url . '/embed/" frameborder="0"></iframe>',
);
} | [
"public",
"function",
"fakeResponse",
"(",
")",
"{",
"preg_match",
"(",
"'~amcharts\\.com/([^ /]+)~i'",
",",
"$",
"this",
"->",
"url",
",",
"$",
"matches",
")",
";",
"$",
"url",
"=",
"'http://live.amcharts.com/'",
".",
"$",
"matches",
"[",
"'1'",
"]",
";",
... | inline {@inheritdoc} | [
"inline",
"{"
] | train | https://github.com/mpratt/Embera/blob/84df7a11426c017f1aae493a5994babddffac571/Lib/Embera/Providers/AmCharts.php#L43-L58 |
mpratt/Embera | Lib/Embera/Providers/FunnyOrDie.php | FunnyOrDie.normalizeUrl | protected function normalizeUrl()
{
if (preg_match('~\.com/embed/~i', $this->url))
$this->url = new \Embera\Url(str_ireplace('/embed/', '/videos/', $this->url));
} | php | protected function normalizeUrl()
{
if (preg_match('~\.com/embed/~i', $this->url))
$this->url = new \Embera\Url(str_ireplace('/embed/', '/videos/', $this->url));
} | [
"protected",
"function",
"normalizeUrl",
"(",
")",
"{",
"if",
"(",
"preg_match",
"(",
"'~\\.com/embed/~i'",
",",
"$",
"this",
"->",
"url",
")",
")",
"$",
"this",
"->",
"url",
"=",
"new",
"\\",
"Embera",
"\\",
"Url",
"(",
"str_ireplace",
"(",
"'/embed/'",... | inline {@inheritdoc} | [
"inline",
"{"
] | train | https://github.com/mpratt/Embera/blob/84df7a11426c017f1aae493a5994babddffac571/Lib/Embera/Providers/FunnyOrDie.php#L33-L37 |
mpratt/Embera | Lib/Embera/Providers/Deviantart.php | Deviantart.modifyResponse | protected function modifyResponse(array $response = array())
{
if (empty($response['html']))
{
if (strtolower($response['type']) == 'photo')
{
$html = '<a href="' . $response['url'] . '" target="_blank">';
$html .= '<img class="deviantart-oembed" src="' . $response['thumbnail_url_200h'] . '" width="' . $response['thumbnail_width_200h'] . '" height="' . $response['thumbnail_height_200h'] . '" alt="' . htmlspecialchars($response['title'], ENT_QUOTES, 'UTF-8') . '" title="' . htmlspecialchars($response['title'], ENT_QUOTES, 'UTF-8') . '">';
$html .= '</a>';
$response['html'] = $html;
}
}
return $response;
} | php | protected function modifyResponse(array $response = array())
{
if (empty($response['html']))
{
if (strtolower($response['type']) == 'photo')
{
$html = '<a href="' . $response['url'] . '" target="_blank">';
$html .= '<img class="deviantart-oembed" src="' . $response['thumbnail_url_200h'] . '" width="' . $response['thumbnail_width_200h'] . '" height="' . $response['thumbnail_height_200h'] . '" alt="' . htmlspecialchars($response['title'], ENT_QUOTES, 'UTF-8') . '" title="' . htmlspecialchars($response['title'], ENT_QUOTES, 'UTF-8') . '">';
$html .= '</a>';
$response['html'] = $html;
}
}
return $response;
} | [
"protected",
"function",
"modifyResponse",
"(",
"array",
"$",
"response",
"=",
"array",
"(",
")",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"response",
"[",
"'html'",
"]",
")",
")",
"{",
"if",
"(",
"strtolower",
"(",
"$",
"response",
"[",
"'type'",
"]"... | inline {@inheritdoc} | [
"inline",
"{"
] | train | https://github.com/mpratt/Embera/blob/84df7a11426c017f1aae493a5994babddffac571/Lib/Embera/Providers/Deviantart.php#L32-L47 |
mpratt/Embera | Lib/Embera/Providers/Sketchfab.php | Sketchfab.normalizeUrl | protected function normalizeUrl()
{
$this->url->stripWWW();
$this->url->convertToHttps();
// old urls
if (preg_match('~sketchfab\.com/show/([^/]+)/?$~i', $this->url, $matches)) {
$this->url = new \Embera\Url('https://sketchfab.com/models/' . $matches[1]);
} else if (preg_match('~(/embed/?)$~', $this->url)) {
$this->url = new \Embera\Url(preg_replace('~(/embed/?)$~', '', $this->url));
}
} | php | protected function normalizeUrl()
{
$this->url->stripWWW();
$this->url->convertToHttps();
// old urls
if (preg_match('~sketchfab\.com/show/([^/]+)/?$~i', $this->url, $matches)) {
$this->url = new \Embera\Url('https://sketchfab.com/models/' . $matches[1]);
} else if (preg_match('~(/embed/?)$~', $this->url)) {
$this->url = new \Embera\Url(preg_replace('~(/embed/?)$~', '', $this->url));
}
} | [
"protected",
"function",
"normalizeUrl",
"(",
")",
"{",
"$",
"this",
"->",
"url",
"->",
"stripWWW",
"(",
")",
";",
"$",
"this",
"->",
"url",
"->",
"convertToHttps",
"(",
")",
";",
"// old urls",
"if",
"(",
"preg_match",
"(",
"'~sketchfab\\.com/show/([^/]+)/?... | inline {@inheritdoc} | [
"inline",
"{"
] | train | https://github.com/mpratt/Embera/blob/84df7a11426c017f1aae493a5994babddffac571/Lib/Embera/Providers/Sketchfab.php#L36-L47 |
mpratt/Embera | Lib/Embera/Providers/Sketchfab.php | Sketchfab.fakeResponse | public function fakeResponse()
{
if (preg_match('~sketchfab\.com/(?:[^/]+)/folders/([^/]+)$~i', $this->url, $m)) {
$url = 'https://sketchfab.com/playlists/embed?folder=' . $m['1'];
} else {
$url = str_replace('/show/', '/embed/', $this->url) . '/embed';
}
return array(
'type' => 'rich',
'provider_name' => 'Sketchfab',
'provider_url' => 'http://sketchfab.com',
'html' => '<iframe width="{width}" height="{height}" src="' . $url . '" frameborder="0" allowfullscreen mozallowfullscreen="true" webkitallowfullscreen="true" onmousewheel=""></iframe>'
);
} | php | public function fakeResponse()
{
if (preg_match('~sketchfab\.com/(?:[^/]+)/folders/([^/]+)$~i', $this->url, $m)) {
$url = 'https://sketchfab.com/playlists/embed?folder=' . $m['1'];
} else {
$url = str_replace('/show/', '/embed/', $this->url) . '/embed';
}
return array(
'type' => 'rich',
'provider_name' => 'Sketchfab',
'provider_url' => 'http://sketchfab.com',
'html' => '<iframe width="{width}" height="{height}" src="' . $url . '" frameborder="0" allowfullscreen mozallowfullscreen="true" webkitallowfullscreen="true" onmousewheel=""></iframe>'
);
} | [
"public",
"function",
"fakeResponse",
"(",
")",
"{",
"if",
"(",
"preg_match",
"(",
"'~sketchfab\\.com/(?:[^/]+)/folders/([^/]+)$~i'",
",",
"$",
"this",
"->",
"url",
",",
"$",
"m",
")",
")",
"{",
"$",
"url",
"=",
"'https://sketchfab.com/playlists/embed?folder='",
"... | inline {@inheritdoc} | [
"inline",
"{"
] | train | https://github.com/mpratt/Embera/blob/84df7a11426c017f1aae493a5994babddffac571/Lib/Embera/Providers/Sketchfab.php#L60-L74 |
mpratt/Embera | Lib/Embera/Providers.php | Providers.findServices | protected function findServices(array $urls = array())
{
$return = array();
$this->extractCustomParams($this->config['custom_params']);
foreach (array_unique($urls) as $u) {
try {
$host = $this->getHost($u);
if (isset($this->services[$host])) {
$provider = new \ReflectionClass($this->services[$host]);
$return[$u] = $provider->newInstance($u, $this->config, $this->oembed);
if (isset($this->customParams[$host])) {
$return[$u]->appendParams($this->customParams[$host]);
}
}
} catch (\Exception $e) {
//echo $e->getMessage() . PHP_EOL;
}
}
return $return;
} | php | protected function findServices(array $urls = array())
{
$return = array();
$this->extractCustomParams($this->config['custom_params']);
foreach (array_unique($urls) as $u) {
try {
$host = $this->getHost($u);
if (isset($this->services[$host])) {
$provider = new \ReflectionClass($this->services[$host]);
$return[$u] = $provider->newInstance($u, $this->config, $this->oembed);
if (isset($this->customParams[$host])) {
$return[$u]->appendParams($this->customParams[$host]);
}
}
} catch (\Exception $e) {
//echo $e->getMessage() . PHP_EOL;
}
}
return $return;
} | [
"protected",
"function",
"findServices",
"(",
"array",
"$",
"urls",
"=",
"array",
"(",
")",
")",
"{",
"$",
"return",
"=",
"array",
"(",
")",
";",
"$",
"this",
"->",
"extractCustomParams",
"(",
"$",
"this",
"->",
"config",
"[",
"'custom_params'",
"]",
"... | Finds services for the given $urls.
@param array $urls An array with all the available urls
@return array An Array with loaded services | [
"Finds",
"services",
"for",
"the",
"given",
"$urls",
"."
] | train | https://github.com/mpratt/Embera/blob/84df7a11426c017f1aae493a5994babddffac571/Lib/Embera/Providers.php#L201-L223 |
mpratt/Embera | Lib/Embera/Providers.php | Providers.addProvider | public function addProvider($host, $class, array $params = array())
{
$host = preg_replace('~^(?:www)\.~i', '', strtolower($host));
$this->services[$host] = $class;
$this->customParams[$host] = $params;
} | php | public function addProvider($host, $class, array $params = array())
{
$host = preg_replace('~^(?:www)\.~i', '', strtolower($host));
$this->services[$host] = $class;
$this->customParams[$host] = $params;
} | [
"public",
"function",
"addProvider",
"(",
"$",
"host",
",",
"$",
"class",
",",
"array",
"$",
"params",
"=",
"array",
"(",
")",
")",
"{",
"$",
"host",
"=",
"preg_replace",
"(",
"'~^(?:www)\\.~i'",
",",
"''",
",",
"strtolower",
"(",
"$",
"host",
")",
"... | Adds a new Provider into the service map
@param string $host The host for the map
@param string|object $class The class or object that should manage the provider
@param array $params Custom parameters that should be sent in the url for this Provider
@return void | [
"Adds",
"a",
"new",
"Provider",
"into",
"the",
"service",
"map"
] | train | https://github.com/mpratt/Embera/blob/84df7a11426c017f1aae493a5994babddffac571/Lib/Embera/Providers.php#L233-L238 |
mpratt/Embera | Lib/Embera/Providers.php | Providers.getHost | protected function getHost($url)
{
$data = parse_url($url);
if (empty($data['host'])) {
throw new \InvalidArgumentException('The Url: ' . $url . ' seems to be invalid');
}
$host = preg_replace('~^(?:www|player)\.~i', '', strtolower($data['host']));
if (isset($this->services[$host])) {
return $host;
} else if (isset($this->services['*.' . $host])) {
return '*.' . $host;
} else if (!empty($this->wildCardHosts)) {
$trans = array('\*' => '(?:.*)');
foreach ($this->wildCardHosts as $value) {
$regex = strtr(preg_quote($value, '~'), $trans);
if (preg_match('~' . $regex . '~i', $host)) {
return $value;
}
}
}
return $host;
} | php | protected function getHost($url)
{
$data = parse_url($url);
if (empty($data['host'])) {
throw new \InvalidArgumentException('The Url: ' . $url . ' seems to be invalid');
}
$host = preg_replace('~^(?:www|player)\.~i', '', strtolower($data['host']));
if (isset($this->services[$host])) {
return $host;
} else if (isset($this->services['*.' . $host])) {
return '*.' . $host;
} else if (!empty($this->wildCardHosts)) {
$trans = array('\*' => '(?:.*)');
foreach ($this->wildCardHosts as $value) {
$regex = strtr(preg_quote($value, '~'), $trans);
if (preg_match('~' . $regex . '~i', $host)) {
return $value;
}
}
}
return $host;
} | [
"protected",
"function",
"getHost",
"(",
"$",
"url",
")",
"{",
"$",
"data",
"=",
"parse_url",
"(",
"$",
"url",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"data",
"[",
"'host'",
"]",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
... | Gets a normalized host for the given $url
@param string $url
@return string
@throws InvalidArgumentException when the url seems to be invalid | [
"Gets",
"a",
"normalized",
"host",
"for",
"the",
"given",
"$url"
] | train | https://github.com/mpratt/Embera/blob/84df7a11426c017f1aae493a5994babddffac571/Lib/Embera/Providers.php#L248-L271 |
mpratt/Embera | Lib/Embera/Providers.php | Providers.extractCustomParams | protected function extractCustomParams(array $params = array())
{
foreach ($params as $name => $values) {
foreach ($this->services as $host => $service) {
if (preg_match('~' . preg_quote($name, '~') . '~i', $service)) {
$this->customParams[$host] = (array) $values;
}
}
}
} | php | protected function extractCustomParams(array $params = array())
{
foreach ($params as $name => $values) {
foreach ($this->services as $host => $service) {
if (preg_match('~' . preg_quote($name, '~') . '~i', $service)) {
$this->customParams[$host] = (array) $values;
}
}
}
} | [
"protected",
"function",
"extractCustomParams",
"(",
"array",
"$",
"params",
"=",
"array",
"(",
")",
")",
"{",
"foreach",
"(",
"$",
"params",
"as",
"$",
"name",
"=>",
"$",
"values",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"services",
"as",
"$",
... | Extracts custom parameters for a Provider
@param array $params
@return array | [
"Extracts",
"custom",
"parameters",
"for",
"a",
"Provider"
] | train | https://github.com/mpratt/Embera/blob/84df7a11426c017f1aae493a5994babddffac571/Lib/Embera/Providers.php#L279-L288 |
mpratt/Embera | Lib/Embera/Providers.php | Providers.getAll | public function getAll($urls)
{
$this->wildCardHosts = array_filter(array_keys($this->services), function($key) {
return (strpos($key, '*') !== false);
});
return $this->findServices((array) $urls);
} | php | public function getAll($urls)
{
$this->wildCardHosts = array_filter(array_keys($this->services), function($key) {
return (strpos($key, '*') !== false);
});
return $this->findServices((array) $urls);
} | [
"public",
"function",
"getAll",
"(",
"$",
"urls",
")",
"{",
"$",
"this",
"->",
"wildCardHosts",
"=",
"array_filter",
"(",
"array_keys",
"(",
"$",
"this",
"->",
"services",
")",
",",
"function",
"(",
"$",
"key",
")",
"{",
"return",
"(",
"strpos",
"(",
... | Returns an array with all valid services found.
@param array|string $urls An array with urls or a url string
@return array | [
"Returns",
"an",
"array",
"with",
"all",
"valid",
"services",
"found",
"."
] | train | https://github.com/mpratt/Embera/blob/84df7a11426c017f1aae493a5994babddffac571/Lib/Embera/Providers.php#L296-L303 |
mpratt/Embera | Lib/Embera/Providers/CollegeHumor.php | CollegeHumor.modifyResponse | protected function modifyResponse(array $response = array())
{
if (!empty($response['html'])) {
$spam = array('~<p>(?:.*)</p>~i', '~<div (?:.*)</div>~i');
$response['html'] = preg_replace($spam, '', $response['html']);
}
return $response;
} | php | protected function modifyResponse(array $response = array())
{
if (!empty($response['html'])) {
$spam = array('~<p>(?:.*)</p>~i', '~<div (?:.*)</div>~i');
$response['html'] = preg_replace($spam, '', $response['html']);
}
return $response;
} | [
"protected",
"function",
"modifyResponse",
"(",
"array",
"$",
"response",
"=",
"array",
"(",
")",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"response",
"[",
"'html'",
"]",
")",
")",
"{",
"$",
"spam",
"=",
"array",
"(",
"'~<p>(?:.*)</p>~i'",
",",
"... | inline {@inheritdoc} | [
"inline",
"{"
] | train | https://github.com/mpratt/Embera/blob/84df7a11426c017f1aae493a5994babddffac571/Lib/Embera/Providers/CollegeHumor.php#L32-L40 |
mpratt/Embera | Lib/Embera/Providers/Scribd.php | Scribd.modifyResponse | protected function modifyResponse(array $response = array())
{
if (!empty($response['html']))
{
$response['html'] = str_replace('#{root_url}', 'https://www.scribd.com/', $response['html']);
$response['html'] = preg_replace('~\s+~i', ' ', $response['html']); // Remove double spaces
}
return $response;
} | php | protected function modifyResponse(array $response = array())
{
if (!empty($response['html']))
{
$response['html'] = str_replace('#{root_url}', 'https://www.scribd.com/', $response['html']);
$response['html'] = preg_replace('~\s+~i', ' ', $response['html']); // Remove double spaces
}
return $response;
} | [
"protected",
"function",
"modifyResponse",
"(",
"array",
"$",
"response",
"=",
"array",
"(",
")",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"response",
"[",
"'html'",
"]",
")",
")",
"{",
"$",
"response",
"[",
"'html'",
"]",
"=",
"str_replace",
"("... | inline {@inheritdoc} | [
"inline",
"{"
] | train | https://github.com/mpratt/Embera/blob/84df7a11426c017f1aae493a5994babddffac571/Lib/Embera/Providers/Scribd.php#L33-L42 |
mpratt/Embera | Lib/Embera/Formatter.php | Formatter.setTemplate | public function setTemplate($template, $body = null)
{
$this->template = $template;
if (!is_null($body)) {
return $this->transform($body);
}
return '';
} | php | public function setTemplate($template, $body = null)
{
$this->template = $template;
if (!is_null($body)) {
return $this->transform($body);
}
return '';
} | [
"public",
"function",
"setTemplate",
"(",
"$",
"template",
",",
"$",
"body",
"=",
"null",
")",
"{",
"$",
"this",
"->",
"template",
"=",
"$",
"template",
";",
"if",
"(",
"!",
"is_null",
"(",
"$",
"body",
")",
")",
"{",
"return",
"$",
"this",
"->",
... | Sets a template with placeholders, that should be
replaced by the data from an oembed response.
@param string $template
@param string|array $body An array or string with Urls
@return string | [
"Sets",
"a",
"template",
"with",
"placeholders",
"that",
"should",
"be",
"replaced",
"by",
"the",
"data",
"from",
"an",
"oembed",
"response",
"."
] | train | https://github.com/mpratt/Embera/blob/84df7a11426c017f1aae493a5994babddffac571/Lib/Embera/Formatter.php#L55-L64 |
mpratt/Embera | Lib/Embera/Formatter.php | Formatter.transform | public function transform($body = null)
{
$providers = array();
if ($urls = $this->embera->getUrlInfo($body)) {
foreach ($urls as $url => $data) {
if (!$this->allowOffline && (int) $data['embera_using_fake'] === 1) {
$this->errors[] = 'Using fake oembed response on ' . $url;
continue;
}
$providers[$url] = $this->replace($data, $this->template);
}
}
if (is_array($body)) {
$return = implode('', $providers);
} else {
$return = str_replace(array_keys($providers), array_values($providers), $body);
}
// Remove unchanged placeholders
return preg_replace('~{([\w\d\-_]+)}~i', '', $return);
} | php | public function transform($body = null)
{
$providers = array();
if ($urls = $this->embera->getUrlInfo($body)) {
foreach ($urls as $url => $data) {
if (!$this->allowOffline && (int) $data['embera_using_fake'] === 1) {
$this->errors[] = 'Using fake oembed response on ' . $url;
continue;
}
$providers[$url] = $this->replace($data, $this->template);
}
}
if (is_array($body)) {
$return = implode('', $providers);
} else {
$return = str_replace(array_keys($providers), array_values($providers), $body);
}
// Remove unchanged placeholders
return preg_replace('~{([\w\d\-_]+)}~i', '', $return);
} | [
"public",
"function",
"transform",
"(",
"$",
"body",
"=",
"null",
")",
"{",
"$",
"providers",
"=",
"array",
"(",
")",
";",
"if",
"(",
"$",
"urls",
"=",
"$",
"this",
"->",
"embera",
"->",
"getUrlInfo",
"(",
"$",
"body",
")",
")",
"{",
"foreach",
"... | This method transforms an array or a string with urls
into another string using a specified template.
@param string|array $body An array or string with Urls
@return string | [
"This",
"method",
"transforms",
"an",
"array",
"or",
"a",
"string",
"with",
"urls",
"into",
"another",
"string",
"using",
"a",
"specified",
"template",
"."
] | train | https://github.com/mpratt/Embera/blob/84df7a11426c017f1aae493a5994babddffac571/Lib/Embera/Formatter.php#L73-L96 |
mpratt/Embera | Lib/Embera/Formatter.php | Formatter.replace | protected function replace(array $data, $template, $prefix = null)
{
foreach ($data as $k => $d) {
if (is_array($d)) {
return $this->replace($d, $template, $k . '.');
} else {
$template = str_replace('{' . (!empty($prefix) ? $prefix . $k : $k) . '}', $d, $template);
}
}
return $template;
} | php | protected function replace(array $data, $template, $prefix = null)
{
foreach ($data as $k => $d) {
if (is_array($d)) {
return $this->replace($d, $template, $k . '.');
} else {
$template = str_replace('{' . (!empty($prefix) ? $prefix . $k : $k) . '}', $d, $template);
}
}
return $template;
} | [
"protected",
"function",
"replace",
"(",
"array",
"$",
"data",
",",
"$",
"template",
",",
"$",
"prefix",
"=",
"null",
")",
"{",
"foreach",
"(",
"$",
"data",
"as",
"$",
"k",
"=>",
"$",
"d",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"d",
")",
")... | Replaces the given $data inside the $template
@param array $data
@param string $template
@param string $prefix
@return string | [
"Replaces",
"the",
"given",
"$data",
"inside",
"the",
"$template"
] | train | https://github.com/mpratt/Embera/blob/84df7a11426c017f1aae493a5994babddffac571/Lib/Embera/Formatter.php#L106-L117 |
mpratt/Embera | Lib/Embera/Providers/AolOn.php | AolOn.modifyResponse | protected function modifyResponse(array $response = array())
{
if (!empty($response['html']))
{
$replace = array('<![CDATA[' => '', ']]>' => '', '\'' => '"');
$response['html'] = str_ireplace(array_keys($replace), array_values($replace), $response['html']);
}
return $response;
} | php | protected function modifyResponse(array $response = array())
{
if (!empty($response['html']))
{
$replace = array('<![CDATA[' => '', ']]>' => '', '\'' => '"');
$response['html'] = str_ireplace(array_keys($replace), array_values($replace), $response['html']);
}
return $response;
} | [
"protected",
"function",
"modifyResponse",
"(",
"array",
"$",
"response",
"=",
"array",
"(",
")",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"response",
"[",
"'html'",
"]",
")",
")",
"{",
"$",
"replace",
"=",
"array",
"(",
"'<![CDATA['",
"=>",
"''"... | inline {@inheritdoc} | [
"inline",
"{"
] | train | https://github.com/mpratt/Embera/blob/84df7a11426c017f1aae493a5994babddffac571/Lib/Embera/Providers/AolOn.php#L42-L51 |
mpratt/Embera | Lib/Embera/Providers/GithubGist.php | GithubGist.modifyResponse | protected function modifyResponse(array $response = array())
{
$this->url->discardChanges();
if (preg_match('~github\.com/([^/]+)/([a-z0-9]+)~i', $this->url, $matches))
$response['html'] = '<script type="text/javascript" src="https://gist.github.com/' . $matches['1'] . '/' . $matches['2'] . '.js"></script>';
return $response;
} | php | protected function modifyResponse(array $response = array())
{
$this->url->discardChanges();
if (preg_match('~github\.com/([^/]+)/([a-z0-9]+)~i', $this->url, $matches))
$response['html'] = '<script type="text/javascript" src="https://gist.github.com/' . $matches['1'] . '/' . $matches['2'] . '.js"></script>';
return $response;
} | [
"protected",
"function",
"modifyResponse",
"(",
"array",
"$",
"response",
"=",
"array",
"(",
")",
")",
"{",
"$",
"this",
"->",
"url",
"->",
"discardChanges",
"(",
")",
";",
"if",
"(",
"preg_match",
"(",
"'~github\\.com/([^/]+)/([a-z0-9]+)~i'",
",",
"$",
"thi... | inline {@inheritdoc} | [
"inline",
"{"
] | train | https://github.com/mpratt/Embera/blob/84df7a11426c017f1aae493a5994babddffac571/Lib/Embera/Providers/GithubGist.php#L41-L48 |
mpratt/Embera | Lib/Embera/Providers/GithubGist.php | GithubGist.fakeResponse | public function fakeResponse()
{
$this->url->discardChanges();
if (preg_match('~github\.com/([^/]+)/([a-z0-9]+)~i', $this->url, $matches))
{
return array(
'type' => 'rich',
'provider_name' => 'GitHub',
'provider_url' => 'https://github.com',
'html' => '<script type="text/javascript" src="https://gist.github.com/' . $matches['1'] . '/' . $matches['2'] . '.js"></script>',
'title' => 'gist:' . $matches['2']
);
}
return array();
} | php | public function fakeResponse()
{
$this->url->discardChanges();
if (preg_match('~github\.com/([^/]+)/([a-z0-9]+)~i', $this->url, $matches))
{
return array(
'type' => 'rich',
'provider_name' => 'GitHub',
'provider_url' => 'https://github.com',
'html' => '<script type="text/javascript" src="https://gist.github.com/' . $matches['1'] . '/' . $matches['2'] . '.js"></script>',
'title' => 'gist:' . $matches['2']
);
}
return array();
} | [
"public",
"function",
"fakeResponse",
"(",
")",
"{",
"$",
"this",
"->",
"url",
"->",
"discardChanges",
"(",
")",
";",
"if",
"(",
"preg_match",
"(",
"'~github\\.com/([^/]+)/([a-z0-9]+)~i'",
",",
"$",
"this",
"->",
"url",
",",
"$",
"matches",
")",
")",
"{",
... | inline {@inheritdoc} | [
"inline",
"{"
] | train | https://github.com/mpratt/Embera/blob/84df7a11426c017f1aae493a5994babddffac571/Lib/Embera/Providers/GithubGist.php#L51-L66 |
mpratt/Embera | Lib/Embera/HtmlProcessor.php | HtmlProcessor.process | public function process($content)
{
foreach ($this->tags as $t) {
$content = $this->reserveTag($content, $t);
}
$content = strtr($content, $this->replacementTable);
return $this->restoreHolders($content);
} | php | public function process($content)
{
foreach ($this->tags as $t) {
$content = $this->reserveTag($content, $t);
}
$content = strtr($content, $this->replacementTable);
return $this->restoreHolders($content);
} | [
"public",
"function",
"process",
"(",
"$",
"content",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"tags",
"as",
"$",
"t",
")",
"{",
"$",
"content",
"=",
"$",
"this",
"->",
"reserveTag",
"(",
"$",
"content",
",",
"$",
"t",
")",
";",
"}",
"$",
"... | Process the content and does the replacements
@param string $content
@return string | [
"Process",
"the",
"content",
"and",
"does",
"the",
"replacements"
] | train | https://github.com/mpratt/Embera/blob/84df7a11426c017f1aae493a5994babddffac571/Lib/Embera/HtmlProcessor.php#L50-L58 |
mpratt/Embera | Lib/Embera/HtmlProcessor.php | HtmlProcessor.reserveTag | protected function reserveTag($content, $tag)
{
if (stripos($content, '<' . $tag) !== false) {
if (in_array(strtolower($tag), array('img'))) {
$pattern = '~(<' . preg_quote($tag, '~') . '[^>]+\>)~i';
} else {
$pattern = '~(<' . preg_quote($tag, '~') . '\\b[^>]*?>[\\s\\S]*?<\\/' . preg_quote($tag, '~') . '>)~i';
}
return preg_replace_callback($pattern, array($this, 'placeHolder'), $content);
}
return $content;
} | php | protected function reserveTag($content, $tag)
{
if (stripos($content, '<' . $tag) !== false) {
if (in_array(strtolower($tag), array('img'))) {
$pattern = '~(<' . preg_quote($tag, '~') . '[^>]+\>)~i';
} else {
$pattern = '~(<' . preg_quote($tag, '~') . '\\b[^>]*?>[\\s\\S]*?<\\/' . preg_quote($tag, '~') . '>)~i';
}
return preg_replace_callback($pattern, array($this, 'placeHolder'), $content);
}
return $content;
} | [
"protected",
"function",
"reserveTag",
"(",
"$",
"content",
",",
"$",
"tag",
")",
"{",
"if",
"(",
"stripos",
"(",
"$",
"content",
",",
"'<'",
".",
"$",
"tag",
")",
"!==",
"false",
")",
"{",
"if",
"(",
"in_array",
"(",
"strtolower",
"(",
"$",
"tag",... | Reserves a tag, which in this case, all it does is replace the html tag
with a placeholder.
@param string $content
@param string $tag
@return string | [
"Reserves",
"a",
"tag",
"which",
"in",
"this",
"case",
"all",
"it",
"does",
"is",
"replace",
"the",
"html",
"tag",
"with",
"a",
"placeholder",
"."
] | train | https://github.com/mpratt/Embera/blob/84df7a11426c017f1aae493a5994babddffac571/Lib/Embera/HtmlProcessor.php#L68-L82 |
mpratt/Embera | Lib/Embera/HtmlProcessor.php | HtmlProcessor.placeHolder | protected function placeHolder(array $matches)
{
$placeholder = '%{{' . md5(time() . count($this->holder) . mt_rand(0, 500)) . '}}%';
$this->holder[$placeholder] = $matches['1'];
return $placeholder;
} | php | protected function placeHolder(array $matches)
{
$placeholder = '%{{' . md5(time() . count($this->holder) . mt_rand(0, 500)) . '}}%';
$this->holder[$placeholder] = $matches['1'];
return $placeholder;
} | [
"protected",
"function",
"placeHolder",
"(",
"array",
"$",
"matches",
")",
"{",
"$",
"placeholder",
"=",
"'%{{'",
".",
"md5",
"(",
"time",
"(",
")",
".",
"count",
"(",
"$",
"this",
"->",
"holder",
")",
".",
"mt_rand",
"(",
"0",
",",
"500",
")",
")"... | Assigns a placeholder to the matched content. Its used by preg_replace_callback
@param array $matches
@return string | [
"Assigns",
"a",
"placeholder",
"to",
"the",
"matched",
"content",
".",
"Its",
"used",
"by",
"preg_replace_callback"
] | train | https://github.com/mpratt/Embera/blob/84df7a11426c017f1aae493a5994babddffac571/Lib/Embera/HtmlProcessor.php#L90-L96 |
mpratt/Embera | Lib/Embera/HtmlProcessor.php | HtmlProcessor.restoreHolders | protected function restoreHolders($content)
{
if (!empty($this->holder)) {
/**
* Now the question that you might be asking yourself is, why use a 'for' loop instead
* of the plain 'str_replace' function once?
*
* Well, since html can be nested, there might be cases were a placeholder was placed inside
* another placeholder and if we do just one 'str_replace', we might not get the full original
* content.
*
* In order to ensure that no data is lost, we need to run 'str_replace' for each time a tag
* was registered in the constructor. That is the worst case scenario, most of the times, the loop
* is just going to run once and repeat the cycle only if there are signs that another placeholder is in
* the content.
*/
$count = count($this->tags) + 1;
for ($i=0; $i < $count; $i++) {
$content = str_replace(array_keys($this->holder), array_values($this->holder), $content);
if (strpos($content, '%{{') === false) {
break;
}
}
}
return $content;
} | php | protected function restoreHolders($content)
{
if (!empty($this->holder)) {
/**
* Now the question that you might be asking yourself is, why use a 'for' loop instead
* of the plain 'str_replace' function once?
*
* Well, since html can be nested, there might be cases were a placeholder was placed inside
* another placeholder and if we do just one 'str_replace', we might not get the full original
* content.
*
* In order to ensure that no data is lost, we need to run 'str_replace' for each time a tag
* was registered in the constructor. That is the worst case scenario, most of the times, the loop
* is just going to run once and repeat the cycle only if there are signs that another placeholder is in
* the content.
*/
$count = count($this->tags) + 1;
for ($i=0; $i < $count; $i++) {
$content = str_replace(array_keys($this->holder), array_values($this->holder), $content);
if (strpos($content, '%{{') === false) {
break;
}
}
}
return $content;
} | [
"protected",
"function",
"restoreHolders",
"(",
"$",
"content",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"this",
"->",
"holder",
")",
")",
"{",
"/**\n * Now the question that you might be asking yourself is, why use a 'for' loop instead\n * of the ... | Restores all the dummy placeholders with the original content
@param string $content
@return string | [
"Restores",
"all",
"the",
"dummy",
"placeholders",
"with",
"the",
"original",
"content"
] | train | https://github.com/mpratt/Embera/blob/84df7a11426c017f1aae493a5994babddffac571/Lib/Embera/HtmlProcessor.php#L104-L132 |
mpratt/Embera | Lib/Embera/Providers/Facebook.php | Facebook.validateUrl | protected function validateUrl()
{
$this->url->convertToHttps();
return ($this->urlMatchesPattern(array_merge($this->postPatterns, $this->videoPatterns, $this->pagePatterns)));
} | php | protected function validateUrl()
{
$this->url->convertToHttps();
return ($this->urlMatchesPattern(array_merge($this->postPatterns, $this->videoPatterns, $this->pagePatterns)));
} | [
"protected",
"function",
"validateUrl",
"(",
")",
"{",
"$",
"this",
"->",
"url",
"->",
"convertToHttps",
"(",
")",
";",
"return",
"(",
"$",
"this",
"->",
"urlMatchesPattern",
"(",
"array_merge",
"(",
"$",
"this",
"->",
"postPatterns",
",",
"$",
"this",
"... | inline {@inheritdoc} | [
"inline",
"{"
] | train | https://github.com/mpratt/Embera/blob/84df7a11426c017f1aae493a5994babddffac571/Lib/Embera/Providers/Facebook.php#L94-L98 |
mpratt/Embera | Lib/Embera/Providers/Facebook.php | Facebook.urlMatchesPattern | protected function urlMatchesPattern(array $patternList)
{
foreach ($patternList as $p) {
if (preg_match($p, $this->url)) {
return true;
}
}
return false;
} | php | protected function urlMatchesPattern(array $patternList)
{
foreach ($patternList as $p) {
if (preg_match($p, $this->url)) {
return true;
}
}
return false;
} | [
"protected",
"function",
"urlMatchesPattern",
"(",
"array",
"$",
"patternList",
")",
"{",
"foreach",
"(",
"$",
"patternList",
"as",
"$",
"p",
")",
"{",
"if",
"(",
"preg_match",
"(",
"$",
"p",
",",
"$",
"this",
"->",
"url",
")",
")",
"{",
"return",
"t... | Checks if $this->url matches the given list of patterns
@param array $patternList Array with regex
@return bool | [
"Checks",
"if",
"$this",
"-",
">",
"url",
"matches",
"the",
"given",
"list",
"of",
"patterns"
] | train | https://github.com/mpratt/Embera/blob/84df7a11426c017f1aae493a5994babddffac571/Lib/Embera/Providers/Facebook.php#L106-L115 |
mpratt/Embera | Lib/Embera/Providers/Facebook.php | Facebook.getInfo | public function getInfo()
{
if ($this->urlMatchesPattern($this->videoPatterns)) {
$this->apiUrl = 'https://www.facebook.com/plugins/video/oembed.json/';
} elseif ($this->urlMatchesPattern($this->postPatterns)) {
$this->apiUrl = 'https://www.facebook.com/plugins/post/oembed.json/';
} else {
$this->apiUrl = 'https://www.facebook.com/plugins/page/oembed.json/';
}
return parent::getInfo();
} | php | public function getInfo()
{
if ($this->urlMatchesPattern($this->videoPatterns)) {
$this->apiUrl = 'https://www.facebook.com/plugins/video/oembed.json/';
} elseif ($this->urlMatchesPattern($this->postPatterns)) {
$this->apiUrl = 'https://www.facebook.com/plugins/post/oembed.json/';
} else {
$this->apiUrl = 'https://www.facebook.com/plugins/page/oembed.json/';
}
return parent::getInfo();
} | [
"public",
"function",
"getInfo",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"urlMatchesPattern",
"(",
"$",
"this",
"->",
"videoPatterns",
")",
")",
"{",
"$",
"this",
"->",
"apiUrl",
"=",
"'https://www.facebook.com/plugins/video/oembed.json/'",
";",
"}",
"els... | inline {@inheritdoc}
Im overriding this method because I need to set the
endpoint based on the given url. By default we're always assuming
it is a post url unless we have a specific video match.
Why? Because we already did url validation and We dont want
to loop over both sets of patterns all over again right? So
we just need to loop over the smaller one ;) | [
"inline",
"{",
"@inheritdoc",
"}"
] | train | https://github.com/mpratt/Embera/blob/84df7a11426c017f1aae493a5994babddffac571/Lib/Embera/Providers/Facebook.php#L128-L139 |
mpratt/Embera | Lib/Embera/Providers/Facebook.php | Facebook.modifyResponse | protected function modifyResponse(array $response = array())
{
if (!empty($response['html'])) {
$iframe = '<iframe id="embera-iframe-{md5}" class="embera-facebook-iframe" src="https://www.facebook.com/plugins/post.php?href={url}&width={width}&height={height}&show_text=true&appId" width="{width}" height="{height}"" style="border:none;overflow:hidden" scrolling="no" frameborder="0" allowTransparency="true"></iframe>';
if (!empty($response['height'])) {
$height = $response['height'];
} else {
$height = min(680, (int) ($response['width'] + 100));
}
$table = array(
'{url}' => rawurlencode($this->url),
'{md5}' => substr(md5($this->url), 0, 5),
'{width}' => $response['width'],
'{height}' => $height,
);
// Backup the real response
$response['raw']['html'] = $response['html'];
// Replace the html response
$response['html'] = str_replace(array_keys($table), array_values($table), $iframe);
}
return $response;
} | php | protected function modifyResponse(array $response = array())
{
if (!empty($response['html'])) {
$iframe = '<iframe id="embera-iframe-{md5}" class="embera-facebook-iframe" src="https://www.facebook.com/plugins/post.php?href={url}&width={width}&height={height}&show_text=true&appId" width="{width}" height="{height}"" style="border:none;overflow:hidden" scrolling="no" frameborder="0" allowTransparency="true"></iframe>';
if (!empty($response['height'])) {
$height = $response['height'];
} else {
$height = min(680, (int) ($response['width'] + 100));
}
$table = array(
'{url}' => rawurlencode($this->url),
'{md5}' => substr(md5($this->url), 0, 5),
'{width}' => $response['width'],
'{height}' => $height,
);
// Backup the real response
$response['raw']['html'] = $response['html'];
// Replace the html response
$response['html'] = str_replace(array_keys($table), array_values($table), $iframe);
}
return $response;
} | [
"protected",
"function",
"modifyResponse",
"(",
"array",
"$",
"response",
"=",
"array",
"(",
")",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"response",
"[",
"'html'",
"]",
")",
")",
"{",
"$",
"iframe",
"=",
"'<iframe id=\"embera-iframe-{md5}\" class=\"emb... | inline {@inheritdoc}
Need to modify the html response, to use the iframe instead.
The html returned by facebook always adds the javascript code
and the famous <div id="fb-root"></div>.
When embedding multiple links, the code seems to conflict and doesnt
embed properly | [
"inline",
"{",
"@inheritdoc",
"}"
] | train | https://github.com/mpratt/Embera/blob/84df7a11426c017f1aae493a5994babddffac571/Lib/Embera/Providers/Facebook.php#L151-L172 |
mpratt/Embera | Lib/Embera/Providers/Dipity.php | Dipity.fakeResponse | public function fakeResponse()
{
$this->url->stripLastSlash();
$title = preg_replace('~^(.*)/~', '', $this->url);
$title = str_replace('-', ' ', $title);
$html = '<div class="dipity_embed" style="width:{width}px; margin:0; padding:0;">';
$html .= '<iframe width="{width}" height="{height}" src="' . (string) $this->url . '/?mode=embed&skin=true_mono&z=0#tl" style="border:1px solid #CCC;"></iframe>';
$html .= '<p style="margin:0;font-family:Arial,sans;font-size:13px;text-align:center"><a href="' . (string) $this->url . '/">' . $title . '</a> on <a href="http://www.dipity.com/">Dipity</a>.</p>';
$html .= '</div>';
return array(
'type' => 'rich',
'provider_name' => 'Dipity',
'provider_url' => 'http://www.dipity.com',
'html' => $html,
);
} | php | public function fakeResponse()
{
$this->url->stripLastSlash();
$title = preg_replace('~^(.*)/~', '', $this->url);
$title = str_replace('-', ' ', $title);
$html = '<div class="dipity_embed" style="width:{width}px; margin:0; padding:0;">';
$html .= '<iframe width="{width}" height="{height}" src="' . (string) $this->url . '/?mode=embed&skin=true_mono&z=0#tl" style="border:1px solid #CCC;"></iframe>';
$html .= '<p style="margin:0;font-family:Arial,sans;font-size:13px;text-align:center"><a href="' . (string) $this->url . '/">' . $title . '</a> on <a href="http://www.dipity.com/">Dipity</a>.</p>';
$html .= '</div>';
return array(
'type' => 'rich',
'provider_name' => 'Dipity',
'provider_url' => 'http://www.dipity.com',
'html' => $html,
);
} | [
"public",
"function",
"fakeResponse",
"(",
")",
"{",
"$",
"this",
"->",
"url",
"->",
"stripLastSlash",
"(",
")",
";",
"$",
"title",
"=",
"preg_replace",
"(",
"'~^(.*)/~'",
",",
"''",
",",
"$",
"this",
"->",
"url",
")",
";",
"$",
"title",
"=",
"str_re... | inline {@inheritdoc} | [
"inline",
"{"
] | train | https://github.com/mpratt/Embera/blob/84df7a11426c017f1aae493a5994babddffac571/Lib/Embera/Providers/Dipity.php#L33-L50 |
mpratt/Embera | Lib/Embera/Providers/IFTTT.php | IFTTT.fakeResponse | public function fakeResponse()
{
preg_match('~/([0-9]+)/?$~i', $this->url, $matches);
$html = '<a href="https://ifttt.com/view_embed_recipe/' . $matches['1'] . '" target="_blank" class="embed_recipe embed_recipe-l_28" id= "embed_recipe-' . $matches['1'] . '"><img src="https://ifttt.com/recipe_embed_img/' . $matches['1'] . '" alt="" width="{width}px"/></a>';
$html .= '<script async type="text/javascript" src= "//ifttt.com/assets/embed_recipe.js"></script>';
return array(
'type' => 'rich',
'provider_name' => 'IFTTT',
'provider_url' => 'https://ifttt.com',
'html' => $html
);
} | php | public function fakeResponse()
{
preg_match('~/([0-9]+)/?$~i', $this->url, $matches);
$html = '<a href="https://ifttt.com/view_embed_recipe/' . $matches['1'] . '" target="_blank" class="embed_recipe embed_recipe-l_28" id= "embed_recipe-' . $matches['1'] . '"><img src="https://ifttt.com/recipe_embed_img/' . $matches['1'] . '" alt="" width="{width}px"/></a>';
$html .= '<script async type="text/javascript" src= "//ifttt.com/assets/embed_recipe.js"></script>';
return array(
'type' => 'rich',
'provider_name' => 'IFTTT',
'provider_url' => 'https://ifttt.com',
'html' => $html
);
} | [
"public",
"function",
"fakeResponse",
"(",
")",
"{",
"preg_match",
"(",
"'~/([0-9]+)/?$~i'",
",",
"$",
"this",
"->",
"url",
",",
"$",
"matches",
")",
";",
"$",
"html",
"=",
"'<a href=\"https://ifttt.com/view_embed_recipe/'",
".",
"$",
"matches",
"[",
"'1'",
"]... | inline {@inheritdoc} | [
"inline",
"{"
] | train | https://github.com/mpratt/Embera/blob/84df7a11426c017f1aae493a5994babddffac571/Lib/Embera/Providers/IFTTT.php#L33-L44 |
mpratt/Embera | Lib/Embera/Providers/Instagram.php | Instagram.modifyResponse | protected function modifyResponse(array $response = array())
{
if (empty($response['html']) && !empty($response['url'])) {
$extension = strtolower(pathinfo(parse_url($response['url'],PHP_URL_PATH),PATHINFO_EXTENSION));
if (in_array($extension, array('jpg', 'jpeg', 'png', 'gif'))) {
$html = '<a href="' . $response['url'] . '" target="_blank">';
$html .= '<img class="instagram-oembed" src="' . $response['url'] . '" width="' . $response['width'] . '" height="' . $response['height'] . '" alt="' . htmlspecialchars($response['title'], ENT_QUOTES, 'UTF-8') . '" title="' . htmlspecialchars($response['title'], ENT_QUOTES, 'UTF-8') . '">';
$html .= '</a>';
$response['html'] = $html;
}
}
return $response;
} | php | protected function modifyResponse(array $response = array())
{
if (empty($response['html']) && !empty($response['url'])) {
$extension = strtolower(pathinfo(parse_url($response['url'],PHP_URL_PATH),PATHINFO_EXTENSION));
if (in_array($extension, array('jpg', 'jpeg', 'png', 'gif'))) {
$html = '<a href="' . $response['url'] . '" target="_blank">';
$html .= '<img class="instagram-oembed" src="' . $response['url'] . '" width="' . $response['width'] . '" height="' . $response['height'] . '" alt="' . htmlspecialchars($response['title'], ENT_QUOTES, 'UTF-8') . '" title="' . htmlspecialchars($response['title'], ENT_QUOTES, 'UTF-8') . '">';
$html .= '</a>';
$response['html'] = $html;
}
}
return $response;
} | [
"protected",
"function",
"modifyResponse",
"(",
"array",
"$",
"response",
"=",
"array",
"(",
")",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"response",
"[",
"'html'",
"]",
")",
"&&",
"!",
"empty",
"(",
"$",
"response",
"[",
"'url'",
"]",
")",
")",
"{... | inline {@inheritdoc} | [
"inline",
"{"
] | train | https://github.com/mpratt/Embera/blob/84df7a11426c017f1aae493a5994babddffac571/Lib/Embera/Providers/Instagram.php#L32-L45 |
mpratt/Embera | Lib/Embera/Providers/Bambuser.php | Bambuser.normalizeUrl | public function normalizeUrl()
{
if (preg_match('~bambuser\.com/channel/(?:[^/]+)/broadcast/([0-9]+)~i', $this->url, $matches)) {
$this->url = new \Embera\Url('http://bambuser.com/v/' . $matches['1']);
}
} | php | public function normalizeUrl()
{
if (preg_match('~bambuser\.com/channel/(?:[^/]+)/broadcast/([0-9]+)~i', $this->url, $matches)) {
$this->url = new \Embera\Url('http://bambuser.com/v/' . $matches['1']);
}
} | [
"public",
"function",
"normalizeUrl",
"(",
")",
"{",
"if",
"(",
"preg_match",
"(",
"'~bambuser\\.com/channel/(?:[^/]+)/broadcast/([0-9]+)~i'",
",",
"$",
"this",
"->",
"url",
",",
"$",
"matches",
")",
")",
"{",
"$",
"this",
"->",
"url",
"=",
"new",
"\\",
"Emb... | inline {@inheritdoc} | [
"inline",
"{"
] | train | https://github.com/mpratt/Embera/blob/84df7a11426c017f1aae493a5994babddffac571/Lib/Embera/Providers/Bambuser.php#L37-L42 |
mpratt/Embera | Lib/Embera/Providers/Bambuser.php | Bambuser.fakeResponse | public function fakeResponse()
{
$defaults = array(
'type' => 'video',
'provider_name' => 'Bambuser.com',
'provider_url' => 'http://bambuser.com',
);
$html = '<object id="bplayer" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="{width}" height="{height}">';
$html .= '<embed allowfullscreen="true" allowscriptaccess="always" wmode="transparent" type="application/x-shockwave-flash" name="bplayer" src="https://static.bambuser.com/r/player.swf?{query}&context=oembed" width="{width}" height="{height}" />';
$html .= '<param name="movie" value="https://static.bambuser.com/r/player.swf?context=oembed&{query}" />';
$html .= '<param name="allowfullscreen" value="true" />';
$html .= '<param name="allowscriptaccess" value="always" />';
$html .= '<param name="wmode" value="transparent" />';
$html .= '</object>';
if (preg_match('~/v/([0-9]+)$~i', $this->url, $matches)) {
return array_merge(
$defaults,
array('html' => str_replace('{query}', 'vid=' . $matches['1'], $html))
);
}
else if (preg_match('~/channel/([^/]+)~i', $this->url, $matches))
{
return array_merge(
$defaults,
array('html' => str_replace('{query}', 'username=' . urlencode($matches['1']), $html))
);
}
return array();
} | php | public function fakeResponse()
{
$defaults = array(
'type' => 'video',
'provider_name' => 'Bambuser.com',
'provider_url' => 'http://bambuser.com',
);
$html = '<object id="bplayer" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="{width}" height="{height}">';
$html .= '<embed allowfullscreen="true" allowscriptaccess="always" wmode="transparent" type="application/x-shockwave-flash" name="bplayer" src="https://static.bambuser.com/r/player.swf?{query}&context=oembed" width="{width}" height="{height}" />';
$html .= '<param name="movie" value="https://static.bambuser.com/r/player.swf?context=oembed&{query}" />';
$html .= '<param name="allowfullscreen" value="true" />';
$html .= '<param name="allowscriptaccess" value="always" />';
$html .= '<param name="wmode" value="transparent" />';
$html .= '</object>';
if (preg_match('~/v/([0-9]+)$~i', $this->url, $matches)) {
return array_merge(
$defaults,
array('html' => str_replace('{query}', 'vid=' . $matches['1'], $html))
);
}
else if (preg_match('~/channel/([^/]+)~i', $this->url, $matches))
{
return array_merge(
$defaults,
array('html' => str_replace('{query}', 'username=' . urlencode($matches['1']), $html))
);
}
return array();
} | [
"public",
"function",
"fakeResponse",
"(",
")",
"{",
"$",
"defaults",
"=",
"array",
"(",
"'type'",
"=>",
"'video'",
",",
"'provider_name'",
"=>",
"'Bambuser.com'",
",",
"'provider_url'",
"=>",
"'http://bambuser.com'",
",",
")",
";",
"$",
"html",
"=",
"'<object... | inline {@inheritdoc} | [
"inline",
"{"
] | train | https://github.com/mpratt/Embera/blob/84df7a11426c017f1aae493a5994babddffac571/Lib/Embera/Providers/Bambuser.php#L45-L76 |
jarektkaczyk/eloquence-base | src/Subquery.php | Subquery.getValue | public function getValue()
{
$sql = '('.$this->query->toSql().')';
if ($this->alias) {
$alias = $this->query->getGrammar()->wrapTable($this->alias);
$sql .= ' as '.$alias;
}
return $sql;
} | php | public function getValue()
{
$sql = '('.$this->query->toSql().')';
if ($this->alias) {
$alias = $this->query->getGrammar()->wrapTable($this->alias);
$sql .= ' as '.$alias;
}
return $sql;
} | [
"public",
"function",
"getValue",
"(",
")",
"{",
"$",
"sql",
"=",
"'('",
".",
"$",
"this",
"->",
"query",
"->",
"toSql",
"(",
")",
".",
"')'",
";",
"if",
"(",
"$",
"this",
"->",
"alias",
")",
"{",
"$",
"alias",
"=",
"$",
"this",
"->",
"query",
... | Evaluate query as string.
@return string | [
"Evaluate",
"query",
"as",
"string",
"."
] | train | https://github.com/jarektkaczyk/eloquence-base/blob/46f885cde97704bb263faa237fba6760b838bb5a/src/Subquery.php#L67-L78 |
jarektkaczyk/eloquence-base | src/Query/Builder.php | Builder.aggregate | public function aggregate($function, $columns = ['*'])
{
$this->aggregate = compact('function', 'columns');
$previousColumns = $this->columns;
if (!$this->from instanceof Subquery) {
// We will also back up the select bindings since the select clause will be
// removed when performing the aggregate function. Once the query is run
// we will add the bindings back onto this query so they can get used.
$previousSelectBindings = $this->bindings['select'];
$this->bindings['select'] = [];
}
$results = $this->get($columns);
// Once we have executed the query, we will reset the aggregate property so
// that more select queries can be executed against the database without
// the aggregate value getting in the way when the grammar builds it.
$this->aggregate = null;
$this->columns = $previousColumns;
if (!$this->from instanceof Subquery) {
$this->bindings['select'] = $previousSelectBindings;
}
if (isset($results[0])) {
$result = array_change_key_case((array) $results[0]);
return $result['aggregate'];
}
} | php | public function aggregate($function, $columns = ['*'])
{
$this->aggregate = compact('function', 'columns');
$previousColumns = $this->columns;
if (!$this->from instanceof Subquery) {
// We will also back up the select bindings since the select clause will be
// removed when performing the aggregate function. Once the query is run
// we will add the bindings back onto this query so they can get used.
$previousSelectBindings = $this->bindings['select'];
$this->bindings['select'] = [];
}
$results = $this->get($columns);
// Once we have executed the query, we will reset the aggregate property so
// that more select queries can be executed against the database without
// the aggregate value getting in the way when the grammar builds it.
$this->aggregate = null;
$this->columns = $previousColumns;
if (!$this->from instanceof Subquery) {
$this->bindings['select'] = $previousSelectBindings;
}
if (isset($results[0])) {
$result = array_change_key_case((array) $results[0]);
return $result['aggregate'];
}
} | [
"public",
"function",
"aggregate",
"(",
"$",
"function",
",",
"$",
"columns",
"=",
"[",
"'*'",
"]",
")",
"{",
"$",
"this",
"->",
"aggregate",
"=",
"compact",
"(",
"'function'",
",",
"'columns'",
")",
";",
"$",
"previousColumns",
"=",
"$",
"this",
"->",... | Execute an aggregate function on the database.
@param string $function
@param array $columns
@return float|int | [
"Execute",
"an",
"aggregate",
"function",
"on",
"the",
"database",
"."
] | train | https://github.com/jarektkaczyk/eloquence-base/blob/46f885cde97704bb263faa237fba6760b838bb5a/src/Query/Builder.php#L16-L49 |
jarektkaczyk/eloquence-base | src/Query/Builder.php | Builder.runPaginationCountQuery | protected function runPaginationCountQuery($columns = ['*'])
{
$bindings = $this->from instanceof Subquery ? ['order'] : ['select', 'order'];
return $this->cloneWithout(['columns', 'orders', 'limit', 'offset'])
->cloneWithoutBindings($bindings)
->setAggregate('count', $this->withoutSelectAliases($columns))
->get()->all();
} | php | protected function runPaginationCountQuery($columns = ['*'])
{
$bindings = $this->from instanceof Subquery ? ['order'] : ['select', 'order'];
return $this->cloneWithout(['columns', 'orders', 'limit', 'offset'])
->cloneWithoutBindings($bindings)
->setAggregate('count', $this->withoutSelectAliases($columns))
->get()->all();
} | [
"protected",
"function",
"runPaginationCountQuery",
"(",
"$",
"columns",
"=",
"[",
"'*'",
"]",
")",
"{",
"$",
"bindings",
"=",
"$",
"this",
"->",
"from",
"instanceof",
"Subquery",
"?",
"[",
"'order'",
"]",
":",
"[",
"'select'",
",",
"'order'",
"]",
";",
... | Run a pagination count query.
@param array $columns
@return array | [
"Run",
"a",
"pagination",
"count",
"query",
"."
] | train | https://github.com/jarektkaczyk/eloquence-base/blob/46f885cde97704bb263faa237fba6760b838bb5a/src/Query/Builder.php#L97-L105 |
jarektkaczyk/eloquence-base | src/Searchable/ColumnCollection.php | ColumnCollection.getWeights | public function getWeights()
{
$weights = [];
foreach ($this->columns as $column) {
$weights[$column->getMapping()] = $column->getWeight();
}
return $weights;
} | php | public function getWeights()
{
$weights = [];
foreach ($this->columns as $column) {
$weights[$column->getMapping()] = $column->getWeight();
}
return $weights;
} | [
"public",
"function",
"getWeights",
"(",
")",
"{",
"$",
"weights",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"columns",
"as",
"$",
"column",
")",
"{",
"$",
"weights",
"[",
"$",
"column",
"->",
"getMapping",
"(",
")",
"]",
"=",
"$",
"... | Get array of columns mappings and weights.
@return array | [
"Get",
"array",
"of",
"columns",
"mappings",
"and",
"weights",
"."
] | train | https://github.com/jarektkaczyk/eloquence-base/blob/46f885cde97704bb263faa237fba6760b838bb5a/src/Searchable/ColumnCollection.php#L75-L84 |
jarektkaczyk/eloquence-base | src/Searchable/Parser.php | Parser.addMissingWeights | protected function addMissingWeights(array $columns)
{
$parsed = [];
foreach ($columns as $column => $weight) {
if (is_numeric($column)) {
list($column, $weight) = [$weight, $this->weight];
}
$parsed[$column] = $weight;
}
return $parsed;
} | php | protected function addMissingWeights(array $columns)
{
$parsed = [];
foreach ($columns as $column => $weight) {
if (is_numeric($column)) {
list($column, $weight) = [$weight, $this->weight];
}
$parsed[$column] = $weight;
}
return $parsed;
} | [
"protected",
"function",
"addMissingWeights",
"(",
"array",
"$",
"columns",
")",
"{",
"$",
"parsed",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"columns",
"as",
"$",
"column",
"=>",
"$",
"weight",
")",
"{",
"if",
"(",
"is_numeric",
"(",
"$",
"column",
... | Add search weight to the columns if missing.
@param array $columns | [
"Add",
"search",
"weight",
"to",
"the",
"columns",
"if",
"missing",
"."
] | train | https://github.com/jarektkaczyk/eloquence-base/blob/46f885cde97704bb263faa237fba6760b838bb5a/src/Searchable/Parser.php#L54-L67 |
jarektkaczyk/eloquence-base | src/Searchable/Parser.php | Parser.parseQuery | public function parseQuery($query, $fulltext = true)
{
$words = $this->splitString($query);
if ($fulltext) {
$words = $this->addWildcards($words);
}
return $words;
} | php | public function parseQuery($query, $fulltext = true)
{
$words = $this->splitString($query);
if ($fulltext) {
$words = $this->addWildcards($words);
}
return $words;
} | [
"public",
"function",
"parseQuery",
"(",
"$",
"query",
",",
"$",
"fulltext",
"=",
"true",
")",
"{",
"$",
"words",
"=",
"$",
"this",
"->",
"splitString",
"(",
"$",
"query",
")",
";",
"if",
"(",
"$",
"fulltext",
")",
"{",
"$",
"words",
"=",
"$",
"t... | Parse query string into separate words with wildcards if applicable.
@param string $query
@param boolean $fulltext
@return array | [
"Parse",
"query",
"string",
"into",
"separate",
"words",
"with",
"wildcards",
"if",
"applicable",
"."
] | train | https://github.com/jarektkaczyk/eloquence-base/blob/46f885cde97704bb263faa237fba6760b838bb5a/src/Searchable/Parser.php#L87-L96 |
jarektkaczyk/eloquence-base | src/Searchable/Parser.php | Parser.addWildcards | protected function addWildcards(array $words)
{
$token = $this->wildcard;
return array_map(function ($word) use ($token) {
return preg_replace('/\*+/', '*', "{$token}{$word}{$token}");
}, $words);
} | php | protected function addWildcards(array $words)
{
$token = $this->wildcard;
return array_map(function ($word) use ($token) {
return preg_replace('/\*+/', '*', "{$token}{$word}{$token}");
}, $words);
} | [
"protected",
"function",
"addWildcards",
"(",
"array",
"$",
"words",
")",
"{",
"$",
"token",
"=",
"$",
"this",
"->",
"wildcard",
";",
"return",
"array_map",
"(",
"function",
"(",
"$",
"word",
")",
"use",
"(",
"$",
"token",
")",
"{",
"return",
"preg_rep... | Add wildcard tokens to the words.
@param array $words | [
"Add",
"wildcard",
"tokens",
"to",
"the",
"words",
"."
] | train | https://github.com/jarektkaczyk/eloquence-base/blob/46f885cde97704bb263faa237fba6760b838bb5a/src/Searchable/Parser.php#L116-L123 |
jarektkaczyk/eloquence-base | src/AttributeCleaner/Observer.php | Observer.cleanAttributes | protected function cleanAttributes(CleansAttributes $model)
{
$dirty = array_keys($model->getDirty());
$invalidColumns = array_diff($dirty, $model->getColumnListing());
foreach ($invalidColumns as $column) {
unset($model->{$column});
}
} | php | protected function cleanAttributes(CleansAttributes $model)
{
$dirty = array_keys($model->getDirty());
$invalidColumns = array_diff($dirty, $model->getColumnListing());
foreach ($invalidColumns as $column) {
unset($model->{$column});
}
} | [
"protected",
"function",
"cleanAttributes",
"(",
"CleansAttributes",
"$",
"model",
")",
"{",
"$",
"dirty",
"=",
"array_keys",
"(",
"$",
"model",
"->",
"getDirty",
"(",
")",
")",
";",
"$",
"invalidColumns",
"=",
"array_diff",
"(",
"$",
"dirty",
",",
"$",
... | Get rid of attributes that are not correct columns on this model's table.
@param \Sofa\Eloquence\Contracts\CleansAttributes $model
@return void | [
"Get",
"rid",
"of",
"attributes",
"that",
"are",
"not",
"correct",
"columns",
"on",
"this",
"model",
"s",
"table",
"."
] | train | https://github.com/jarektkaczyk/eloquence-base/blob/46f885cde97704bb263faa237fba6760b838bb5a/src/AttributeCleaner/Observer.php#L28-L37 |
jarektkaczyk/eloquence-base | src/Builder.php | Builder.get | public function get($columns = ['*'])
{
if ($this->query->from instanceof Subquery) {
$this->wheresToSubquery($this->query->from);
}
return parent::get($columns);
} | php | public function get($columns = ['*'])
{
if ($this->query->from instanceof Subquery) {
$this->wheresToSubquery($this->query->from);
}
return parent::get($columns);
} | [
"public",
"function",
"get",
"(",
"$",
"columns",
"=",
"[",
"'*'",
"]",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"query",
"->",
"from",
"instanceof",
"Subquery",
")",
"{",
"$",
"this",
"->",
"wheresToSubquery",
"(",
"$",
"this",
"->",
"query",
"->",
... | Execute the query as a "select" statement.
@param array $columns
@return \Illuminate\Database\Eloquent\Collection | [
"Execute",
"the",
"query",
"as",
"a",
"select",
"statement",
"."
] | train | https://github.com/jarektkaczyk/eloquence-base/blob/46f885cde97704bb263faa237fba6760b838bb5a/src/Builder.php#L52-L59 |
jarektkaczyk/eloquence-base | src/Builder.php | Builder.search | public function search($query, $columns = null, $fulltext = true, $threshold = null)
{
if (is_bool($columns)) {
list($fulltext, $columns) = [$columns, []];
}
$parser = static::$parser->make();
$words = is_array($query) ? $query : $parser->parseQuery($query, $fulltext);
$columns = $parser->parseWeights($columns ?: $this->model->getSearchableColumns());
if (count($words) && count($columns)) {
$this->query->from($this->buildSubquery($words, $columns, $threshold));
}
return $this;
} | php | public function search($query, $columns = null, $fulltext = true, $threshold = null)
{
if (is_bool($columns)) {
list($fulltext, $columns) = [$columns, []];
}
$parser = static::$parser->make();
$words = is_array($query) ? $query : $parser->parseQuery($query, $fulltext);
$columns = $parser->parseWeights($columns ?: $this->model->getSearchableColumns());
if (count($words) && count($columns)) {
$this->query->from($this->buildSubquery($words, $columns, $threshold));
}
return $this;
} | [
"public",
"function",
"search",
"(",
"$",
"query",
",",
"$",
"columns",
"=",
"null",
",",
"$",
"fulltext",
"=",
"true",
",",
"$",
"threshold",
"=",
"null",
")",
"{",
"if",
"(",
"is_bool",
"(",
"$",
"columns",
")",
")",
"{",
"list",
"(",
"$",
"ful... | Search through any columns on current table or any defined relations
and return results ordered by search relevance.
@param array|string $query
@param array $columns
@param boolean $fulltext
@param float $threshold
@return $this | [
"Search",
"through",
"any",
"columns",
"on",
"current",
"table",
"or",
"any",
"defined",
"relations",
"and",
"return",
"results",
"ordered",
"by",
"search",
"relevance",
"."
] | train | https://github.com/jarektkaczyk/eloquence-base/blob/46f885cde97704bb263faa237fba6760b838bb5a/src/Builder.php#L71-L88 |
jarektkaczyk/eloquence-base | src/Builder.php | Builder.buildSubquery | protected function buildSubquery(array $words, array $mappings, $threshold)
{
$subquery = new SearchableSubquery($this->query->newQuery(), $this->model->getTable());
$columns = $this->joinForSearch($mappings, $subquery);
$threshold = (is_null($threshold))
? array_sum($columns->getWeights()) / 4
: (float) $threshold;
$subquery->select($this->model->getTable() . '.*')
->from($this->model->getTable())
->groupBy($this->model->getQualifiedKeyName());
$this->addSearchClauses($subquery, $columns, $words, $threshold);
return $subquery;
} | php | protected function buildSubquery(array $words, array $mappings, $threshold)
{
$subquery = new SearchableSubquery($this->query->newQuery(), $this->model->getTable());
$columns = $this->joinForSearch($mappings, $subquery);
$threshold = (is_null($threshold))
? array_sum($columns->getWeights()) / 4
: (float) $threshold;
$subquery->select($this->model->getTable() . '.*')
->from($this->model->getTable())
->groupBy($this->model->getQualifiedKeyName());
$this->addSearchClauses($subquery, $columns, $words, $threshold);
return $subquery;
} | [
"protected",
"function",
"buildSubquery",
"(",
"array",
"$",
"words",
",",
"array",
"$",
"mappings",
",",
"$",
"threshold",
")",
"{",
"$",
"subquery",
"=",
"new",
"SearchableSubquery",
"(",
"$",
"this",
"->",
"query",
"->",
"newQuery",
"(",
")",
",",
"$"... | Build the search subquery.
@param array $words
@param array $mappings
@param float $threshold
@return \Sofa\Eloquence\Searchable\Subquery | [
"Build",
"the",
"search",
"subquery",
"."
] | train | https://github.com/jarektkaczyk/eloquence-base/blob/46f885cde97704bb263faa237fba6760b838bb5a/src/Builder.php#L98-L115 |
jarektkaczyk/eloquence-base | src/Builder.php | Builder.addSearchClauses | protected function addSearchClauses(
SearchableSubquery $subquery,
ColumnCollection $columns,
array $words,
$threshold
) {
$whereBindings = $this->searchSelect($subquery, $columns, $words, $threshold);
// For morphOne/morphMany support we need to port the bindings from JoinClauses.
$joinBindings = collect($subquery->getQuery()->joins)->flatMap(function ($join) {
return $join->getBindings();
})->all();
$this->addBinding($joinBindings, 'select');
// Developer may want to skip the score threshold filtering by passing zero
// value as threshold in order to simply order full result by relevance.
// Otherwise we are going to add where clauses for speed improvement.
if ($threshold > 0) {
$this->searchWhere($subquery, $columns, $words, $whereBindings);
}
$this->query->where('relevance', '>=', new Expression(number_format($threshold, 2)));
$this->query->orders = array_merge(
[['column' => 'relevance', 'direction' => 'desc']],
(array) $this->query->orders
);
} | php | protected function addSearchClauses(
SearchableSubquery $subquery,
ColumnCollection $columns,
array $words,
$threshold
) {
$whereBindings = $this->searchSelect($subquery, $columns, $words, $threshold);
// For morphOne/morphMany support we need to port the bindings from JoinClauses.
$joinBindings = collect($subquery->getQuery()->joins)->flatMap(function ($join) {
return $join->getBindings();
})->all();
$this->addBinding($joinBindings, 'select');
// Developer may want to skip the score threshold filtering by passing zero
// value as threshold in order to simply order full result by relevance.
// Otherwise we are going to add where clauses for speed improvement.
if ($threshold > 0) {
$this->searchWhere($subquery, $columns, $words, $whereBindings);
}
$this->query->where('relevance', '>=', new Expression(number_format($threshold, 2)));
$this->query->orders = array_merge(
[['column' => 'relevance', 'direction' => 'desc']],
(array) $this->query->orders
);
} | [
"protected",
"function",
"addSearchClauses",
"(",
"SearchableSubquery",
"$",
"subquery",
",",
"ColumnCollection",
"$",
"columns",
",",
"array",
"$",
"words",
",",
"$",
"threshold",
")",
"{",
"$",
"whereBindings",
"=",
"$",
"this",
"->",
"searchSelect",
"(",
"$... | Add select and where clauses on the subquery.
@param \Sofa\Eloquence\Searchable\Subquery $subquery
@param \Sofa\Eloquence\Searchable\ColumnCollection $columns
@param array $words
@param float $threshold
@return void | [
"Add",
"select",
"and",
"where",
"clauses",
"on",
"the",
"subquery",
"."
] | train | https://github.com/jarektkaczyk/eloquence-base/blob/46f885cde97704bb263faa237fba6760b838bb5a/src/Builder.php#L126-L154 |
jarektkaczyk/eloquence-base | src/Builder.php | Builder.searchSelect | protected function searchSelect(SearchableSubquery $subquery, ColumnCollection $columns, array $words)
{
$cases = $bindings = [];
foreach ($columns as $column) {
list($cases[], $binding) = $this->buildCase($column, $words);
$bindings = array_merge_recursive($bindings, $binding);
}
$select = implode(' + ', $cases);
$subquery->selectRaw("max({$select}) as relevance");
$this->addBinding($bindings['select'], 'select');
return $bindings['where'];
} | php | protected function searchSelect(SearchableSubquery $subquery, ColumnCollection $columns, array $words)
{
$cases = $bindings = [];
foreach ($columns as $column) {
list($cases[], $binding) = $this->buildCase($column, $words);
$bindings = array_merge_recursive($bindings, $binding);
}
$select = implode(' + ', $cases);
$subquery->selectRaw("max({$select}) as relevance");
$this->addBinding($bindings['select'], 'select');
return $bindings['where'];
} | [
"protected",
"function",
"searchSelect",
"(",
"SearchableSubquery",
"$",
"subquery",
",",
"ColumnCollection",
"$",
"columns",
",",
"array",
"$",
"words",
")",
"{",
"$",
"cases",
"=",
"$",
"bindings",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"columns",
"as"... | Apply relevance select on the subquery.
@param \Sofa\Eloquence\Searchable\Subquery $subquery
@param \Sofa\Eloquence\Searchable\ColumnCollection $columns
@param array $words
@return array | [
"Apply",
"relevance",
"select",
"on",
"the",
"subquery",
"."
] | train | https://github.com/jarektkaczyk/eloquence-base/blob/46f885cde97704bb263faa237fba6760b838bb5a/src/Builder.php#L164-L181 |
jarektkaczyk/eloquence-base | src/Builder.php | Builder.searchWhere | protected function searchWhere(
SearchableSubquery $subquery,
ColumnCollection $columns,
array $words,
array $bindings
) {
$operator = $this->getLikeOperator();
$wheres = [];
foreach ($columns as $column) {
$wheres[] = implode(
' or ',
array_fill(0, count($words), sprintf('%s %s ?', $column->getWrapped(), $operator))
);
}
$where = implode(' or ', $wheres);
$subquery->whereRaw("({$where})");
$this->addBinding($bindings, 'select');
} | php | protected function searchWhere(
SearchableSubquery $subquery,
ColumnCollection $columns,
array $words,
array $bindings
) {
$operator = $this->getLikeOperator();
$wheres = [];
foreach ($columns as $column) {
$wheres[] = implode(
' or ',
array_fill(0, count($words), sprintf('%s %s ?', $column->getWrapped(), $operator))
);
}
$where = implode(' or ', $wheres);
$subquery->whereRaw("({$where})");
$this->addBinding($bindings, 'select');
} | [
"protected",
"function",
"searchWhere",
"(",
"SearchableSubquery",
"$",
"subquery",
",",
"ColumnCollection",
"$",
"columns",
",",
"array",
"$",
"words",
",",
"array",
"$",
"bindings",
")",
"{",
"$",
"operator",
"=",
"$",
"this",
"->",
"getLikeOperator",
"(",
... | Apply where clauses on the subquery.
@param \Sofa\Eloquence\Searchable\Subquery $subquery
@param \Sofa\Eloquence\Searchable\ColumnCollection $columns
@param array $words
@return void | [
"Apply",
"where",
"clauses",
"on",
"the",
"subquery",
"."
] | train | https://github.com/jarektkaczyk/eloquence-base/blob/46f885cde97704bb263faa237fba6760b838bb5a/src/Builder.php#L191-L213 |
jarektkaczyk/eloquence-base | src/Builder.php | Builder.wheresToSubquery | protected function wheresToSubquery(SearchableSubquery $subquery)
{
$bindingKey = 0;
$typesToMove = [
'basic', 'in', 'notin', 'between', 'null',
'notnull', 'date', 'day', 'month', 'year',
];
// Here we are going to move all the where clauses that we might apply
// on the subquery in order to improve performance, since this way
// we can drastically reduce number of joined rows on subquery.
foreach ((array) $this->query->wheres as $key => $where) {
$type = strtolower($where['type']);
$bindingsCount = $this->countBindings($where, $type);
if (in_array($type, $typesToMove) && $this->model->hasColumn($where['column'])) {
unset($this->query->wheres[$key]);
$where['column'] = $this->model->getTable() . '.' . $where['column'];
$subquery->getQuery()->wheres[] = $where;
$whereBindings = $this->query->getRawBindings()['where'];
$bindings = array_splice($whereBindings, $bindingKey, $bindingsCount);
$this->query->setBindings($whereBindings, 'where');
$this->query->addBinding($bindings, 'select');
// if where is not to be moved onto the subquery, let's increment
// binding key appropriately, so we can reliably move binding
// for the next where clauses in the loop that is running.
} else {
$bindingKey += $bindingsCount;
}
}
} | php | protected function wheresToSubquery(SearchableSubquery $subquery)
{
$bindingKey = 0;
$typesToMove = [
'basic', 'in', 'notin', 'between', 'null',
'notnull', 'date', 'day', 'month', 'year',
];
// Here we are going to move all the where clauses that we might apply
// on the subquery in order to improve performance, since this way
// we can drastically reduce number of joined rows on subquery.
foreach ((array) $this->query->wheres as $key => $where) {
$type = strtolower($where['type']);
$bindingsCount = $this->countBindings($where, $type);
if (in_array($type, $typesToMove) && $this->model->hasColumn($where['column'])) {
unset($this->query->wheres[$key]);
$where['column'] = $this->model->getTable() . '.' . $where['column'];
$subquery->getQuery()->wheres[] = $where;
$whereBindings = $this->query->getRawBindings()['where'];
$bindings = array_splice($whereBindings, $bindingKey, $bindingsCount);
$this->query->setBindings($whereBindings, 'where');
$this->query->addBinding($bindings, 'select');
// if where is not to be moved onto the subquery, let's increment
// binding key appropriately, so we can reliably move binding
// for the next where clauses in the loop that is running.
} else {
$bindingKey += $bindingsCount;
}
}
} | [
"protected",
"function",
"wheresToSubquery",
"(",
"SearchableSubquery",
"$",
"subquery",
")",
"{",
"$",
"bindingKey",
"=",
"0",
";",
"$",
"typesToMove",
"=",
"[",
"'basic'",
",",
"'in'",
",",
"'notin'",
",",
"'between'",
",",
"'null'",
",",
"'notnull'",
",",... | Move where clauses to subquery to improve performance.
@param \Sofa\Eloquence\Searchable\Subquery $subquery
@return void | [
"Move",
"where",
"clauses",
"to",
"subquery",
"to",
"improve",
"performance",
"."
] | train | https://github.com/jarektkaczyk/eloquence-base/blob/46f885cde97704bb263faa237fba6760b838bb5a/src/Builder.php#L221-L260 |
jarektkaczyk/eloquence-base | src/Builder.php | Builder.countBindings | protected function countBindings(array $where, $type)
{
if ($this->isHasWhere($where, $type)) {
return substr_count($where['column'] . $where['value'], '?');
} elseif ($type === 'basic') {
return (int) !$where['value'] instanceof Expression;
} elseif (in_array($type, ['basic', 'date', 'year', 'month', 'day'])) {
return (int) !$where['value'] instanceof Expression;
} elseif (in_array($type, ['null', 'notnull'])) {
return 0;
} elseif ($type === 'between') {
return 2;
} elseif (in_array($type, ['in', 'notin'])) {
return count($where['values']);
} elseif ($type === 'raw') {
return substr_count($where['sql'], '?');
} elseif (in_array($type, ['nested', 'sub', 'exists', 'notexists', 'insub', 'notinsub'])) {
return count($where['query']->getBindings());
}
} | php | protected function countBindings(array $where, $type)
{
if ($this->isHasWhere($where, $type)) {
return substr_count($where['column'] . $where['value'], '?');
} elseif ($type === 'basic') {
return (int) !$where['value'] instanceof Expression;
} elseif (in_array($type, ['basic', 'date', 'year', 'month', 'day'])) {
return (int) !$where['value'] instanceof Expression;
} elseif (in_array($type, ['null', 'notnull'])) {
return 0;
} elseif ($type === 'between') {
return 2;
} elseif (in_array($type, ['in', 'notin'])) {
return count($where['values']);
} elseif ($type === 'raw') {
return substr_count($where['sql'], '?');
} elseif (in_array($type, ['nested', 'sub', 'exists', 'notexists', 'insub', 'notinsub'])) {
return count($where['query']->getBindings());
}
} | [
"protected",
"function",
"countBindings",
"(",
"array",
"$",
"where",
",",
"$",
"type",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isHasWhere",
"(",
"$",
"where",
",",
"$",
"type",
")",
")",
"{",
"return",
"substr_count",
"(",
"$",
"where",
"[",
"'colu... | Get number of bindings provided for a where clause.
@param array $where
@param string $type
@return integer | [
"Get",
"number",
"of",
"bindings",
"provided",
"for",
"a",
"where",
"clause",
"."
] | train | https://github.com/jarektkaczyk/eloquence-base/blob/46f885cde97704bb263faa237fba6760b838bb5a/src/Builder.php#L269-L288 |
jarektkaczyk/eloquence-base | src/Builder.php | Builder.buildCase | protected function buildCase(Column $column, array $words)
{
// THIS IS BAD
// @todo refactor
$operator = $this->getLikeOperator();
$bindings['select'] = $bindings['where'] = array_map(function ($word) {
return $this->caseBinding($word);
}, $words);
$case = $this->buildEqualsCase($column, $words);
if (strpos(implode('', $words), '*') !== false) {
$leftMatching = [];
foreach ($words as $key => $word) {
if ($this->isLeftMatching($word)) {
$leftMatching[] = sprintf('%s %s ?', $column->getWrapped(), $operator);
$bindings['select'][] = $bindings['where'][$key] = $this->caseBinding($word) . '%';
}
}
if (count($leftMatching)) {
$leftMatching = implode(' or ', $leftMatching);
$score = 5 * $column->getWeight();
$case .= " + case when {$leftMatching} then {$score} else 0 end";
}
$wildcards = [];
foreach ($words as $key => $word) {
if ($this->isWildcard($word)) {
$wildcards[] = sprintf('%s %s ?', $column->getWrapped(), $operator);
$bindings['select'][] = $bindings['where'][$key] = '%'.$this->caseBinding($word) . '%';
}
}
if (count($wildcards)) {
$wildcards = implode(' or ', $wildcards);
$score = 1 * $column->getWeight();
$case .= " + case when {$wildcards} then {$score} else 0 end";
}
}
return [$case, $bindings];
} | php | protected function buildCase(Column $column, array $words)
{
// THIS IS BAD
// @todo refactor
$operator = $this->getLikeOperator();
$bindings['select'] = $bindings['where'] = array_map(function ($word) {
return $this->caseBinding($word);
}, $words);
$case = $this->buildEqualsCase($column, $words);
if (strpos(implode('', $words), '*') !== false) {
$leftMatching = [];
foreach ($words as $key => $word) {
if ($this->isLeftMatching($word)) {
$leftMatching[] = sprintf('%s %s ?', $column->getWrapped(), $operator);
$bindings['select'][] = $bindings['where'][$key] = $this->caseBinding($word) . '%';
}
}
if (count($leftMatching)) {
$leftMatching = implode(' or ', $leftMatching);
$score = 5 * $column->getWeight();
$case .= " + case when {$leftMatching} then {$score} else 0 end";
}
$wildcards = [];
foreach ($words as $key => $word) {
if ($this->isWildcard($word)) {
$wildcards[] = sprintf('%s %s ?', $column->getWrapped(), $operator);
$bindings['select'][] = $bindings['where'][$key] = '%'.$this->caseBinding($word) . '%';
}
}
if (count($wildcards)) {
$wildcards = implode(' or ', $wildcards);
$score = 1 * $column->getWeight();
$case .= " + case when {$wildcards} then {$score} else 0 end";
}
}
return [$case, $bindings];
} | [
"protected",
"function",
"buildCase",
"(",
"Column",
"$",
"column",
",",
"array",
"$",
"words",
")",
"{",
"// THIS IS BAD",
"// @todo refactor",
"$",
"operator",
"=",
"$",
"this",
"->",
"getLikeOperator",
"(",
")",
";",
"$",
"bindings",
"[",
"'select'",
"]",... | Build case clause from all words for a single column.
@param \Sofa\Eloquence\Searchable\Column $column
@param array $words
@return array | [
"Build",
"case",
"clause",
"from",
"all",
"words",
"for",
"a",
"single",
"column",
"."
] | train | https://github.com/jarektkaczyk/eloquence-base/blob/46f885cde97704bb263faa237fba6760b838bb5a/src/Builder.php#L311-L357 |
jarektkaczyk/eloquence-base | src/Builder.php | Builder.buildEqualsCase | protected function buildEqualsCase(Column $column, array $words)
{
$equals = implode(' or ', array_fill(0, count($words), sprintf('%s = ?', $column->getWrapped())));
$score = 15 * $column->getWeight();
return "case when {$equals} then {$score} else 0 end";
} | php | protected function buildEqualsCase(Column $column, array $words)
{
$equals = implode(' or ', array_fill(0, count($words), sprintf('%s = ?', $column->getWrapped())));
$score = 15 * $column->getWeight();
return "case when {$equals} then {$score} else 0 end";
} | [
"protected",
"function",
"buildEqualsCase",
"(",
"Column",
"$",
"column",
",",
"array",
"$",
"words",
")",
"{",
"$",
"equals",
"=",
"implode",
"(",
"' or '",
",",
"array_fill",
"(",
"0",
",",
"count",
"(",
"$",
"words",
")",
",",
"sprintf",
"(",
"'%s =... | Build basic search case for 'equals' comparison.
@param \Sofa\Eloquence\Searchable\Column $column
@param array $words
@return string | [
"Build",
"basic",
"search",
"case",
"for",
"equals",
"comparison",
"."
] | train | https://github.com/jarektkaczyk/eloquence-base/blob/46f885cde97704bb263faa237fba6760b838bb5a/src/Builder.php#L379-L386 |
jarektkaczyk/eloquence-base | src/Builder.php | Builder.joinForSearch | protected function joinForSearch($mappings, $subquery)
{
$mappings = is_array($mappings) ? $mappings : (array) $mappings;
$columns = new ColumnCollection;
$grammar = $this->query->getGrammar();
$joiner = static::$joinerFactory->make($subquery->getQuery(), $this->model);
// Here we loop through the search mappings in order to join related tables
// appropriately and build a searchable column collection, which we will
// use to build select and where clauses with correct table prefixes.
foreach ($mappings as $mapping => $weight) {
if (strpos($mapping, '.') !== false) {
list($relation, $column) = $this->model->parseMappedColumn($mapping);
$related = $joiner->leftJoin($relation);
$columns->add(
new Column($grammar, $related->getTable(), $column, $mapping, $weight)
);
} else {
$columns->add(
new Column($grammar, $this->model->getTable(), $mapping, $mapping, $weight)
);
}
}
return $columns;
} | php | protected function joinForSearch($mappings, $subquery)
{
$mappings = is_array($mappings) ? $mappings : (array) $mappings;
$columns = new ColumnCollection;
$grammar = $this->query->getGrammar();
$joiner = static::$joinerFactory->make($subquery->getQuery(), $this->model);
// Here we loop through the search mappings in order to join related tables
// appropriately and build a searchable column collection, which we will
// use to build select and where clauses with correct table prefixes.
foreach ($mappings as $mapping => $weight) {
if (strpos($mapping, '.') !== false) {
list($relation, $column) = $this->model->parseMappedColumn($mapping);
$related = $joiner->leftJoin($relation);
$columns->add(
new Column($grammar, $related->getTable(), $column, $mapping, $weight)
);
} else {
$columns->add(
new Column($grammar, $this->model->getTable(), $mapping, $mapping, $weight)
);
}
}
return $columns;
} | [
"protected",
"function",
"joinForSearch",
"(",
"$",
"mappings",
",",
"$",
"subquery",
")",
"{",
"$",
"mappings",
"=",
"is_array",
"(",
"$",
"mappings",
")",
"?",
"$",
"mappings",
":",
"(",
"array",
")",
"$",
"mappings",
";",
"$",
"columns",
"=",
"new",... | Join related tables on the search subquery.
@param array $mappings
@param \Sofa\Eloquence\Searchable\Subquery $subquery
@return \Sofa\Eloquence\Searchable\ColumnCollection | [
"Join",
"related",
"tables",
"on",
"the",
"search",
"subquery",
"."
] | train | https://github.com/jarektkaczyk/eloquence-base/blob/46f885cde97704bb263faa237fba6760b838bb5a/src/Builder.php#L433-L463 |
jarektkaczyk/eloquence-base | src/Builder.php | Builder.prefixColumnsForJoin | public function prefixColumnsForJoin()
{
if (!$columns = $this->query->columns) {
return $this->select($this->model->getTable() . '.*');
}
foreach ($columns as $key => $column) {
if ($this->model->hasColumn($column)) {
$columns[$key] = $this->model->getTable() . '.' . $column;
}
}
$this->query->columns = $columns;
return $this;
} | php | public function prefixColumnsForJoin()
{
if (!$columns = $this->query->columns) {
return $this->select($this->model->getTable() . '.*');
}
foreach ($columns as $key => $column) {
if ($this->model->hasColumn($column)) {
$columns[$key] = $this->model->getTable() . '.' . $column;
}
}
$this->query->columns = $columns;
return $this;
} | [
"public",
"function",
"prefixColumnsForJoin",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"columns",
"=",
"$",
"this",
"->",
"query",
"->",
"columns",
")",
"{",
"return",
"$",
"this",
"->",
"select",
"(",
"$",
"this",
"->",
"model",
"->",
"getTable",
"(",
")... | Prefix selected columns with table name in order to avoid collisions.
@return $this | [
"Prefix",
"selected",
"columns",
"with",
"table",
"name",
"in",
"order",
"to",
"avoid",
"collisions",
"."
] | train | https://github.com/jarektkaczyk/eloquence-base/blob/46f885cde97704bb263faa237fba6760b838bb5a/src/Builder.php#L470-L485 |
jarektkaczyk/eloquence-base | src/Builder.php | Builder.joinRelations | public function joinRelations($relations, $type = 'inner')
{
if (is_null($this->joiner)) {
$this->joiner = static::$joinerFactory->make($this);
}
if (!is_array($relations)) {
list($relations, $type) = [func_get_args(), 'inner'];
}
foreach ($relations as $relation) {
$this->joiner->join($relation, $type);
}
return $this;
} | php | public function joinRelations($relations, $type = 'inner')
{
if (is_null($this->joiner)) {
$this->joiner = static::$joinerFactory->make($this);
}
if (!is_array($relations)) {
list($relations, $type) = [func_get_args(), 'inner'];
}
foreach ($relations as $relation) {
$this->joiner->join($relation, $type);
}
return $this;
} | [
"public",
"function",
"joinRelations",
"(",
"$",
"relations",
",",
"$",
"type",
"=",
"'inner'",
")",
"{",
"if",
"(",
"is_null",
"(",
"$",
"this",
"->",
"joiner",
")",
")",
"{",
"$",
"this",
"->",
"joiner",
"=",
"static",
"::",
"$",
"joinerFactory",
"... | Join related tables.
@param array|string $relations
@param string $type
@return $this | [
"Join",
"related",
"tables",
"."
] | train | https://github.com/jarektkaczyk/eloquence-base/blob/46f885cde97704bb263faa237fba6760b838bb5a/src/Builder.php#L494-L509 |
jarektkaczyk/eloquence-base | src/Builder.php | Builder.leftJoinRelations | public function leftJoinRelations($relations)
{
$relations = is_array($relations) ? $relations : func_get_args();
return $this->joinRelations($relations, 'left');
} | php | public function leftJoinRelations($relations)
{
$relations = is_array($relations) ? $relations : func_get_args();
return $this->joinRelations($relations, 'left');
} | [
"public",
"function",
"leftJoinRelations",
"(",
"$",
"relations",
")",
"{",
"$",
"relations",
"=",
"is_array",
"(",
"$",
"relations",
")",
"?",
"$",
"relations",
":",
"func_get_args",
"(",
")",
";",
"return",
"$",
"this",
"->",
"joinRelations",
"(",
"$",
... | Left join related tables.
@param array|string $relations
@return $this | [
"Left",
"join",
"related",
"tables",
"."
] | train | https://github.com/jarektkaczyk/eloquence-base/blob/46f885cde97704bb263faa237fba6760b838bb5a/src/Builder.php#L517-L522 |
jarektkaczyk/eloquence-base | src/Builder.php | Builder.rightJoinRelations | public function rightJoinRelations($relations)
{
$relations = is_array($relations) ? $relations : func_get_args();
return $this->joinRelations($relations, 'right');
} | php | public function rightJoinRelations($relations)
{
$relations = is_array($relations) ? $relations : func_get_args();
return $this->joinRelations($relations, 'right');
} | [
"public",
"function",
"rightJoinRelations",
"(",
"$",
"relations",
")",
"{",
"$",
"relations",
"=",
"is_array",
"(",
"$",
"relations",
")",
"?",
"$",
"relations",
":",
"func_get_args",
"(",
")",
";",
"return",
"$",
"this",
"->",
"joinRelations",
"(",
"$",
... | Right join related tables.
@param array|string $relations
@return $this | [
"Right",
"join",
"related",
"tables",
"."
] | train | https://github.com/jarektkaczyk/eloquence-base/blob/46f885cde97704bb263faa237fba6760b838bb5a/src/Builder.php#L530-L535 |
jarektkaczyk/eloquence-base | src/Eloquence.php | Eloquence.isWhereNullByArgs | protected function isWhereNullByArgs(ArgumentBag $args)
{
return is_null($args->get('operator'))
|| is_null($args->get('value')) && !in_array($args->get('operator'), ['<>', '!=']);
} | php | protected function isWhereNullByArgs(ArgumentBag $args)
{
return is_null($args->get('operator'))
|| is_null($args->get('value')) && !in_array($args->get('operator'), ['<>', '!=']);
} | [
"protected",
"function",
"isWhereNullByArgs",
"(",
"ArgumentBag",
"$",
"args",
")",
"{",
"return",
"is_null",
"(",
"$",
"args",
"->",
"get",
"(",
"'operator'",
")",
")",
"||",
"is_null",
"(",
"$",
"args",
"->",
"get",
"(",
"'value'",
")",
")",
"&&",
"!... | Determine whether where is a whereNull by the arguments passed to where method.
@param ArgumentBag $args
@return boolean | [
"Determine",
"whether",
"where",
"is",
"a",
"whereNull",
"by",
"the",
"arguments",
"passed",
"to",
"where",
"method",
"."
] | train | https://github.com/jarektkaczyk/eloquence-base/blob/46f885cde97704bb263faa237fba6760b838bb5a/src/Eloquence.php#L64-L68 |
jarektkaczyk/eloquence-base | src/Eloquence.php | Eloquence.extractColumnAlias | protected function extractColumnAlias($column)
{
$alias = $column;
if (strpos($column, ' as ') !== false) {
list($column, $alias) = explode(' as ', $column);
}
return [$column, $alias];
} | php | protected function extractColumnAlias($column)
{
$alias = $column;
if (strpos($column, ' as ') !== false) {
list($column, $alias) = explode(' as ', $column);
}
return [$column, $alias];
} | [
"protected",
"function",
"extractColumnAlias",
"(",
"$",
"column",
")",
"{",
"$",
"alias",
"=",
"$",
"column",
";",
"if",
"(",
"strpos",
"(",
"$",
"column",
",",
"' as '",
")",
"!==",
"false",
")",
"{",
"list",
"(",
"$",
"column",
",",
"$",
"alias",
... | Extract real name and alias from the sql select clause.
@param string $column
@return array | [
"Extract",
"real",
"name",
"and",
"alias",
"from",
"the",
"sql",
"select",
"clause",
"."
] | train | https://github.com/jarektkaczyk/eloquence-base/blob/46f885cde97704bb263faa237fba6760b838bb5a/src/Eloquence.php#L76-L85 |
jarektkaczyk/eloquence-base | src/Eloquence.php | Eloquence.parseMappedColumn | public function parseMappedColumn($mapping)
{
$segments = explode('.', $mapping);
$column = array_pop($segments);
$target = implode('.', $segments);
return [$target, $column];
} | php | public function parseMappedColumn($mapping)
{
$segments = explode('.', $mapping);
$column = array_pop($segments);
$target = implode('.', $segments);
return [$target, $column];
} | [
"public",
"function",
"parseMappedColumn",
"(",
"$",
"mapping",
")",
"{",
"$",
"segments",
"=",
"explode",
"(",
"'.'",
",",
"$",
"mapping",
")",
";",
"$",
"column",
"=",
"array_pop",
"(",
"$",
"segments",
")",
";",
"$",
"target",
"=",
"implode",
"(",
... | Get the target relation and column from the mapping.
@param string $mapping
@return array | [
"Get",
"the",
"target",
"relation",
"and",
"column",
"from",
"the",
"mapping",
"."
] | train | https://github.com/jarektkaczyk/eloquence-base/blob/46f885cde97704bb263faa237fba6760b838bb5a/src/Eloquence.php#L93-L102 |
jarektkaczyk/eloquence-base | src/Eloquence.php | Eloquence.loadColumnListing | protected static function loadColumnListing()
{
if (empty(static::$columnListing)) {
$instance = new static;
static::$columnListing = $instance->getConnection()
->getSchemaBuilder()
->getColumnListing($instance->getTable());
}
} | php | protected static function loadColumnListing()
{
if (empty(static::$columnListing)) {
$instance = new static;
static::$columnListing = $instance->getConnection()
->getSchemaBuilder()
->getColumnListing($instance->getTable());
}
} | [
"protected",
"static",
"function",
"loadColumnListing",
"(",
")",
"{",
"if",
"(",
"empty",
"(",
"static",
"::",
"$",
"columnListing",
")",
")",
"{",
"$",
"instance",
"=",
"new",
"static",
";",
"static",
"::",
"$",
"columnListing",
"=",
"$",
"instance",
"... | Fetch model table columns.
@return void | [
"Fetch",
"model",
"table",
"columns",
"."
] | train | https://github.com/jarektkaczyk/eloquence-base/blob/46f885cde97704bb263faa237fba6760b838bb5a/src/Eloquence.php#L144-L153 |
jarektkaczyk/eloquence-base | src/Relations/JoinerFactory.php | JoinerFactory.make | public static function make($query, Model $model = null)
{
if ($query instanceof EloquentBuilder) {
$model = $query->getModel();
$query = $query->getQuery();
}
return new Joiner($query, $model);
} | php | public static function make($query, Model $model = null)
{
if ($query instanceof EloquentBuilder) {
$model = $query->getModel();
$query = $query->getQuery();
}
return new Joiner($query, $model);
} | [
"public",
"static",
"function",
"make",
"(",
"$",
"query",
",",
"Model",
"$",
"model",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"query",
"instanceof",
"EloquentBuilder",
")",
"{",
"$",
"model",
"=",
"$",
"query",
"->",
"getModel",
"(",
")",
";",
"$",
... | Create new joiner instance.
@param \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Query\Builder $query
@param \Illuminate\Database\Eloquent\Model $model
@return \Sofa\Eloquence\Relations\Joiner | [
"Create",
"new",
"joiner",
"instance",
"."
] | train | https://github.com/jarektkaczyk/eloquence-base/blob/46f885cde97704bb263faa237fba6760b838bb5a/src/Relations/JoinerFactory.php#L18-L26 |
jarektkaczyk/eloquence-base | src/Relations/Joiner.php | Joiner.join | public function join($target, $type = 'inner')
{
$related = $this->model;
foreach (explode('.', $target) as $segment) {
$related = $this->joinSegment($related, $segment, $type);
}
return $related;
} | php | public function join($target, $type = 'inner')
{
$related = $this->model;
foreach (explode('.', $target) as $segment) {
$related = $this->joinSegment($related, $segment, $type);
}
return $related;
} | [
"public",
"function",
"join",
"(",
"$",
"target",
",",
"$",
"type",
"=",
"'inner'",
")",
"{",
"$",
"related",
"=",
"$",
"this",
"->",
"model",
";",
"foreach",
"(",
"explode",
"(",
"'.'",
",",
"$",
"target",
")",
"as",
"$",
"segment",
")",
"{",
"$... | Join related tables.
@param string $target
@param string $type
@return \Illuminate\Database\Eloquent\Model | [
"Join",
"related",
"tables",
"."
] | train | https://github.com/jarektkaczyk/eloquence-base/blob/46f885cde97704bb263faa237fba6760b838bb5a/src/Relations/Joiner.php#L56-L65 |
jarektkaczyk/eloquence-base | src/Relations/Joiner.php | Joiner.joinSegment | protected function joinSegment(Model $parent, $segment, $type)
{
$relation = $parent->{$segment}();
$related = $relation->getRelated();
$table = $related->getTable();
if ($relation instanceof BelongsToMany || $relation instanceof HasManyThrough) {
$this->joinIntermediate($parent, $relation, $type);
}
if (!$this->alreadyJoined($join = $this->getJoinClause($parent, $relation, $table, $type))) {
$this->query->joins[] = $join;
}
return $related;
} | php | protected function joinSegment(Model $parent, $segment, $type)
{
$relation = $parent->{$segment}();
$related = $relation->getRelated();
$table = $related->getTable();
if ($relation instanceof BelongsToMany || $relation instanceof HasManyThrough) {
$this->joinIntermediate($parent, $relation, $type);
}
if (!$this->alreadyJoined($join = $this->getJoinClause($parent, $relation, $table, $type))) {
$this->query->joins[] = $join;
}
return $related;
} | [
"protected",
"function",
"joinSegment",
"(",
"Model",
"$",
"parent",
",",
"$",
"segment",
",",
"$",
"type",
")",
"{",
"$",
"relation",
"=",
"$",
"parent",
"->",
"{",
"$",
"segment",
"}",
"(",
")",
";",
"$",
"related",
"=",
"$",
"relation",
"->",
"g... | Join relation's table accordingly.
@param \Illuminate\Database\Eloquent\Model $parent
@param string $segment
@param string $type
@return \Illuminate\Database\Eloquent\Model | [
"Join",
"relation",
"s",
"table",
"accordingly",
"."
] | train | https://github.com/jarektkaczyk/eloquence-base/blob/46f885cde97704bb263faa237fba6760b838bb5a/src/Relations/Joiner.php#L97-L112 |
jarektkaczyk/eloquence-base | src/Relations/Joiner.php | Joiner.getJoinClause | protected function getJoinClause(Model $parent, Relation $relation, $table, $type)
{
list($fk, $pk) = $this->getJoinKeys($relation);
$join = (new Join($this->query, $type, $table))->on($fk, '=', $pk);
if (in_array(SoftDeletes::class, class_uses_recursive($relation->getRelated()))) {
$join->whereNull($relation->getRelated()->getQualifiedDeletedAtColumn());
}
if ($relation instanceof MorphOneOrMany) {
$join->where($relation->getQualifiedMorphType(), '=', $parent->getMorphClass());
} elseif ($relation instanceof MorphToMany || $relation instanceof MorphByMany) {
$join->where($relation->getMorphType(), '=', $parent->getMorphClass());
}
return $join;
} | php | protected function getJoinClause(Model $parent, Relation $relation, $table, $type)
{
list($fk, $pk) = $this->getJoinKeys($relation);
$join = (new Join($this->query, $type, $table))->on($fk, '=', $pk);
if (in_array(SoftDeletes::class, class_uses_recursive($relation->getRelated()))) {
$join->whereNull($relation->getRelated()->getQualifiedDeletedAtColumn());
}
if ($relation instanceof MorphOneOrMany) {
$join->where($relation->getQualifiedMorphType(), '=', $parent->getMorphClass());
} elseif ($relation instanceof MorphToMany || $relation instanceof MorphByMany) {
$join->where($relation->getMorphType(), '=', $parent->getMorphClass());
}
return $join;
} | [
"protected",
"function",
"getJoinClause",
"(",
"Model",
"$",
"parent",
",",
"Relation",
"$",
"relation",
",",
"$",
"table",
",",
"$",
"type",
")",
"{",
"list",
"(",
"$",
"fk",
",",
"$",
"pk",
")",
"=",
"$",
"this",
"->",
"getJoinKeys",
"(",
"$",
"r... | Get the join clause for related table.
@param \Illuminate\Database\Eloquent\Model $parent
@param \Illuminate\Database\Eloquent\Relations\Relation $relation
@param string $type
@param string $table
@return \Illuminate\Database\Query\JoinClause | [
"Get",
"the",
"join",
"clause",
"for",
"related",
"table",
"."
] | train | https://github.com/jarektkaczyk/eloquence-base/blob/46f885cde97704bb263faa237fba6760b838bb5a/src/Relations/Joiner.php#L134-L151 |
jarektkaczyk/eloquence-base | src/Relations/Joiner.php | Joiner.joinIntermediate | protected function joinIntermediate(Model $parent, Relation $relation, $type)
{
if ($relation instanceof BelongsToMany) {
$table = $relation->getTable();
$fk = $relation->getQualifiedForeignPivotKeyName();
} else {
$table = $relation->getParent()->getTable();
$fk = $relation->getQualifiedFirstKeyName();
}
$pk = $parent->getQualifiedKeyName();
if (!$this->alreadyJoined($join = (new Join($this->query, $type, $table))->on($fk, '=', $pk))) {
$this->query->joins[] = $join;
}
} | php | protected function joinIntermediate(Model $parent, Relation $relation, $type)
{
if ($relation instanceof BelongsToMany) {
$table = $relation->getTable();
$fk = $relation->getQualifiedForeignPivotKeyName();
} else {
$table = $relation->getParent()->getTable();
$fk = $relation->getQualifiedFirstKeyName();
}
$pk = $parent->getQualifiedKeyName();
if (!$this->alreadyJoined($join = (new Join($this->query, $type, $table))->on($fk, '=', $pk))) {
$this->query->joins[] = $join;
}
} | [
"protected",
"function",
"joinIntermediate",
"(",
"Model",
"$",
"parent",
",",
"Relation",
"$",
"relation",
",",
"$",
"type",
")",
"{",
"if",
"(",
"$",
"relation",
"instanceof",
"BelongsToMany",
")",
"{",
"$",
"table",
"=",
"$",
"relation",
"->",
"getTable... | Join pivot or 'through' table.
@param \Illuminate\Database\Eloquent\Model $parent
@param \Illuminate\Database\Eloquent\Relations\Relation $relation
@param string $type
@return void | [
"Join",
"pivot",
"or",
"through",
"table",
"."
] | train | https://github.com/jarektkaczyk/eloquence-base/blob/46f885cde97704bb263faa237fba6760b838bb5a/src/Relations/Joiner.php#L161-L176 |
jarektkaczyk/eloquence-base | src/Relations/Joiner.php | Joiner.getJoinKeys | protected function getJoinKeys(Relation $relation)
{
if ($relation instanceof MorphTo) {
throw new LogicException("MorphTo relation cannot be joined.");
}
if ($relation instanceof HasOneOrMany) {
return [$relation->getQualifiedForeignKeyName(), $relation->getQualifiedParentKeyName()];
}
if ($relation instanceof BelongsTo) {
return [$relation->getQualifiedForeignKeyName(), $relation->getQualifiedOwnerKeyName()];
}
if ($relation instanceof BelongsToMany) {
return [$relation->getQualifiedRelatedPivotKeyName(), $relation->getRelated()->getQualifiedKeyName()];
}
if ($relation instanceof HasManyThrough) {
$fk = $relation->getQualifiedFarKeyName();
return [$fk, $relation->getParent()->getQualifiedKeyName()];
}
} | php | protected function getJoinKeys(Relation $relation)
{
if ($relation instanceof MorphTo) {
throw new LogicException("MorphTo relation cannot be joined.");
}
if ($relation instanceof HasOneOrMany) {
return [$relation->getQualifiedForeignKeyName(), $relation->getQualifiedParentKeyName()];
}
if ($relation instanceof BelongsTo) {
return [$relation->getQualifiedForeignKeyName(), $relation->getQualifiedOwnerKeyName()];
}
if ($relation instanceof BelongsToMany) {
return [$relation->getQualifiedRelatedPivotKeyName(), $relation->getRelated()->getQualifiedKeyName()];
}
if ($relation instanceof HasManyThrough) {
$fk = $relation->getQualifiedFarKeyName();
return [$fk, $relation->getParent()->getQualifiedKeyName()];
}
} | [
"protected",
"function",
"getJoinKeys",
"(",
"Relation",
"$",
"relation",
")",
"{",
"if",
"(",
"$",
"relation",
"instanceof",
"MorphTo",
")",
"{",
"throw",
"new",
"LogicException",
"(",
"\"MorphTo relation cannot be joined.\"",
")",
";",
"}",
"if",
"(",
"$",
"... | Get pair of the keys from relation in order to join the table.
@param \Illuminate\Database\Eloquent\Relations\Relation $relation
@return array
@throws \LogicException | [
"Get",
"pair",
"of",
"the",
"keys",
"from",
"relation",
"in",
"order",
"to",
"join",
"the",
"table",
"."
] | train | https://github.com/jarektkaczyk/eloquence-base/blob/46f885cde97704bb263faa237fba6760b838bb5a/src/Relations/Joiner.php#L186-L209 |
LibreDTE/libredte-lib | lib/Sii.php | Sii.getURL | public static function getURL($recurso, $ambiente = null)
{
$ambiente = self::getAmbiente($ambiente);
// si es anulación masiva de folios
if ($recurso=='/anulacionMsvDteInternet') {
$servidor = $ambiente ? 'www4c' : 'www4';
}
// servidor estandar (maullin o palena)
else {
$servidor = self::getServidor($ambiente);
}
// entregar URL
return 'https://'.$servidor.'.sii.cl'.$recurso;
} | php | public static function getURL($recurso, $ambiente = null)
{
$ambiente = self::getAmbiente($ambiente);
// si es anulación masiva de folios
if ($recurso=='/anulacionMsvDteInternet') {
$servidor = $ambiente ? 'www4c' : 'www4';
}
// servidor estandar (maullin o palena)
else {
$servidor = self::getServidor($ambiente);
}
// entregar URL
return 'https://'.$servidor.'.sii.cl'.$recurso;
} | [
"public",
"static",
"function",
"getURL",
"(",
"$",
"recurso",
",",
"$",
"ambiente",
"=",
"null",
")",
"{",
"$",
"ambiente",
"=",
"self",
"::",
"getAmbiente",
"(",
"$",
"ambiente",
")",
";",
"// si es anulación masiva de folios",
"if",
"(",
"$",
"recurso",
... | Método que entrega la URL de un recurso en el SII según el ambiente que se esté usando
@param recurso Recurso del sitio del SII que se desea obtener la URL
@param ambiente Ambiente que se desea obtener el servidor, si es null se autodetectará
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2018-05-18 | [
"Método",
"que",
"entrega",
"la",
"URL",
"de",
"un",
"recurso",
"en",
"el",
"SII",
"según",
"el",
"ambiente",
"que",
"se",
"esté",
"usando"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii.php#L430-L443 |
LibreDTE/libredte-lib | lib/Sii.php | Sii.wsdl | public static function wsdl($servicio, $ambiente = null)
{
// determinar ambiente que se debe usar
$ambiente = self::getAmbiente($ambiente);
// entregar WSDL local (modificados para ambiente de certificación)
if ($ambiente==self::CERTIFICACION) {
$wsdl = dirname(dirname(__FILE__)).'/wsdl/'.self::$config['servidor'][$ambiente].'/'.$servicio.'.jws';
if (is_readable($wsdl))
return $wsdl;
}
// entregar WSDL oficial desde SII
$location = isset(self::$config['wsdl'][$servicio]) ? self::$config['wsdl'][$servicio] : self::$config['wsdl']['*'];
$wsdl = str_replace(
['{servidor}', '{servicio}'],
[self::$config['servidor'][$ambiente], $servicio],
$location
);
// entregar wsdl
return $wsdl;
} | php | public static function wsdl($servicio, $ambiente = null)
{
// determinar ambiente que se debe usar
$ambiente = self::getAmbiente($ambiente);
// entregar WSDL local (modificados para ambiente de certificación)
if ($ambiente==self::CERTIFICACION) {
$wsdl = dirname(dirname(__FILE__)).'/wsdl/'.self::$config['servidor'][$ambiente].'/'.$servicio.'.jws';
if (is_readable($wsdl))
return $wsdl;
}
// entregar WSDL oficial desde SII
$location = isset(self::$config['wsdl'][$servicio]) ? self::$config['wsdl'][$servicio] : self::$config['wsdl']['*'];
$wsdl = str_replace(
['{servidor}', '{servicio}'],
[self::$config['servidor'][$ambiente], $servicio],
$location
);
// entregar wsdl
return $wsdl;
} | [
"public",
"static",
"function",
"wsdl",
"(",
"$",
"servicio",
",",
"$",
"ambiente",
"=",
"null",
")",
"{",
"// determinar ambiente que se debe usar",
"$",
"ambiente",
"=",
"self",
"::",
"getAmbiente",
"(",
"$",
"ambiente",
")",
";",
"// entregar WSDL local (modifi... | Método para obtener el WSDL
\code{.php}
$wsdl = \sasco\LibreDTE\Sii::wsdl('CrSeed'); // WSDL para pedir semilla
\endcode
Para forzar el uso del WSDL de certificación hay dos maneras, una es
pasando un segundo parámetro al método get con valor Sii::CERTIFICACION:
\code{.php}
$wsdl = \sasco\LibreDTE\Sii::wsdl('CrSeed', \sasco\LibreDTE\Sii::CERTIFICACION);
\endcode
La otra manera, para evitar este segundo parámetro, es asignar el valor a
través de la configuración:
\code{.php}
\sasco\LibreDTE\Sii::setAmbiente(\sasco\LibreDTE\Sii::CERTIFICACION);
\endcode
@param servicio Servicio por el cual se está solicitando su WSDL
@param ambiente Ambiente a usar: Sii::PRODUCCION o Sii::CERTIFICACION o null (para detección automática)
@return URL del WSDL del servicio según ambiente solicitado
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2016-06-11 | [
"Método",
"para",
"obtener",
"el",
"WSDL"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii.php#L472-L491 |
LibreDTE/libredte-lib | lib/Sii.php | Sii.request | public static function request($wsdl, $request, $args = null, $retry = null)
{
if (is_numeric($args)) {
$retry = (int)$args;
$args = null;
}
if (!$retry) {
$retry = self::$retry;
}
if ($args and !is_array($args)) {
$args = [$args];
}
$options = ['cache_wsdl' => WSDL_CACHE_DISK];
if (!self::$verificar_ssl) {
if (self::getAmbiente()==self::PRODUCCION) {
$msg = Estado::get(Estado::ENVIO_SSL_SIN_VERIFICAR);
\sasco\LibreDTE\Log::write(Estado::ENVIO_SSL_SIN_VERIFICAR, $msg, LOG_WARNING);
}
$options['stream_context'] = stream_context_create([
'ssl' => [
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
]
]);
}
try {
$soap = new \SoapClient(self::wsdl($wsdl), $options);
} catch (\Exception $e) {
$msg = $e->getMessage();
if (isset($e->getTrace()[0]['args'][1]) and is_string($e->getTrace()[0]['args'][1])) {
$msg .= ': '.$e->getTrace()[0]['args'][1];
}
\sasco\LibreDTE\Log::write(Estado::REQUEST_ERROR_SOAP, Estado::get(Estado::REQUEST_ERROR_SOAP, $msg));
return false;
}
for ($i=0; $i<$retry; $i++) {
try {
if ($args) {
$body = call_user_func_array([$soap, $request], $args);
} else {
$body = $soap->$request();
}
break;
} catch (\Exception $e) {
$msg = $e->getMessage();
if (isset($e->getTrace()[0]['args'][1]) and is_string($e->getTrace()[0]['args'][1])) {
$msg .= ': '.$e->getTrace()[0]['args'][1];
}
\sasco\LibreDTE\Log::write(Estado::REQUEST_ERROR_SOAP, Estado::get(Estado::REQUEST_ERROR_SOAP, $msg));
$body = null;
usleep(200000); // pausa de 0.2 segundos antes de volver a intentar el envío
}
}
if ($body===null) {
\sasco\LibreDTE\Log::write(Estado::REQUEST_ERROR_BODY, Estado::get(Estado::REQUEST_ERROR_BODY, $wsdl, $retry));
return false;
}
return new \SimpleXMLElement($body, LIBXML_COMPACT);
} | php | public static function request($wsdl, $request, $args = null, $retry = null)
{
if (is_numeric($args)) {
$retry = (int)$args;
$args = null;
}
if (!$retry) {
$retry = self::$retry;
}
if ($args and !is_array($args)) {
$args = [$args];
}
$options = ['cache_wsdl' => WSDL_CACHE_DISK];
if (!self::$verificar_ssl) {
if (self::getAmbiente()==self::PRODUCCION) {
$msg = Estado::get(Estado::ENVIO_SSL_SIN_VERIFICAR);
\sasco\LibreDTE\Log::write(Estado::ENVIO_SSL_SIN_VERIFICAR, $msg, LOG_WARNING);
}
$options['stream_context'] = stream_context_create([
'ssl' => [
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
]
]);
}
try {
$soap = new \SoapClient(self::wsdl($wsdl), $options);
} catch (\Exception $e) {
$msg = $e->getMessage();
if (isset($e->getTrace()[0]['args'][1]) and is_string($e->getTrace()[0]['args'][1])) {
$msg .= ': '.$e->getTrace()[0]['args'][1];
}
\sasco\LibreDTE\Log::write(Estado::REQUEST_ERROR_SOAP, Estado::get(Estado::REQUEST_ERROR_SOAP, $msg));
return false;
}
for ($i=0; $i<$retry; $i++) {
try {
if ($args) {
$body = call_user_func_array([$soap, $request], $args);
} else {
$body = $soap->$request();
}
break;
} catch (\Exception $e) {
$msg = $e->getMessage();
if (isset($e->getTrace()[0]['args'][1]) and is_string($e->getTrace()[0]['args'][1])) {
$msg .= ': '.$e->getTrace()[0]['args'][1];
}
\sasco\LibreDTE\Log::write(Estado::REQUEST_ERROR_SOAP, Estado::get(Estado::REQUEST_ERROR_SOAP, $msg));
$body = null;
usleep(200000); // pausa de 0.2 segundos antes de volver a intentar el envío
}
}
if ($body===null) {
\sasco\LibreDTE\Log::write(Estado::REQUEST_ERROR_BODY, Estado::get(Estado::REQUEST_ERROR_BODY, $wsdl, $retry));
return false;
}
return new \SimpleXMLElement($body, LIBXML_COMPACT);
} | [
"public",
"static",
"function",
"request",
"(",
"$",
"wsdl",
",",
"$",
"request",
",",
"$",
"args",
"=",
"null",
",",
"$",
"retry",
"=",
"null",
")",
"{",
"if",
"(",
"is_numeric",
"(",
"$",
"args",
")",
")",
"{",
"$",
"retry",
"=",
"(",
"int",
... | Método para realizar una solicitud al servicio web del SII
@param wsdl Nombre del WSDL que se usará
@param request Nombre de la función que se ejecutará en el servicio web
@param args Argumentos que se pasarán al servicio web
@param retry Intentos que se realizarán como máximo para obtener respuesta
@return Objeto SimpleXMLElement con la espuesta del servicio web consultado
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2018-11-12 | [
"Método",
"para",
"realizar",
"una",
"solicitud",
"al",
"servicio",
"web",
"del",
"SII"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii.php#L503-L562 |
LibreDTE/libredte-lib | lib/Sii.php | Sii.enviar | public static function enviar($usuario, $empresa, $dte, $token, $gzip = false, $retry = null)
{
// definir datos que se usarán en el envío
list($rutSender, $dvSender) = explode('-', str_replace('.', '', $usuario));
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().'/dte_'.md5(microtime().$token.$dte).'.'.($gzip?'gz':'xml');
} while (file_exists($file));
if ($gzip) {
$dte = gzencode($dte);
if ($dte===false) {
\sasco\LibreDTE\Log::write(Estado::ENVIO_ERROR_GZIP, Estado::get(Estado::ENVIO_ERROR_GZIP));
return false;
}
}
file_put_contents($file, $dte);
$data = [
'rutSender' => $rutSender,
'dvSender' => $dvSender,
'rutCompany' => $rutCompany,
'dvCompany' => $dvCompany,
'archivo' => curl_file_create(
$file,
$gzip ? 'application/gzip' : 'application/xml',
basename($file)
),
];
// definir reintentos si no se pasaron
if (!$retry) {
$retry = self::$retry;
}
// 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://'.self::$config['servidor'][self::getAmbiente()].'.sii.cl/cgi_dte/UPL/DTEUpload';
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 (!self::$verificar_ssl) {
if (self::getAmbiente()==self::PRODUCCION) {
$msg = Estado::get(Estado::ENVIO_SSL_SIN_VERIFICAR);
\sasco\LibreDTE\Log::write(Estado::ENVIO_SSL_SIN_VERIFICAR, $msg, 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(Estado::ENVIO_ERROR_CURL, Estado::get(Estado::ENVIO_ERROR_CURL, curl_error($curl)));
}
if ($response=='Error 500') {
\sasco\LibreDTE\Log::write(Estado::ENVIO_ERROR_500, Estado::get(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(Estado::ENVIO_ERROR_XML, Estado::get(Estado::ENVIO_ERROR_XML, $e->getMessage()));
return false;
}
if ($xml->STATUS!=0) {
\sasco\LibreDTE\Log::write(
$xml->STATUS,
Estado::get($xml->STATUS).(isset($xml->DETAIL)?'. '.implode("\n", (array)$xml->DETAIL->ERROR):'')
);
}
return $xml;
} | php | public static function enviar($usuario, $empresa, $dte, $token, $gzip = false, $retry = null)
{
// definir datos que se usarán en el envío
list($rutSender, $dvSender) = explode('-', str_replace('.', '', $usuario));
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().'/dte_'.md5(microtime().$token.$dte).'.'.($gzip?'gz':'xml');
} while (file_exists($file));
if ($gzip) {
$dte = gzencode($dte);
if ($dte===false) {
\sasco\LibreDTE\Log::write(Estado::ENVIO_ERROR_GZIP, Estado::get(Estado::ENVIO_ERROR_GZIP));
return false;
}
}
file_put_contents($file, $dte);
$data = [
'rutSender' => $rutSender,
'dvSender' => $dvSender,
'rutCompany' => $rutCompany,
'dvCompany' => $dvCompany,
'archivo' => curl_file_create(
$file,
$gzip ? 'application/gzip' : 'application/xml',
basename($file)
),
];
// definir reintentos si no se pasaron
if (!$retry) {
$retry = self::$retry;
}
// 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://'.self::$config['servidor'][self::getAmbiente()].'.sii.cl/cgi_dte/UPL/DTEUpload';
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 (!self::$verificar_ssl) {
if (self::getAmbiente()==self::PRODUCCION) {
$msg = Estado::get(Estado::ENVIO_SSL_SIN_VERIFICAR);
\sasco\LibreDTE\Log::write(Estado::ENVIO_SSL_SIN_VERIFICAR, $msg, 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(Estado::ENVIO_ERROR_CURL, Estado::get(Estado::ENVIO_ERROR_CURL, curl_error($curl)));
}
if ($response=='Error 500') {
\sasco\LibreDTE\Log::write(Estado::ENVIO_ERROR_500, Estado::get(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(Estado::ENVIO_ERROR_XML, Estado::get(Estado::ENVIO_ERROR_XML, $e->getMessage()));
return false;
}
if ($xml->STATUS!=0) {
\sasco\LibreDTE\Log::write(
$xml->STATUS,
Estado::get($xml->STATUS).(isset($xml->DETAIL)?'. '.implode("\n", (array)$xml->DETAIL->ERROR):'')
);
}
return $xml;
} | [
"public",
"static",
"function",
"enviar",
"(",
"$",
"usuario",
",",
"$",
"empresa",
",",
"$",
"dte",
",",
"$",
"token",
",",
"$",
"gzip",
"=",
"false",
",",
"$",
"retry",
"=",
"null",
")",
"{",
"// definir datos que se usarán en el envío",
"list",
"(",
"... | Método que realiza el envío de un DTE al SII
Referencia: http://www.sii.cl/factura_electronica/factura_mercado/envio.pdf
@param usuario RUN del usuario que envía el DTE
@param empresa RUT de la empresa emisora del DTE
@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 gzip Permite enviar el archivo XML comprimido al servidor
@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 Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2017-10-23 | [
"Método",
"que",
"realiza",
"el",
"envío",
"de",
"un",
"DTE",
"al",
"SII",
"Referencia",
":",
"http",
":",
"//",
"www",
".",
"sii",
".",
"cl",
"/",
"factura_electronica",
"/",
"factura_mercado",
"/",
"envio",
".",
"pdf"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii.php#L599-L690 |
LibreDTE/libredte-lib | lib/Sii.php | Sii.cert | public static function cert($idk = null)
{
// si se pasó un idk y existe el archivo asociado se entrega
if ($idk) {
$cert = dirname(dirname(__FILE__)).'/certs/'.$idk.'.cer';
if (is_readable($cert)) {
return file_get_contents($cert);
}
}
// buscar certificado y entregar si existe o =false si no
$ambiente = self::getAmbiente();
$cert = dirname(dirname(__FILE__)).'/certs/'.self::$config['certs'][$ambiente].'.cer';
if (!is_readable($cert)) {
\sasco\LibreDTE\Log::write(Estado::SII_ERROR_CERTIFICADO, Estado::get(Estado::SII_ERROR_CERTIFICADO, self::$config['certs'][$ambiente]));
return false;
}
return file_get_contents($cert);
} | php | public static function cert($idk = null)
{
// si se pasó un idk y existe el archivo asociado se entrega
if ($idk) {
$cert = dirname(dirname(__FILE__)).'/certs/'.$idk.'.cer';
if (is_readable($cert)) {
return file_get_contents($cert);
}
}
// buscar certificado y entregar si existe o =false si no
$ambiente = self::getAmbiente();
$cert = dirname(dirname(__FILE__)).'/certs/'.self::$config['certs'][$ambiente].'.cer';
if (!is_readable($cert)) {
\sasco\LibreDTE\Log::write(Estado::SII_ERROR_CERTIFICADO, Estado::get(Estado::SII_ERROR_CERTIFICADO, self::$config['certs'][$ambiente]));
return false;
}
return file_get_contents($cert);
} | [
"public",
"static",
"function",
"cert",
"(",
"$",
"idk",
"=",
"null",
")",
"{",
"// si se pasó un idk y existe el archivo asociado se entrega",
"if",
"(",
"$",
"idk",
")",
"{",
"$",
"cert",
"=",
"dirname",
"(",
"dirname",
"(",
"__FILE__",
")",
")",
".",
"'/c... | Método para obtener la clave pública (certificado X.509) del SII
\code{.php}
$pub_key = \sasco\LibreDTE\Sii::cert(100); // Certificado IDK 100 (certificación)
\endcode
@param idk IDK de la clave pública del SII. Si no se indica se tratará de determinar con el ambiente que se esté usando
@return Contenido del certificado
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2015-09-16 | [
"Método",
"para",
"obtener",
"la",
"clave",
"pública",
"(",
"certificado",
"X",
".",
"509",
")",
"del",
"SII"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii.php#L704-L721 |
LibreDTE/libredte-lib | lib/Sii.php | Sii.setAmbiente | public static function setAmbiente($ambiente = self::PRODUCCION)
{
$ambiente = $ambiente ? self::CERTIFICACION : self::PRODUCCION;
if ($ambiente==self::CERTIFICACION) {
self::setVerificarSSL(false);
}
self::$ambiente = $ambiente;
} | php | public static function setAmbiente($ambiente = self::PRODUCCION)
{
$ambiente = $ambiente ? self::CERTIFICACION : self::PRODUCCION;
if ($ambiente==self::CERTIFICACION) {
self::setVerificarSSL(false);
}
self::$ambiente = $ambiente;
} | [
"public",
"static",
"function",
"setAmbiente",
"(",
"$",
"ambiente",
"=",
"self",
"::",
"PRODUCCION",
")",
"{",
"$",
"ambiente",
"=",
"$",
"ambiente",
"?",
"self",
"::",
"CERTIFICACION",
":",
"self",
"::",
"PRODUCCION",
";",
"if",
"(",
"$",
"ambiente",
"... | Método que asigna el ambiente que se usará por defecto (si no está
asignado con la constante _LibreDTE_CERTIFICACION_)
@param ambiente Ambiente a usar: Sii::PRODUCCION o Sii::CERTIFICACION
@warning No se está verificando SSL en ambiente de certificación
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2016-08-28 | [
"Método",
"que",
"asigna",
"el",
"ambiente",
"que",
"se",
"usará",
"por",
"defecto",
"(",
"si",
"no",
"está",
"asignado",
"con",
"la",
"constante",
"_LibreDTE_CERTIFICACION_",
")"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii.php#L731-L738 |
LibreDTE/libredte-lib | lib/Sii.php | Sii.getAmbiente | public static function getAmbiente($ambiente = null)
{
if ($ambiente===null) {
if (defined('_LibreDTE_CERTIFICACION_'))
$ambiente = (int)_LibreDTE_CERTIFICACION_;
else
$ambiente = self::$ambiente;
}
return $ambiente;
} | php | public static function getAmbiente($ambiente = null)
{
if ($ambiente===null) {
if (defined('_LibreDTE_CERTIFICACION_'))
$ambiente = (int)_LibreDTE_CERTIFICACION_;
else
$ambiente = self::$ambiente;
}
return $ambiente;
} | [
"public",
"static",
"function",
"getAmbiente",
"(",
"$",
"ambiente",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"ambiente",
"===",
"null",
")",
"{",
"if",
"(",
"defined",
"(",
"'_LibreDTE_CERTIFICACION_'",
")",
")",
"$",
"ambiente",
"=",
"(",
"int",
")",
"... | Método que determina el ambiente que se debe utilizar: producción o
certificación
@param ambiente Ambiente a usar: Sii::PRODUCCION o Sii::CERTIFICACION o null (para detección automática)
@return Ambiente que se debe utilizar
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2015-09-07 | [
"Método",
"que",
"determina",
"el",
"ambiente",
"que",
"se",
"debe",
"utilizar",
":",
"producción",
"o",
"certificación"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii.php#L748-L757 |
LibreDTE/libredte-lib | lib/Sii.php | Sii.getContribuyentes | public static function getContribuyentes(\sasco\LibreDTE\FirmaElectronica $Firma, $ambiente = null, $dia = null)
{
// solicitar token
$token = \sasco\LibreDTE\Sii\Autenticacion::getToken($Firma);
if (!$token)
return false;
// definir ambiente y servidor
$ambiente = self::getAmbiente($ambiente);
$servidor = self::$config['servidor'][$ambiente];
// preparar consulta curl
$curl = curl_init();
$header = [
'User-Agent: Mozilla/4.0 (compatible; PROG 1.0; LibreDTE)',
'Referer: https://'.$servidor.'.sii.cl/cvc/dte/ee_empresas_dte.html',
'Cookie: TOKEN='.$token,
'Accept-Encoding' => 'gzip, deflate, sdch',
];
$dia = $dia===null ? date('Ymd') : str_replace('-', '', $dia);
$url = 'https://'.$servidor.'.sii.cl/cvc_cgi/dte/ce_empresas_dwnld?NOMBRE_ARCHIVO=ce_empresas_dwnld_'.$dia.'.csv';
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á un error de nivel E_USER_NOTICE
if (!self::$verificar_ssl) {
if ($ambiente==self::PRODUCCION) {
$msg = Estado::get(Estado::ENVIO_SSL_SIN_VERIFICAR);
\sasco\LibreDTE\Log::write(Estado::ENVIO_SSL_SIN_VERIFICAR, $msg, LOG_WARNING);
}
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
}
// realizar consulta curl
$response = curl_exec($curl);
if (!$response)
return false;
// cerrar sesión curl
curl_close($curl);
// entregar datos del archivo CSV
ini_set('memory_limit', '1024M');
$lines = explode("\n", $response);
$n_lines = count($lines);
$data = [];
for ($i=1; $i<$n_lines; $i++) {
$row = str_getcsv($lines[$i], ';', '');
unset($lines[$i]);
if (!isset($row[5]))
continue;
for ($j=0; $j<6; $j++)
$row[$j] = trim($row[$j]);
$row[1] = utf8_decode($row[1]);
$row[4] = strtolower($row[4]);
$row[5] = strtolower($row[5]);
$data[] = $row;
}
return $data;
} | php | public static function getContribuyentes(\sasco\LibreDTE\FirmaElectronica $Firma, $ambiente = null, $dia = null)
{
// solicitar token
$token = \sasco\LibreDTE\Sii\Autenticacion::getToken($Firma);
if (!$token)
return false;
// definir ambiente y servidor
$ambiente = self::getAmbiente($ambiente);
$servidor = self::$config['servidor'][$ambiente];
// preparar consulta curl
$curl = curl_init();
$header = [
'User-Agent: Mozilla/4.0 (compatible; PROG 1.0; LibreDTE)',
'Referer: https://'.$servidor.'.sii.cl/cvc/dte/ee_empresas_dte.html',
'Cookie: TOKEN='.$token,
'Accept-Encoding' => 'gzip, deflate, sdch',
];
$dia = $dia===null ? date('Ymd') : str_replace('-', '', $dia);
$url = 'https://'.$servidor.'.sii.cl/cvc_cgi/dte/ce_empresas_dwnld?NOMBRE_ARCHIVO=ce_empresas_dwnld_'.$dia.'.csv';
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á un error de nivel E_USER_NOTICE
if (!self::$verificar_ssl) {
if ($ambiente==self::PRODUCCION) {
$msg = Estado::get(Estado::ENVIO_SSL_SIN_VERIFICAR);
\sasco\LibreDTE\Log::write(Estado::ENVIO_SSL_SIN_VERIFICAR, $msg, LOG_WARNING);
}
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
}
// realizar consulta curl
$response = curl_exec($curl);
if (!$response)
return false;
// cerrar sesión curl
curl_close($curl);
// entregar datos del archivo CSV
ini_set('memory_limit', '1024M');
$lines = explode("\n", $response);
$n_lines = count($lines);
$data = [];
for ($i=1; $i<$n_lines; $i++) {
$row = str_getcsv($lines[$i], ';', '');
unset($lines[$i]);
if (!isset($row[5]))
continue;
for ($j=0; $j<6; $j++)
$row[$j] = trim($row[$j]);
$row[1] = utf8_decode($row[1]);
$row[4] = strtolower($row[4]);
$row[5] = strtolower($row[5]);
$data[] = $row;
}
return $data;
} | [
"public",
"static",
"function",
"getContribuyentes",
"(",
"\\",
"sasco",
"\\",
"LibreDTE",
"\\",
"FirmaElectronica",
"$",
"Firma",
",",
"$",
"ambiente",
"=",
"null",
",",
"$",
"dia",
"=",
"null",
")",
"{",
"// solicitar token",
"$",
"token",
"=",
"\\",
"sa... | Método que entrega un arreglo con todos los datos de los contribuyentes
que operan con factura electrónica descargados desde el SII
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2017-07-07 | [
"Método",
"que",
"entrega",
"un",
"arreglo",
"con",
"todos",
"los",
"datos",
"de",
"los",
"contribuyentes",
"que",
"operan",
"con",
"factura",
"electrónica",
"descargados",
"desde",
"el",
"SII"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii.php#L776-L832 |
LibreDTE/libredte-lib | lib/Sii.php | Sii.getDireccionRegional | public static function getDireccionRegional($comuna)
{
if (!$comuna) {
return 'N.N.';
}
if (!is_numeric($comuna)) {
$direccion = mb_strtoupper($comuna, 'UTF-8');
return isset(self::$direcciones_regionales[$direccion]) ? self::$direcciones_regionales[$direccion] : $direccion;
}
return 'SUC '.$comuna;
} | php | public static function getDireccionRegional($comuna)
{
if (!$comuna) {
return 'N.N.';
}
if (!is_numeric($comuna)) {
$direccion = mb_strtoupper($comuna, 'UTF-8');
return isset(self::$direcciones_regionales[$direccion]) ? self::$direcciones_regionales[$direccion] : $direccion;
}
return 'SUC '.$comuna;
} | [
"public",
"static",
"function",
"getDireccionRegional",
"(",
"$",
"comuna",
")",
"{",
"if",
"(",
"!",
"$",
"comuna",
")",
"{",
"return",
"'N.N.'",
";",
"}",
"if",
"(",
"!",
"is_numeric",
"(",
"$",
"comuna",
")",
")",
"{",
"$",
"direccion",
"=",
"mb_s... | Método que entrega la dirección regional según la comuna que se esté
consultando
@param comuna de la sucursal del emior o bien código de la sucursal del SII
@return Dirección regional del SII
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2017-11-07 | [
"Método",
"que",
"entrega",
"la",
"dirección",
"regional",
"según",
"la",
"comuna",
"que",
"se",
"esté",
"consultando"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii.php#L842-L852 |
LibreDTE/libredte-lib | lib/Sii/Dte/PDF/LibroCompraVenta.php | LibroCompraVenta.agregar | public function agregar(array $libro)
{
$this->startPageGroup();
$this->AddPage();
if (isset($libro['LibroCompraVenta']))
$libro = $libro['LibroCompraVenta'];
// título del libro
$this->SetFont('helvetica', 'B', 16);
$this->Texto('Libro de '.ucfirst(strtolower($libro['EnvioLibro']['Caratula']['TipoOperacion'])), null, null, 'C');
$this->Ln();
$this->Ln();
// carátula
$this->SetFont('helvetica', 'B', 12);
$this->Texto('I.- Carátula');
$this->Ln();
$this->Ln();
$this->SetFont('helvetica', '', 9);
$titulos = ['Emisor', 'Firma', 'Período', 'Resolución', 'N°', 'Operación', 'Tipo de libro', 'Tipo de envio', 'Aut. rectific.'];
$this->addTable($titulos, [$libro['EnvioLibro']['Caratula']]);
$this->Ln();
// resumenes
$this->SetFont('helvetica', 'B', 12);
$this->Texto('II.- Resumen');
$this->Ln();
$this->Ln();
$this->SetFont('helvetica', '', 9);
if (isset($libro['EnvioLibro']['ResumenPeriodo']['TotalesPeriodo'])) {
// agregar resumen
if (!isset($libro['EnvioLibro']['ResumenPeriodo']['TotalesPeriodo'][0])) {
$libro['EnvioLibro']['ResumenPeriodo']['TotalesPeriodo'] = [$libro['EnvioLibro']['ResumenPeriodo']['TotalesPeriodo']];
}
$resumen = [];
$total_resumen = [
'TotDoc' => 0,
'TotMntExe' => 0,
'TotMntNeto' => 0,
'TotMntIVA' => 0,
'CodImp' => 0,
'TotMntImp' => 0,
'TotIVARetParcial' => 0,
'TotIVARetTotal' => 0,
'TotIVANoRetenido' => 0,
'TotMntTotal' => 0,
];
foreach ($libro['EnvioLibro']['ResumenPeriodo']['TotalesPeriodo'] as $total) {
// contabilizar totales del resumen
$total_resumen['TotDoc'] += $total['TotDoc'];
if (in_array($total['TpoDoc'], $this->dte_tipo_operacion['suma'])) {
$total_resumen['TotMntExe'] += !empty($total['TotMntExe']) ? $total['TotMntExe'] : 0;
$total_resumen['TotMntNeto'] += !empty($total['TotMntNeto']) ? $total['TotMntNeto'] : 0;
$total_resumen['TotMntIVA'] += !empty($total['TotMntIVA']) ? $total['TotMntIVA'] : 0;
$total_resumen['TotMntImp'] += !empty($total['TotOtrosImp']['TotMntImp']) ? $total['TotOtrosImp']['TotMntImp'] : 0;
$total_resumen['TotIVARetParcial'] += !empty($total['TotIVARetParcial']) ? $total['TotIVARetParcial'] : 0;
$total_resumen['TotIVARetTotal'] += !empty($total['TotIVARetTotal']) ? $total['TotIVARetTotal'] : 0;
$total_resumen['TotIVANoRetenido'] += !empty($total['TotIVANoRetenido']) ? $total['TotIVANoRetenido'] : 0;
$total_resumen['TotMntTotal'] += $total['TotMntTotal'];
}
else if (in_array($total['TpoDoc'], $this->dte_tipo_operacion['resta'])) {
$total_resumen['TotMntExe'] -= !empty($total['TotMntExe']) ? $total['TotMntExe'] : 0;
$total_resumen['TotMntNeto'] -= !empty($total['TotMntNeto']) ? $total['TotMntNeto'] : 0;
$total_resumen['TotMntIVA'] -= !empty($total['TotMntIVA']) ? $total['TotMntIVA'] : 0;
$total_resumen['TotMntImp'] -= !empty($total['TotOtrosImp']['TotMntImp']) ? $total['TotOtrosImp']['TotMntImp'] : 0;
$total_resumen['TotIVARetParcial'] -= !empty($total['TotIVARetParcial']) ? $total['TotIVARetParcial'] : 0;
$total_resumen['TotIVARetTotal'] -= !empty($total['TotIVARetTotal']) ? $total['TotIVARetTotal'] : 0;
$total_resumen['TotIVANoRetenido'] -= !empty($total['TotIVANoRetenido']) ? $total['TotIVANoRetenido'] : 0;
$total_resumen['TotMntTotal'] -= $total['TotMntTotal'];
}
// agregar al resumen
$resumen[] = [
$total['TpoDoc'],
num($total['TotDoc']),
!empty($total['TotMntExe']) ? num($total['TotMntExe']) : '',
!empty($total['TotMntNeto']) ? num($total['TotMntNeto']) : '',
!empty($total['TotMntIVA']) ? num($total['TotMntIVA']) : '',
!empty($total['TotOtrosImp']['CodImp']) ? $total['TotOtrosImp']['CodImp'] : '',
!empty($total['TotOtrosImp']['TotMntImp']) ? num($total['TotOtrosImp']['TotMntImp']) : '',
!empty($total['TotIVARetParcial']) ? num($total['TotIVARetParcial']) : '',
!empty($total['TotIVARetTotal']) ? num($total['TotIVARetTotal']) : '',
!empty($total['TotIVANoRetenido']) ? num($total['TotIVANoRetenido']) : '',
num($total['TotMntTotal']),
];
}
// agregar totales
$resumen[] = [
'',
num($total_resumen['TotDoc']),
!empty($total_resumen['TotMntExe']) ? num($total_resumen['TotMntExe']) : '',
!empty($total_resumen['TotMntNeto']) ? num($total_resumen['TotMntNeto']) : '',
!empty($total_resumen['TotMntIVA']) ? num($total_resumen['TotMntIVA']) : '',
'',
!empty($total_resumen['TotMntImp']) ? num($total_resumen['TotMntImp']) : '',
!empty($total_resumen['TotIVARetParcial']) ? num($total_resumen['TotIVARetParcial']) : '',
!empty($total_resumen['TotIVARetTotal']) ? num($total_resumen['TotIVARetTotal']) : '',
!empty($total_resumen['TotIVANoRetenido']) ? num($total_resumen['TotIVANoRetenido']) : '',
num($total_resumen['TotMntTotal']),
];
// agregar tabla
$titulos = ['DTE', 'Total', 'Exento', 'Neto', 'IVA', 'Imp', 'Monto', 'Ret parc.', 'Ret tot.', 'No reten.', 'Total'];
$this->addTable($titulos, $resumen, ['width'=>[10, 19, 26, 27, 26, 10, 26, 26, 26, 26, 27]]);
} else {
$this->Texto('Sin movimientos');
$this->Ln();
$this->Ln();
}
// detalle
$this->SetFont('helvetica', 'B', 12);
$this->Texto('III.- Detalle');
$this->Ln();
$this->Ln();
$this->SetFont('helvetica', '', 9);
if (isset($libro['EnvioLibro']['Detalle'])) {
if (!isset($libro['EnvioLibro']['Detalle'][0])) {
$libro['EnvioLibro']['Detalle'] = [$libro['EnvioLibro']['Detalle']];
}
$detalle = [];
foreach ($libro['EnvioLibro']['Detalle'] as $d) {
// impuesto adicional
if (!empty($d['OtrosImp'])) {
if (!isset($d['OtrosImp'][0]))
$d['OtrosImp'] = [$d['OtrosImp']];
$n_OtrosImp = count($d['OtrosImp']);
} else $n_OtrosImp = 0;
// se agrega detalle
$detalle[] = [
$d['TpoDoc'],
$d['NroDoc'],
!empty($d['FchDoc']) ? $d['FchDoc'] : ((!empty($d['Anulado']) && $d['Anulado']=='A') ? 'ANULADO' : ''),
!empty($d['RUTDoc']) ? $d['RUTDoc'] : '',
!empty($d['MntExe']) ? num($d['MntExe']) : '',
!empty($d['MntNeto']) ? num($d['MntNeto']) : '',
!empty($d['MntIVA']) ? num($d['MntIVA']) : '',
$n_OtrosImp ? $d['OtrosImp'][0]['CodImp'] : '',
$n_OtrosImp ? $d['OtrosImp'][0]['TasaImp'] : '',
$n_OtrosImp ? num($d['OtrosImp'][0]['MntImp']) : '',
!empty($d['IVARetParcial']) ? num($d['IVARetParcial']) : '',
!empty($d['IVARetTotal']) ? num($d['IVARetTotal']) : '',
!empty($d['IVANoRetenido']) ? num($d['IVANoRetenido']) : '',
isset($d['MntTotal']) ? num($d['MntTotal']) : '',
];
// agregar otros impuestos adicionales
if ($n_OtrosImp>1) {
for ($i=1; $i<$n_OtrosImp; $i++) {
$detalle[] = [
'',
'',
'',
'',
'',
'',
'',
$d['OtrosImp'][$i]['CodImp'],
$d['OtrosImp'][$i]['TasaImp'],
num($d['OtrosImp'][$i]['MntImp']),
'',
'',
'',
'',
];
}
}
}
$titulos = ['DTE', 'Folio', 'Emisión', 'RUT', 'Exento', 'Neto', 'IVA', 'Imp', 'Tasa', 'Monto', 'Ret parc.', 'Ret tot.', 'No reten.', 'Total'];
$this->addTable($titulos, $detalle, ['fontsize'=>9, 'width'=>[10, 19, 20, 20, 20, 20, 20, 10, 10, 20, 20, 20, 20, 20]], false);
} else {
$this->Texto('No hay detalle de documentos');
$this->Ln();
$this->Ln();
}
// firma
$this->SetFont('helvetica', 'B', 12);
$this->Texto('IV.- Firma electrónica');
$this->Ln();
$this->Ln();
$this->SetFont('helvetica', '', 9);
$titulos = ['Fecha y hora', 'Digest'];
$this->addTable($titulos, [[
str_replace('T', ' ', $libro['EnvioLibro']['TmstFirma']),
isset($libro['Signature']) ? $libro['Signature']['SignedInfo']['Reference']['DigestValue'] : 'Sin firma',
]]);
} | php | public function agregar(array $libro)
{
$this->startPageGroup();
$this->AddPage();
if (isset($libro['LibroCompraVenta']))
$libro = $libro['LibroCompraVenta'];
// título del libro
$this->SetFont('helvetica', 'B', 16);
$this->Texto('Libro de '.ucfirst(strtolower($libro['EnvioLibro']['Caratula']['TipoOperacion'])), null, null, 'C');
$this->Ln();
$this->Ln();
// carátula
$this->SetFont('helvetica', 'B', 12);
$this->Texto('I.- Carátula');
$this->Ln();
$this->Ln();
$this->SetFont('helvetica', '', 9);
$titulos = ['Emisor', 'Firma', 'Período', 'Resolución', 'N°', 'Operación', 'Tipo de libro', 'Tipo de envio', 'Aut. rectific.'];
$this->addTable($titulos, [$libro['EnvioLibro']['Caratula']]);
$this->Ln();
// resumenes
$this->SetFont('helvetica', 'B', 12);
$this->Texto('II.- Resumen');
$this->Ln();
$this->Ln();
$this->SetFont('helvetica', '', 9);
if (isset($libro['EnvioLibro']['ResumenPeriodo']['TotalesPeriodo'])) {
// agregar resumen
if (!isset($libro['EnvioLibro']['ResumenPeriodo']['TotalesPeriodo'][0])) {
$libro['EnvioLibro']['ResumenPeriodo']['TotalesPeriodo'] = [$libro['EnvioLibro']['ResumenPeriodo']['TotalesPeriodo']];
}
$resumen = [];
$total_resumen = [
'TotDoc' => 0,
'TotMntExe' => 0,
'TotMntNeto' => 0,
'TotMntIVA' => 0,
'CodImp' => 0,
'TotMntImp' => 0,
'TotIVARetParcial' => 0,
'TotIVARetTotal' => 0,
'TotIVANoRetenido' => 0,
'TotMntTotal' => 0,
];
foreach ($libro['EnvioLibro']['ResumenPeriodo']['TotalesPeriodo'] as $total) {
// contabilizar totales del resumen
$total_resumen['TotDoc'] += $total['TotDoc'];
if (in_array($total['TpoDoc'], $this->dte_tipo_operacion['suma'])) {
$total_resumen['TotMntExe'] += !empty($total['TotMntExe']) ? $total['TotMntExe'] : 0;
$total_resumen['TotMntNeto'] += !empty($total['TotMntNeto']) ? $total['TotMntNeto'] : 0;
$total_resumen['TotMntIVA'] += !empty($total['TotMntIVA']) ? $total['TotMntIVA'] : 0;
$total_resumen['TotMntImp'] += !empty($total['TotOtrosImp']['TotMntImp']) ? $total['TotOtrosImp']['TotMntImp'] : 0;
$total_resumen['TotIVARetParcial'] += !empty($total['TotIVARetParcial']) ? $total['TotIVARetParcial'] : 0;
$total_resumen['TotIVARetTotal'] += !empty($total['TotIVARetTotal']) ? $total['TotIVARetTotal'] : 0;
$total_resumen['TotIVANoRetenido'] += !empty($total['TotIVANoRetenido']) ? $total['TotIVANoRetenido'] : 0;
$total_resumen['TotMntTotal'] += $total['TotMntTotal'];
}
else if (in_array($total['TpoDoc'], $this->dte_tipo_operacion['resta'])) {
$total_resumen['TotMntExe'] -= !empty($total['TotMntExe']) ? $total['TotMntExe'] : 0;
$total_resumen['TotMntNeto'] -= !empty($total['TotMntNeto']) ? $total['TotMntNeto'] : 0;
$total_resumen['TotMntIVA'] -= !empty($total['TotMntIVA']) ? $total['TotMntIVA'] : 0;
$total_resumen['TotMntImp'] -= !empty($total['TotOtrosImp']['TotMntImp']) ? $total['TotOtrosImp']['TotMntImp'] : 0;
$total_resumen['TotIVARetParcial'] -= !empty($total['TotIVARetParcial']) ? $total['TotIVARetParcial'] : 0;
$total_resumen['TotIVARetTotal'] -= !empty($total['TotIVARetTotal']) ? $total['TotIVARetTotal'] : 0;
$total_resumen['TotIVANoRetenido'] -= !empty($total['TotIVANoRetenido']) ? $total['TotIVANoRetenido'] : 0;
$total_resumen['TotMntTotal'] -= $total['TotMntTotal'];
}
// agregar al resumen
$resumen[] = [
$total['TpoDoc'],
num($total['TotDoc']),
!empty($total['TotMntExe']) ? num($total['TotMntExe']) : '',
!empty($total['TotMntNeto']) ? num($total['TotMntNeto']) : '',
!empty($total['TotMntIVA']) ? num($total['TotMntIVA']) : '',
!empty($total['TotOtrosImp']['CodImp']) ? $total['TotOtrosImp']['CodImp'] : '',
!empty($total['TotOtrosImp']['TotMntImp']) ? num($total['TotOtrosImp']['TotMntImp']) : '',
!empty($total['TotIVARetParcial']) ? num($total['TotIVARetParcial']) : '',
!empty($total['TotIVARetTotal']) ? num($total['TotIVARetTotal']) : '',
!empty($total['TotIVANoRetenido']) ? num($total['TotIVANoRetenido']) : '',
num($total['TotMntTotal']),
];
}
// agregar totales
$resumen[] = [
'',
num($total_resumen['TotDoc']),
!empty($total_resumen['TotMntExe']) ? num($total_resumen['TotMntExe']) : '',
!empty($total_resumen['TotMntNeto']) ? num($total_resumen['TotMntNeto']) : '',
!empty($total_resumen['TotMntIVA']) ? num($total_resumen['TotMntIVA']) : '',
'',
!empty($total_resumen['TotMntImp']) ? num($total_resumen['TotMntImp']) : '',
!empty($total_resumen['TotIVARetParcial']) ? num($total_resumen['TotIVARetParcial']) : '',
!empty($total_resumen['TotIVARetTotal']) ? num($total_resumen['TotIVARetTotal']) : '',
!empty($total_resumen['TotIVANoRetenido']) ? num($total_resumen['TotIVANoRetenido']) : '',
num($total_resumen['TotMntTotal']),
];
// agregar tabla
$titulos = ['DTE', 'Total', 'Exento', 'Neto', 'IVA', 'Imp', 'Monto', 'Ret parc.', 'Ret tot.', 'No reten.', 'Total'];
$this->addTable($titulos, $resumen, ['width'=>[10, 19, 26, 27, 26, 10, 26, 26, 26, 26, 27]]);
} else {
$this->Texto('Sin movimientos');
$this->Ln();
$this->Ln();
}
// detalle
$this->SetFont('helvetica', 'B', 12);
$this->Texto('III.- Detalle');
$this->Ln();
$this->Ln();
$this->SetFont('helvetica', '', 9);
if (isset($libro['EnvioLibro']['Detalle'])) {
if (!isset($libro['EnvioLibro']['Detalle'][0])) {
$libro['EnvioLibro']['Detalle'] = [$libro['EnvioLibro']['Detalle']];
}
$detalle = [];
foreach ($libro['EnvioLibro']['Detalle'] as $d) {
// impuesto adicional
if (!empty($d['OtrosImp'])) {
if (!isset($d['OtrosImp'][0]))
$d['OtrosImp'] = [$d['OtrosImp']];
$n_OtrosImp = count($d['OtrosImp']);
} else $n_OtrosImp = 0;
// se agrega detalle
$detalle[] = [
$d['TpoDoc'],
$d['NroDoc'],
!empty($d['FchDoc']) ? $d['FchDoc'] : ((!empty($d['Anulado']) && $d['Anulado']=='A') ? 'ANULADO' : ''),
!empty($d['RUTDoc']) ? $d['RUTDoc'] : '',
!empty($d['MntExe']) ? num($d['MntExe']) : '',
!empty($d['MntNeto']) ? num($d['MntNeto']) : '',
!empty($d['MntIVA']) ? num($d['MntIVA']) : '',
$n_OtrosImp ? $d['OtrosImp'][0]['CodImp'] : '',
$n_OtrosImp ? $d['OtrosImp'][0]['TasaImp'] : '',
$n_OtrosImp ? num($d['OtrosImp'][0]['MntImp']) : '',
!empty($d['IVARetParcial']) ? num($d['IVARetParcial']) : '',
!empty($d['IVARetTotal']) ? num($d['IVARetTotal']) : '',
!empty($d['IVANoRetenido']) ? num($d['IVANoRetenido']) : '',
isset($d['MntTotal']) ? num($d['MntTotal']) : '',
];
// agregar otros impuestos adicionales
if ($n_OtrosImp>1) {
for ($i=1; $i<$n_OtrosImp; $i++) {
$detalle[] = [
'',
'',
'',
'',
'',
'',
'',
$d['OtrosImp'][$i]['CodImp'],
$d['OtrosImp'][$i]['TasaImp'],
num($d['OtrosImp'][$i]['MntImp']),
'',
'',
'',
'',
];
}
}
}
$titulos = ['DTE', 'Folio', 'Emisión', 'RUT', 'Exento', 'Neto', 'IVA', 'Imp', 'Tasa', 'Monto', 'Ret parc.', 'Ret tot.', 'No reten.', 'Total'];
$this->addTable($titulos, $detalle, ['fontsize'=>9, 'width'=>[10, 19, 20, 20, 20, 20, 20, 10, 10, 20, 20, 20, 20, 20]], false);
} else {
$this->Texto('No hay detalle de documentos');
$this->Ln();
$this->Ln();
}
// firma
$this->SetFont('helvetica', 'B', 12);
$this->Texto('IV.- Firma electrónica');
$this->Ln();
$this->Ln();
$this->SetFont('helvetica', '', 9);
$titulos = ['Fecha y hora', 'Digest'];
$this->addTable($titulos, [[
str_replace('T', ' ', $libro['EnvioLibro']['TmstFirma']),
isset($libro['Signature']) ? $libro['Signature']['SignedInfo']['Reference']['DigestValue'] : 'Sin firma',
]]);
} | [
"public",
"function",
"agregar",
"(",
"array",
"$",
"libro",
")",
"{",
"$",
"this",
"->",
"startPageGroup",
"(",
")",
";",
"$",
"this",
"->",
"AddPage",
"(",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"libro",
"[",
"'LibroCompraVenta'",
"]",
")",
")",
... | Método que agrega un libro al PDF
@param libro
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2016-10-06 | [
"Método",
"que",
"agrega",
"un",
"libro",
"al",
"PDF"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Dte/PDF/LibroCompraVenta.php#L56-L235 |
LibreDTE/libredte-lib | lib/Sii/Dte/Base/DteImpreso.php | DteImpreso.getTipo | protected function getTipo($tipo)
{
if (!is_numeric($tipo) and !isset($this->tipos[$tipo])) {
return $tipo;
}
return isset($this->tipos[$tipo]) ? strtoupper($this->tipos[$tipo]) : 'Documento '.$tipo;
} | php | protected function getTipo($tipo)
{
if (!is_numeric($tipo) and !isset($this->tipos[$tipo])) {
return $tipo;
}
return isset($this->tipos[$tipo]) ? strtoupper($this->tipos[$tipo]) : 'Documento '.$tipo;
} | [
"protected",
"function",
"getTipo",
"(",
"$",
"tipo",
")",
"{",
"if",
"(",
"!",
"is_numeric",
"(",
"$",
"tipo",
")",
"and",
"!",
"isset",
"(",
"$",
"this",
"->",
"tipos",
"[",
"$",
"tipo",
"]",
")",
")",
"{",
"return",
"$",
"tipo",
";",
"}",
"r... | Método que entrega la glosa del tipo de documento
@param tipo Código del tipo de documento
@return Glosa del tipo de documento
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2016-11-18 | [
"Método",
"que",
"entrega",
"la",
"glosa",
"del",
"tipo",
"de",
"documento"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Dte/Base/DteImpreso.php#L202-L208 |
LibreDTE/libredte-lib | lib/Sii/Dte/Base/DteImpreso.php | DteImpreso.num | protected function num($n)
{
if (!is_numeric($n)) {
return $n;
}
$broken_number = explode('.', (string)$n);
if (isset($broken_number[1])) {
return number_format($broken_number[0], 0, ',', '.').','.$broken_number[1];
}
return number_format($broken_number[0], 0, ',', '.');
} | php | protected function num($n)
{
if (!is_numeric($n)) {
return $n;
}
$broken_number = explode('.', (string)$n);
if (isset($broken_number[1])) {
return number_format($broken_number[0], 0, ',', '.').','.$broken_number[1];
}
return number_format($broken_number[0], 0, ',', '.');
} | [
"protected",
"function",
"num",
"(",
"$",
"n",
")",
"{",
"if",
"(",
"!",
"is_numeric",
"(",
"$",
"n",
")",
")",
"{",
"return",
"$",
"n",
";",
"}",
"$",
"broken_number",
"=",
"explode",
"(",
"'.'",
",",
"(",
"string",
")",
"$",
"n",
")",
";",
... | Método que formatea un número con separador de miles y decimales (si
corresponden)
@param n Número que se desea formatear
@return Número formateado
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2016-04-05 | [
"Método",
"que",
"formatea",
"un",
"número",
"con",
"separador",
"de",
"miles",
"y",
"decimales",
"(",
"si",
"corresponden",
")"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Dte/Base/DteImpreso.php#L218-L228 |
LibreDTE/libredte-lib | lib/Sii/Dte/Base/DteImpreso.php | DteImpreso.date | protected function date($date, $mostrar_dia = true)
{
$dias = ['Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado'];
$meses = ['enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio', 'julio', 'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre'];
$unixtime = strtotime($date);
$fecha = date(($mostrar_dia?'\D\I\A ':'').'j \d\e \M\E\S \d\e\l Y', $unixtime);
$dia = $dias[date('w', $unixtime)];
$mes = $meses[date('n', $unixtime)-1];
return str_replace(array('DIA', 'MES'), array($dia, $mes), $fecha);
} | php | protected function date($date, $mostrar_dia = true)
{
$dias = ['Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado'];
$meses = ['enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio', 'julio', 'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre'];
$unixtime = strtotime($date);
$fecha = date(($mostrar_dia?'\D\I\A ':'').'j \d\e \M\E\S \d\e\l Y', $unixtime);
$dia = $dias[date('w', $unixtime)];
$mes = $meses[date('n', $unixtime)-1];
return str_replace(array('DIA', 'MES'), array($dia, $mes), $fecha);
} | [
"protected",
"function",
"date",
"(",
"$",
"date",
",",
"$",
"mostrar_dia",
"=",
"true",
")",
"{",
"$",
"dias",
"=",
"[",
"'Domingo'",
",",
"'Lunes'",
",",
"'Martes'",
",",
"'Miércoles',",
" ",
"Jueves',",
" ",
"Viernes',",
" ",
"Sábado'];",
"",
"",
"$... | Método que formatea una fecha en formato YYYY-MM-DD a un string
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2016-04-28 | [
"Método",
"que",
"formatea",
"una",
"fecha",
"en",
"formato",
"YYYY",
"-",
"MM",
"-",
"DD",
"a",
"un",
"string"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Dte/Base/DteImpreso.php#L235-L244 |
LibreDTE/libredte-lib | lib/Sii/Dte/Formatos.php | Formatos.toArray | public static function toArray($formato, $datos)
{
$class = '\sasco\LibreDTE\Sii\Dte\Formatos\\'.str_replace('.', '\\', $formato);
if (!class_exists($class)) {
$class = '\sasco\LibreDTE\Sii\Dte\Formatos\\'.str_replace('.', '\\', strtoupper($formato));
if (!class_exists($class)) {
$class = '\sasco\LibreDTE\Sii\Dte\Formatos\\'.str_replace('.', '\\', strtolower($formato));
if (!class_exists($class)) {
throw new \Exception('Formato '.$formato.' no es válido como entrada para datos del DTE');
}
}
}
return $class::toArray($datos);
} | php | public static function toArray($formato, $datos)
{
$class = '\sasco\LibreDTE\Sii\Dte\Formatos\\'.str_replace('.', '\\', $formato);
if (!class_exists($class)) {
$class = '\sasco\LibreDTE\Sii\Dte\Formatos\\'.str_replace('.', '\\', strtoupper($formato));
if (!class_exists($class)) {
$class = '\sasco\LibreDTE\Sii\Dte\Formatos\\'.str_replace('.', '\\', strtolower($formato));
if (!class_exists($class)) {
throw new \Exception('Formato '.$formato.' no es válido como entrada para datos del DTE');
}
}
}
return $class::toArray($datos);
} | [
"public",
"static",
"function",
"toArray",
"(",
"$",
"formato",
",",
"$",
"datos",
")",
"{",
"$",
"class",
"=",
"'\\sasco\\LibreDTE\\Sii\\Dte\\Formatos\\\\'",
".",
"str_replace",
"(",
"'.'",
",",
"'\\\\'",
",",
"$",
"formato",
")",
";",
"if",
"(",
"!",
"cl... | Método que convierte los datos en el formato de entrada a un arreglo PHP
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2016-09-12 | [
"Método",
"que",
"convierte",
"los",
"datos",
"en",
"el",
"formato",
"de",
"entrada",
"a",
"un",
"arreglo",
"PHP"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Dte/Formatos.php#L42-L55 |
LibreDTE/libredte-lib | lib/Sii/Dte/Formatos.php | Formatos.toJSON | public static function toJSON($formato, $datos)
{
return json_encode(self::toArray($formato, $datos), JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
} | php | public static function toJSON($formato, $datos)
{
return json_encode(self::toArray($formato, $datos), JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
} | [
"public",
"static",
"function",
"toJSON",
"(",
"$",
"formato",
",",
"$",
"datos",
")",
"{",
"return",
"json_encode",
"(",
"self",
"::",
"toArray",
"(",
"$",
"formato",
",",
"$",
"datos",
")",
",",
"JSON_UNESCAPED_UNICODE",
"|",
"JSON_PRETTY_PRINT",
")",
";... | Método que convierte los datos en el formato de entrada al formato
oficial en JSON
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2018-01-19 | [
"Método",
"que",
"convierte",
"los",
"datos",
"en",
"el",
"formato",
"de",
"entrada",
"al",
"formato",
"oficial",
"en",
"JSON"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Dte/Formatos.php#L63-L66 |
LibreDTE/libredte-lib | lib/Sii/Dte/Formatos.php | Formatos.getFormatos | public static function getFormatos()
{
if (!self::$formatos) {
$dir = dirname(__FILE__).'/Formatos';
$formatos = scandir($dir);
foreach($formatos as &$formato) {
if ($formato[0]=='.')
continue;
if (is_dir($dir.'/'.$formato)) {
$subformatos = scandir($dir.'/'.$formato);
foreach($subformatos as &$subformato) {
if ($subformato[0]=='.')
continue;
self::$formatos[] = $formato.'.'.substr($subformato, 0, -4);
}
} else {
self::$formatos[] = substr($formato, 0, -4);
}
}
}
return self::$formatos;
} | php | public static function getFormatos()
{
if (!self::$formatos) {
$dir = dirname(__FILE__).'/Formatos';
$formatos = scandir($dir);
foreach($formatos as &$formato) {
if ($formato[0]=='.')
continue;
if (is_dir($dir.'/'.$formato)) {
$subformatos = scandir($dir.'/'.$formato);
foreach($subformatos as &$subformato) {
if ($subformato[0]=='.')
continue;
self::$formatos[] = $formato.'.'.substr($subformato, 0, -4);
}
} else {
self::$formatos[] = substr($formato, 0, -4);
}
}
}
return self::$formatos;
} | [
"public",
"static",
"function",
"getFormatos",
"(",
")",
"{",
"if",
"(",
"!",
"self",
"::",
"$",
"formatos",
")",
"{",
"$",
"dir",
"=",
"dirname",
"(",
"__FILE__",
")",
".",
"'/Formatos'",
";",
"$",
"formatos",
"=",
"scandir",
"(",
"$",
"dir",
")",
... | Método que obtiene el listado de formatos soportados (para los que existe
un parser)
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2016-09-12 | [
"Método",
"que",
"obtiene",
"el",
"listado",
"de",
"formatos",
"soportados",
"(",
"para",
"los",
"que",
"existe",
"un",
"parser",
")"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Dte/Formatos.php#L74-L95 |
LibreDTE/libredte-lib | lib/Sii/Dte/PDF/Dte.php | Dte.setAnchoColumnasDetalle | public function setAnchoColumnasDetalle(array $anchos)
{
foreach ($anchos as $col => $ancho) {
if (isset($this->detalle_cols[$col]) and $ancho) {
$this->detalle_cols[$col]['width'] = (int)$ancho;
}
}
} | php | public function setAnchoColumnasDetalle(array $anchos)
{
foreach ($anchos as $col => $ancho) {
if (isset($this->detalle_cols[$col]) and $ancho) {
$this->detalle_cols[$col]['width'] = (int)$ancho;
}
}
} | [
"public",
"function",
"setAnchoColumnasDetalle",
"(",
"array",
"$",
"anchos",
")",
"{",
"foreach",
"(",
"$",
"anchos",
"as",
"$",
"col",
"=>",
"$",
"ancho",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"detalle_cols",
"[",
"$",
"col",
"]",
"... | Método que asigna el ancho e las columnas del detalle desde un arreglo
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2016-08-03 | [
"Método",
"que",
"asigna",
"el",
"ancho",
"e",
"las",
"columnas",
"del",
"detalle",
"desde",
"un",
"arreglo"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Dte/PDF/Dte.php#L117-L124 |
LibreDTE/libredte-lib | lib/Sii/Dte/PDF/Dte.php | Dte.agregar | public function agregar(array $dte, $timbre = null)
{
$this->dte = $dte['Encabezado']['IdDoc']['TipoDTE'];
// papel hoja carta
if (!$this->papelContinuo) {
$this->agregarNormal($dte, $timbre);
}
// papel contínuo 57mm
else if ($this->papelContinuo==57) {
$this->agregarContinuo57($dte, $timbre);
}
// papel contínuo 75 o 80mm
else {
$this->agregarContinuo($dte, $timbre, $this->papelContinuo);
}
} | php | public function agregar(array $dte, $timbre = null)
{
$this->dte = $dte['Encabezado']['IdDoc']['TipoDTE'];
// papel hoja carta
if (!$this->papelContinuo) {
$this->agregarNormal($dte, $timbre);
}
// papel contínuo 57mm
else if ($this->papelContinuo==57) {
$this->agregarContinuo57($dte, $timbre);
}
// papel contínuo 75 o 80mm
else {
$this->agregarContinuo($dte, $timbre, $this->papelContinuo);
}
} | [
"public",
"function",
"agregar",
"(",
"array",
"$",
"dte",
",",
"$",
"timbre",
"=",
"null",
")",
"{",
"$",
"this",
"->",
"dte",
"=",
"$",
"dte",
"[",
"'Encabezado'",
"]",
"[",
"'IdDoc'",
"]",
"[",
"'TipoDTE'",
"]",
";",
"// papel hoja carta",
"if",
"... | Método que agrega un documento tributario, ya sea en formato de una
página o papel contínuo según se haya indicado en el constructor
@param dte Arreglo con los datos del XML (tag Documento)
@param timbre String XML con el tag TED del DTE
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2017-07-13 | [
"Método",
"que",
"agrega",
"un",
"documento",
"tributario",
"ya",
"sea",
"en",
"formato",
"de",
"una",
"página",
"o",
"papel",
"contínuo",
"según",
"se",
"haya",
"indicado",
"en",
"el",
"constructor"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Dte/PDF/Dte.php#L144-L159 |
LibreDTE/libredte-lib | lib/Sii/Dte/PDF/Dte.php | Dte.agregarNormal | private function agregarNormal(array $dte, $timbre)
{
// agregar página para la factura
$this->AddPage();
// agregar cabecera del documento
$y[] = $this->agregarEmisor($dte['Encabezado']['Emisor']);
$y[] = $this->agregarFolio(
$dte['Encabezado']['Emisor']['RUTEmisor'],
$dte['Encabezado']['IdDoc']['TipoDTE'],
$dte['Encabezado']['IdDoc']['Folio'],
!empty($dte['Encabezado']['Emisor']['CmnaOrigen']) ? $dte['Encabezado']['Emisor']['CmnaOrigen'] : null
);
// datos del documento
$this->setY(max($y));
$this->Ln();
$y = [];
$y[] = $this->agregarDatosEmision($dte['Encabezado']['IdDoc'], !empty($dte['Encabezado']['Emisor']['CdgVendedor'])?$dte['Encabezado']['Emisor']['CdgVendedor']:null);
$y[] = $this->agregarReceptor($dte['Encabezado']);
$this->setY(max($y));
$this->agregarTraslado(
!empty($dte['Encabezado']['IdDoc']['IndTraslado']) ? $dte['Encabezado']['IdDoc']['IndTraslado'] : null,
!empty($dte['Encabezado']['Transporte']) ? $dte['Encabezado']['Transporte'] : null
);
if (!empty($dte['Referencia'])) {
$this->agregarReferencia($dte['Referencia']);
}
$this->agregarDetalle($dte['Detalle']);
if (!empty($dte['DscRcgGlobal'])) {
$this->agregarSubTotal($dte['Detalle']);
$this->agregarDescuentosRecargos($dte['DscRcgGlobal']);
}
if (!empty($dte['Encabezado']['IdDoc']['MntPagos'])) {
$this->agregarPagos($dte['Encabezado']['IdDoc']['MntPagos']);
}
// agregar observaciones
$this->x_fin_datos = $this->getY();
$this->agregarObservacion($dte['Encabezado']['IdDoc']);
if (!$this->timbre_pie) {
$this->Ln();
}
$this->x_fin_datos = $this->getY();
$this->agregarTotales($dte['Encabezado']['Totales'], !empty($dte['Encabezado']['OtraMoneda']) ? $dte['Encabezado']['OtraMoneda'] : null);
// agregar timbre
$this->agregarTimbre($timbre);
// agregar acuse de recibo y leyenda cedible
if ($this->cedible and !in_array($dte['Encabezado']['IdDoc']['TipoDTE'], $this->sinAcuseRecibo)) {
$this->agregarAcuseRecibo();
$this->agregarLeyendaDestino($dte['Encabezado']['IdDoc']['TipoDTE']);
}
} | php | private function agregarNormal(array $dte, $timbre)
{
// agregar página para la factura
$this->AddPage();
// agregar cabecera del documento
$y[] = $this->agregarEmisor($dte['Encabezado']['Emisor']);
$y[] = $this->agregarFolio(
$dte['Encabezado']['Emisor']['RUTEmisor'],
$dte['Encabezado']['IdDoc']['TipoDTE'],
$dte['Encabezado']['IdDoc']['Folio'],
!empty($dte['Encabezado']['Emisor']['CmnaOrigen']) ? $dte['Encabezado']['Emisor']['CmnaOrigen'] : null
);
// datos del documento
$this->setY(max($y));
$this->Ln();
$y = [];
$y[] = $this->agregarDatosEmision($dte['Encabezado']['IdDoc'], !empty($dte['Encabezado']['Emisor']['CdgVendedor'])?$dte['Encabezado']['Emisor']['CdgVendedor']:null);
$y[] = $this->agregarReceptor($dte['Encabezado']);
$this->setY(max($y));
$this->agregarTraslado(
!empty($dte['Encabezado']['IdDoc']['IndTraslado']) ? $dte['Encabezado']['IdDoc']['IndTraslado'] : null,
!empty($dte['Encabezado']['Transporte']) ? $dte['Encabezado']['Transporte'] : null
);
if (!empty($dte['Referencia'])) {
$this->agregarReferencia($dte['Referencia']);
}
$this->agregarDetalle($dte['Detalle']);
if (!empty($dte['DscRcgGlobal'])) {
$this->agregarSubTotal($dte['Detalle']);
$this->agregarDescuentosRecargos($dte['DscRcgGlobal']);
}
if (!empty($dte['Encabezado']['IdDoc']['MntPagos'])) {
$this->agregarPagos($dte['Encabezado']['IdDoc']['MntPagos']);
}
// agregar observaciones
$this->x_fin_datos = $this->getY();
$this->agregarObservacion($dte['Encabezado']['IdDoc']);
if (!$this->timbre_pie) {
$this->Ln();
}
$this->x_fin_datos = $this->getY();
$this->agregarTotales($dte['Encabezado']['Totales'], !empty($dte['Encabezado']['OtraMoneda']) ? $dte['Encabezado']['OtraMoneda'] : null);
// agregar timbre
$this->agregarTimbre($timbre);
// agregar acuse de recibo y leyenda cedible
if ($this->cedible and !in_array($dte['Encabezado']['IdDoc']['TipoDTE'], $this->sinAcuseRecibo)) {
$this->agregarAcuseRecibo();
$this->agregarLeyendaDestino($dte['Encabezado']['IdDoc']['TipoDTE']);
}
} | [
"private",
"function",
"agregarNormal",
"(",
"array",
"$",
"dte",
",",
"$",
"timbre",
")",
"{",
"// agregar página para la factura",
"$",
"this",
"->",
"AddPage",
"(",
")",
";",
"// agregar cabecera del documento",
"$",
"y",
"[",
"]",
"=",
"$",
"this",
"->",
... | Método que agrega una página con el documento tributario
@param dte Arreglo con los datos del XML (tag Documento)
@param timbre String XML con el tag TED del DTE
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2017-11-07 | [
"Método",
"que",
"agrega",
"una",
"página",
"con",
"el",
"documento",
"tributario"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Dte/PDF/Dte.php#L168-L217 |
LibreDTE/libredte-lib | lib/Sii/Dte/PDF/Dte.php | Dte.agregarContinuo | private function agregarContinuo(array $dte, $timbre, $width, $height = 0)
{
// determinar alto de la página y agregarla
$this->logo = null;
$x_start = 1;
$y_start = 1;
$offset = 14;
// determinar alto de la página y agregarla
$this->AddPage('P', [$height ? $height : $this->papel_continuo_alto, $width]);
// agregar cabecera del documento
$y = $this->agregarFolio(
$dte['Encabezado']['Emisor']['RUTEmisor'],
$dte['Encabezado']['IdDoc']['TipoDTE'],
$dte['Encabezado']['IdDoc']['Folio'],
$dte['Encabezado']['Emisor']['CmnaOrigen'],
$x_start, $y_start, $width-($x_start*4), 10,
[0,0,0]
);
$y = $this->agregarEmisor($dte['Encabezado']['Emisor'], $x_start, $y+2, $width-($x_start*45), 8, 9, [0,0,0]);
// datos del documento
$this->SetY($y);
$this->Ln();
$this->setFont('', '', 8);
$this->agregarDatosEmision($dte['Encabezado']['IdDoc'], !empty($dte['Encabezado']['Emisor']['CdgVendedor'])?$dte['Encabezado']['Emisor']['CdgVendedor']:null, $x_start, $offset, false);
$this->agregarReceptor($dte['Encabezado'], $x_start, $offset);
$this->agregarTraslado(
!empty($dte['Encabezado']['IdDoc']['IndTraslado']) ? $dte['Encabezado']['IdDoc']['IndTraslado'] : null,
!empty($dte['Encabezado']['Transporte']) ? $dte['Encabezado']['Transporte'] : null,
$x_start, $offset
);
if (!empty($dte['Referencia'])) {
$this->agregarReferencia($dte['Referencia'], $x_start, $offset);
}
$this->Ln();
$this->agregarDetalleContinuo($dte['Detalle']);
if (!empty($dte['DscRcgGlobal'])) {
$this->Ln();
$this->Ln();
$this->agregarSubTotal($dte['Detalle'], $x_start);
$this->agregarDescuentosRecargos($dte['DscRcgGlobal'], $x_start);
}
if (!empty($dte['Encabezado']['IdDoc']['MntPagos'])) {
$this->Ln();
$this->Ln();
$this->agregarPagos($dte['Encabezado']['IdDoc']['MntPagos'], $x_start);
}
$this->agregarTotales($dte['Encabezado']['Totales'], !empty($dte['Encabezado']['OtraMoneda']) ? $dte['Encabezado']['OtraMoneda'] : null, $this->y+6, 23, 17);
// agregar acuse de recibo y leyenda cedible
if ($this->cedible and !in_array($dte['Encabezado']['IdDoc']['TipoDTE'], $this->sinAcuseRecibo)) {
$this->agregarAcuseReciboContinuo(3, $this->y+6, 68, 34);
$this->agregarLeyendaDestinoContinuo($dte['Encabezado']['IdDoc']['TipoDTE']);
}
// agregar timbre
$y = $this->agregarObservacion($dte['Encabezado']['IdDoc'], $x_start, $this->y+6);
$this->agregarTimbre($timbre, -10, $x_start, $y+6, 70, 6);
// si el alto no se pasó, entonces es con autocálculo, se elimina esta página y se pasa el alto
// que se logró determinar para crear la página con el alto correcto
if (!$height) {
$this->deletePage($this->PageNo());
$this->agregarContinuo($dte, $timbre, $width, $this->getY()+30);
}
} | php | private function agregarContinuo(array $dte, $timbre, $width, $height = 0)
{
// determinar alto de la página y agregarla
$this->logo = null;
$x_start = 1;
$y_start = 1;
$offset = 14;
// determinar alto de la página y agregarla
$this->AddPage('P', [$height ? $height : $this->papel_continuo_alto, $width]);
// agregar cabecera del documento
$y = $this->agregarFolio(
$dte['Encabezado']['Emisor']['RUTEmisor'],
$dte['Encabezado']['IdDoc']['TipoDTE'],
$dte['Encabezado']['IdDoc']['Folio'],
$dte['Encabezado']['Emisor']['CmnaOrigen'],
$x_start, $y_start, $width-($x_start*4), 10,
[0,0,0]
);
$y = $this->agregarEmisor($dte['Encabezado']['Emisor'], $x_start, $y+2, $width-($x_start*45), 8, 9, [0,0,0]);
// datos del documento
$this->SetY($y);
$this->Ln();
$this->setFont('', '', 8);
$this->agregarDatosEmision($dte['Encabezado']['IdDoc'], !empty($dte['Encabezado']['Emisor']['CdgVendedor'])?$dte['Encabezado']['Emisor']['CdgVendedor']:null, $x_start, $offset, false);
$this->agregarReceptor($dte['Encabezado'], $x_start, $offset);
$this->agregarTraslado(
!empty($dte['Encabezado']['IdDoc']['IndTraslado']) ? $dte['Encabezado']['IdDoc']['IndTraslado'] : null,
!empty($dte['Encabezado']['Transporte']) ? $dte['Encabezado']['Transporte'] : null,
$x_start, $offset
);
if (!empty($dte['Referencia'])) {
$this->agregarReferencia($dte['Referencia'], $x_start, $offset);
}
$this->Ln();
$this->agregarDetalleContinuo($dte['Detalle']);
if (!empty($dte['DscRcgGlobal'])) {
$this->Ln();
$this->Ln();
$this->agregarSubTotal($dte['Detalle'], $x_start);
$this->agregarDescuentosRecargos($dte['DscRcgGlobal'], $x_start);
}
if (!empty($dte['Encabezado']['IdDoc']['MntPagos'])) {
$this->Ln();
$this->Ln();
$this->agregarPagos($dte['Encabezado']['IdDoc']['MntPagos'], $x_start);
}
$this->agregarTotales($dte['Encabezado']['Totales'], !empty($dte['Encabezado']['OtraMoneda']) ? $dte['Encabezado']['OtraMoneda'] : null, $this->y+6, 23, 17);
// agregar acuse de recibo y leyenda cedible
if ($this->cedible and !in_array($dte['Encabezado']['IdDoc']['TipoDTE'], $this->sinAcuseRecibo)) {
$this->agregarAcuseReciboContinuo(3, $this->y+6, 68, 34);
$this->agregarLeyendaDestinoContinuo($dte['Encabezado']['IdDoc']['TipoDTE']);
}
// agregar timbre
$y = $this->agregarObservacion($dte['Encabezado']['IdDoc'], $x_start, $this->y+6);
$this->agregarTimbre($timbre, -10, $x_start, $y+6, 70, 6);
// si el alto no se pasó, entonces es con autocálculo, se elimina esta página y se pasa el alto
// que se logró determinar para crear la página con el alto correcto
if (!$height) {
$this->deletePage($this->PageNo());
$this->agregarContinuo($dte, $timbre, $width, $this->getY()+30);
}
} | [
"private",
"function",
"agregarContinuo",
"(",
"array",
"$",
"dte",
",",
"$",
"timbre",
",",
"$",
"width",
",",
"$",
"height",
"=",
"0",
")",
"{",
"// determinar alto de la página y agregarla",
"$",
"this",
"->",
"logo",
"=",
"null",
";",
"$",
"x_start",
"... | Método que agrega una página con el documento tributario en papel
contínuo
@param dte Arreglo con los datos del XML (tag Documento)
@param timbre String XML con el tag TED del DTE
@param width Ancho del papel contínuo en mm
@author Pablo Reyes (https://github.com/pabloxp)
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2017-10-24 | [
"Método",
"que",
"agrega",
"una",
"página",
"con",
"el",
"documento",
"tributario",
"en",
"papel",
"contínuo"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Dte/PDF/Dte.php#L229-L290 |
LibreDTE/libredte-lib | lib/Sii/Dte/PDF/Dte.php | Dte.agregarContinuo57 | private function agregarContinuo57(array $dte, $timbre, $width = 57, $height = 0)
{
// determinar alto de la página y agregarla
$this->AddPage('P', [$height ? $height : $this->papel_continuo_alto, $width]);
$x = 1;
$y = 5;
$this->SetXY($x,$y);
// agregar datos del documento
$this->setFont('', '', 8);
$this->MultiTexto(!empty($dte['Encabezado']['Emisor']['RznSoc']) ? $dte['Encabezado']['Emisor']['RznSoc'] : $dte['Encabezado']['Emisor']['RznSocEmisor'], $x, null, '', $width-2);
$this->MultiTexto($dte['Encabezado']['Emisor']['RUTEmisor'], $x, null, '', $width-2);
$this->MultiTexto('Giro: '.(!empty($dte['Encabezado']['Emisor']['GiroEmis']) ? $dte['Encabezado']['Emisor']['GiroEmis'] : $dte['Encabezado']['Emisor']['GiroEmisor']), $x, null, '', $width-2);
$this->MultiTexto($dte['Encabezado']['Emisor']['DirOrigen'].', '.$dte['Encabezado']['Emisor']['CmnaOrigen'], $x, null, '', $width-2);
if (!empty($dte['Encabezado']['Emisor']['Sucursal'])) {
$this->MultiTexto('Sucursal: '.$dte['Encabezado']['Emisor']['Sucursal'], $x, null, '', $width-2);
}
if (!empty($this->casa_matriz)) {
$this->MultiTexto('Casa matriz: '.$this->casa_matriz, $x, null, '', $width-2);
}
$this->MultiTexto($this->getTipo($dte['Encabezado']['IdDoc']['TipoDTE']).' N° '.$dte['Encabezado']['IdDoc']['Folio'], $x, null, '', $width-2);
$this->MultiTexto('Fecha: '.date('d/m/Y', strtotime($dte['Encabezado']['IdDoc']['FchEmis'])), $x, null, '', $width-2);
// si no es boleta no nominativa se agregan datos receptor
if ($dte['Encabezado']['Receptor']['RUTRecep']!='66666666-6') {
$this->Ln();
$this->MultiTexto('Receptor: '.$dte['Encabezado']['Receptor']['RUTRecep'], $x, null, '', $width-2);
$this->MultiTexto($dte['Encabezado']['Receptor']['RznSocRecep'], $x, null, '', $width-2);
if (!empty($dte['Encabezado']['Receptor']['GiroRecep'])) {
$this->MultiTexto('Giro: '.$dte['Encabezado']['Receptor']['GiroRecep'], $x, null, '', $width-2);
}
if (!empty($dte['Encabezado']['Receptor']['DirRecep'])) {
$this->MultiTexto($dte['Encabezado']['Receptor']['DirRecep'].', '.$dte['Encabezado']['Receptor']['CmnaRecep'], $x, null, '', $width-2);
}
}
$this->Ln();
// hay un sólo detalle
if (!isset($dte['Detalle'][0])) {
$this->MultiTexto($dte['Detalle']['NmbItem'].': $'.$this->num($dte['Detalle']['MontoItem']), $x, null, '', $width-2);
}
// hay más de un detalle
else {
foreach ($dte['Detalle'] as $d) {
$this->MultiTexto($d['NmbItem'].': $'.$this->num($d['MontoItem']), $x, null, '', $width-2);
}
if (in_array($dte['Encabezado']['IdDoc']['TipoDTE'], [39, 41])) {
$this->MultiTexto('TOTAL: $'.$this->num($dte['Encabezado']['Totales']['MntTotal']), $x, null, '', $width-2);
}
}
// si no es boleta se coloca EXENTO, NETO, IVA y TOTAL si corresponde
if (!in_array($dte['Encabezado']['IdDoc']['TipoDTE'], [39, 41])) {
if (!empty($dte['Encabezado']['Totales']['MntExe'])) {
$this->MultiTexto('EXENTO: $'.$this->num($dte['Encabezado']['Totales']['MntExe']), $x, null, '', $width-2);
}
if (!empty($dte['Encabezado']['Totales']['MntNeto'])) {
$this->MultiTexto('NETO: $'.$this->num($dte['Encabezado']['Totales']['MntNeto']), $x, null, '', $width-2);
}
if (!empty($dte['Encabezado']['Totales']['IVA'])) {
$this->MultiTexto('IVA: $'.$this->num($dte['Encabezado']['Totales']['IVA']), $x, null, '', $width-2);
}
$this->MultiTexto('TOTAL: $'.$this->num($dte['Encabezado']['Totales']['MntTotal']), $x, null, '', $width-2);
}
// agregar acuse de recibo y leyenda cedible
if ($this->cedible and !in_array($dte['Encabezado']['IdDoc']['TipoDTE'], $this->sinAcuseRecibo)) {
$this->agregarAcuseReciboContinuo(-1, $this->y+6, $width+2, 34);
$this->agregarLeyendaDestinoContinuo($dte['Encabezado']['IdDoc']['TipoDTE']);
}
// agregar timbre
if (!empty($dte['Encabezado']['IdDoc']['TermPagoGlosa'])) {
$this->Ln();
$this->MultiTexto('Observación: '.$dte['Encabezado']['IdDoc']['TermPagoGlosa']."\n\n", $x);
}
$this->agregarTimbre($timbre, -11, $x, $this->GetY()+6, 55, 6);
// si el alto no se pasó, entonces es con autocálculo, se elimina esta página y se pasa el alto
// que se logró determinar para crear la página con el alto correcto
if (!$height) {
$this->deletePage($this->PageNo());
$this->agregarContinuo57($dte, $timbre, $width, $this->getY()+30);
}
} | php | private function agregarContinuo57(array $dte, $timbre, $width = 57, $height = 0)
{
// determinar alto de la página y agregarla
$this->AddPage('P', [$height ? $height : $this->papel_continuo_alto, $width]);
$x = 1;
$y = 5;
$this->SetXY($x,$y);
// agregar datos del documento
$this->setFont('', '', 8);
$this->MultiTexto(!empty($dte['Encabezado']['Emisor']['RznSoc']) ? $dte['Encabezado']['Emisor']['RznSoc'] : $dte['Encabezado']['Emisor']['RznSocEmisor'], $x, null, '', $width-2);
$this->MultiTexto($dte['Encabezado']['Emisor']['RUTEmisor'], $x, null, '', $width-2);
$this->MultiTexto('Giro: '.(!empty($dte['Encabezado']['Emisor']['GiroEmis']) ? $dte['Encabezado']['Emisor']['GiroEmis'] : $dte['Encabezado']['Emisor']['GiroEmisor']), $x, null, '', $width-2);
$this->MultiTexto($dte['Encabezado']['Emisor']['DirOrigen'].', '.$dte['Encabezado']['Emisor']['CmnaOrigen'], $x, null, '', $width-2);
if (!empty($dte['Encabezado']['Emisor']['Sucursal'])) {
$this->MultiTexto('Sucursal: '.$dte['Encabezado']['Emisor']['Sucursal'], $x, null, '', $width-2);
}
if (!empty($this->casa_matriz)) {
$this->MultiTexto('Casa matriz: '.$this->casa_matriz, $x, null, '', $width-2);
}
$this->MultiTexto($this->getTipo($dte['Encabezado']['IdDoc']['TipoDTE']).' N° '.$dte['Encabezado']['IdDoc']['Folio'], $x, null, '', $width-2);
$this->MultiTexto('Fecha: '.date('d/m/Y', strtotime($dte['Encabezado']['IdDoc']['FchEmis'])), $x, null, '', $width-2);
// si no es boleta no nominativa se agregan datos receptor
if ($dte['Encabezado']['Receptor']['RUTRecep']!='66666666-6') {
$this->Ln();
$this->MultiTexto('Receptor: '.$dte['Encabezado']['Receptor']['RUTRecep'], $x, null, '', $width-2);
$this->MultiTexto($dte['Encabezado']['Receptor']['RznSocRecep'], $x, null, '', $width-2);
if (!empty($dte['Encabezado']['Receptor']['GiroRecep'])) {
$this->MultiTexto('Giro: '.$dte['Encabezado']['Receptor']['GiroRecep'], $x, null, '', $width-2);
}
if (!empty($dte['Encabezado']['Receptor']['DirRecep'])) {
$this->MultiTexto($dte['Encabezado']['Receptor']['DirRecep'].', '.$dte['Encabezado']['Receptor']['CmnaRecep'], $x, null, '', $width-2);
}
}
$this->Ln();
// hay un sólo detalle
if (!isset($dte['Detalle'][0])) {
$this->MultiTexto($dte['Detalle']['NmbItem'].': $'.$this->num($dte['Detalle']['MontoItem']), $x, null, '', $width-2);
}
// hay más de un detalle
else {
foreach ($dte['Detalle'] as $d) {
$this->MultiTexto($d['NmbItem'].': $'.$this->num($d['MontoItem']), $x, null, '', $width-2);
}
if (in_array($dte['Encabezado']['IdDoc']['TipoDTE'], [39, 41])) {
$this->MultiTexto('TOTAL: $'.$this->num($dte['Encabezado']['Totales']['MntTotal']), $x, null, '', $width-2);
}
}
// si no es boleta se coloca EXENTO, NETO, IVA y TOTAL si corresponde
if (!in_array($dte['Encabezado']['IdDoc']['TipoDTE'], [39, 41])) {
if (!empty($dte['Encabezado']['Totales']['MntExe'])) {
$this->MultiTexto('EXENTO: $'.$this->num($dte['Encabezado']['Totales']['MntExe']), $x, null, '', $width-2);
}
if (!empty($dte['Encabezado']['Totales']['MntNeto'])) {
$this->MultiTexto('NETO: $'.$this->num($dte['Encabezado']['Totales']['MntNeto']), $x, null, '', $width-2);
}
if (!empty($dte['Encabezado']['Totales']['IVA'])) {
$this->MultiTexto('IVA: $'.$this->num($dte['Encabezado']['Totales']['IVA']), $x, null, '', $width-2);
}
$this->MultiTexto('TOTAL: $'.$this->num($dte['Encabezado']['Totales']['MntTotal']), $x, null, '', $width-2);
}
// agregar acuse de recibo y leyenda cedible
if ($this->cedible and !in_array($dte['Encabezado']['IdDoc']['TipoDTE'], $this->sinAcuseRecibo)) {
$this->agregarAcuseReciboContinuo(-1, $this->y+6, $width+2, 34);
$this->agregarLeyendaDestinoContinuo($dte['Encabezado']['IdDoc']['TipoDTE']);
}
// agregar timbre
if (!empty($dte['Encabezado']['IdDoc']['TermPagoGlosa'])) {
$this->Ln();
$this->MultiTexto('Observación: '.$dte['Encabezado']['IdDoc']['TermPagoGlosa']."\n\n", $x);
}
$this->agregarTimbre($timbre, -11, $x, $this->GetY()+6, 55, 6);
// si el alto no se pasó, entonces es con autocálculo, se elimina esta página y se pasa el alto
// que se logró determinar para crear la página con el alto correcto
if (!$height) {
$this->deletePage($this->PageNo());
$this->agregarContinuo57($dte, $timbre, $width, $this->getY()+30);
}
} | [
"private",
"function",
"agregarContinuo57",
"(",
"array",
"$",
"dte",
",",
"$",
"timbre",
",",
"$",
"width",
"=",
"57",
",",
"$",
"height",
"=",
"0",
")",
"{",
"// determinar alto de la página y agregarla",
"$",
"this",
"->",
"AddPage",
"(",
"'P'",
",",
"[... | Método que agrega una página con el documento tributario
@param dte Arreglo con los datos del XML (tag Documento)
@param timbre String XML con el tag TED del DTE
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2018-11-04 | [
"Método",
"que",
"agrega",
"una",
"página",
"con",
"el",
"documento",
"tributario"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Dte/PDF/Dte.php#L299-L376 |
LibreDTE/libredte-lib | lib/Sii/Dte/PDF/Dte.php | Dte.agregarEmisor | protected function agregarEmisor(array $emisor, $x = 10, $y = 15, $w = 75, $w_img = 30, $font_size = null, array $color = null)
{
// logo del documento
if (isset($this->logo)) {
$this->Image(
$this->logo['uri'],
$x,
$y,
!$this->logo['posicion']?$w_img:null, $this->logo['posicion']?($w_img/2):null,
'PNG',
(isset($emisor['url'])?$emisor['url']:''),
'T'
);
if ($this->logo['posicion']) {
$this->SetY($this->y + ($w_img/2));
$w += 40;
} else {
$x = $this->x+3;
}
} else {
$this->y = $y-2;
$w += 40;
}
// agregar datos del emisor
$this->setFont('', 'B', $font_size ? $font_size : 14);
$this->SetTextColorArray($color===null?[32, 92, 144]:$color);
$this->MultiTexto(!empty($emisor['RznSoc']) ? $emisor['RznSoc'] : $emisor['RznSocEmisor'], $x, $this->y+2, 'L', $w);
$this->setFont('', 'B', $font_size ? $font_size : 9);
$this->SetTextColorArray([0,0,0]);
$this->MultiTexto(!empty($emisor['GiroEmis']) ? $emisor['GiroEmis'] : $emisor['GiroEmisor'], $x, $this->y, 'L', $w);
$comuna = !empty($emisor['CmnaOrigen']) ? $emisor['CmnaOrigen'] : null;
$ciudad = !empty($emisor['CiudadOrigen']) ? $emisor['CiudadOrigen'] : \sasco\LibreDTE\Chile::getCiudad($comuna);
$this->MultiTexto($emisor['DirOrigen'].($comuna?(', '.$comuna):'').($ciudad?(', '.$ciudad):''), $x, $this->y, 'L', $w);
if (!empty($emisor['Sucursal'])) {
$this->MultiTexto('Sucursal: '.$emisor['Sucursal'], $x, $this->y, 'L', $w);
}
if (!empty($this->casa_matriz)) {
$this->MultiTexto('Casa matriz: '.$this->casa_matriz, $x, $this->y, 'L', $w);
}
$contacto = [];
if (!empty($emisor['Telefono'])) {
if (!is_array($emisor['Telefono']))
$emisor['Telefono'] = [$emisor['Telefono']];
foreach ($emisor['Telefono'] as $t)
$contacto[] = $t;
}
if (!empty($emisor['CorreoEmisor'])) {
$contacto[] = $emisor['CorreoEmisor'];
}
if ($contacto) {
$this->MultiTexto(implode(' / ', $contacto), $x, $this->y, 'L', $w);
}
return $this->y;
} | php | protected function agregarEmisor(array $emisor, $x = 10, $y = 15, $w = 75, $w_img = 30, $font_size = null, array $color = null)
{
// logo del documento
if (isset($this->logo)) {
$this->Image(
$this->logo['uri'],
$x,
$y,
!$this->logo['posicion']?$w_img:null, $this->logo['posicion']?($w_img/2):null,
'PNG',
(isset($emisor['url'])?$emisor['url']:''),
'T'
);
if ($this->logo['posicion']) {
$this->SetY($this->y + ($w_img/2));
$w += 40;
} else {
$x = $this->x+3;
}
} else {
$this->y = $y-2;
$w += 40;
}
// agregar datos del emisor
$this->setFont('', 'B', $font_size ? $font_size : 14);
$this->SetTextColorArray($color===null?[32, 92, 144]:$color);
$this->MultiTexto(!empty($emisor['RznSoc']) ? $emisor['RznSoc'] : $emisor['RznSocEmisor'], $x, $this->y+2, 'L', $w);
$this->setFont('', 'B', $font_size ? $font_size : 9);
$this->SetTextColorArray([0,0,0]);
$this->MultiTexto(!empty($emisor['GiroEmis']) ? $emisor['GiroEmis'] : $emisor['GiroEmisor'], $x, $this->y, 'L', $w);
$comuna = !empty($emisor['CmnaOrigen']) ? $emisor['CmnaOrigen'] : null;
$ciudad = !empty($emisor['CiudadOrigen']) ? $emisor['CiudadOrigen'] : \sasco\LibreDTE\Chile::getCiudad($comuna);
$this->MultiTexto($emisor['DirOrigen'].($comuna?(', '.$comuna):'').($ciudad?(', '.$ciudad):''), $x, $this->y, 'L', $w);
if (!empty($emisor['Sucursal'])) {
$this->MultiTexto('Sucursal: '.$emisor['Sucursal'], $x, $this->y, 'L', $w);
}
if (!empty($this->casa_matriz)) {
$this->MultiTexto('Casa matriz: '.$this->casa_matriz, $x, $this->y, 'L', $w);
}
$contacto = [];
if (!empty($emisor['Telefono'])) {
if (!is_array($emisor['Telefono']))
$emisor['Telefono'] = [$emisor['Telefono']];
foreach ($emisor['Telefono'] as $t)
$contacto[] = $t;
}
if (!empty($emisor['CorreoEmisor'])) {
$contacto[] = $emisor['CorreoEmisor'];
}
if ($contacto) {
$this->MultiTexto(implode(' / ', $contacto), $x, $this->y, 'L', $w);
}
return $this->y;
} | [
"protected",
"function",
"agregarEmisor",
"(",
"array",
"$",
"emisor",
",",
"$",
"x",
"=",
"10",
",",
"$",
"y",
"=",
"15",
",",
"$",
"w",
"=",
"75",
",",
"$",
"w_img",
"=",
"30",
",",
"$",
"font_size",
"=",
"null",
",",
"array",
"$",
"color",
"... | Método que agrega los datos de la empresa
Orden de los datos:
- Razón social del emisor
- Giro del emisor (sin abreviar)
- Dirección casa central del emisor
- Dirección sucursales
@param emisor Arreglo con los datos del emisor (tag Emisor del XML)
@param x Posición horizontal de inicio en el PDF
@param y Posición vertical de inicio en el PDF
@param w Ancho de la información del emisor
@param w_img Ancho máximo de la imagen
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2018-06-15 | [
"Método",
"que",
"agrega",
"los",
"datos",
"de",
"la",
"empresa",
"Orden",
"de",
"los",
"datos",
":",
"-",
"Razón",
"social",
"del",
"emisor",
"-",
"Giro",
"del",
"emisor",
"(",
"sin",
"abreviar",
")",
"-",
"Dirección",
"casa",
"central",
"del",
"emisor"... | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Dte/PDF/Dte.php#L393-L446 |
LibreDTE/libredte-lib | lib/Sii/Dte/PDF/Dte.php | Dte.agregarFolio | protected function agregarFolio($rut, $tipo, $folio, $sucursal_sii = null, $x = 130, $y = 15, $w = 70, $font_size = null, array $color = null)
{
if ($color===null) {
$color = $tipo ? ($tipo==52 ? [0,172,140] : [255,0,0]) : [0,0,0];
}
$this->SetTextColorArray($color);
// colocar rut emisor, glosa documento y folio
list($rut, $dv) = explode('-', $rut);
$this->setFont ('', 'B', $font_size ? $font_size : 15);
$this->MultiTexto('R.U.T.: '.$this->num($rut).'-'.$dv, $x, $y+4, 'C', $w);
$this->setFont('', 'B', $font_size ? $font_size : 12);
$this->MultiTexto($this->getTipo($tipo), $x, null, 'C', $w);
$this->setFont('', 'B', $font_size ? $font_size : 15);
$this->MultiTexto('N° '.$folio, $x, null, 'C', $w);
// dibujar rectángulo rojo
$this->Rect($x, $y, $w, round($this->getY()-$y+3), 'D', ['all' => ['width' => 0.5, 'color' => $color]]);
// colocar unidad del SII
$this->setFont('', 'B', $font_size ? $font_size : 10);
if ($tipo) {
$this->Texto('S.I.I. - '.\sasco\LibreDTE\Sii::getDireccionRegional($sucursal_sii), $x, $this->getY()+4, 'C', $w);
}
$this->SetTextColorArray([0,0,0]);
$this->Ln();
return $this->y;
} | php | protected function agregarFolio($rut, $tipo, $folio, $sucursal_sii = null, $x = 130, $y = 15, $w = 70, $font_size = null, array $color = null)
{
if ($color===null) {
$color = $tipo ? ($tipo==52 ? [0,172,140] : [255,0,0]) : [0,0,0];
}
$this->SetTextColorArray($color);
// colocar rut emisor, glosa documento y folio
list($rut, $dv) = explode('-', $rut);
$this->setFont ('', 'B', $font_size ? $font_size : 15);
$this->MultiTexto('R.U.T.: '.$this->num($rut).'-'.$dv, $x, $y+4, 'C', $w);
$this->setFont('', 'B', $font_size ? $font_size : 12);
$this->MultiTexto($this->getTipo($tipo), $x, null, 'C', $w);
$this->setFont('', 'B', $font_size ? $font_size : 15);
$this->MultiTexto('N° '.$folio, $x, null, 'C', $w);
// dibujar rectángulo rojo
$this->Rect($x, $y, $w, round($this->getY()-$y+3), 'D', ['all' => ['width' => 0.5, 'color' => $color]]);
// colocar unidad del SII
$this->setFont('', 'B', $font_size ? $font_size : 10);
if ($tipo) {
$this->Texto('S.I.I. - '.\sasco\LibreDTE\Sii::getDireccionRegional($sucursal_sii), $x, $this->getY()+4, 'C', $w);
}
$this->SetTextColorArray([0,0,0]);
$this->Ln();
return $this->y;
} | [
"protected",
"function",
"agregarFolio",
"(",
"$",
"rut",
",",
"$",
"tipo",
",",
"$",
"folio",
",",
"$",
"sucursal_sii",
"=",
"null",
",",
"$",
"x",
"=",
"130",
",",
"$",
"y",
"=",
"15",
",",
"$",
"w",
"=",
"70",
",",
"$",
"font_size",
"=",
"nu... | Método que agrega el recuadro con el folio
Recuadro:
- Tamaño mínimo 1.5x5.5 cms
- En lado derecho (negro o rojo)
- Enmarcado por una línea de entre 0.5 y 1 mm de espesor
- Tamaño máximo 4x8 cms
- Letras tamaño 10 o superior en mayúsculas y negritas
- Datos del recuadro: RUT emisor, nombre de documento en 2 líneas,
folio.
- Bajo el recuadro indicar la Dirección regional o Unidad del SII a la
que pertenece el emisor
@param rut RUT del emisor
@param tipo Código o glosa del tipo de documento
@param sucursal_sii Código o glosa de la sucursal del SII del Emisor
@param x Posición horizontal de inicio en el PDF
@param y Posición vertical de inicio en el PDF
@param w Ancho de la información del emisor
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2016-12-02 | [
"Método",
"que",
"agrega",
"el",
"recuadro",
"con",
"el",
"folio",
"Recuadro",
":",
"-",
"Tamaño",
"mínimo",
"1",
".",
"5x5",
".",
"5",
"cms",
"-",
"En",
"lado",
"derecho",
"(",
"negro",
"o",
"rojo",
")",
"-",
"Enmarcado",
"por",
"una",
"línea",
"de"... | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Dte/PDF/Dte.php#L469-L493 |
LibreDTE/libredte-lib | lib/Sii/Dte/PDF/Dte.php | Dte.agregarDatosEmision | protected function agregarDatosEmision($IdDoc, $CdgVendedor, $x = 10, $offset = 22, $mostrar_dia = true)
{
// si es hoja carta
if ($x==10) {
$y = $this->GetY();
// fecha emisión
$this->setFont('', 'B', null);
$this->MultiTexto($this->date($IdDoc['FchEmis'], $mostrar_dia), $x, null, 'R');
$this->setFont('', '', null);
// período facturación
if (!empty($IdDoc['PeriodoDesde']) and !empty($IdDoc['PeriodoHasta'])) {
$this->MultiTexto('Período del '.date('d/m/y', strtotime($IdDoc['PeriodoDesde'])).' al '.date('d/m/y', strtotime($IdDoc['PeriodoHasta'])), $x, null, 'R');
}
// pago anticicado
if (!empty($IdDoc['FchCancel'])) {
$this->MultiTexto('Pagado el '.$this->date($IdDoc['FchCancel'], false), $x, null, 'R');
}
// fecha vencimiento
if (!empty($IdDoc['FchVenc'])) {
$this->MultiTexto('Vence el '.$this->date($IdDoc['FchVenc'], false), $x, null, 'R');
}
// forma de pago nacional
if (!empty($IdDoc['FmaPago'])) {
$this->MultiTexto('Venta: '.strtolower($this->formas_pago[$IdDoc['FmaPago']]), $x, null, 'R');
}
// forma de pago exportación
if (!empty($IdDoc['FmaPagExp'])) {
$this->MultiTexto('Venta: '.strtolower($this->formas_pago_exportacion[$IdDoc['FmaPagExp']]), $x, null, 'R');
}
// vendedor
if (!empty($CdgVendedor)) {
$this->MultiTexto('Vendedor: '.$CdgVendedor, $x, null, 'R');
}
$y_end = $this->GetY();
$this->SetY($y);
}
// papel contínuo
else {
// fecha de emisión
$this->setFont('', 'B', null);
$this->Texto('Emisión', $x);
$this->Texto(':', $x+$offset);
$this->setFont('', '', null);
$this->MultiTexto($this->date($IdDoc['FchEmis'], $mostrar_dia), $x+$offset+2);
// forma de pago nacional
if (!empty($IdDoc['FmaPago'])) {
$this->setFont('', 'B', null);
$this->Texto('Venta', $x);
$this->Texto(':', $x+$offset);
$this->setFont('', '', null);
$this->MultiTexto($this->formas_pago[$IdDoc['FmaPago']], $x+$offset+2);
}
// forma de pago exportación
if (!empty($IdDoc['FmaPagExp'])) {
$this->setFont('', 'B', null);
$this->Texto('Venta', $x);
$this->Texto(':', $x+$offset);
$this->setFont('', '', null);
$this->MultiTexto($this->formas_pago_exportacion[$IdDoc['FmaPagExp']], $x+$offset+2);
}
// pago anticicado
if (!empty($IdDoc['FchCancel'])) {
$this->setFont('', 'B', null);
$this->Texto('Pagado el', $x);
$this->Texto(':', $x+$offset);
$this->setFont('', '', null);
$this->MultiTexto($this->date($IdDoc['FchCancel'], $mostrar_dia), $x+$offset+2);
}
// fecha vencimiento
if (!empty($IdDoc['FchVenc'])) {
$this->setFont('', 'B', null);
$this->Texto('Vence el', $x);
$this->Texto(':', $x+$offset);
$this->setFont('', '', null);
$this->MultiTexto($this->date($IdDoc['FchVenc'], $mostrar_dia), $x+$offset+2);
}
$y_end = $this->GetY();
}
return $y_end;
} | php | protected function agregarDatosEmision($IdDoc, $CdgVendedor, $x = 10, $offset = 22, $mostrar_dia = true)
{
// si es hoja carta
if ($x==10) {
$y = $this->GetY();
// fecha emisión
$this->setFont('', 'B', null);
$this->MultiTexto($this->date($IdDoc['FchEmis'], $mostrar_dia), $x, null, 'R');
$this->setFont('', '', null);
// período facturación
if (!empty($IdDoc['PeriodoDesde']) and !empty($IdDoc['PeriodoHasta'])) {
$this->MultiTexto('Período del '.date('d/m/y', strtotime($IdDoc['PeriodoDesde'])).' al '.date('d/m/y', strtotime($IdDoc['PeriodoHasta'])), $x, null, 'R');
}
// pago anticicado
if (!empty($IdDoc['FchCancel'])) {
$this->MultiTexto('Pagado el '.$this->date($IdDoc['FchCancel'], false), $x, null, 'R');
}
// fecha vencimiento
if (!empty($IdDoc['FchVenc'])) {
$this->MultiTexto('Vence el '.$this->date($IdDoc['FchVenc'], false), $x, null, 'R');
}
// forma de pago nacional
if (!empty($IdDoc['FmaPago'])) {
$this->MultiTexto('Venta: '.strtolower($this->formas_pago[$IdDoc['FmaPago']]), $x, null, 'R');
}
// forma de pago exportación
if (!empty($IdDoc['FmaPagExp'])) {
$this->MultiTexto('Venta: '.strtolower($this->formas_pago_exportacion[$IdDoc['FmaPagExp']]), $x, null, 'R');
}
// vendedor
if (!empty($CdgVendedor)) {
$this->MultiTexto('Vendedor: '.$CdgVendedor, $x, null, 'R');
}
$y_end = $this->GetY();
$this->SetY($y);
}
// papel contínuo
else {
// fecha de emisión
$this->setFont('', 'B', null);
$this->Texto('Emisión', $x);
$this->Texto(':', $x+$offset);
$this->setFont('', '', null);
$this->MultiTexto($this->date($IdDoc['FchEmis'], $mostrar_dia), $x+$offset+2);
// forma de pago nacional
if (!empty($IdDoc['FmaPago'])) {
$this->setFont('', 'B', null);
$this->Texto('Venta', $x);
$this->Texto(':', $x+$offset);
$this->setFont('', '', null);
$this->MultiTexto($this->formas_pago[$IdDoc['FmaPago']], $x+$offset+2);
}
// forma de pago exportación
if (!empty($IdDoc['FmaPagExp'])) {
$this->setFont('', 'B', null);
$this->Texto('Venta', $x);
$this->Texto(':', $x+$offset);
$this->setFont('', '', null);
$this->MultiTexto($this->formas_pago_exportacion[$IdDoc['FmaPagExp']], $x+$offset+2);
}
// pago anticicado
if (!empty($IdDoc['FchCancel'])) {
$this->setFont('', 'B', null);
$this->Texto('Pagado el', $x);
$this->Texto(':', $x+$offset);
$this->setFont('', '', null);
$this->MultiTexto($this->date($IdDoc['FchCancel'], $mostrar_dia), $x+$offset+2);
}
// fecha vencimiento
if (!empty($IdDoc['FchVenc'])) {
$this->setFont('', 'B', null);
$this->Texto('Vence el', $x);
$this->Texto(':', $x+$offset);
$this->setFont('', '', null);
$this->MultiTexto($this->date($IdDoc['FchVenc'], $mostrar_dia), $x+$offset+2);
}
$y_end = $this->GetY();
}
return $y_end;
} | [
"protected",
"function",
"agregarDatosEmision",
"(",
"$",
"IdDoc",
",",
"$",
"CdgVendedor",
",",
"$",
"x",
"=",
"10",
",",
"$",
"offset",
"=",
"22",
",",
"$",
"mostrar_dia",
"=",
"true",
")",
"{",
"// si es hoja carta",
"if",
"(",
"$",
"x",
"==",
"10",... | Método que agrega los datos de la emisión del DTE que no son los dato del
receptor
@param IdDoc Información general del documento
@param x Posición horizontal de inicio en el PDF
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2017-06-15 | [
"Método",
"que",
"agrega",
"los",
"datos",
"de",
"la",
"emisión",
"del",
"DTE",
"que",
"no",
"son",
"los",
"dato",
"del",
"receptor"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Dte/PDF/Dte.php#L503-L582 |
LibreDTE/libredte-lib | lib/Sii/Dte/PDF/Dte.php | Dte.agregarReceptor | protected function agregarReceptor(array $Encabezado, $x = 10, $offset = 22)
{
$receptor = $Encabezado['Receptor'];
if (!empty($receptor['RUTRecep']) and $receptor['RUTRecep']!='66666666-6') {
list($rut, $dv) = explode('-', $receptor['RUTRecep']);
$this->setFont('', 'B', null);
$this->Texto(in_array($this->dte, [39, 41]) ? 'R.U.N.' : 'R.U.T.', $x);
$this->Texto(':', $x+$offset);
$this->setFont('', '', null);
$this->MultiTexto($this->num($rut).'-'.$dv, $x+$offset+2);
}
if (!empty($receptor['RznSocRecep'])) {
$this->setFont('', 'B', null);
$this->Texto(in_array($this->dte, [39, 41]) ? 'Nombre' : 'Razón social', $x);
$this->Texto(':', $x+$offset);
$this->setFont('', '', null);
$this->MultiTexto($receptor['RznSocRecep'], $x+$offset+2, null, '', $x==10?105:0);
}
if (!empty($receptor['GiroRecep'])) {
$this->setFont('', 'B', null);
$this->Texto('Giro', $x);
$this->Texto(':', $x+$offset);
$this->setFont('', '', null);
$this->MultiTexto($receptor['GiroRecep'], $x+$offset+2);
}
if (!empty($receptor['DirRecep'])) {
$this->setFont('', 'B', null);
$this->Texto('Dirección', $x);
$this->Texto(':', $x+$offset);
$this->setFont('', '', null);
$ciudad = !empty($receptor['CiudadRecep']) ? $receptor['CiudadRecep'] : (
!empty($receptor['CmnaRecep']) ? \sasco\LibreDTE\Chile::getCiudad($receptor['CmnaRecep']) : ''
);
$this->MultiTexto($receptor['DirRecep'].(!empty($receptor['CmnaRecep'])?(', '.$receptor['CmnaRecep']):'').($ciudad?(', '.$ciudad):''), $x+$offset+2);
}
if (!empty($receptor['Extranjero']['Nacionalidad'])) {
$this->setFont('', 'B', null);
$this->Texto('Nacionalidad', $x);
$this->Texto(':', $x+$offset);
$this->setFont('', '', null);
$this->MultiTexto(\sasco\LibreDTE\Sii\Aduana::getNacionalidad($receptor['Extranjero']['Nacionalidad']), $x+$offset+2);
}
if (!empty($receptor['Extranjero']['NumId'])) {
$this->setFont('', 'B', null);
$this->Texto('N° ID extranj.', $x);
$this->Texto(':', $x+$offset);
$this->setFont('', '', null);
$this->MultiTexto($receptor['Extranjero']['NumId'], $x+$offset+2);
}
$contacto = [];
if (!empty($receptor['Contacto']))
$contacto[] = $receptor['Contacto'];
if (!empty($receptor['CorreoRecep']))
$contacto[] = $receptor['CorreoRecep'];
if (!empty($contacto)) {
$this->setFont('', 'B', null);
$this->Texto('Contacto', $x);
$this->Texto(':', $x+$offset);
$this->setFont('', '', null);
$this->MultiTexto(implode(' / ', $contacto), $x+$offset+2);
}
if (!empty($Encabezado['RUTSolicita'])) {
list($rut, $dv) = explode('-', $Encabezado['RUTSolicita']);
$this->setFont('', 'B', null);
$this->Texto('RUT solicita', $x);
$this->Texto(':', $x+$offset);
$this->setFont('', '', null);
$this->MultiTexto($this->num($rut).'-'.$dv, $x+$offset+2);
}
if (!empty($receptor['CdgIntRecep'])) {
$this->setFont('', 'B', null);
$this->Texto('Cód. recep.', $x);
$this->Texto(':', $x+$offset);
$this->setFont('', '', null);
$this->MultiTexto($receptor['CdgIntRecep'], $x+$offset+2, null, '', $x==10?105:0);
}
return $this->GetY();
} | php | protected function agregarReceptor(array $Encabezado, $x = 10, $offset = 22)
{
$receptor = $Encabezado['Receptor'];
if (!empty($receptor['RUTRecep']) and $receptor['RUTRecep']!='66666666-6') {
list($rut, $dv) = explode('-', $receptor['RUTRecep']);
$this->setFont('', 'B', null);
$this->Texto(in_array($this->dte, [39, 41]) ? 'R.U.N.' : 'R.U.T.', $x);
$this->Texto(':', $x+$offset);
$this->setFont('', '', null);
$this->MultiTexto($this->num($rut).'-'.$dv, $x+$offset+2);
}
if (!empty($receptor['RznSocRecep'])) {
$this->setFont('', 'B', null);
$this->Texto(in_array($this->dte, [39, 41]) ? 'Nombre' : 'Razón social', $x);
$this->Texto(':', $x+$offset);
$this->setFont('', '', null);
$this->MultiTexto($receptor['RznSocRecep'], $x+$offset+2, null, '', $x==10?105:0);
}
if (!empty($receptor['GiroRecep'])) {
$this->setFont('', 'B', null);
$this->Texto('Giro', $x);
$this->Texto(':', $x+$offset);
$this->setFont('', '', null);
$this->MultiTexto($receptor['GiroRecep'], $x+$offset+2);
}
if (!empty($receptor['DirRecep'])) {
$this->setFont('', 'B', null);
$this->Texto('Dirección', $x);
$this->Texto(':', $x+$offset);
$this->setFont('', '', null);
$ciudad = !empty($receptor['CiudadRecep']) ? $receptor['CiudadRecep'] : (
!empty($receptor['CmnaRecep']) ? \sasco\LibreDTE\Chile::getCiudad($receptor['CmnaRecep']) : ''
);
$this->MultiTexto($receptor['DirRecep'].(!empty($receptor['CmnaRecep'])?(', '.$receptor['CmnaRecep']):'').($ciudad?(', '.$ciudad):''), $x+$offset+2);
}
if (!empty($receptor['Extranjero']['Nacionalidad'])) {
$this->setFont('', 'B', null);
$this->Texto('Nacionalidad', $x);
$this->Texto(':', $x+$offset);
$this->setFont('', '', null);
$this->MultiTexto(\sasco\LibreDTE\Sii\Aduana::getNacionalidad($receptor['Extranjero']['Nacionalidad']), $x+$offset+2);
}
if (!empty($receptor['Extranjero']['NumId'])) {
$this->setFont('', 'B', null);
$this->Texto('N° ID extranj.', $x);
$this->Texto(':', $x+$offset);
$this->setFont('', '', null);
$this->MultiTexto($receptor['Extranjero']['NumId'], $x+$offset+2);
}
$contacto = [];
if (!empty($receptor['Contacto']))
$contacto[] = $receptor['Contacto'];
if (!empty($receptor['CorreoRecep']))
$contacto[] = $receptor['CorreoRecep'];
if (!empty($contacto)) {
$this->setFont('', 'B', null);
$this->Texto('Contacto', $x);
$this->Texto(':', $x+$offset);
$this->setFont('', '', null);
$this->MultiTexto(implode(' / ', $contacto), $x+$offset+2);
}
if (!empty($Encabezado['RUTSolicita'])) {
list($rut, $dv) = explode('-', $Encabezado['RUTSolicita']);
$this->setFont('', 'B', null);
$this->Texto('RUT solicita', $x);
$this->Texto(':', $x+$offset);
$this->setFont('', '', null);
$this->MultiTexto($this->num($rut).'-'.$dv, $x+$offset+2);
}
if (!empty($receptor['CdgIntRecep'])) {
$this->setFont('', 'B', null);
$this->Texto('Cód. recep.', $x);
$this->Texto(':', $x+$offset);
$this->setFont('', '', null);
$this->MultiTexto($receptor['CdgIntRecep'], $x+$offset+2, null, '', $x==10?105:0);
}
return $this->GetY();
} | [
"protected",
"function",
"agregarReceptor",
"(",
"array",
"$",
"Encabezado",
",",
"$",
"x",
"=",
"10",
",",
"$",
"offset",
"=",
"22",
")",
"{",
"$",
"receptor",
"=",
"$",
"Encabezado",
"[",
"'Receptor'",
"]",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
... | Método que agrega los datos del receptor
@param receptor Arreglo con los datos del receptor (tag Receptor del XML)
@param x Posición horizontal de inicio en el PDF
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2019-02-13 | [
"Método",
"que",
"agrega",
"los",
"datos",
"del",
"receptor"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Dte/PDF/Dte.php#L591-L668 |
LibreDTE/libredte-lib | lib/Sii/Dte/PDF/Dte.php | Dte.agregarTraslado | protected function agregarTraslado($IndTraslado, array $Transporte = null, $x = 10, $offset = 22)
{
// agregar tipo de traslado
if ($IndTraslado) {
$this->setFont('', 'B', null);
$this->Texto('Tipo oper.', $x);
$this->Texto(':', $x+$offset);
$this->setFont('', '', null);
$this->MultiTexto($this->traslados[$IndTraslado], $x+$offset+2);
}
// agregar información de transporte
if ($Transporte) {
$transporte = '';
if (!empty($Transporte['DirDest']) and !empty($Transporte['CmnaDest'])) {
$transporte .= 'a '.$Transporte['DirDest'].', '.$Transporte['CmnaDest'];
}
if (!empty($Transporte['RUTTrans']))
$transporte .= ' por '.$Transporte['RUTTrans'];
if (!empty($Transporte['Patente']))
$transporte .= ' en vehículo '.$Transporte['Patente'];
if (isset($Transporte['Chofer']) and is_array($Transporte['Chofer'])) {
if (!empty($Transporte['Chofer']['NombreChofer']))
$transporte .= ' con chofer '.$Transporte['Chofer']['NombreChofer'];
if (!empty($Transporte['Chofer']['RUTChofer']))
$transporte .= ' ('.$Transporte['Chofer']['RUTChofer'].')';
}
if ($transporte) {
$this->setFont('', 'B', null);
$this->Texto('Traslado', $x);
$this->Texto(':', $x+$offset);
$this->setFont('', '', null);
$this->MultiTexto(ucfirst(trim($transporte)), $x+$offset+2);
}
}
// agregar información de aduana
if (!empty($Transporte['Aduana']) and is_array($Transporte['Aduana'])) {
$col = 0;
foreach ($Transporte['Aduana'] as $tag => $codigo) {
if ($codigo===false)
continue;
$glosa = \sasco\LibreDTE\Sii\Aduana::getGlosa($tag);
$valor = \sasco\LibreDTE\Sii\Aduana::getValor($tag, $codigo);
if ($glosa!==false and $valor!==false) {
if ($tag=='TipoBultos' and $col) {
$col = abs($col-110);
$this->Ln();
}
$this->setFont('', 'B', null);
$this->Texto($glosa, $x+$col);
$this->Texto(':', $x+$offset+$col);
$this->setFont('', '', null);
$this->Texto($valor, $x+$offset+2+$col);
if ($tag=='TipoBultos')
$col = abs($col-110);
if ($col)
$this->Ln();
$col = abs($col-110);
}
}
if ($col)
$this->Ln();
}
} | php | protected function agregarTraslado($IndTraslado, array $Transporte = null, $x = 10, $offset = 22)
{
// agregar tipo de traslado
if ($IndTraslado) {
$this->setFont('', 'B', null);
$this->Texto('Tipo oper.', $x);
$this->Texto(':', $x+$offset);
$this->setFont('', '', null);
$this->MultiTexto($this->traslados[$IndTraslado], $x+$offset+2);
}
// agregar información de transporte
if ($Transporte) {
$transporte = '';
if (!empty($Transporte['DirDest']) and !empty($Transporte['CmnaDest'])) {
$transporte .= 'a '.$Transporte['DirDest'].', '.$Transporte['CmnaDest'];
}
if (!empty($Transporte['RUTTrans']))
$transporte .= ' por '.$Transporte['RUTTrans'];
if (!empty($Transporte['Patente']))
$transporte .= ' en vehículo '.$Transporte['Patente'];
if (isset($Transporte['Chofer']) and is_array($Transporte['Chofer'])) {
if (!empty($Transporte['Chofer']['NombreChofer']))
$transporte .= ' con chofer '.$Transporte['Chofer']['NombreChofer'];
if (!empty($Transporte['Chofer']['RUTChofer']))
$transporte .= ' ('.$Transporte['Chofer']['RUTChofer'].')';
}
if ($transporte) {
$this->setFont('', 'B', null);
$this->Texto('Traslado', $x);
$this->Texto(':', $x+$offset);
$this->setFont('', '', null);
$this->MultiTexto(ucfirst(trim($transporte)), $x+$offset+2);
}
}
// agregar información de aduana
if (!empty($Transporte['Aduana']) and is_array($Transporte['Aduana'])) {
$col = 0;
foreach ($Transporte['Aduana'] as $tag => $codigo) {
if ($codigo===false)
continue;
$glosa = \sasco\LibreDTE\Sii\Aduana::getGlosa($tag);
$valor = \sasco\LibreDTE\Sii\Aduana::getValor($tag, $codigo);
if ($glosa!==false and $valor!==false) {
if ($tag=='TipoBultos' and $col) {
$col = abs($col-110);
$this->Ln();
}
$this->setFont('', 'B', null);
$this->Texto($glosa, $x+$col);
$this->Texto(':', $x+$offset+$col);
$this->setFont('', '', null);
$this->Texto($valor, $x+$offset+2+$col);
if ($tag=='TipoBultos')
$col = abs($col-110);
if ($col)
$this->Ln();
$col = abs($col-110);
}
}
if ($col)
$this->Ln();
}
} | [
"protected",
"function",
"agregarTraslado",
"(",
"$",
"IndTraslado",
",",
"array",
"$",
"Transporte",
"=",
"null",
",",
"$",
"x",
"=",
"10",
",",
"$",
"offset",
"=",
"22",
")",
"{",
"// agregar tipo de traslado",
"if",
"(",
"$",
"IndTraslado",
")",
"{",
... | Método que agrega los datos del traslado
@param IndTraslado
@param Transporte
@param x Posición horizontal de inicio en el PDF
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2016-08-03 | [
"Método",
"que",
"agrega",
"los",
"datos",
"del",
"traslado"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Dte/PDF/Dte.php#L678-L740 |
LibreDTE/libredte-lib | lib/Sii/Dte/PDF/Dte.php | Dte.agregarReferencia | protected function agregarReferencia($referencias, $x = 10, $offset = 22)
{
if (!isset($referencias[0]))
$referencias = [$referencias];
foreach($referencias as $r) {
$texto = $r['NroLinRef'].' - ';
if (!empty($r['TpoDocRef'])) {
$texto .= $this->getTipo($r['TpoDocRef']).' ';
}
if (!empty($r['FolioRef'])) {
if (is_numeric($r['FolioRef'])) {
$texto .= ' N° '.$r['FolioRef'].' ';
} else {
$texto .= ' '.$r['FolioRef'].' ';
}
}
if (!empty($r['FchRef'])) {
$texto .= 'del '.date('d/m/Y', strtotime($r['FchRef']));
}
if (isset($r['RazonRef']) and $r['RazonRef']!==false) {
$texto = $texto.': '.$r['RazonRef'];
}
$this->setFont('', 'B', null);
$this->Texto('Referencia', $x);
$this->Texto(':', $x+$offset);
$this->setFont('', '', null);
$this->MultiTexto($texto, $x+$offset+2);
}
} | php | protected function agregarReferencia($referencias, $x = 10, $offset = 22)
{
if (!isset($referencias[0]))
$referencias = [$referencias];
foreach($referencias as $r) {
$texto = $r['NroLinRef'].' - ';
if (!empty($r['TpoDocRef'])) {
$texto .= $this->getTipo($r['TpoDocRef']).' ';
}
if (!empty($r['FolioRef'])) {
if (is_numeric($r['FolioRef'])) {
$texto .= ' N° '.$r['FolioRef'].' ';
} else {
$texto .= ' '.$r['FolioRef'].' ';
}
}
if (!empty($r['FchRef'])) {
$texto .= 'del '.date('d/m/Y', strtotime($r['FchRef']));
}
if (isset($r['RazonRef']) and $r['RazonRef']!==false) {
$texto = $texto.': '.$r['RazonRef'];
}
$this->setFont('', 'B', null);
$this->Texto('Referencia', $x);
$this->Texto(':', $x+$offset);
$this->setFont('', '', null);
$this->MultiTexto($texto, $x+$offset+2);
}
} | [
"protected",
"function",
"agregarReferencia",
"(",
"$",
"referencias",
",",
"$",
"x",
"=",
"10",
",",
"$",
"offset",
"=",
"22",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"referencias",
"[",
"0",
"]",
")",
")",
"$",
"referencias",
"=",
"[",
"$",
... | Método que agrega las referencias del documento
@param referencias Arreglo con las referencias del documento (tag Referencia del XML)
@param x Posición horizontal de inicio en el PDF
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2017-09-25 | [
"Método",
"que",
"agrega",
"las",
"referencias",
"del",
"documento"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Dte/PDF/Dte.php#L749-L777 |
LibreDTE/libredte-lib | lib/Sii/Dte/PDF/Dte.php | Dte.agregarDetalle | protected function agregarDetalle($detalle, $x = 10, $html = true)
{
if (!isset($detalle[0]))
$detalle = [$detalle];
$this->setFont('', '', $this->detalle_fuente);
// titulos
$titulos = [];
$titulos_keys = array_keys($this->detalle_cols);
foreach ($this->detalle_cols as $key => $info) {
$titulos[$key] = $info['title'];
}
// normalizar cada detalle
$dte_exento = in_array($this->dte, [34, 110, 111, 112]);
foreach ($detalle as &$item) {
// quitar columnas
foreach ($item as $col => $valor) {
if ($col=='DscItem' and !empty($item['DscItem'])) {
$item['NmbItem'] .= !$this->item_detalle_posicion ? ($html?'<br/>':"\n") : ': ';
if ($html) {
$item['NmbItem'] .= '<span style="font-size:0.7em">'.$item['DscItem'].'</span>';
} else {
$item['NmbItem'] .= $item['DscItem'];
}
}
if ($col=='DescuentoPct' and !empty($item['DescuentoPct'])) {
$item['DescuentoMonto'] = $item['DescuentoPct'].'%';
}
if ($col=='RecargoPct' and !empty($item['RecargoPct'])) {
$item['RecargoMonto'] = $item['RecargoPct'].'%';
}
if (!in_array($col, $titulos_keys) or ($dte_exento and $col=='IndExe')) {
unset($item[$col]);
}
}
// ajustes a IndExe
if (isset($item['IndExe'])) {
if ($item['IndExe']==1)
$item['IndExe'] = 'EX';
else if ($item['IndExe']==2)
$item['IndExe'] = 'NF';
}
// agregar todas las columnas que se podrían imprimir en la tabla
$item_default = [];
foreach ($this->detalle_cols as $key => $info)
$item_default[$key] = false;
$item = array_merge($item_default, $item);
// si hay código de item se extrae su valor
if (!empty($item['CdgItem']['VlrCodigo'])){
$item['CdgItem'] = $item['CdgItem']['VlrCodigo'];
}
// dar formato a números
foreach (['QtyItem', 'PrcItem', 'DescuentoMonto', 'RecargoMonto', 'MontoItem'] as $col) {
if ($item[$col]) {
$item[$col] = is_numeric($item[$col]) ? $this->num($item[$col]) : $item[$col];
}
}
}
// opciones
$options = ['align'=>[]];
$i = 0;
foreach ($this->detalle_cols as $info) {
if (isset($info['width']))
$options['width'][$i] = $info['width'];
$options['align'][$i] = $info['align'];
$i++;
}
// agregar tabla de detalle
$this->Ln();
$this->SetX($x);
$this->addTableWithoutEmptyCols($titulos, $detalle, $options);
} | php | protected function agregarDetalle($detalle, $x = 10, $html = true)
{
if (!isset($detalle[0]))
$detalle = [$detalle];
$this->setFont('', '', $this->detalle_fuente);
// titulos
$titulos = [];
$titulos_keys = array_keys($this->detalle_cols);
foreach ($this->detalle_cols as $key => $info) {
$titulos[$key] = $info['title'];
}
// normalizar cada detalle
$dte_exento = in_array($this->dte, [34, 110, 111, 112]);
foreach ($detalle as &$item) {
// quitar columnas
foreach ($item as $col => $valor) {
if ($col=='DscItem' and !empty($item['DscItem'])) {
$item['NmbItem'] .= !$this->item_detalle_posicion ? ($html?'<br/>':"\n") : ': ';
if ($html) {
$item['NmbItem'] .= '<span style="font-size:0.7em">'.$item['DscItem'].'</span>';
} else {
$item['NmbItem'] .= $item['DscItem'];
}
}
if ($col=='DescuentoPct' and !empty($item['DescuentoPct'])) {
$item['DescuentoMonto'] = $item['DescuentoPct'].'%';
}
if ($col=='RecargoPct' and !empty($item['RecargoPct'])) {
$item['RecargoMonto'] = $item['RecargoPct'].'%';
}
if (!in_array($col, $titulos_keys) or ($dte_exento and $col=='IndExe')) {
unset($item[$col]);
}
}
// ajustes a IndExe
if (isset($item['IndExe'])) {
if ($item['IndExe']==1)
$item['IndExe'] = 'EX';
else if ($item['IndExe']==2)
$item['IndExe'] = 'NF';
}
// agregar todas las columnas que se podrían imprimir en la tabla
$item_default = [];
foreach ($this->detalle_cols as $key => $info)
$item_default[$key] = false;
$item = array_merge($item_default, $item);
// si hay código de item se extrae su valor
if (!empty($item['CdgItem']['VlrCodigo'])){
$item['CdgItem'] = $item['CdgItem']['VlrCodigo'];
}
// dar formato a números
foreach (['QtyItem', 'PrcItem', 'DescuentoMonto', 'RecargoMonto', 'MontoItem'] as $col) {
if ($item[$col]) {
$item[$col] = is_numeric($item[$col]) ? $this->num($item[$col]) : $item[$col];
}
}
}
// opciones
$options = ['align'=>[]];
$i = 0;
foreach ($this->detalle_cols as $info) {
if (isset($info['width']))
$options['width'][$i] = $info['width'];
$options['align'][$i] = $info['align'];
$i++;
}
// agregar tabla de detalle
$this->Ln();
$this->SetX($x);
$this->addTableWithoutEmptyCols($titulos, $detalle, $options);
} | [
"protected",
"function",
"agregarDetalle",
"(",
"$",
"detalle",
",",
"$",
"x",
"=",
"10",
",",
"$",
"html",
"=",
"true",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"detalle",
"[",
"0",
"]",
")",
")",
"$",
"detalle",
"=",
"[",
"$",
"detalle",
... | Método que agrega el detalle del documento
@param detalle Arreglo con el detalle del documento (tag Detalle del XML)
@param x Posición horizontal de inicio en el PDF
@param y Posición vertical de inicio en el PDF
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2018-11-04 | [
"Método",
"que",
"agrega",
"el",
"detalle",
"del",
"documento"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Dte/PDF/Dte.php#L787-L857 |
LibreDTE/libredte-lib | lib/Sii/Dte/PDF/Dte.php | Dte.agregarDetalleContinuo | protected function agregarDetalleContinuo($detalle, $x = 3)
{
$this->SetY($this->getY()+1);
$p1x = $x;
$p1y = $this->y;
$p2x = $this->getPageWidth() - 2;
$p2y = $p1y; // Use same y for a straight line
$style = array('width' => 0.2,'color' => array(0, 0, 0));
$this->Line($p1x, $p1y, $p2x, $p2y, $style);
$this->Texto($this->detalle_cols['NmbItem']['title'], $x+1, $this->y, ucfirst($this->detalle_cols['NmbItem']['align'][0]), $this->detalle_cols['NmbItem']['width']);
$this->Texto($this->detalle_cols['PrcItem']['title'], $x+15, $this->y, ucfirst($this->detalle_cols['PrcItem']['align'][0]), $this->detalle_cols['PrcItem']['width']);
$this->Texto($this->detalle_cols['QtyItem']['title'], $x+35, $this->y, ucfirst($this->detalle_cols['QtyItem']['align'][0]), $this->detalle_cols['QtyItem']['width']);
$this->Texto($this->detalle_cols['MontoItem']['title'], $x+45, $this->y, ucfirst($this->detalle_cols['MontoItem']['align'][0]), $this->detalle_cols['MontoItem']['width']);
$this->Line($p1x, $p1y+4, $p2x, $p2y+4, $style);
if (!isset($detalle[0]))
$detalle = [$detalle];
$this->SetY($this->getY()+2);
foreach($detalle as &$d) {
$this->MultiTexto($d['NmbItem'], $x+1, $this->y+4, ucfirst($this->detalle_cols['NmbItem']['align'][0]), $this->detalle_cols['NmbItem']['width']);
$this->Texto(number_format($d['PrcItem'],0,',','.'), $x+15, $this->y, ucfirst($this->detalle_cols['PrcItem']['align'][0]), $this->detalle_cols['PrcItem']['width']);
$this->Texto($this->num($d['QtyItem']), $x+35, $this->y, ucfirst($this->detalle_cols['QtyItem']['align'][0]), $this->detalle_cols['QtyItem']['width']);
$this->Texto($this->num($d['MontoItem']), $x+45, $this->y, ucfirst($this->detalle_cols['MontoItem']['align'][0]), $this->detalle_cols['MontoItem']['width']);
}
$this->Line($p1x, $this->y+4, $p2x, $this->y+4, $style);
} | php | protected function agregarDetalleContinuo($detalle, $x = 3)
{
$this->SetY($this->getY()+1);
$p1x = $x;
$p1y = $this->y;
$p2x = $this->getPageWidth() - 2;
$p2y = $p1y; // Use same y for a straight line
$style = array('width' => 0.2,'color' => array(0, 0, 0));
$this->Line($p1x, $p1y, $p2x, $p2y, $style);
$this->Texto($this->detalle_cols['NmbItem']['title'], $x+1, $this->y, ucfirst($this->detalle_cols['NmbItem']['align'][0]), $this->detalle_cols['NmbItem']['width']);
$this->Texto($this->detalle_cols['PrcItem']['title'], $x+15, $this->y, ucfirst($this->detalle_cols['PrcItem']['align'][0]), $this->detalle_cols['PrcItem']['width']);
$this->Texto($this->detalle_cols['QtyItem']['title'], $x+35, $this->y, ucfirst($this->detalle_cols['QtyItem']['align'][0]), $this->detalle_cols['QtyItem']['width']);
$this->Texto($this->detalle_cols['MontoItem']['title'], $x+45, $this->y, ucfirst($this->detalle_cols['MontoItem']['align'][0]), $this->detalle_cols['MontoItem']['width']);
$this->Line($p1x, $p1y+4, $p2x, $p2y+4, $style);
if (!isset($detalle[0]))
$detalle = [$detalle];
$this->SetY($this->getY()+2);
foreach($detalle as &$d) {
$this->MultiTexto($d['NmbItem'], $x+1, $this->y+4, ucfirst($this->detalle_cols['NmbItem']['align'][0]), $this->detalle_cols['NmbItem']['width']);
$this->Texto(number_format($d['PrcItem'],0,',','.'), $x+15, $this->y, ucfirst($this->detalle_cols['PrcItem']['align'][0]), $this->detalle_cols['PrcItem']['width']);
$this->Texto($this->num($d['QtyItem']), $x+35, $this->y, ucfirst($this->detalle_cols['QtyItem']['align'][0]), $this->detalle_cols['QtyItem']['width']);
$this->Texto($this->num($d['MontoItem']), $x+45, $this->y, ucfirst($this->detalle_cols['MontoItem']['align'][0]), $this->detalle_cols['MontoItem']['width']);
}
$this->Line($p1x, $this->y+4, $p2x, $this->y+4, $style);
} | [
"protected",
"function",
"agregarDetalleContinuo",
"(",
"$",
"detalle",
",",
"$",
"x",
"=",
"3",
")",
"{",
"$",
"this",
"->",
"SetY",
"(",
"$",
"this",
"->",
"getY",
"(",
")",
"+",
"1",
")",
";",
"$",
"p1x",
"=",
"$",
"x",
";",
"$",
"p1y",
"=",... | Método que agrega el detalle del documento
@param detalle Arreglo con el detalle del documento (tag Detalle del XML)
@param x Posición horizontal de inicio en el PDF
@param y Posición vertical de inicio en el PDF
@author Pablo Reyes (https://github.com/pabloxp)
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2016-12-13 | [
"Método",
"que",
"agrega",
"el",
"detalle",
"del",
"documento"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Dte/PDF/Dte.php#L868-L892 |
LibreDTE/libredte-lib | lib/Sii/Dte/PDF/Dte.php | Dte.agregarSubTotal | protected function agregarSubTotal(array $detalle, $x = 10) {
$subtotal = 0;
if (!isset($detalle[0])) {
$detalle = [$detalle];
}
foreach($detalle as &$d) {
if (!empty($d['MontoItem'])) {
$subtotal += $d['MontoItem'];
}
}
if ($this->papelContinuo) {
$this->Texto('Subtotal: '.$this->num($subtotal), $x);
} else {
$this->Texto('Subtotal:', 77, null, 'R', 100);
$this->Texto($this->num($subtotal), 177, null, 'R', 22);
}
$this->Ln();
} | php | protected function agregarSubTotal(array $detalle, $x = 10) {
$subtotal = 0;
if (!isset($detalle[0])) {
$detalle = [$detalle];
}
foreach($detalle as &$d) {
if (!empty($d['MontoItem'])) {
$subtotal += $d['MontoItem'];
}
}
if ($this->papelContinuo) {
$this->Texto('Subtotal: '.$this->num($subtotal), $x);
} else {
$this->Texto('Subtotal:', 77, null, 'R', 100);
$this->Texto($this->num($subtotal), 177, null, 'R', 22);
}
$this->Ln();
} | [
"protected",
"function",
"agregarSubTotal",
"(",
"array",
"$",
"detalle",
",",
"$",
"x",
"=",
"10",
")",
"{",
"$",
"subtotal",
"=",
"0",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"detalle",
"[",
"0",
"]",
")",
")",
"{",
"$",
"detalle",
"=",
"[",
... | Método que agrega el subtotal del DTE
@param detalle Arreglo con los detalles del documentos para poder
calcular subtotal
@param x Posición horizontal de inicio en el PDF
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2016-08-17 | [
"Método",
"que",
"agrega",
"el",
"subtotal",
"del",
"DTE"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Dte/PDF/Dte.php#L902-L919 |
LibreDTE/libredte-lib | lib/Sii/Dte/PDF/Dte.php | Dte.agregarDescuentosRecargos | protected function agregarDescuentosRecargos(array $descuentosRecargos, $x = 10)
{
if (!isset($descuentosRecargos[0])) {
$descuentosRecargos = [$descuentosRecargos];
}
foreach($descuentosRecargos as $dr) {
$tipo = $dr['TpoMov']=='D' ? 'Descuento' : 'Recargo';
if (!empty($dr['IndExeDR'])) {
$tipo .= ' EX';
}
$valor = $dr['TpoValor']=='%' ? $dr['ValorDR'].'%' : $this->num($dr['ValorDR']);
if ($this->papelContinuo) {
$this->Texto($tipo.' global: '.$valor.(!empty($dr['GlosaDR'])?(' ('.$dr['GlosaDR'].')'):''), $x);
} else {
$this->Texto($tipo.(!empty($dr['GlosaDR'])?(' ('.$dr['GlosaDR'].')'):'').':', 77, null, 'R', 100);
$this->Texto($valor, 177, null, 'R', 22);
}
$this->Ln();
}
} | php | protected function agregarDescuentosRecargos(array $descuentosRecargos, $x = 10)
{
if (!isset($descuentosRecargos[0])) {
$descuentosRecargos = [$descuentosRecargos];
}
foreach($descuentosRecargos as $dr) {
$tipo = $dr['TpoMov']=='D' ? 'Descuento' : 'Recargo';
if (!empty($dr['IndExeDR'])) {
$tipo .= ' EX';
}
$valor = $dr['TpoValor']=='%' ? $dr['ValorDR'].'%' : $this->num($dr['ValorDR']);
if ($this->papelContinuo) {
$this->Texto($tipo.' global: '.$valor.(!empty($dr['GlosaDR'])?(' ('.$dr['GlosaDR'].')'):''), $x);
} else {
$this->Texto($tipo.(!empty($dr['GlosaDR'])?(' ('.$dr['GlosaDR'].')'):'').':', 77, null, 'R', 100);
$this->Texto($valor, 177, null, 'R', 22);
}
$this->Ln();
}
} | [
"protected",
"function",
"agregarDescuentosRecargos",
"(",
"array",
"$",
"descuentosRecargos",
",",
"$",
"x",
"=",
"10",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"descuentosRecargos",
"[",
"0",
"]",
")",
")",
"{",
"$",
"descuentosRecargos",
"=",
"[",
... | Método que agrega los descuentos y/o recargos globales del documento
@param descuentosRecargos Arreglo con los descuentos y/o recargos del documento (tag DscRcgGlobal del XML)
@param x Posición horizontal de inicio en el PDF
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2018-05-29 | [
"Método",
"que",
"agrega",
"los",
"descuentos",
"y",
"/",
"o",
"recargos",
"globales",
"del",
"documento"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Dte/PDF/Dte.php#L928-L947 |
LibreDTE/libredte-lib | lib/Sii/Dte/PDF/Dte.php | Dte.agregarPagos | protected function agregarPagos(array $pagos, $x = 10)
{
if (!isset($pagos[0]))
$pagos = [$pagos];
$this->Texto('Pago(s) programado(s):', $x);
$this->Ln();
foreach($pagos as $p) {
$this->Texto(' - '.$this->date($p['FchPago'], false).': $'.$this->num($p['MntPago']).'.-'.(!empty($p['GlosaPagos'])?(' ('.$p['GlosaPagos'].')'):''), $x);
$this->Ln();
}
} | php | protected function agregarPagos(array $pagos, $x = 10)
{
if (!isset($pagos[0]))
$pagos = [$pagos];
$this->Texto('Pago(s) programado(s):', $x);
$this->Ln();
foreach($pagos as $p) {
$this->Texto(' - '.$this->date($p['FchPago'], false).': $'.$this->num($p['MntPago']).'.-'.(!empty($p['GlosaPagos'])?(' ('.$p['GlosaPagos'].')'):''), $x);
$this->Ln();
}
} | [
"protected",
"function",
"agregarPagos",
"(",
"array",
"$",
"pagos",
",",
"$",
"x",
"=",
"10",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"pagos",
"[",
"0",
"]",
")",
")",
"$",
"pagos",
"=",
"[",
"$",
"pagos",
"]",
";",
"$",
"this",
"->",
"... | Método que agrega los pagos del documento
@param pagos Arreglo con los pagos del documento
@param x Posición horizontal de inicio en el PDF
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2016-07-24 | [
"Método",
"que",
"agrega",
"los",
"pagos",
"del",
"documento"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Dte/PDF/Dte.php#L956-L966 |
LibreDTE/libredte-lib | lib/Sii/Dte/PDF/Dte.php | Dte.agregarTotales | protected function agregarTotales(array $totales, $otra_moneda, $y = 190, $x = 145, $offset = 25)
{
$y = (!$this->papelContinuo and !$this->timbre_pie) ? $this->x_fin_datos : $y;
// normalizar totales
$totales = array_merge([
'TpoMoneda' => false,
'MntNeto' => false,
'MntExe' => false,
'TasaIVA' => false,
'IVA' => false,
'IVANoRet' => false,
'CredEC' => false,
'MntTotal' => false,
'MontoNF' => false,
'MontoPeriodo' => false,
'SaldoAnterior' => false,
'VlrPagar' => false,
], $totales);
// glosas
$glosas = [
'TpoMoneda' => 'Moneda',
'MntNeto' => 'Neto $',
'MntExe' => 'Exento $',
'IVA' => 'IVA ('.$totales['TasaIVA'].'%) $',
'IVANoRet' => 'IVA no retenido $',
'CredEC' => 'Desc. 65% IVA $',
'MntTotal' => 'Total $',
'MontoNF' => 'Monto no facturable $',
'MontoPeriodo' => 'Monto período $',
'SaldoAnterior' => 'Saldo anterior $',
'VlrPagar' => 'Valor a pagar $',
];
// agregar impuestos adicionales y retenciones
if (!empty($totales['ImptoReten'])) {
$ImptoReten = $totales['ImptoReten'];
$MntTotal = $totales['MntTotal'];
unset($totales['ImptoReten'], $totales['MntTotal']);
if (!isset($ImptoReten[0])) {
$ImptoReten = [$ImptoReten];
}
foreach($ImptoReten as $i) {
$totales['ImptoReten_'.$i['TipoImp']] = $i['MontoImp'];
if (!empty($i['TasaImp'])) {
$glosas['ImptoReten_'.$i['TipoImp']] = \sasco\LibreDTE\Sii\ImpuestosAdicionales::getGlosa($i['TipoImp']).' ('.$i['TasaImp'].'%) $';
} else {
$glosas['ImptoReten_'.$i['TipoImp']] = \sasco\LibreDTE\Sii\ImpuestosAdicionales::getGlosa($i['TipoImp']).' $';
}
}
$totales['MntTotal'] = $MntTotal;
}
// agregar cada uno de los totales
$this->setY($y);
$this->setFont('', 'B', null);
foreach ($totales as $key => $total) {
if ($total!==false and isset($glosas[$key])) {
$y = $this->GetY();
if (!$this->cedible or $this->papelContinuo) {
$this->Texto($glosas[$key].' :', $x, null, 'R', 30);
$this->Texto($this->num($total), $x+$offset, $y, 'R', 30);
$this->Ln();
} else {
$this->MultiTexto($glosas[$key].' :', $x, null, 'R', 30);
$y_new = $this->GetY();
$this->Texto($this->num($total), $x+$offset, $y, 'R', 30);
$this->SetY($y_new);
}
}
}
// agregar totales en otra moneda
if (!empty($otra_moneda)) {
if (!isset($otra_moneda[0])) {
$otra_moneda = [$otra_moneda];
}
$this->setFont('', '', null);
$this->Ln();
foreach ($otra_moneda as $om) {
$y = $this->GetY();
if (!$this->cedible or $this->papelContinuo) {
$this->Texto('Total '.$om['TpoMoneda'].' :', $x, null, 'R', 30);
$this->Texto($this->num($om['MntTotOtrMnda']), $x+$offset, $y, 'R', 30);
$this->Ln();
} else {
$this->MultiTexto('Total '.$om['TpoMoneda'].' :', $x, null, 'R', 30);
$y_new = $this->GetY();
$this->Texto($this->num($om['MntTotOtrMnda']), $x+$offset, $y, 'R', 30);
$this->SetY($y_new);
}
}
$this->setFont('', 'B', null);
}
} | php | protected function agregarTotales(array $totales, $otra_moneda, $y = 190, $x = 145, $offset = 25)
{
$y = (!$this->papelContinuo and !$this->timbre_pie) ? $this->x_fin_datos : $y;
// normalizar totales
$totales = array_merge([
'TpoMoneda' => false,
'MntNeto' => false,
'MntExe' => false,
'TasaIVA' => false,
'IVA' => false,
'IVANoRet' => false,
'CredEC' => false,
'MntTotal' => false,
'MontoNF' => false,
'MontoPeriodo' => false,
'SaldoAnterior' => false,
'VlrPagar' => false,
], $totales);
// glosas
$glosas = [
'TpoMoneda' => 'Moneda',
'MntNeto' => 'Neto $',
'MntExe' => 'Exento $',
'IVA' => 'IVA ('.$totales['TasaIVA'].'%) $',
'IVANoRet' => 'IVA no retenido $',
'CredEC' => 'Desc. 65% IVA $',
'MntTotal' => 'Total $',
'MontoNF' => 'Monto no facturable $',
'MontoPeriodo' => 'Monto período $',
'SaldoAnterior' => 'Saldo anterior $',
'VlrPagar' => 'Valor a pagar $',
];
// agregar impuestos adicionales y retenciones
if (!empty($totales['ImptoReten'])) {
$ImptoReten = $totales['ImptoReten'];
$MntTotal = $totales['MntTotal'];
unset($totales['ImptoReten'], $totales['MntTotal']);
if (!isset($ImptoReten[0])) {
$ImptoReten = [$ImptoReten];
}
foreach($ImptoReten as $i) {
$totales['ImptoReten_'.$i['TipoImp']] = $i['MontoImp'];
if (!empty($i['TasaImp'])) {
$glosas['ImptoReten_'.$i['TipoImp']] = \sasco\LibreDTE\Sii\ImpuestosAdicionales::getGlosa($i['TipoImp']).' ('.$i['TasaImp'].'%) $';
} else {
$glosas['ImptoReten_'.$i['TipoImp']] = \sasco\LibreDTE\Sii\ImpuestosAdicionales::getGlosa($i['TipoImp']).' $';
}
}
$totales['MntTotal'] = $MntTotal;
}
// agregar cada uno de los totales
$this->setY($y);
$this->setFont('', 'B', null);
foreach ($totales as $key => $total) {
if ($total!==false and isset($glosas[$key])) {
$y = $this->GetY();
if (!$this->cedible or $this->papelContinuo) {
$this->Texto($glosas[$key].' :', $x, null, 'R', 30);
$this->Texto($this->num($total), $x+$offset, $y, 'R', 30);
$this->Ln();
} else {
$this->MultiTexto($glosas[$key].' :', $x, null, 'R', 30);
$y_new = $this->GetY();
$this->Texto($this->num($total), $x+$offset, $y, 'R', 30);
$this->SetY($y_new);
}
}
}
// agregar totales en otra moneda
if (!empty($otra_moneda)) {
if (!isset($otra_moneda[0])) {
$otra_moneda = [$otra_moneda];
}
$this->setFont('', '', null);
$this->Ln();
foreach ($otra_moneda as $om) {
$y = $this->GetY();
if (!$this->cedible or $this->papelContinuo) {
$this->Texto('Total '.$om['TpoMoneda'].' :', $x, null, 'R', 30);
$this->Texto($this->num($om['MntTotOtrMnda']), $x+$offset, $y, 'R', 30);
$this->Ln();
} else {
$this->MultiTexto('Total '.$om['TpoMoneda'].' :', $x, null, 'R', 30);
$y_new = $this->GetY();
$this->Texto($this->num($om['MntTotOtrMnda']), $x+$offset, $y, 'R', 30);
$this->SetY($y_new);
}
}
$this->setFont('', 'B', null);
}
} | [
"protected",
"function",
"agregarTotales",
"(",
"array",
"$",
"totales",
",",
"$",
"otra_moneda",
",",
"$",
"y",
"=",
"190",
",",
"$",
"x",
"=",
"145",
",",
"$",
"offset",
"=",
"25",
")",
"{",
"$",
"y",
"=",
"(",
"!",
"$",
"this",
"->",
"papelCon... | Método que agrega los totales del documento
@param totales Arreglo con los totales (tag Totales del XML)
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2017-10-05 | [
"Método",
"que",
"agrega",
"los",
"totales",
"del",
"documento"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Dte/PDF/Dte.php#L974-L1064 |
LibreDTE/libredte-lib | lib/Sii/Dte/PDF/Dte.php | Dte.agregarObservacion | protected function agregarObservacion($IdDoc, $x = 10, $y = 190)
{
$y = (!$this->papelContinuo and !$this->timbre_pie) ? $this->x_fin_datos : $y;
if (!$this->papelContinuo and $this->timbre_pie) {
$y -= 15;
}
$this->SetXY($x, $y);
if (!empty($IdDoc['TermPagoGlosa'])) {
$this->MultiTexto('Observación: '.$IdDoc['TermPagoGlosa']);
}
if (!empty($IdDoc['MedioPago']) or !empty($IdDoc['TermPagoDias'])) {
$pago = [];
if (!empty($IdDoc['MedioPago'])) {
$medio = 'Medio de pago: '.(!empty($this->medios_pago[$IdDoc['MedioPago']]) ? $this->medios_pago[$IdDoc['MedioPago']] : $IdDoc['MedioPago']);
if (!empty($IdDoc['BcoPago'])) {
$medio .= ' a '.$IdDoc['BcoPago'];
}
if (!empty($IdDoc['TpoCtaPago'])) {
$medio .= ' en cuenta '.strtolower($IdDoc['TpoCtaPago']);
}
if (!empty($IdDoc['NumCtaPago'])) {
$medio .= ' N° '.$IdDoc['NumCtaPago'];
}
$pago[] = $medio;
}
if (!empty($IdDoc['TermPagoDias'])) {
$pago[] = 'Días de pago: '.$IdDoc['TermPagoDias'];
}
$this->SetXY($x, $this->GetY());
$this->MultiTexto(implode(' / ', $pago));
}
return $this->GetY();
} | php | protected function agregarObservacion($IdDoc, $x = 10, $y = 190)
{
$y = (!$this->papelContinuo and !$this->timbre_pie) ? $this->x_fin_datos : $y;
if (!$this->papelContinuo and $this->timbre_pie) {
$y -= 15;
}
$this->SetXY($x, $y);
if (!empty($IdDoc['TermPagoGlosa'])) {
$this->MultiTexto('Observación: '.$IdDoc['TermPagoGlosa']);
}
if (!empty($IdDoc['MedioPago']) or !empty($IdDoc['TermPagoDias'])) {
$pago = [];
if (!empty($IdDoc['MedioPago'])) {
$medio = 'Medio de pago: '.(!empty($this->medios_pago[$IdDoc['MedioPago']]) ? $this->medios_pago[$IdDoc['MedioPago']] : $IdDoc['MedioPago']);
if (!empty($IdDoc['BcoPago'])) {
$medio .= ' a '.$IdDoc['BcoPago'];
}
if (!empty($IdDoc['TpoCtaPago'])) {
$medio .= ' en cuenta '.strtolower($IdDoc['TpoCtaPago']);
}
if (!empty($IdDoc['NumCtaPago'])) {
$medio .= ' N° '.$IdDoc['NumCtaPago'];
}
$pago[] = $medio;
}
if (!empty($IdDoc['TermPagoDias'])) {
$pago[] = 'Días de pago: '.$IdDoc['TermPagoDias'];
}
$this->SetXY($x, $this->GetY());
$this->MultiTexto(implode(' / ', $pago));
}
return $this->GetY();
} | [
"protected",
"function",
"agregarObservacion",
"(",
"$",
"IdDoc",
",",
"$",
"x",
"=",
"10",
",",
"$",
"y",
"=",
"190",
")",
"{",
"$",
"y",
"=",
"(",
"!",
"$",
"this",
"->",
"papelContinuo",
"and",
"!",
"$",
"this",
"->",
"timbre_pie",
")",
"?",
"... | Método que coloca las diferentes observaciones que puede tener el documnto
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2018-06-15 | [
"Método",
"que",
"coloca",
"las",
"diferentes",
"observaciones",
"que",
"puede",
"tener",
"el",
"documnto"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Dte/PDF/Dte.php#L1071-L1103 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.