repo
stringlengths
7
63
file_url
stringlengths
81
284
file_path
stringlengths
5
200
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:02:33
2026-01-05 05:24:06
truncated
bool
2 classes
xielei/swoole-worker
https://github.com/xielei/swoole-worker/blob/f7a5b731d86f62c9040056f08a3a513fd3f90e28/src/Cmd/UpdateSession.php
src/Cmd/UpdateSession.php
<?php declare(strict_types=1); namespace Xielei\Swoole\Cmd; use Swoole\Coroutine\Server\Connection; use Xielei\Swoole\Interfaces\CmdInterface; use Xielei\Swoole\Gateway; class UpdateSession implements CmdInterface { public static function getCommandCode(): int { return 26; } public static function encode(int $fd, array $session): string { return pack('CN', self::getCommandCode(), $fd) . serialize($session); } public static function decode(string $buffer): array { $data = unpack('Nfd', $buffer); $data['session'] = unserialize(substr($buffer, 4)); return $data; } public static function execute(Gateway $gateway, Connection $conn, string $buffer) { $data = self::decode($buffer); if (isset($gateway->fd_list[$data['fd']])) { $gateway->fd_list[$data['fd']]['session'] = array_merge($gateway->fd_list[$data['fd']]['session'] ?? [], $data['session']); } } }
php
Apache-2.0
f7a5b731d86f62c9040056f08a3a513fd3f90e28
2026-01-05T04:57:25.551053Z
false
xielei/swoole-worker
https://github.com/xielei/swoole-worker/blob/f7a5b731d86f62c9040056f08a3a513fd3f90e28/src/Cmd/BindUid.php
src/Cmd/BindUid.php
<?php declare(strict_types=1); namespace Xielei\Swoole\Cmd; use Swoole\Coroutine\Server\Connection; use Xielei\Swoole\Interfaces\CmdInterface; use Xielei\Swoole\Gateway; class BindUid implements CmdInterface { public static function getCommandCode(): int { return 1; } public static function encode(int $fd, string $uid): string { return pack('CN', self::getCommandCode(), $fd) . $uid; } public static function decode(string $buffer): array { $res = unpack('Nfd', $buffer); $res['uid'] = substr($buffer, 4); return $res; } public static function execute(Gateway $gateway, Connection $conn, string $buffer) { $data = self::decode($buffer); if (isset($gateway->fd_list[$data['fd']])) { if (!isset($gateway->uid_list[$data['uid']])) { $gateway->uid_list[$data['uid']] = []; } if ($old_bind_uid = $gateway->fd_list[$data['fd']]['uid']) { unset($gateway->uid_list[$old_bind_uid][$data['fd']]); if (isset($gateway->uid_list[$old_bind_uid]) && !$gateway->uid_list[$old_bind_uid]) { unset($gateway->uid_list[$old_bind_uid]); } } $gateway->fd_list[$data['fd']]['uid'] = $data['uid']; $gateway->uid_list[$data['uid']][$data['fd']] = $data['fd']; } } }
php
Apache-2.0
f7a5b731d86f62c9040056f08a3a513fd3f90e28
2026-01-05T04:57:25.551053Z
false
xielei/swoole-worker
https://github.com/xielei/swoole-worker/blob/f7a5b731d86f62c9040056f08a3a513fd3f90e28/src/Cmd/GetUidListByGroup.php
src/Cmd/GetUidListByGroup.php
<?php declare(strict_types=1); namespace Xielei\Swoole\Cmd; use Swoole\Coroutine\Server\Connection; use Xielei\Swoole\Interfaces\CmdInterface; use Xielei\Swoole\Gateway; use Xielei\Swoole\Protocol; class GetUidListByGroup implements CmdInterface { public static function getCommandCode(): int { return 15; } public static function encode(string $group): string { return pack('C', self::getCommandCode()) . $group; } public static function decode(string $buffer): array { return [ 'group' => $buffer, ]; } public static function execute(Gateway $gateway, Connection $conn, string $buffer) { $data = self::decode($buffer); $uid_list = []; foreach ($gateway->group_list[$data['group']] ?? [] as $fd) { if (isset($gateway->fd_list[$fd]['uid']) && $gateway->fd_list[$fd]['uid']) { $uid_list[] = $gateway->fd_list[$fd]['uid']; } } $uid_list = array_filter(array_unique($uid_list)); $buffer = ''; foreach ($uid_list as $uid) { $buffer .= pack('C', strlen((string) $uid)) . $uid; } $conn->send(Protocol::encode($buffer)); } }
php
Apache-2.0
f7a5b731d86f62c9040056f08a3a513fd3f90e28
2026-01-05T04:57:25.551053Z
false
xielei/swoole-worker
https://github.com/xielei/swoole-worker/blob/f7a5b731d86f62c9040056f08a3a513fd3f90e28/src/Cmd/GetClientCountByUid.php
src/Cmd/GetClientCountByUid.php
<?php declare(strict_types=1); namespace Xielei\Swoole\Cmd; use Swoole\Coroutine\Server\Connection; use Xielei\Swoole\Interfaces\CmdInterface; use Xielei\Swoole\Gateway; use Xielei\Swoole\Protocol; class GetClientCountByUid implements CmdInterface { public static function getCommandCode(): int { return 6; } public static function encode(string $uid): string { return pack('C', self::getCommandCode()) . $uid; } public static function decode(string $buffer): array { return [ 'uid' => $buffer, ]; } public static function execute(Gateway $gateway, Connection $conn, string $buffer) { $data = self::decode($buffer); $buffer = pack('N', count($gateway->uid_list[$data['uid']] ?? [])); $conn->send(Protocol::encode($buffer)); } }
php
Apache-2.0
f7a5b731d86f62c9040056f08a3a513fd3f90e28
2026-01-05T04:57:25.551053Z
false
xielei/swoole-worker
https://github.com/xielei/swoole-worker/blob/f7a5b731d86f62c9040056f08a3a513fd3f90e28/src/Cmd/SendToGroup.php
src/Cmd/SendToGroup.php
<?php declare(strict_types=1); namespace Xielei\Swoole\Cmd; use Swoole\Coroutine\Server\Connection; use Xielei\Swoole\Interfaces\CmdInterface; use Xielei\Swoole\Gateway; class SendToGroup implements CmdInterface { public static function getCommandCode(): int { return 22; } public static function encode(string $group, string $message, array $without_fd_list = []): string { return pack('CCn', self::getCommandCode(), strlen($group), count($without_fd_list)) . $group . ($without_fd_list ? pack('N*', ...$without_fd_list) : '') . $message; } public static function decode(string $buffer): array { $tmp = unpack('Cgroup_len/ncount', $buffer); return [ 'group' => substr($buffer, 3, $tmp['group_len']), 'without_fd_list' => unpack('N*', substr($buffer, 3 + $tmp['group_len'], $tmp['count'] * 4)), 'message' => substr($buffer, 3 + $tmp['group_len'] + $tmp['count'] * 4), ]; } public static function execute(Gateway $gateway, Connection $conn, string $buffer) { $data = self::decode($buffer); $fd_list = $gateway->group_list[$data['group']] ?? []; foreach ($fd_list as $fd) { if (!in_array($fd, $data['without_fd_list'])) { $gateway->sendToClient($fd, $data['message']); } } } }
php
Apache-2.0
f7a5b731d86f62c9040056f08a3a513fd3f90e28
2026-01-05T04:57:25.551053Z
false
xielei/swoole-worker
https://github.com/xielei/swoole-worker/blob/f7a5b731d86f62c9040056f08a3a513fd3f90e28/src/Cmd/SetSession.php
src/Cmd/SetSession.php
<?php declare(strict_types=1); namespace Xielei\Swoole\Cmd; use Swoole\Coroutine\Server\Connection; use Xielei\Swoole\Interfaces\CmdInterface; use Xielei\Swoole\Gateway; class SetSession implements CmdInterface { public static function getCommandCode(): int { return 23; } public static function encode(int $fd, array $session): string { return pack('CN', self::getCommandCode(), $fd) . serialize($session); } public static function decode(string $buffer): array { $data = unpack('Nfd', $buffer); $data['session'] = unserialize(substr($buffer, 4)); return $data; } public static function execute(Gateway $gateway, Connection $conn, string $buffer) { $data = self::decode($buffer); if (isset($gateway->fd_list[$data['fd']])) { $gateway->fd_list[$data['fd']]['session'] = $data['session']; } } }
php
Apache-2.0
f7a5b731d86f62c9040056f08a3a513fd3f90e28
2026-01-05T04:57:25.551053Z
false
xielei/swoole-worker
https://github.com/xielei/swoole-worker/blob/f7a5b731d86f62c9040056f08a3a513fd3f90e28/src/Helper/TaskEvent.php
src/Helper/TaskEvent.php
<?php declare(strict_types=1); namespace Xielei\Swoole\Helper; use Swoole\Server\PipeMessage; use Swoole\Server\Task; use Xielei\Swoole\Interfaces\TaskEventInterface; use Xielei\Swoole\Worker; class TaskEvent implements TaskEventInterface { public $worker; public function __construct(Worker $worker) { $this->worker = $worker; } public function onWorkerStart() { } public function onWorkerExit() { } public function onWorkerStop() { } public function onTask(Task $task) { } public function onPipeMessage(PipeMessage $pipeMessage) { } }
php
Apache-2.0
f7a5b731d86f62c9040056f08a3a513fd3f90e28
2026-01-05T04:57:25.551053Z
false
xielei/swoole-worker
https://github.com/xielei/swoole-worker/blob/f7a5b731d86f62c9040056f08a3a513fd3f90e28/src/Helper/WorkerEvent.php
src/Helper/WorkerEvent.php
<?php declare(strict_types=1); namespace Xielei\Swoole\Helper; use Swoole\Server\PipeMessage; use Swoole\Server\TaskResult; use Xielei\Swoole\Interfaces\WorkerEventInterface; use Xielei\Swoole\Worker; class WorkerEvent implements WorkerEventInterface { public $worker; public function __construct(Worker $worker) { $this->worker = $worker; } public function onWorkerStart() { } public function onWorkerExit() { } public function onWorkerStop() { } public function onFinish(TaskResult $taskResult) { } public function onPipeMessage(PipeMessage $pipeMessage) { } public function onConnect(string $client, array $session) { } public function onReceive(string $client, array $session, string $data) { } public function onOpen(string $client, array $session, array $request) { $this->onConnect($client, $session); } public function onMessage(string $client, array $session, array $frame) { switch ($frame['opcode']) { case WEBSOCKET_OPCODE_TEXT: case WEBSOCKET_OPCODE_BINARY: $this->onReceive($client, $session, $frame['data']); break; default: break; } } public function onClose(string $client, array $session, array $bind) { } }
php
Apache-2.0
f7a5b731d86f62c9040056f08a3a513fd3f90e28
2026-01-05T04:57:25.551053Z
false
xielei/swoole-worker
https://github.com/xielei/swoole-worker/blob/f7a5b731d86f62c9040056f08a3a513fd3f90e28/src/Library/Client.php
src/Library/Client.php
<?php declare(strict_types=1); namespace Xielei\Swoole\Library; use Swoole\ConnectionPool; use Swoole\Coroutine; use Swoole\Coroutine\Client as CoroutineClient; use Xielei\Swoole\Service; class Client { public $onStart; public $onConnect; public $onMessage; public $onClose; public $onError; public $onStop; private $host = null; private $port = null; private $pool = null; private $stoped = false; public function __construct(string $host, int $port) { $this->host = $host; $this->port = $port; $this->pool = new ConnectionPool(function () use ($host, $port) { $conn = new CoroutineClient(SWOOLE_SOCK_TCP); $conn->set([ 'open_length_check' => true, 'package_length_type' => 'N', 'package_length_offset' => 0, 'package_body_offset' => 0, ]); Service::debug("create client {$host}:{$port}"); return $conn; }, 1); } public function start() { Coroutine::create(function () { $this->emit('start'); $this->connect(); while (!$this->stoped) { $conn = $this->pool->get(); $buffer = $conn->recv(1); if ($buffer === '') { $conn->close(true); $this->pool->put($conn); Service::debug("close2 {$this->host}:{$this->port}"); $this->emit('close'); } elseif ($buffer === false) { $errCode = $conn->errCode; if ($errCode !== SOCKET_ETIMEDOUT) { $conn->close(true); $this->pool->put($conn); $this->emit('error', $errCode); Service::debug("close3 {$this->host}:{$this->port}"); $this->emit('close'); } else { $this->pool->put($conn); $this->emit('error', $errCode); } } elseif ($buffer) { $this->pool->put($conn); $this->emit('message', $buffer); } else { $conn->close(true); $this->pool->put($conn); Service::debug("close4 {$this->host}:{$this->port}"); $this->emit('close'); } } $conn = $this->pool->get(); if ($conn->isConnected()) { $conn->close(); } $this->pool->close(); $this->emit('close'); $this->emit('stop'); }); } public function send(string $buffer) { if (!$this->stoped) { $conn = $this->pool->get(); $res = strlen($buffer) === $conn->send($buffer); $this->pool->put($conn); return $res; } } public function sendAndRecv(string $buffer, float $timeout = 1) { if (!$this->stoped) { $conn = $this->pool->get(); $len = $conn->send($buffer); if (strlen($buffer) === $len) { $res = $conn->recv($timeout); if ($res === '') { $conn->close(); } $this->pool->put($conn); return $res; } else { $this->pool->put($conn); } } } public function connect(float $timeout = 1) { if (!$this->stoped) { $conn = $this->pool->get(); if (false === $conn->connect($this->host, $this->port, $timeout)) { $conn->close(true); $this->pool->put($conn); Service::debug("close1 {$this->host}:{$this->port}"); $this->emit('close'); } else { Service::debug("connect success {$this->host}:{$this->port}"); $this->pool->put($conn); $this->emit('connect'); } } } public function on(string $event, callable $callback) { $event = 'on' . ucfirst(strtolower($event)); $this->$event = $callback; } public function stop() { $this->stoped = true; } private function emit(string $event, ...$param) { $event = 'on' . ucfirst(strtolower($event)); if ($this->$event !== null) { call_user_func($this->$event, ...$param); } } public function __destruct() { $this->stoped = true; } }
php
Apache-2.0
f7a5b731d86f62c9040056f08a3a513fd3f90e28
2026-01-05T04:57:25.551053Z
false
xielei/swoole-worker
https://github.com/xielei/swoole-worker/blob/f7a5b731d86f62c9040056f08a3a513fd3f90e28/src/Library/ClientPool.php
src/Library/ClientPool.php
<?php declare (strict_types = 1); namespace Xielei\Swoole\Library; use Swoole\ConnectionPool; use Swoole\Coroutine\Socket; class ClientPool extends ConnectionPool { public function __construct(string $host, int $port, int $size = 1024) { $constructor = function () use ($host, $port): Socket { $conn = new Socket(AF_INET, SOCK_STREAM, 0); $conn->setProtocol([ 'open_length_check' => true, 'package_length_type' => 'N', 'package_length_offset' => 0, 'package_body_offset' => 0, ]); if (!$conn->connect($host, $port)) { $conn->close(true); } return $conn; }; parent::__construct($constructor, $size); } public function getConn() { $conn = $this->get(); if (!$conn->checkLiveness()) { $this->num -= 1; $conn = $this->getConn(); } return $conn; } public function send(string $buffer): bool { $conn = $this->getConn(); $res = $conn->send($buffer); if (strlen($buffer) === $res) { $this->put($conn); return true; } else { $conn->close(true); $this->num -= 1; return false; } } public function sendAndRecv(string $buffer, float $timeout = 1): ?string { $conn = $this->getConn(); $res = $conn->send($buffer); if (strlen($buffer) !== $res) { $conn->close(true); $this->num -= 1; } else { $recv = $conn->recv(0, $timeout); if ($recv === '') { $conn->close(true); $this->num -= 1; } elseif ($recv === false) { if ($conn->errCode !== SOCKET_ETIMEDOUT) { $conn->close(true); $this->num -= 1; } else { $this->put($conn); } } else { $this->put($conn); return $recv; } } return null; } }
php
Apache-2.0
f7a5b731d86f62c9040056f08a3a513fd3f90e28
2026-01-05T04:57:25.551053Z
false
xielei/swoole-worker
https://github.com/xielei/swoole-worker/blob/f7a5b731d86f62c9040056f08a3a513fd3f90e28/src/Library/Globals.php
src/Library/Globals.php
<?php declare(strict_types=1); namespace Xielei\Swoole\Library; use Swoole\Coroutine\Server\Connection; class Globals extends SockServer { protected $data = []; public function __construct() { parent::__construct(function (Connection $conn, $params) { if (!is_array($params)) { return; } switch (array_shift($params)) { case 'get': list($name) = $params; self::sendToConn($conn, $this->getValue($this->data, explode('.', $name))); break; case 'set': list($name, $value) = $params; $this->setValue($this->data, explode('.', $name), $value); self::sendToConn($conn, true); break; case 'unset': list($name) = $params; self::sendToConn($conn, $this->unsetValue($this->data, explode('.', $name))); break; case 'isset': list($name) = $params; self::sendToConn($conn, $this->issetValue($this->data, explode('.', $name))); break; default: self::sendToConn($conn, 'no cmd..'); break; } }); } public function get(string $name, $default = null) { $res = $this->sendAndReceive(['get', $name]); return is_null($res) ? $default : $res; } public function set(string $name, $value): bool { return $this->sendAndReceive(['set', $name, $value]); } public function unset(string $name) { return $this->sendAndReceive(['unset', $name]); } public function isset(string $name): bool { return $this->sendAndReceive(['isset', $name]); } private function issetValue(array $data, array $path): bool { $key = array_shift($path); if (!$path) { return isset($data[$key]) ? true : false; } else { if (isset($data[$key])) { return $this->issetValue($data[$key], $path); } else { return false; } } } private function unsetValue(array &$data, array $path): bool { $key = array_shift($path); if (!$path) { unset($data[$key]); return true; } else { if (isset($data[$key])) { return $this->unsetValue($data[$key], $path); } else { return true; } } } private function getValue(array $data, array $path, $default = null) { $key = array_shift($path); if (!$path) { return isset($data[$key]) ? $data[$key] : $default; } else { if (isset($data[$key])) { return $this->getValue($data[$key], $path, $default); } else { return $default; } } } private function setValue(array &$data, array $path, $value) { $key = array_shift($path); if ($path) { if (!isset($data[$key])) { $data[$key] = []; } $this->setValue($data[$key], $path, $value); } else { $data[$key] = $value; } } }
php
Apache-2.0
f7a5b731d86f62c9040056f08a3a513fd3f90e28
2026-01-05T04:57:25.551053Z
false
xielei/swoole-worker
https://github.com/xielei/swoole-worker/blob/f7a5b731d86f62c9040056f08a3a513fd3f90e28/src/Library/Reload.php
src/Library/Reload.php
<?php declare(strict_types=1); namespace Xielei\Swoole\Library; class Reload { private static $watch = []; private static $filetimes = []; public static function init(array $watch = []) { self::$watch = $watch; $tmp_filetimes = []; foreach ($watch as $item) { self::getFilesTime($item, $tmp_filetimes); } self::$filetimes = $tmp_filetimes; } public static function check() { clearstatcache(); $tmp_filetimes = []; foreach (self::$watch as $item) { self::getFilesTime($item, $tmp_filetimes); } if ($tmp_filetimes != self::$filetimes) { self::$filetimes = $tmp_filetimes; return true; } return false; } private static function getFilesTime($path, &$files) { if (is_dir($path)) { $dp = dir($path); while ($file = $dp->read()) { if ($file !== "." && $file !== "..") { self::getFilesTime($path . "/" . $file, $files); } } $dp->close(); } if (is_file($path)) { $files[$path] = filemtime($path); } } }
php
Apache-2.0
f7a5b731d86f62c9040056f08a3a513fd3f90e28
2026-01-05T04:57:25.551053Z
false
xielei/swoole-worker
https://github.com/xielei/swoole-worker/blob/f7a5b731d86f62c9040056f08a3a513fd3f90e28/src/Library/Server.php
src/Library/Server.php
<?php declare(strict_types=1); namespace Xielei\Swoole\Library; use Swoole\Coroutine; use Swoole\Coroutine\Server as CoroutineServer; use Swoole\Coroutine\Server\Connection; use Xielei\Swoole\Service; class Server { public $onStart; public $onConnect; public $onMessage; public $onClose; public $onError; public $onStop; private $server = null; private $stoped = false; public function __construct(string $host, int $port) { Service::debug("create server {$host}:{$port}"); $server = new CoroutineServer($host, $port, false, true); $server->set([ 'open_length_check' => true, 'package_length_type' => 'N', 'package_length_offset' => 0, 'package_body_offset' => 0, 'heartbeat_idle_time' => 60, 'heartbeat_check_interval' => 6, ]); $server->handle(function (Connection $conn) { $this->emit('connect', $conn); while (!$this->stoped) { $buffer = $conn->recv(1); if ($buffer === '') { Service::debug("server close1"); $conn->close(); $this->emit('close', $conn); break; } elseif ($buffer === false) { $errCode = swoole_last_error(); $this->emit('error', $conn, $errCode); if ($errCode !== SOCKET_ETIMEDOUT) { $conn->close(); $this->emit('close', $conn); break; } } else { $this->emit('message', $conn, $buffer); } } Service::debug("server close5"); $conn->close(); $this->emit('close', $conn); }); $this->server = $server; } public function start() { $this->emit('start'); Coroutine::create(function () { $this->server->start(); }); } public function stop() { $this->stoped = true; $this->server->shutdown(); $this->emit('stop'); } public function on(string $event, callable $callback) { $event = 'on' . ucfirst(strtolower($event)); $this->$event = $callback; } private function emit(string $event, ...$param) { $event = 'on' . ucfirst(strtolower($event)); if ($this->$event !== null) { call_user_func($this->$event, ...$param); } } }
php
Apache-2.0
f7a5b731d86f62c9040056f08a3a513fd3f90e28
2026-01-05T04:57:25.551053Z
false
xielei/swoole-worker
https://github.com/xielei/swoole-worker/blob/f7a5b731d86f62c9040056f08a3a513fd3f90e28/src/Library/Config.php
src/Library/Config.php
<?php declare(strict_types=1); namespace Xielei\Swoole\Library; class Config { private static $configs = []; public static function load(string $file) { foreach (require $file as $key => $value) { Config::set($key, $value); } } public static function set(string $key, $value) { self::$configs[$key] = $value; } public static function get(string $key, $default = null) { return self::$configs[$key] ?? $default; } public static function delete(string $key) { unset(self::$configs[$key]); } public static function isset(string $key) { return isset(self::$configs[$key]); } }
php
Apache-2.0
f7a5b731d86f62c9040056f08a3a513fd3f90e28
2026-01-05T04:57:25.551053Z
false
xielei/swoole-worker
https://github.com/xielei/swoole-worker/blob/f7a5b731d86f62c9040056f08a3a513fd3f90e28/src/Library/SockServer.php
src/Library/SockServer.php
<?php declare(strict_types=1); namespace Xielei\Swoole\Library; use Exception; use Swoole\ConnectionPool; use Swoole\Coroutine; use Swoole\Coroutine\Server\Connection; use Swoole\Process; use Swoole\Coroutine\Server; use Swoole\Coroutine\Client; use Xielei\Swoole\Protocol; class SockServer { private $sock_file; private $callback; private $pool; public function __construct(callable $callback, string $sock_file = null) { $this->sock_file = $sock_file ?: ('/var/run/' . uniqid() . '.sock'); $this->callback = $callback; $this->pool = new ConnectionPool(function () { $client = new Client(SWOOLE_UNIX_STREAM); $client->set([ 'open_length_check' => true, 'package_length_type' => 'N', 'package_length_offset' => 0, 'package_body_offset' => 0, ]); connect: if (!$client->connect($this->sock_file)) { $client->close(); Coroutine::sleep(0.001); goto connect; } return $client; }); } public function mountTo(\Swoole\Server $server) { $server->addProcess(new Process(function (Process $process) { $this->startLanServer(); }, false, 2, true)); } public function getSockFile(): string { return $this->sock_file; } public function sendAndReceive($data) { $client = $this->pool->get(); $client->send(Protocol::encode(serialize($data))); $res = unserialize(Protocol::decode($client->recv())); $this->pool->put($client); return $res; } public function streamWriteAndRead($data) { $fp = stream_socket_client("unix://{$this->sock_file}", $errno, $errstr); if (!$fp) { throw new Exception("$errstr", $errno); } else { fwrite($fp, Protocol::encode(serialize($data))); $res = unserialize(Protocol::decode(fread($fp, 40960))); fclose($fp); return $res; } } private function startLanServer() { $server = new Server('unix:' . $this->sock_file); $server->set([ 'open_length_check' => true, 'package_length_type' => 'N', 'package_length_offset' => 0, 'package_body_offset' => 0, ]); $server->handle(function (Connection $conn) { while (true) { $buffer = $conn->recv(1); if ($buffer === '') { $conn->close(); break; } elseif ($buffer === false) { if (swoole_last_error() !== SOCKET_ETIMEDOUT) { $conn->close(); break; } } else { $res = unserialize(Protocol::decode($buffer)); call_user_func($this->callback ?: function () { }, $conn, $res); } } }); $server->start(); } public static function sendToConn(Connection $conn, $data) { $conn->send(Protocol::encode(serialize($data))); } }
php
Apache-2.0
f7a5b731d86f62c9040056f08a3a513fd3f90e28
2026-01-05T04:57:25.551053Z
false
xielei/swoole-worker
https://github.com/xielei/swoole-worker/blob/f7a5b731d86f62c9040056f08a3a513fd3f90e28/src/init/event_worker.php
src/init/event_worker.php
<?php use Xielei\Swoole\Helper\WorkerEvent as HelperWorkerEvent; class WorkerEvent extends HelperWorkerEvent { }
php
Apache-2.0
f7a5b731d86f62c9040056f08a3a513fd3f90e28
2026-01-05T04:57:25.551053Z
false
xielei/swoole-worker
https://github.com/xielei/swoole-worker/blob/f7a5b731d86f62c9040056f08a3a513fd3f90e28/src/init/event_task.php
src/init/event_task.php
<?php use Xielei\Swoole\Helper\TaskEvent as HelperTaskEvent; class TaskEvent extends HelperTaskEvent { }
php
Apache-2.0
f7a5b731d86f62c9040056f08a3a513fd3f90e28
2026-01-05T04:57:25.551053Z
false
xielei/swoole-worker
https://github.com/xielei/swoole-worker/blob/f7a5b731d86f62c9040056f08a3a513fd3f90e28/src/init/worker.php
src/init/worker.php
<?php use function Composer\Autoload\includeFile; use Swoole\Server; use Swoole\Server\PipeMessage; use Xielei\Swoole\Api; use Xielei\Swoole\Library\Config; use Xielei\Swoole\Service; use Xielei\Swoole\Worker; /** * @var Worker $this */ $this->on('WorkerStart', function (Server $server, int $worker_id, ...$args) { $this->sendToProcess([ 'event' => 'gateway_address_list', 'worker_id' => $worker_id, ]); Api::$address_list = &$this->gateway_address_list; if ($server->taskworker) { includeFile(Config::get('task_file', __DIR__ . '/event_task.php')); $this->event = new \TaskEvent($this); } else { includeFile(Config::get('worker_file', __DIR__ . '/event_worker.php')); $this->event = new \WorkerEvent($this); } $this->dispatch('onWorkerStart', $worker_id, ...$args); }); $this->on('PipeMessage', function (Server $server, PipeMessage $pipeMessage, ...$args) { if ($pipeMessage->worker_id >= $server->setting['worker_num'] + $server->setting['task_worker_num']) { $data = unserialize($pipeMessage->data); switch ($data['event']) { case 'gateway_address_list': $this->gateway_address_list = $data['gateway_address_list']; break; case 'gateway_event': $this->onGatewayMessage($data['buffer'], $data['address']); break; default: Service::debug("PipeMessage event not found~ data:{$pipeMessage->data}"); break; } } else { $this->dispatch('onPipeMessage', $pipeMessage, ...$args); } }); $this->on('WorkerExit', function (Server $server, ...$args) { $this->dispatch('onWorkerExit', ...$args); }); $this->on('WorkerStop', function (Server $server, ...$args) { $this->dispatch('onWorkerStop', ...$args); }); $this->on('Task', function (Server $server, ...$args) { $this->dispatch('onTask', ...$args); }); $this->on('Finish', function (Server $server, ...$args) { $this->dispatch('onFinish', ...$args); });
php
Apache-2.0
f7a5b731d86f62c9040056f08a3a513fd3f90e28
2026-01-05T04:57:25.551053Z
false
xielei/swoole-worker
https://github.com/xielei/swoole-worker/blob/f7a5b731d86f62c9040056f08a3a513fd3f90e28/src/init/register.php
src/init/register.php
<?php use Swoole\Server; use Swoole\Server\Event; use Xielei\Swoole\Protocol; use Swoole\Timer; use Xielei\Swoole\Library\Config; use Xielei\Swoole\Register; use Xielei\Swoole\Service; /** * @var Register $this */ $this->on('Connect', function (Server $server, Event $event) { Timer::after(3000, function () use ($server, $event) { if ( $this->globals->isset('gateway_address_list.' . $event->fd) || $this->globals->isset('worker_fd_list.' . $event->fd) ) { return; } if ($server->exist($event->fd)) { Service::debug("close timeout fd:{$event->fd}"); $server->close($event->fd); } }); }); $this->on('Receive', function (Server $server, Event $event) { $data = unpack('Ccmd/A*load', Protocol::decode($event->data)); switch ($data['cmd']) { case Protocol::GATEWAY_CONNECT: $load = unpack('Nlan_host/nlan_port', $data['load']); $load['register_secret'] = substr($data['load'], 6); if (Config::get('register_secret', '') && $load['register_secret'] !== Config::get('register_secret', '')) { Service::debug("GATEWAY_CONNECT failure. register_secret invalid~"); $server->close($event->fd); return; } $this->globals->set('gateway_address_list.' . $event->fd, pack('Nn', $load['lan_host'], $load['lan_port'])); $this->broadcastGatewayAddressList(); break; case Protocol::WORKER_CONNECT: if (Config::get('register_secret', '') && ($data['load'] !== Config::get('register_secret', ''))) { Service::debug("WORKER_CONNECT failure. register_secret invalid~"); $server->close($event->fd); return; } $this->globals->set('worker_fd_list.' . $event->fd, $event->fd); $this->broadcastGatewayAddressList($event->fd); break; case Protocol::PING: break; default: Service::debug("undefined cmd and closed by register"); $server->close($event->fd); break; } }); $this->on('Close', function (Server $server, Event $event) { if ($this->globals->isset('worker_fd_list.' . $event->fd)) { $this->globals->unset('worker_fd_list.' . $event->fd); } if ($this->globals->isset('gateway_address_list.' . $event->fd)) { $this->globals->unset('gateway_address_list.' . $event->fd); $this->broadcastGatewayAddressList(); } });
php
Apache-2.0
f7a5b731d86f62c9040056f08a3a513fd3f90e28
2026-01-05T04:57:25.551053Z
false
xielei/swoole-worker
https://github.com/xielei/swoole-worker/blob/f7a5b731d86f62c9040056f08a3a513fd3f90e28/src/init/gateway.php
src/init/gateway.php
<?php use Swoole\Server; use Swoole\Timer; use Xielei\Swoole\Gateway; use Xielei\Swoole\Library\Config; /** * @var Gateway $this */ foreach (['Connect', 'Open', 'Receive', 'Message'] as $event) { $this->on($event, function (Server $server, ...$args) use ($event) { if (Config::get('throttle', false)) { $info = $server->getClientInfo($args[0]->fd, $args[0]->reactor_id, true); if (is_array($info) && isset($info['remote_ip'])) { $ip = $info['remote_ip']; if (!isset($this->throttle_list[$ip])) { $this->throttle_list[$ip] = [ 'timer' => Timer::tick(Config::get('throttle_interval', 10000), function () use ($ip) { if ($this->throttle_list[$ip]['fd_list']) { $this->throttle_list[$ip]['times'] = Config::get('throttle_times', 100); } else { Timer::clear($this->throttle_list[$ip]['timer']); unset($this->throttle_list[$ip]); } }), 'times' => Config::get('throttle_times', 100), 'fd_list' => [], ]; } if (!isset($this->throttle_list[$ip]['fd_list'][$args[0]->fd])) { $this->throttle_list[$ip]['fd_list'][$args[0]->fd] = $args[0]->fd; } $this->throttle_list[$ip]['times'] -= 1; if ($this->throttle_list[$ip]['times'] < 0) { switch (Config::get('throttle_close', 2)) { case 1: case 2: $server->close($args[0]->fd, Config::get('throttle_close', 2) == 2 ? true : null); break; case 3: case 4: foreach ($this->throttle_list[$ip]['fd_list'] as $value) { $server->close($value, Config::get('throttle_close', 2) == 4 ? true : null); } break; default: break; } return; } } } $this->sendToProcess([ 'event' => $event, 'args' => array_map(function ($arg) { return (array)$arg; }, $args), ]); }); } $this->on('Close', function (Server $server, ...$args) { if (Config::get('throttle', false)) { $info = $server->getClientInfo($args[0]->fd, $args[0]->reactor_id, true); if (is_array($info) && isset($info['remote_ip'])) { $ip = $info['remote_ip']; unset($this->throttle_list[$ip]['fd_list'][$args[0]->fd]); } } $this->sendToProcess([ 'event' => 'Close', 'args' => array_map(function ($arg) { return (array)$arg; }, $args), ]); }); $this->on('WorkerExit', function (Server $server, ...$args) { foreach ($this->throttle_list as $value) { Timer::clear($value['timer']); } });
php
Apache-2.0
f7a5b731d86f62c9040056f08a3a513fd3f90e28
2026-01-05T04:57:25.551053Z
false
promatik/PHP-JS-CSS-Minifier
https://github.com/promatik/PHP-JS-CSS-Minifier/blob/d36df2bba166201fa683ea9c9880f9482b814107/minifier.php
minifier.php
<?php /* * JS and CSS Minifier * version: 1.0 (2013-08-26) * * This document is licensed as free software under the terms of the * MIT License: http://www.opensource.org/licenses/mit-license.php * * António Almeida wrote this plugin, which proclaims: * "NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK." * * This plugin uses online webservices from javascript-minifier.com and cssminifier.com * This services are property of Andy Chilton, http://chilts.org/ * * Copyrighted 2013 by António Almeida, promatik. */ function minifyJS($arr) { minify($arr, 'https://www.toptal.com/developers/javascript-minifier/raw'); } function minifyCSS($arr) { minify($arr, 'https://cssminifier.com/raw'); } function minify($arr, $url) { foreach ($arr as $key => $value) { $handler = fopen($value, 'w') or die("File <a href='".$value."'>".$value.'</a> error!<br />'); fwrite($handler, getMinified($url, file_get_contents($key))); fclose($handler); echo "File <a href='".$value."'>".$value.'</a> done!<br />'; } } function getMinified($url, $content) { $postdata = ['http' => [ 'method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => http_build_query(['input' => $content]), ]]; return file_get_contents($url, false, stream_context_create($postdata)); }
php
MIT
d36df2bba166201fa683ea9c9880f9482b814107
2026-01-05T04:57:28.443393Z
false
promatik/PHP-JS-CSS-Minifier
https://github.com/promatik/PHP-JS-CSS-Minifier/blob/d36df2bba166201fa683ea9c9880f9482b814107/minify.php
minify.php
<body style="font-family: monospace;"> <?php include_once 'minifier.php'; /** * FILES ARRAYs * Keys as input, Values as output. */ $js = [ 'js/main.js' => 'js/main.min.js', // ... ]; $css = [ 'css/main.css' => 'css/main.min.css', // ... ]; minifyJS($js); minifyCSS($css); ?> </body>
php
MIT
d36df2bba166201fa683ea9c9880f9482b814107
2026-01-05T04:57:28.443393Z
false
madnest/madzipper
https://github.com/madnest/madzipper/blob/527c35105820a0b4c8cfdadd3f475b26d62d9ac2/src/Madnest/Madzipper/Madzipper.php
src/Madnest/Madzipper/Madzipper.php
<?php namespace Madnest\Madzipper; use Exception; use Illuminate\Filesystem\Filesystem; use Illuminate\Support\Str; use Madnest\Madzipper\Repositories\RepositoryInterface; /** * This Madzipper class is a wrapper around the ZipArchive methods with some handy functions. * * Class Madzipper */ class Madzipper { /** * Constant for extracting. */ const WHITELIST = 1; /** * Constant for extracting. */ const BLACKLIST = 2; /** * Constant for matching only strictly equal file names. */ const EXACT_MATCH = 4; /** * @var string Represents the current location in the archive */ private string $currentFolder = ''; /** * @var Filesystem Handler to the file system */ private Filesystem $file; /** * @var RepositoryInterface Handler to the archive */ private ?RepositoryInterface $repository = null; /** * @var string The path to the current zip file */ private string $filePath; /** * Constructor. */ public function __construct(?Filesystem $fs = null) { $this->file = $fs ? $fs : new Filesystem; } /** * Destructor. * * @return void */ public function __destruct() { if (is_object($this->repository) && $this->repository->isOpen()) { try { $this->repository->close(); } catch (\ValueError $er) { // seemingly the repository was still unitialized (or already closed?) } } } /** * Create a new zip Archive if the file does not exists * opens a zip archive if the file exists. * * @param string $pathToFile The file to open * @param RepositoryInterface|string $type The type of the archive, defaults to zip, possible are zip, phar * * @throws \RuntimeException * @throws \Exception * @throws \InvalidArgumentException */ public function make(string $pathToFile, RepositoryInterface|string $type = 'zip'): self { $new = $this->createArchiveFile($pathToFile); $objectOrName = $type; if (is_string($type)) { $objectOrName = 'Madnest\Madzipper\Repositories\\'.ucwords($type).'Repository'; } if (! is_subclass_of($objectOrName, 'Madnest\Madzipper\Repositories\RepositoryInterface')) { throw new \InvalidArgumentException("Class for '{$objectOrName}' must implement RepositoryInterface interface"); } try { if (is_string($objectOrName)) { $this->repository = new $objectOrName($pathToFile, $new); } else { $this->repository = $type; } } catch (Exception $e) { throw $e; } $this->filePath = $pathToFile; return $this; } /** * Create a new zip archive or open an existing one. * * @throws \Exception */ public function zip(string $pathToFile): self { $this->make($pathToFile); return $this; } /** * Create a new phar file or open one. * * @throws \Exception */ public function phar(string $pathToFile): self { $this->make($pathToFile, 'phar'); return $this; } /** * Create a new rar file or open one. * * @throws \Exception */ public function rar(string $pathToFile): self { $this->make($pathToFile, 'rar'); return $this; } /** * Extracts the opened zip archive to the specified location <br/> * you can provide an array of files and folders and define if they should be a white list * or a black list to extract. By default this method compares file names using "string starts with" logic. * * @param $path string The path to extract to * @param array $files An array of files * @param int $methodFlags The Method the files should be treated * * @throws \Exception */ public function extractTo(string $path, array $files = [], $methodFlags = self::BLACKLIST): void { if (! $this->file->exists($path) && ! $this->file->makeDirectory($path, 0755, true)) { throw new \RuntimeException('Failed to create folder'); } if ($methodFlags & self::EXACT_MATCH) { $matchingMethod = function ($haystack) use ($files) { return in_array($haystack, $files, true); }; } else { $matchingMethod = function ($haystack) use ($files) { return Str::startsWith($haystack, $files); }; } if ($methodFlags & self::WHITELIST) { $this->extractFilesInternal($path, $matchingMethod); } else { // blacklist - extract files that do not match with $matchingMethod $this->extractFilesInternal($path, function ($filename) use ($matchingMethod) { return ! $matchingMethod($filename); }); } } /** * Extracts matching files/folders from the opened zip archive to the specified location. * * @param string $extractToPath The path to extract to * @param string $regex regular expression used to match files. See @link http://php.net/manual/en/reference.pcre.pattern.syntax.php * * @throws \InvalidArgumentException * @throws \RuntimeException */ public function extractMatchingRegex(string $extractToPath, string $regex): void { if (empty($regex)) { throw new \InvalidArgumentException('Missing pass valid regex parameter'); } $this->extractFilesInternal($extractToPath, function ($filename) use ($regex) { $match = preg_match($regex, $filename); if ($match === 1) { return true; } elseif ($match === false) { // invalid pattern for preg_match raises E_WARNING and returns FALSE // so if you have custom error_handler set to catch and throw E_WARNINGs you never end up here // but if you have not - this will throw exception throw new \RuntimeException("regular expression match on '{$filename}' failed with error. Please check if pattern is valid regular expression."); } return false; }); } /** * Gets the content of a single file if available. * * @param $filePath string The full path (including all folders) of the file in the zip * @return mixed returns the content or throws an exception * * @throws \Exception */ public function getFileContent($filePath) { if ($this->repository->fileExists($filePath) === false) { throw new Exception(sprintf('The file "%s" cannot be found', $filePath)); } return $this->repository->getFileContent($filePath); } /** * Add one or multiple files to the zip. * * @param $pathToAdd array|string An array or string of files and folders to add * @param null|mixed $fileName */ public function add(string|array $pathToAdd, ?string $fileName = null): Madzipper { if (is_array($pathToAdd)) { foreach ($pathToAdd as $key => $dir) { if (! is_int($key)) { $this->add($dir, $key); } else { $this->add($dir); } } } elseif ($this->file->isFile($pathToAdd)) { if ($fileName) { $this->addFile($pathToAdd, $fileName); } else { $this->addFile($pathToAdd); } } else { $this->addDir($pathToAdd); } return $this; } /** * Add an empty directory. */ public function addEmptyDir(string $dirName): Madzipper { $this->repository->addEmptyDir($dirName); return $this; } /** * Add a file to the zip using its contents. * * @param $filename string The name of the file to create * @param $content string The file contents * @return $this Madzipper instance */ public function addString(string $filename, string $content): Madzipper { $this->addFromString($filename, $content); return $this; } /** * Gets the status of the zip. * * @return int The status of the internal zip file */ public function getStatus(): string { return $this->repository->getStatus(); } /** * Remove a file or array of files and folders from the zip archive. * * @param $fileToRemove array|string The path/array to the files in the zip * @return $this Madzipper instance */ public function remove(string|array $fileToRemove): Madzipper { if (is_array($fileToRemove)) { $self = $this; $this->repository->each(function ($file) use ($fileToRemove, $self) { if (Str::startsWith($file, $fileToRemove)) { $self->getRepository()->removeFile($file); } }); } else { $this->repository->removeFile($fileToRemove); } return $this; } /** * Returns the path of the current zip file if there is one. * * @return string The path to the file */ public function getFilePath(): string { return $this->filePath; } /** * Sets the password to be used for decompressing. */ public function usePassword(string $password): bool { return $this->repository->usePassword($password); } /** * Closes the zip file and frees all handles. */ public function close(): void { if ($this->repository !== null) { $this->repository->close(); } $this->filePath = ''; } /** * Sets the internal folder to the given path.<br/> * Useful for extracting only a segment of a zip file. */ public function folder(string $path): self { $this->currentFolder = $path; return $this; } /** * Resets the internal folder to the root of the zip file. */ public function home(): self { $this->currentFolder = ''; return $this; } /** * Deletes the archive file. */ public function delete(): void { if ($this->repository !== null) { $this->repository->close(); } $this->file->delete($this->filePath); $this->filePath = ''; } /** * Get the type of the Archive. */ public function getArchiveType(): string { return get_class($this->repository); } /** * Get the current internal folder pointer. */ public function getCurrentFolderPath(): string { return $this->currentFolder; } /** * Checks if a file is present in the archive. */ public function contains(string $fileInArchive): bool { return $this->repository->fileExists($fileInArchive); } public function getRepository(): RepositoryInterface { return $this->repository; } public function getFileHandler(): Filesystem { return $this->file; } /** * Gets the path to the internal folder. */ public function getInternalPath(): string { return empty($this->currentFolder) ? '' : $this->currentFolder.'/'; } /** * List all files that are within the archive. * * @param string|null $regexFilter regular expression to filter returned files/folders. See @link http://php.net/manual/en/reference.pcre.pattern.syntax.php * * @throws \RuntimeException */ public function listFiles(?string $regexFilter = null): array { $filesList = []; if ($regexFilter) { $filter = function ($file) use (&$filesList, $regexFilter) { // push/pop an error handler here to to make sure no error/exception thrown if $expected is not a regex set_error_handler(function () {}); $match = preg_match($regexFilter, $file); restore_error_handler(); if ($match === 1) { $filesList[] = $file; } elseif ($match === false) { throw new \RuntimeException("Regular expression match on '{$file}' failed with error. Please check if pattern is valid regular expression."); } }; } else { $filter = function ($file) use (&$filesList) { $filesList[] = $file; }; } $this->repository->each($filter); return $filesList; } /** * Get the current folder with trailing slash. */ private function getCurrentFolderWithTrailingSlash(): string { if (empty($this->currentFolder)) { return ''; } $lastChar = mb_substr($this->currentFolder, -1); if ($lastChar !== '/' || $lastChar !== '\\') { return $this->currentFolder.'/'; } return $this->currentFolder; } /** * Create archive file. * * @throws \Exception */ private function createArchiveFile(string $pathToZip): bool { if (! $this->file->exists($pathToZip)) { $dirname = dirname($pathToZip); if (! $this->file->exists($dirname) && ! $this->file->makeDirectory($dirname, 0755, true)) { throw new \RuntimeException('Failed to create folder'); } elseif (! $this->file->isWritable($dirname)) { throw new Exception(sprintf('The path "%s" is not writeable', $pathToZip)); } return true; } return false; } /** * Add a directory. */ private function addDir(string $pathToDir): void { // First go over the files in this directory and add them to the repository. foreach ($this->file->files($pathToDir) as $file) { $this->addFile($pathToDir.'/'.basename($file)); } // Now let's visit the subdirectories and add them, too. foreach ($this->file->directories($pathToDir) as $dir) { $old_folder = $this->currentFolder; $this->currentFolder = empty($this->currentFolder) ? basename($dir) : $this->currentFolder.'/'.basename($dir); $this->addDir($pathToDir.'/'.basename($dir)); $this->currentFolder = $old_folder; } } /** * Add the file to the zip. */ private function addFile(string $pathToAdd, ?string $fileName = null): void { if (! $fileName) { $info = pathinfo($pathToAdd); $fileName = isset($info['extension']) ? $info['filename'].'.'.$info['extension'] : $info['filename']; } $this->repository->addFile($pathToAdd, $this->getInternalPath().$fileName); } /** * Add the file to the zip from content. */ private function addFromString(string $filename, string $content): void { $this->repository->addFromString($this->getInternalPath().$filename, $content); } /** * Extracts files from the archive. * * @param string $path The path to extract to * @param callable $matchingMethod The method to match files */ private function extractFilesInternal(string $path, callable $matchingMethod): void { $self = $this; $this->repository->each(function ($file) use ($path, $matchingMethod, $self) { $currentPath = $self->getCurrentFolderWithTrailingSlash(); if (! empty($currentPath) && ! Str::startsWith($file, $currentPath)) { return; } $filename = str_replace($self->getInternalPath(), '', $file); if ($matchingMethod($filename)) { $self->extractOneFileInternal($file, $path); } }); } /** * Extract single file from the archive. * * @throws \RuntimeException */ private function extractOneFileInternal(string $file, string $path): void { $tmpPath = str_replace($this->getInternalPath(), '', $file); // Prevent Zip traversal attacks if (strpos($file, '../') !== false || strpos($file, '..\\') !== false) { throw new \RuntimeException('Special characters found within filenames'); } // We need to create the directory first in case it doesn't exist $dir = pathinfo($path.DIRECTORY_SEPARATOR.$tmpPath, PATHINFO_DIRNAME); if (! $this->file->exists($dir) && ! $this->file->makeDirectory($dir, 0755, true, true)) { throw new \RuntimeException('Failed to create folders'); } $toPath = $path.DIRECTORY_SEPARATOR.$tmpPath; $fileStream = $this->getRepository()->getFileStream($file); $this->getFileHandler()->put($toPath, $fileStream); } }
php
MIT
527c35105820a0b4c8cfdadd3f475b26d62d9ac2
2026-01-05T04:57:38.930252Z
false
madnest/madzipper
https://github.com/madnest/madzipper/blob/527c35105820a0b4c8cfdadd3f475b26d62d9ac2/src/Madnest/Madzipper/MadzipperServiceProvider.php
src/Madnest/Madzipper/MadzipperServiceProvider.php
<?php namespace Madnest\Madzipper; use Illuminate\Foundation\AliasLoader; use Illuminate\Support\ServiceProvider; class MadzipperServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = false; /** * Bootstrap the application events. */ public function boot() {} /** * Register the service provider. */ public function register() { $this->app->singleton('madzipper', function ($app) { $return = $app->make('Madnest\Madzipper\Madzipper'); return $return; }); $this->app->booting(function () { $loader = AliasLoader::getInstance(); $loader->alias('Madzipper', 'Madnest\Madzipper\Facades\Madzipper'); }); } /** * Get the services provided by the provider. * * @return array */ public function provides() { return ['madzipper']; } }
php
MIT
527c35105820a0b4c8cfdadd3f475b26d62d9ac2
2026-01-05T04:57:38.930252Z
false
madnest/madzipper
https://github.com/madnest/madzipper/blob/527c35105820a0b4c8cfdadd3f475b26d62d9ac2/src/Madnest/Madzipper/Facades/Madzipper.php
src/Madnest/Madzipper/Facades/Madzipper.php
<?php namespace Madnest\Madzipper\Facades; use Illuminate\Support\Facades\Facade; class Madzipper extends Facade { protected static function getFacadeAccessor() { return 'madzipper'; } }
php
MIT
527c35105820a0b4c8cfdadd3f475b26d62d9ac2
2026-01-05T04:57:38.930252Z
false
madnest/madzipper
https://github.com/madnest/madzipper/blob/527c35105820a0b4c8cfdadd3f475b26d62d9ac2/src/Madnest/Madzipper/Repositories/ZipRepository.php
src/Madnest/Madzipper/Repositories/ZipRepository.php
<?php namespace Madnest\Madzipper\Repositories; use Exception; use ZipArchive; class ZipRepository implements RepositoryInterface { private ?ZipArchive $archive = null; public bool $open = false; /** * Construct with a given path. * * @throws \Exception */ public function __construct(string $filePath, bool $create = false, mixed $archive = null) { // Check if ZipArchive is available if (! class_exists('ZipArchive')) { throw new Exception('Error: Your PHP version is not compiled with zip support'); } $this->archive = $archive ? $archive : new ZipArchive; $this->open($filePath, $create); } /** * Open the archive. * * @throws Exception */ protected function open(string $filePath, bool $create = false): void { $res = $this->archive->open($filePath, ($create ? ZipArchive::CREATE : 0)); if ($res !== true) { throw new Exception("Error: Failed to open {$filePath}! Error: ".$this->getErrorMessage($res)); } $this->open = true; } /** * Check if the archive is open. */ public function isOpen(): bool { return $this->open ? true : false; } /** * Check if the archive is closed. */ public function isClosed(): bool { return ! $this->open ? true : false; } /** * Add a file to the opened Archive. */ public function addFile(string $pathToFile, string $pathInArchive): void { $this->archive->addFile($pathToFile, $pathInArchive); } /** * Add an empty directory. */ public function addEmptyDir(string $dirName): void { $this->archive->addEmptyDir($dirName); } /** * Add a file to the opened Archive using its contents. */ public function addFromString(string $name, string $content): void { $this->archive->addFromString($name, $content); } /** * Remove a file permanently from the Archive. */ public function removeFile(string $pathInArchive): void { $this->archive->deleteName($pathInArchive); } /** * Get the content of a file. * * @return string */ public function getFileContent(string $pathInArchive): string|false { return $this->archive->getFromName($pathInArchive); } /** * Get the stream of a file. */ public function getFileStream(string $pathInArchive): mixed { return $this->archive->getStream($pathInArchive); } /** * Will loop over every item in the archive and will execute the callback on them * Will provide the filename for every item. */ public function each(callable $callback): void { for ($i = 0; $i < $this->archive->numFiles; $i++) { // skip if folder $stats = $this->archive->statIndex($i); if ($stats['size'] === 0 && $stats['crc'] === 0) { continue; } $callback($this->archive->getNameIndex($i), $this->archive->statIndex($i)); } } /** * Checks whether the file is in the archive. */ public function fileExists(string $fileInArchive): bool { return $this->archive->locateName($fileInArchive) !== false; } /** * Sets the password to be used for decompressing * function named usePassword for clarity. */ public function usePassword(string $password): bool { return $this->archive->setPassword($password); } /** * Returns the status of the archive as a string. */ public function getStatus(): string|false { return $this->archive->getStatusString(); } /** * Closes the archive and saves it. */ public function close(): bool { $this->open = false; return $this->archive->close(); } /** * Get error message. * * @param mixed $resultCode */ private function getErrorMessage(int $resultCode): string { switch ($resultCode) { case ZipArchive::ER_EXISTS: return 'ZipArchive::ER_EXISTS - File already exists.'; case ZipArchive::ER_INCONS: return 'ZipArchive::ER_INCONS - Zip archive inconsistent.'; case ZipArchive::ER_MEMORY: return 'ZipArchive::ER_MEMORY - Malloc failure.'; case ZipArchive::ER_NOENT: return 'ZipArchive::ER_NOENT - No such file.'; case ZipArchive::ER_NOZIP: return 'ZipArchive::ER_NOZIP - Not a zip archive.'; case ZipArchive::ER_OPEN: return 'ZipArchive::ER_OPEN - Can\'t open file.'; case ZipArchive::ER_READ: return 'ZipArchive::ER_READ - Read error.'; case ZipArchive::ER_SEEK: return 'ZipArchive::ER_SEEK - Seek error.'; default: return "An unknown error [{$resultCode}] has occurred."; } } }
php
MIT
527c35105820a0b4c8cfdadd3f475b26d62d9ac2
2026-01-05T04:57:38.930252Z
false
madnest/madzipper
https://github.com/madnest/madzipper/blob/527c35105820a0b4c8cfdadd3f475b26d62d9ac2/src/Madnest/Madzipper/Repositories/RepositoryInterface.php
src/Madnest/Madzipper/Repositories/RepositoryInterface.php
<?php namespace Madnest\Madzipper\Repositories; /** * RepositoryInterface that needs to be implemented by every Repository. * * Class RepositoryInterface */ interface RepositoryInterface { /** * Construct with a given path. * * @param bool $new */ public function __construct(string $filePath, bool $create = false, mixed $archive = null); /** * Check if the archive is open. */ public function isOpen(): bool; /** * Check if the archive is closed. */ public function isClosed(): bool; /** * Add a file to the opened Archive. */ public function addFile(string $pathToFile, string $pathInArchive): void; /** * Add a file to the opened Archive using its contents. */ public function addFromString(string $name, string $content): void; /** * Add an empty directory. */ public function addEmptyDir(string $dirName): void; /** * Remove a file permanently from the Archive. */ public function removeFile(string $pathInArchive): void; /** * Get the content of a file. */ public function getFileContent(string $pathInArchive): string|false; /** * Get the stream of a file. */ public function getFileStream(string $pathInArchive): mixed; /** * Will loop over every item in the archive and will execute the callback on them * Will provide the filename for every item. */ public function each(callable $callback): void; /** * Checks whether the file is in the archive. */ public function fileExists(string $fileInArchive): bool; /** * Sets the password to be used for decompressing. */ public function usePassword(string $password): bool; /** * Returns the status of the archive as a string. */ public function getStatus(): string|false; /** * Closes the archive and saves it. */ public function close(): bool; }
php
MIT
527c35105820a0b4c8cfdadd3f475b26d62d9ac2
2026-01-05T04:57:38.930252Z
false
madnest/madzipper
https://github.com/madnest/madzipper/blob/527c35105820a0b4c8cfdadd3f475b26d62d9ac2/tests/TestCase.php
tests/TestCase.php
<?php namespace Madnest\Madzipper\Tests; use Madnest\Madzipper\MadzipperServiceProvider; // use Mockery; use Orchestra\Testbench\TestCase as Orchestra; abstract class TestCase extends Orchestra { protected function setUp(): void { parent::setUp(); // Debug helper // Mockery::setLoader(new Mockery\Loader\RequireLoader(sys_get_temp_dir())); } /** * @param \Illuminate\Foundation\Application $app * @return array */ protected function getPackageProviders($app) { return [ MadzipperServiceProvider::class, ]; } }
php
MIT
527c35105820a0b4c8cfdadd3f475b26d62d9ac2
2026-01-05T04:57:38.930252Z
false
madnest/madzipper
https://github.com/madnest/madzipper/blob/527c35105820a0b4c8cfdadd3f475b26d62d9ac2/tests/ArrayArchive.php
tests/ArrayArchive.php
<?php namespace Madnest\Madzipper\Tests; use Madnest\Madzipper\Repositories\RepositoryInterface; class ArrayArchive implements RepositoryInterface { private $entries = []; /** * Construct with a given path. * * @param bool $new */ public function __construct($filePath, $new = false, $archiveImplementation = null) {} /** * Check if the archive is open. */ public function isOpen(): bool { return true; } /** * Check if the archive is closed. */ public function isClosed(): bool { return false; } /** * Add a file to the opened Archive. */ public function addFile(string $pathToFile, string $pathInArchive): void { $this->entries[$pathInArchive] = $pathInArchive; } /** * Add a file to the opened Archive using its contents. */ public function addFromString(string $name, string $content): void { $this->entries[$name] = $name; } /** * Remove a file permanently from the Archive. */ public function removeFile(string $pathInArchive): void { unset($this->entries[$pathInArchive]); } /** * Get the content of a file. */ public function getFileContent(string $pathInArchive): string|false { return $this->entries[$pathInArchive]; } /** * Get the stream of a file. */ public function getFileStream(string $pathInArchive): mixed { return $this->entries[$pathInArchive]; } /** * Will loop over every item in the archive and will execute the callback on them * Will provide the filename for every item. */ public function each(callable $callback): void { foreach ($this->entries as $entry) { call_user_func_array($callback, [ 'file' => $entry, ]); } } /** * Checks whether the file is in the archive. */ public function fileExists(string $fileInArchive): bool { return array_key_exists($fileInArchive, $this->entries); } /** * Returns the status of the archive as a string. */ public function getStatus(): string { return 'OK'; } /** * Closes the archive and saves it. */ public function close(): bool { return true; } /** * Add an empty directory. */ public function addEmptyDir(string $dirName): void { // CODE... } /** * Sets the password to be used for decompressing. */ public function usePassword(string $password): bool { // CODE... } }
php
MIT
527c35105820a0b4c8cfdadd3f475b26d62d9ac2
2026-01-05T04:57:38.930252Z
false
madnest/madzipper
https://github.com/madnest/madzipper/blob/527c35105820a0b4c8cfdadd3f475b26d62d9ac2/tests/MadzipperTest.php
tests/MadzipperTest.php
<?php namespace Madnest\Madzipper\Tests; use Exception; use Illuminate\Filesystem\Filesystem; use InvalidArgumentException; use Madnest\Madzipper\Madzipper; use Mockery; use RuntimeException; class MadzipperTest extends TestCase { /** * @var \Madnest\Madzipper\Madzipper */ public $archive; /** * @var \Mockery\Mock */ public $file; protected function setUp(): void { $this->file = Mockery::mock(new Filesystem); $this->archive = new Madzipper($this->file); $this->archive->make('foo', new \Madnest\Madzipper\Tests\ArrayArchive('foo', true)); parent::setUp(); } protected function tearDown(): void { Mockery::close(); } /** @test */ public function an_archive_can_be_made(): void { $this->assertSame(\Madnest\Madzipper\Tests\ArrayArchive::class, $this->archive->getArchiveType()); $this->assertSame('foo', $this->archive->getFilePath()); } /** @test */ public function is_throws_an_exception_when_directory_could_not_be_created(): void { $path = getcwd().time(); $this->file->shouldReceive('makeDirectory') ->with($path, 0755, true) ->andReturn(false); $zip = new Madzipper($this->file); $this->expectException(RuntimeException::class); $this->expectExceptionMessage('Failed to create folder'); $zip->make($path.DIRECTORY_SEPARATOR.'createMe.zip'); } /** @test */ public function files_can_be_added_and_received(): void { $this->file->shouldReceive('isFile')->with('foo.bar') ->times(1)->andReturn(true); $this->file->shouldReceive('isFile')->with('foo') ->times(1)->andReturn(true); $this->archive->add('foo.bar'); $this->archive->add('foo'); $this->assertSame('foo', $this->archive->getFileContent('foo')); $this->assertSame('foo.bar', $this->archive->getFileContent('foo.bar')); } /** @test */ public function files_can_be_added_and_received_as_array(): void { $this->file->shouldReceive('isFile')->with('foo.bar') ->times(1)->andReturn(true); $this->file->shouldReceive('isFile')->with('foo') ->times(1)->andReturn(true); /**Array**/ $this->archive->add([ 'foo.bar', 'foo', ]); $this->assertSame('foo', $this->archive->getFileContent('foo')); $this->assertSame('foo.bar', $this->archive->getFileContent('foo.bar')); } /** @test */ public function files_can_be_added_and_received_as_custom_filename_array(): void { $this->file->shouldReceive('isFile')->with('foo.bar') ->times(1)->andReturn(true); $this->file->shouldReceive('isFile')->with('foo') ->times(1)->andReturn(true); /**Array**/ $this->archive->add([ 'custom.bar' => 'foo.bar', 'custom' => 'foo', ]); $this->assertSame('custom', $this->archive->getFileContent('custom')); $this->assertSame('custom.bar', $this->archive->getFileContent('custom.bar')); } /** @test */ public function files_can_be_added_and_received_with_sub_folder(): void { /* * Add the local folder /path/to/fooDir as folder fooDir to the repository * and make sure the folder structure within the repository is there. */ $this->file->shouldReceive('isFile')->with('/path/to/fooDir') ->once()->andReturn(false); $this->file->shouldReceive('files')->with('/path/to/fooDir') ->once()->andReturn(['fileInFooDir.bar', 'fileInFooDir.foo']); $this->file->shouldReceive('directories')->with('/path/to/fooDir') ->once()->andReturn(['fooSubdir']); $this->file->shouldReceive('files')->with('/path/to/fooDir/fooSubdir') ->once()->andReturn(['fileInFooDir.bar']); $this->file->shouldReceive('directories')->with('/path/to/fooDir/fooSubdir') ->once()->andReturn([]); $this->archive->folder('fooDir') ->add('/path/to/fooDir'); $this->assertSame('fooDir/fileInFooDir.bar', $this->archive->getFileContent('fooDir/fileInFooDir.bar')); $this->assertSame('fooDir/fileInFooDir.foo', $this->archive->getFileContent('fooDir/fileInFooDir.foo')); $this->assertSame('fooDir/fooSubdir/fileInFooDir.bar', $this->archive->getFileContent('fooDir/fooSubdir/fileInFooDir.bar')); } /** @test */ public function exception_is_thrown_when_accessing_content_that_does_not_exist(): void { $this->expectException(Exception::class); $this->expectExceptionMessage('The file "baz" cannot be found'); $this->archive->getFileContent('baz'); } /** @test */ public function files_can_be_removed(): void { $this->file->shouldReceive('isFile')->with('foo') ->andReturn(true); $this->archive->add('foo'); $this->assertTrue($this->archive->contains('foo')); $this->archive->remove('foo'); $this->assertFalse($this->archive->contains('foo')); // ---- $this->file->shouldReceive('isFile')->with('foo') ->andReturn(true); $this->file->shouldReceive('isFile')->with('fooBar') ->andReturn(true); $this->archive->add(['foo', 'fooBar']); $this->assertTrue($this->archive->contains('foo')); $this->assertTrue($this->archive->contains('fooBar')); $this->archive->remove(['foo', 'fooBar']); $this->assertFalse($this->archive->contains('foo')); $this->assertFalse($this->archive->contains('fooBar')); } /** * @test * * @doesNotPerformAssertions * */ public function it_extracts_whitelisted(): void { $this->file ->shouldReceive('isFile') ->with('foo') ->andReturn(true); $this->file ->shouldReceive('isFile') ->with('foo.log') ->andReturn(true); $this->archive ->add('foo') ->add('foo.log'); $this->file ->shouldReceive('put') ->with(realpath('').DIRECTORY_SEPARATOR.'foo', 'foo'); $this->file ->shouldReceive('put') ->with(realpath('').DIRECTORY_SEPARATOR.'foo.log', 'foo.log'); $this->archive ->extractTo(getcwd(), ['foo'], Madzipper::WHITELIST); } /** @test */ public function extracting_throws_exception_when_it_could_not_create_directory(): void { $path = getcwd().time(); $this->file ->shouldReceive('isFile') ->with('foo.log') ->andReturn(true); $this->file->shouldReceive('makeDirectory') ->with($path, 0755, true) ->andReturn(false); $this->archive->add('foo.log'); $this->file->shouldNotReceive('put') ->with(realpath('').DIRECTORY_SEPARATOR.'foo.log', 'foo.log'); $this->expectException(RuntimeException::class); $this->expectExceptionMessage('Failed to create folder'); $this->archive ->extractTo($path, ['foo'], Madzipper::WHITELIST); } /** * @test * * @doesNotPerformAssertions * */ public function it_extracts_whitelisted_from_sub_directory(): void { $this->file->shouldReceive('isFile')->andReturn(true); $this->file->shouldReceive('makeDirectory')->andReturn(true); $this->archive ->folder('foo/bar') ->add('baz') ->add('baz.log'); $this->file ->shouldReceive('put') ->with(realpath('').DIRECTORY_SEPARATOR.'baz', 'foo/bar/baz'); $this->file ->shouldReceive('put') ->with(realpath('').DIRECTORY_SEPARATOR.'baz.log', 'foo/bar/baz.log'); $this->archive ->extractTo(getcwd(), ['baz'], Madzipper::WHITELIST); } /** * @test * * @doesNotPerformAssertions * */ public function it_extracts_whitelist_with_exact_matching(): void { $this->file->shouldReceive('isFile')->andReturn(true); $this->file->shouldReceive('makeDirectory')->andReturn(true); $this->archive ->folder('foo/bar') ->add('baz') ->add('baz.log'); $this->file ->shouldReceive('put') ->with(realpath('').DIRECTORY_SEPARATOR.'baz', 'foo/bar/baz'); $this->archive ->extractTo(getcwd(), ['baz'], Madzipper::WHITELIST | Madzipper::EXACT_MATCH); } /** * @test * * @doesNotPerformAssertions * */ public function it_extracts_whitelist_with_exact_matching_from_sub_directory(): void { $this->file->shouldReceive('isFile')->andReturn(true); $this->file->shouldReceive('exists')->andReturn(false); $this->file->shouldReceive('makeDirectory')->andReturn(true); $this->archive->folder('foo/bar/subDirectory') ->add('bazInSubDirectory') ->add('bazInSubDirectory.log'); $this->archive->folder('foo/bar') ->add('baz') ->add('baz.log'); $subDirectoryPath = realpath('').DIRECTORY_SEPARATOR.'subDirectory'; $subDirectoryFilePath = $subDirectoryPath.'/bazInSubDirectory'; $this->file->shouldReceive('put') ->with($subDirectoryFilePath, 'foo/bar/subDirectory/bazInSubDirectory'); $this->archive ->extractTo(getcwd(), ['subDirectory/bazInSubDirectory'], Madzipper::WHITELIST | Madzipper::EXACT_MATCH); $this->file->shouldHaveReceived('makeDirectory')->with($subDirectoryPath, 0755, true, true); } /** * @test * * @doesNotPerformAssertions * */ public function when_it_extracts_it_ignores_black_listed_files(): void { $this->file->shouldReceive('isFile')->with('foo')->andReturn(true); $this->file->shouldReceive('isFile')->with('bar')->andReturn(true); $this->file->shouldReceive('makeDirectory')->andReturn(true); $this->archive->add('foo')->add('bar'); $this->file->shouldReceive('put')->with(realpath('').DIRECTORY_SEPARATOR.'foo', 'foo'); $this->file->shouldNotReceive('put')->with(realpath('').DIRECTORY_SEPARATOR.'bar', 'bar'); $this->archive->extractTo(getcwd(), ['bar'], Madzipper::BLACKLIST); } /** * @test * * @doesNotPerformAssertions * */ public function when_it_extracts_it_ignores_black_listed_files_from_sub_directory(): void { $currentDir = getcwd(); $this->file->shouldReceive('isFile')->andReturn(true); $this->file->shouldReceive('makeDirectory')->andReturn(true); $this->archive->add('rootLevelFile'); $this->archive->folder('foo/bar/sub') ->add('fileInSubSubDir'); $this->archive->folder('foo/bar') ->add('fileInSubDir') ->add('fileBlackListedInSubDir'); $this->file->shouldReceive('put')->with($currentDir.DIRECTORY_SEPARATOR.'fileInSubDir', 'foo/bar/fileInSubDir'); $this->file->shouldReceive('put')->with($currentDir.DIRECTORY_SEPARATOR.'sub/fileInSubSubDir', 'foo/bar/sub/fileInSubSubDir'); $this->file->shouldNotReceive('put')->with($currentDir.DIRECTORY_SEPARATOR.'fileBlackListedInSubDir', 'fileBlackListedInSubDir'); $this->file->shouldNotReceive('put')->with($currentDir.DIRECTORY_SEPARATOR.'rootLevelFile', 'rootLevelFile'); $this->archive->extractTo($currentDir, ['fileBlackListedInSubDir'], Madzipper::BLACKLIST); } /** * @test * * @doesNotPerformAssertions * */ public function when_it_extracts_it_ignores_black_listed_files_from_sub_directory_with_exact_matching(): void { $this->file->shouldReceive('isFile')->with('baz') ->andReturn(true); $this->file->shouldReceive('makeDirectory')->andReturn(true); $this->file->shouldReceive('isFile')->with('baz.log') ->andReturn(true); $this->archive->folder('foo/bar') ->add('baz') ->add('baz.log'); $this->file->shouldReceive('put')->with(realpath('').DIRECTORY_SEPARATOR.'baz.log', 'foo/bar/baz.log'); $this->archive->extractTo(getcwd(), ['baz'], Madzipper::BLACKLIST | Madzipper::EXACT_MATCH); } /** * @test * * @doesNotPerformAssertions * */ public function is_extracts_matching_regex_from_sub_folder(): void { $this->file->shouldReceive('isFile')->with('baz')->andReturn(true); $this->file->shouldReceive('isFile')->with('baz.log')->andReturn(true); $this->file->shouldReceive('isFile')->with('subFolderFileToIgnore')->andReturn(true); $this->file->shouldReceive('isFile')->with('subFolderFileToExtract.log')->andReturn(true); $this->file->shouldReceive('isFile')->with('rootLevelMustBeIgnored.log')->andReturn(true); $this->file->shouldReceive('makeDirectory')->andReturn(true); $this->archive->add('rootLevelMustBeIgnored.log'); $this->archive->folder('foo/bar/subFolder') ->add('subFolderFileToIgnore') ->add('subFolderFileToExtract.log'); $this->archive->folder('foo/bar') ->add('baz') ->add('baz.log'); $this->file->shouldReceive('put')->with(realpath('').DIRECTORY_SEPARATOR.'baz.log', 'foo/bar/baz.log'); $this->file->shouldReceive('put')->with(realpath('').DIRECTORY_SEPARATOR.'subFolder/subFolderFileToExtract.log', 'foo/bar/subFolder/subFolderFileToExtract.log'); $this->file->shouldNotReceive('put')->with(realpath('').DIRECTORY_SEPARATOR.'rootLevelMustBeIgnored.log', 'rootLevelMustBeIgnored.log'); $this->file->shouldNotReceive('put')->with(realpath('').DIRECTORY_SEPARATOR.'baz', 'foo/bar/baz'); $this->file->shouldNotReceive('put')->with(realpath('').DIRECTORY_SEPARATOR.'subFolder/subFolderFileToIgnore', 'foo/bar/subFolder/subFolderFileToIgnore'); $this->archive->extractMatchingRegex(getcwd(), '/\.log$/i'); } /** @test */ public function it_throws_an_exception_when_extracting_matching_regex_when_regex_is_empty(): void { $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Missing pass valid regex parameter'); $this->archive->extractMatchingRegex(getcwd(), ''); } /** @test */ public function is_can_add_files_to_folders_and_to_home(): void { $this->archive->folder('foo/bar'); $this->assertSame('foo/bar', $this->archive->getCurrentFolderPath()); // ---- $this->file->shouldReceive('isFile')->with('foo')->andReturn(true); $this->archive->add('foo'); $this->assertSame('foo/bar/foo', $this->archive->getFileContent('foo/bar/foo')); // ---- $this->file->shouldReceive('isFile')->with('bar')->andReturn(true); $this->archive->home()->add('bar'); $this->assertSame('bar', $this->archive->getFileContent('bar')); // ---- $this->file->shouldReceive('isFile')->with('baz/bar/bing')->andReturn(true); $this->archive->folder('test')->add('baz/bar/bing'); $this->assertSame('test/bing', $this->archive->getFileContent('test/bing')); } /** @test */ public function is_can_list_files(): void { // testing empty file $this->file->shouldReceive('isFile')->with('foo.file')->andReturn(true); $this->file->shouldReceive('isFile')->with('bar.file')->andReturn(true); $this->assertSame([], $this->archive->listFiles()); // testing not empty file $this->archive->add('foo.file'); $this->archive->add('bar.file'); $this->assertSame(['foo.file', 'bar.file'], $this->archive->listFiles()); // testing with a empty sub dir $this->file->shouldReceive('isFile')->with('/path/to/subDirEmpty')->andReturn(false); $this->file->shouldReceive('files')->with('/path/to/subDirEmpty')->andReturn([]); $this->file->shouldReceive('directories')->with('/path/to/subDirEmpty')->andReturn([]); $this->archive->folder('subDirEmpty')->add('/path/to/subDirEmpty'); $this->assertSame(['foo.file', 'bar.file'], $this->archive->listFiles()); // testing with a not empty sub dir $this->file->shouldReceive('isFile')->with('/path/to/subDir')->andReturn(false); $this->file->shouldReceive('isFile')->with('sub.file')->andReturn(true); $this->file->shouldReceive('files')->with('/path/to/subDir')->andReturn(['sub.file']); $this->file->shouldReceive('directories')->with('/path/to/subDir')->andReturn([]); $this->archive->folder('subDir')->add('/path/to/subDir'); $this->assertSame(['foo.file', 'bar.file', 'subDir/sub.file'], $this->archive->listFiles()); } /** @test */ public function is_can_list_files_with_regex_filter(): void { // add 2 files to root level in zip $this->file->shouldReceive('isFile')->with('foo.file')->andReturn(true); $this->file->shouldReceive('isFile')->with('bar.log')->andReturn(true); $this->archive ->add('foo.file') ->add('bar.log'); // add sub directory with 2 files inside $this->file->shouldReceive('isFile')->with('/path/to/subDir')->andReturn(false); $this->file->shouldReceive('isFile')->with('sub.file')->andReturn(true); $this->file->shouldReceive('isFile')->with('anotherSub.log')->andReturn(true); $this->file->shouldReceive('files')->with('/path/to/subDir')->andReturn(['sub.file', 'anotherSub.log']); $this->file->shouldReceive('directories')->with('/path/to/subDir')->andReturn([]); $this->archive->folder('subDir')->add('/path/to/subDir'); $this->assertSame( ['foo.file', 'subDir/sub.file'], $this->archive->listFiles('/\.file$/i') // filter out files ending with ".file" pattern ); } /** @test */ public function it_throws_an_exception_when_trying_to_list_files_with_invalid_regex_filter(): void { $this->file->shouldReceive('isFile')->with('foo.file')->andReturn(true); $this->archive->add('foo.file'); $this->expectException(RuntimeException::class); $this->expectExceptionMessage('Regular expression match on \'foo.file\' failed with error. Please check if pattern is valid regular expression.'); $invalidPattern = 'asdasd'; $this->archive->listFiles($invalidPattern); } }
php
MIT
527c35105820a0b4c8cfdadd3f475b26d62d9ac2
2026-01-05T04:57:38.930252Z
false
madnest/madzipper
https://github.com/madnest/madzipper/blob/527c35105820a0b4c8cfdadd3f475b26d62d9ac2/tests/Repositories/ZipRepositoryTest.php
tests/Repositories/ZipRepositoryTest.php
<?php namespace Madnest\Madzipper\Tests\Repositories; use Exception; use Madnest\Madzipper\Repositories\ZipRepository; use Madnest\Madzipper\Tests\TestCase; use Mockery; use ZipArchive; class ZipRepositoryTest extends TestCase { /** * @var ZipRepository */ public $zip; /** * @var \Mockery\Mock */ public $mock; protected function setUp(): void { $this->mock = Mockery::mock(new ZipArchive); $this->zip = new ZipRepository('foo', true, $this->mock); parent::setUp(); } protected function tearDown(): void { Mockery::close(); } /** @test */ public function a_zip_repository_can_be_made() { $zip = new ZipRepository('foo.zip', true); $this->assertFalse($zip->fileExists('foo')); } /** @test */ public function it_throws_an_exception_when_trying_to_open_non_existing_zip() { $this->expectException(Exception::class); $this->expectExceptionMessage('Error: Failed to open idonotexist.zip! Error: ZipArchive::ER_'); new ZipRepository('idonotexist.zip', false); } /** @test */ public function it_throws_an_exception_when_trying_to_open_something_else_than_a_zip() { $this->expectException(Exception::class); $this->expectExceptionMessageMatches('/Error: Failed to open (.*)ZipRepositoryTest.php! Error: ZipArchive::ER_NOZIP - Not a zip archive./'); new ZipRepository(__DIR__.DIRECTORY_SEPARATOR.'ZipRepositoryTest.php', false); } /** * @test * * @doesNotPerformAssertions * */ public function it_can_add_files() { $this->mock->shouldReceive('addFile')->once()->with('bar', 'bar'); $this->mock->shouldReceive('addFile')->once()->with('bar', 'foo/bar'); $this->mock->shouldReceive('addFile')->once()->with('foo/bar', 'bar'); $this->zip->addFile('bar', 'bar'); $this->zip->addFile('bar', 'foo/bar'); $this->zip->addFile('foo/bar', 'bar'); } /** * @test * * @doesNotPerformAssertions * */ public function it_can_remove_files() { $this->mock->shouldReceive('deleteName')->once()->with('bar'); $this->mock->shouldReceive('deleteName')->once()->with('foo/bar'); $this->zip->removeFile('bar'); $this->zip->removeFile('foo/bar'); } /** @test */ public function it_can_get_file_content() { $this->mock->shouldReceive('getFromName')->once() ->with('bar')->andReturn('foo'); $this->mock->shouldReceive('getFromName')->once() ->with('foo/bar')->andReturn('baz'); $this->assertSame('foo', $this->zip->getFileContent('bar')); $this->assertSame('baz', $this->zip->getFileContent('foo/bar')); } /** @test */ public function is_can_get_file_stream() { $this->mock->shouldReceive('getStream')->once() ->with('bar')->andReturn('foo'); $this->mock->shouldReceive('getStream')->once() ->with('foo/bar')->andReturn('baz'); $this->assertSame('foo', $this->zip->getFileStream('bar')); $this->assertSame('baz', $this->zip->getFileStream('foo/bar')); } /** @test */ public function it_can_tell_wether_file_exists() { $this->mock->shouldReceive('locateName')->once() ->with('bar')->andReturn(true); $this->mock->shouldReceive('locateName')->once() ->with('foo/bar')->andReturn(false); $this->assertTrue($this->zip->fileExists('bar')); $this->assertFalse($this->zip->fileExists('foo/bar')); } /** * @test * * @doesNotPerformAssertions * */ public function it_can_close() { $this->zip->close(); } }
php
MIT
527c35105820a0b4c8cfdadd3f475b26d62d9ac2
2026-01-05T04:57:38.930252Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/.php-cs-fixer.dist.php
.php-cs-fixer.dist.php
<?php /** * @noinspection PhpUndefinedClassInspection * @noinspection PhpUndefinedNamespaceInspection * @see https://cs.symfony.com/doc/ruleSets/ * @see https://cs.symfony.com/doc/rules/ */ declare(strict_types=1); return (new PhpCsFixer\Config()) ->setRiskyAllowed(true) ->setCacheFile(__DIR__ . '/build/php-cs-fixer.cache') ->setRules([ '@PSR12' => true, // '@PSR12:risky' => true, // '@PHP71Migration:risky' => true, '@PHP80Migration' => true, '@PHP80Migration:risky' => true, 'declare_strict_types' => false, // defined by PHP74Migration:risky // symfony 'array_indentation' => true, 'class_attributes_separation' => true, 'whitespace_after_comma_in_array' => true, 'no_empty_statement' => true, 'no_extra_blank_lines' => true, 'type_declaration_spaces' => true, 'trailing_comma_in_multiline' => ['after_heredoc' => true, 'elements' => ['arrays', 'match', 'parameters']], 'no_blank_lines_after_phpdoc' => true, 'object_operator_without_whitespace' => true, 'binary_operator_spaces' => true, 'phpdoc_scalar' => true, 'no_trailing_comma_in_singleline' => true, 'single_quote' => true, 'no_singleline_whitespace_before_semicolons' => true, 'no_unused_imports' => true, 'yoda_style' => ['equal' => true, 'identical' => true, 'less_and_greater' => null], 'standardize_not_equals' => true, 'concat_space' => ['spacing' => 'one'], 'linebreak_after_opening_tag' => true, 'fully_qualified_strict_types' => true, // symfony:risky 'no_alias_functions' => true, 'self_accessor' => true, // contrib 'not_operator_with_successor_space' => true, 'ordered_imports' => ['imports_order' => ['class', 'function', 'const']], // @PSR12 sort_algorithm: none ]) ->setFinder( PhpCsFixer\Finder::create() ->in(__DIR__) ->append([__FILE__]) ->exclude(['vendor', 'tools', 'build']), ) ;
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/CfdiValidator33.php
src/CfdiUtils/CfdiValidator33.php
<?php namespace CfdiUtils; use CfdiUtils\CadenaOrigen\XsltBuilderPropertyInterface; use CfdiUtils\Validate\CfdiValidatorTrait; use CfdiUtils\Validate\MultiValidator; use CfdiUtils\Validate\MultiValidatorFactory; use CfdiUtils\XmlResolver\XmlResolverPropertyInterface; class CfdiValidator33 implements XmlResolverPropertyInterface, XsltBuilderPropertyInterface { use CfdiValidatorTrait; protected function createVersionedMultiValidator(): MultiValidator { $factory = new MultiValidatorFactory(); return $factory->newReceived33(); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/CfdiCreator33.php
src/CfdiUtils/CfdiCreator33.php
<?php namespace CfdiUtils; use CfdiUtils\CadenaOrigen\XsltBuilderInterface; use CfdiUtils\CadenaOrigen\XsltBuilderPropertyInterface; use CfdiUtils\Certificado\Certificado; use CfdiUtils\Certificado\CertificadoPropertyInterface; use CfdiUtils\Elements\Cfdi33\Comprobante; use CfdiUtils\Validate\Asserts; use CfdiUtils\Validate\MultiValidatorFactory; use CfdiUtils\XmlResolver\XmlResolver; use CfdiUtils\XmlResolver\XmlResolverPropertyInterface; class CfdiCreator33 implements CertificadoPropertyInterface, XmlResolverPropertyInterface, XsltBuilderPropertyInterface { use CfdiCreatorTrait; private Comprobante $comprobante; /** * CfdiCreator33 constructor. */ public function __construct( array $comprobanteAttributes = [], ?Certificado $certificado = null, ?XmlResolver $xmlResolver = null, ?XsltBuilderInterface $xsltBuilder = null, ) { $this->comprobante = new Comprobante(); $this->cfdiCreatorConstructor($comprobanteAttributes, $certificado, $xmlResolver, $xsltBuilder); } public function comprobante(): Comprobante { return $this->comprobante; } public function buildCadenaDeOrigen(): string { $xsltLocation = $this->getXmlResolver()->resolveCadenaOrigenLocation('3.3'); return $this->buildCadenaDeOrigenUsingXsltLocation($xsltLocation); } public function validate(): Asserts { $validator = (new MultiValidatorFactory())->newCreated33(); return $this->validateUsingValidator($validator); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/CfdiCreator40.php
src/CfdiUtils/CfdiCreator40.php
<?php namespace CfdiUtils; use CfdiUtils\CadenaOrigen\XsltBuilderInterface; use CfdiUtils\CadenaOrigen\XsltBuilderPropertyInterface; use CfdiUtils\Certificado\Certificado; use CfdiUtils\Certificado\CertificadoPropertyInterface; use CfdiUtils\Elements\Cfdi40\Comprobante; use CfdiUtils\Validate\Asserts; use CfdiUtils\Validate\MultiValidatorFactory; use CfdiUtils\XmlResolver\XmlResolver; use CfdiUtils\XmlResolver\XmlResolverPropertyInterface; class CfdiCreator40 implements CertificadoPropertyInterface, XmlResolverPropertyInterface, XsltBuilderPropertyInterface { use CfdiCreatorTrait; private Comprobante $comprobante; /** * CfdiCreator40 constructor. */ public function __construct( array $comprobanteAttributes = [], ?Certificado $certificado = null, ?XmlResolver $xmlResolver = null, ?XsltBuilderInterface $xsltBuilder = null, ) { $this->comprobante = new Comprobante(); $this->cfdiCreatorConstructor($comprobanteAttributes, $certificado, $xmlResolver, $xsltBuilder); } public function comprobante(): Comprobante { return $this->comprobante; } public function buildCadenaDeOrigen(): string { $xsltLocation = $this->getXmlResolver()->resolveCadenaOrigenLocation('4.0'); return $this->buildCadenaDeOrigenUsingXsltLocation($xsltLocation); } public function validate(): Asserts { $validator = (new MultiValidatorFactory())->newCreated40(); return $this->validateUsingValidator($validator); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/CfdiCreateObjectException.php
src/CfdiUtils/CfdiCreateObjectException.php
<?php namespace CfdiUtils; use LogicException; use UnexpectedValueException; final class CfdiCreateObjectException extends UnexpectedValueException { /** * @param array<string, UnexpectedValueException> $versionExceptions */ private function __construct(string $message, private array $versionExceptions) { parent::__construct($message); } /** * @param array<string, UnexpectedValueException> $versionException */ public static function withVersionExceptions(array $versionException): self { return new self('Unable to read DOMDocument as CFDI', $versionException); } /** @return string[] */ public function getVersions(): array { return array_keys($this->versionExceptions); } public function getExceptionByVersion(string $version): UnexpectedValueException { if (! isset($this->versionExceptions[$version])) { throw new LogicException("Version $version does not have any exception"); } return $this->versionExceptions[$version]; } /** @return array<string, UnexpectedValueException> */ public function getExceptions(): array { return $this->versionExceptions; } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Cfdi.php
src/CfdiUtils/Cfdi.php
<?php namespace CfdiUtils; use CfdiUtils\Internals\XmlReaderTrait; use DOMDocument; use UnexpectedValueException; /** * This class contains minimum helpers to read CFDI based on DOMDocument * * When the object is instantiated it checks that: * implements the namespace static::CFDI_NAMESPACE using a prefix * the root node is prefix + Comprobante * * This class also provides version information through getVersion() method * * This class also provides conversion to Node for easy access and manipulation, * changes made in Node structure are not reflected into the DOMDocument, * changes made in DOMDocument three are not reflected into the Node, * * Use this class as your starting point to read documents */ class Cfdi { use XmlReaderTrait; /** @var array<string, string> Dictionary of versions and namespaces */ private const CFDI_SPECS = [ '4.0' => 'http://www.sat.gob.mx/cfd/4', '3.3' => 'http://www.sat.gob.mx/cfd/3', '3.2' => 'http://www.sat.gob.mx/cfd/3', ]; public function __construct(DOMDocument $document) { $cfdiVersion = new CfdiVersion(); /** @var array<string, UnexpectedValueException> $exceptions */ $exceptions = []; foreach (self::CFDI_SPECS as $version => $namespace) { try { $this->loadDocumentWithNamespace($cfdiVersion, $document, $namespace); return; } catch (UnexpectedValueException $exception) { $exceptions[$version] = $exception; } } throw CfdiCreateObjectException::withVersionExceptions($exceptions); } /** @throws UnexpectedValueException */ private function loadDocumentWithNamespace(CfdiVersion $cfdiVersion, DOMDocument $document, string $namespace): void { $rootElement = self::checkRootElement($document, $namespace, 'cfdi', 'Comprobante'); $this->version = $cfdiVersion->getFromDOMElement($rootElement); $this->document = clone $document; } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/CfdiValidator40.php
src/CfdiUtils/CfdiValidator40.php
<?php namespace CfdiUtils; use CfdiUtils\CadenaOrigen\XsltBuilderPropertyInterface; use CfdiUtils\Validate\CfdiValidatorTrait; use CfdiUtils\Validate\MultiValidator; use CfdiUtils\Validate\MultiValidatorFactory; use CfdiUtils\XmlResolver\XmlResolverPropertyInterface; class CfdiValidator40 implements XmlResolverPropertyInterface, XsltBuilderPropertyInterface { use CfdiValidatorTrait; protected function createVersionedMultiValidator(): MultiValidator { $factory = new MultiValidatorFactory(); return $factory->newReceived40(); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/CfdiVersion.php
src/CfdiUtils/CfdiVersion.php
<?php namespace CfdiUtils; use CfdiUtils\VersionDiscovery\VersionDiscoverer; /** * This class provides static methods to retrieve the version attribute from a * Comprobante Fiscal Digital por Internet (CFDI) * * It will not check anything but the value of the correct attribute * It will not care if the cfdi is following a schema or element's name * * Possible values are always 3.2, 3.3, 4.0 or empty string */ class CfdiVersion extends VersionDiscoverer { public function rules(): array { return [ '4.0' => 'Version', '3.3' => 'Version', '3.2' => 'version', ]; } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/CfdiCreatorTrait.php
src/CfdiUtils/CfdiCreatorTrait.php
<?php namespace CfdiUtils; use CfdiUtils\CadenaOrigen\DOMBuilder; use CfdiUtils\CadenaOrigen\XsltBuilderInterface; use CfdiUtils\CadenaOrigen\XsltBuilderPropertyTrait; use CfdiUtils\Certificado\Certificado; use CfdiUtils\Certificado\CertificadoPropertyTrait; use CfdiUtils\Nodes\NodeInterface; use CfdiUtils\Nodes\XmlNodeUtils; use CfdiUtils\PemPrivateKey\PemPrivateKey; use CfdiUtils\SumasConceptos\SumasConceptos; use CfdiUtils\SumasConceptos\SumasConceptosWriter; use CfdiUtils\Utils\SatNsDefinitionsMover; use CfdiUtils\Validate\Asserts; use CfdiUtils\Validate\Hydrater; use CfdiUtils\Validate\MultiValidator; use CfdiUtils\XmlResolver\XmlResolver; use CfdiUtils\XmlResolver\XmlResolverPropertyTrait; trait CfdiCreatorTrait { use CertificadoPropertyTrait; use XmlResolverPropertyTrait; use XsltBuilderPropertyTrait; private function cfdiCreatorConstructor( array $comprobanteAttributes = [], ?Certificado $certificado = null, ?XmlResolver $xmlResolver = null, ?XsltBuilderInterface $xsltBuilder = null, ): void { $this->comprobante->addAttributes($comprobanteAttributes); $this->setXmlResolver($xmlResolver ?: new XmlResolver()); if (null !== $certificado) { $this->putCertificado($certificado); } $this->setXsltBuilder($xsltBuilder ?: new DOMBuilder()); } public static function newUsingNode( NodeInterface $node, ?Certificado $certificado = null, ?XmlResolver $xmlResolver = null, ): self { $new = new self([], $certificado, $xmlResolver); $comprobante = $new->comprobante; $comprobante->addAttributes($node->attributes()->exportArray()); foreach ($node as $child) { $comprobante->addChild($child); } return $new; } public function putCertificado(Certificado $certificado, bool $putEmisorRfcNombre = true): void { $this->setCertificado($certificado); $this->comprobante['NoCertificado'] = $certificado->getSerial(); $this->comprobante['Certificado'] = $certificado->getPemContentsOneLine(); if ($putEmisorRfcNombre) { $emisor = $this->comprobante->searchNode('cfdi:Emisor'); if (null === $emisor) { $emisor = $this->comprobante->getEmisor(); } $trimSuffix = 12 === mb_strlen($certificado->getRfc()) && '4.0' === $this->comprobante['Version']; $emisor->addAttributes([ 'Nombre' => $certificado->getName($trimSuffix), 'Rfc' => $certificado->getRfc(), ]); } } public function asXml(): string { return XmlNodeUtils::nodeToXmlString($this->comprobante, true); } public function moveSatDefinitionsToComprobante(): void { $mover = new SatNsDefinitionsMover(); $mover->move($this->comprobante); } public function saveXml(string $filename): bool { return false !== file_put_contents($filename, $this->asXml()); } private function buildCadenaDeOrigenUsingXsltLocation(string $xsltLocation): string { if (! $this->hasXsltBuilder()) { throw new \LogicException( 'Cannot build the cadena de origen since there is no xslt builder' ); } return $this->getXsltBuilder()->build($this->asXml(), $xsltLocation); } public function buildSumasConceptos(int $precision = 2): SumasConceptos { return new SumasConceptos($this->comprobante, $precision); } public function addSumasConceptos(?SumasConceptos $sumasConceptos = null, int $precision = 2): void { if (null === $sumasConceptos) { $sumasConceptos = $this->buildSumasConceptos($precision); } $writer = new SumasConceptosWriter($this->comprobante, $sumasConceptos, $precision); $writer->put(); } public function addSello(string $key, string $passPhrase = ''): void { // create private key $privateKey = new PemPrivateKey($key); if (! $privateKey->open($passPhrase)) { throw new \RuntimeException('Cannot open the private key'); } // check private key belongs to certificado if ( $this->hasCertificado() && ! $privateKey->belongsTo($this->getCertificado()->getPemContents()) ) { throw new \RuntimeException('The private key does not belong to the current certificate'); } // create sign and set into Sello attribute $this->comprobante['Sello'] = base64_encode( $privateKey->sign($this->buildCadenaDeOrigen(), OPENSSL_ALGO_SHA256) ); } private function validateUsingValidator(MultiValidator $validator): Asserts { $hydrater = new Hydrater(); $hydrater->setXmlString($this->asXml()); $hydrater->setXmlResolver(($this->hasXmlResolver()) ? $this->getXmlResolver() : null); $hydrater->setXsltBuilder($this->getXsltBuilder()); $validator->hydrate($hydrater); $asserts = new Asserts(); $validator->validate($this->comprobante, $asserts); return $asserts; } public function __toString(): string { try { return $this->asXml(); } catch (\Throwable) { return ''; } } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Internals/BaseConverterSequence.php
src/CfdiUtils/Internals/BaseConverterSequence.php
<?php namespace CfdiUtils\Internals; /** * This is a value object for BaseConverter containing the sequence * * NOTE: Changes will not be considering a bracking compatibility change since this utility is for internal usage only * @internal */ class BaseConverterSequence implements \Stringable { private string $sequence; private int $length; public function __construct(string $sequence) { self::checkIsValid($sequence); $this->sequence = $sequence; $this->length = strlen($sequence); } public function __toString(): string { return $this->sequence; } public function value(): string { return $this->sequence; } public function length(): int { return $this->length; } public static function isValid(string $value): bool { try { static::checkIsValid($value); return true; } catch (\UnexpectedValueException) { return false; } } public static function checkIsValid(string $sequence): void { $length = strlen($sequence); // is not empty if ($length < 2) { throw new \UnexpectedValueException('Sequence does not contains enough elements'); } if ($length !== mb_strlen($sequence)) { throw new \UnexpectedValueException('Cannot use multibyte strings in dictionary'); } $valuesCount = array_count_values(str_split(strtoupper($sequence))); $repeated = array_filter($valuesCount, fn (int $count): bool => 1 !== $count); if ([] !== $repeated) { throw new \UnexpectedValueException( sprintf('The sequence has not unique values: "%s"', implode(', ', array_keys($repeated))) ); } } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Internals/BaseConverter.php
src/CfdiUtils/Internals/BaseConverter.php
<?php namespace CfdiUtils\Internals; /** * Converts any string of any base to any other base without * PHP native method base_convert's double and float limitations. * * @see https://php.net/base_convert * Original author: https://github.com/credomane/php_baseconvert * * NOTE: Changes will not be considering a bracking compatibility change since this utility is for internal usage only * @internal */ class BaseConverter { public function __construct(private BaseConverterSequence $sequence) { } public static function createBase36(): self { return new self(new BaseConverterSequence('0123456789abcdefghijklmnopqrstuvwxyz')); } public function sequence(): BaseConverterSequence { return $this->sequence; } public function maximumBase(): int { return $this->sequence->length(); } public function convert(string $input, int $frombase, int $tobase): string { if ($frombase < 2 || $frombase > $this->maximumBase()) { throw new \UnexpectedValueException('Invalid from base'); } if ($tobase < 2 || $tobase > $this->maximumBase()) { throw new \UnexpectedValueException('Invalid to base'); } $originalSequence = $this->sequence()->value(); if ('' === $input) { $input = $originalSequence[0]; // use zero as input } $chars = substr($originalSequence, 0, $frombase); if (! preg_match("/^[$chars]+$/", $input)) { throw new \UnexpectedValueException('The number to convert contains invalid characters'); } $length = strlen($input); $values = []; for ($i = 0; $i < $length; $i++) { $values[] = intval(stripos($originalSequence, $input[$i])); } $result = ''; do { $divide = 0; $newlen = 0; for ($i = 0; $i < $length; $i++) { $divide = $divide * $frombase + $values[$i]; if ($divide >= $tobase) { $values[$newlen] = intval($divide / $tobase); $divide = $divide % $tobase; $newlen = $newlen + 1; } elseif ($newlen > 0) { $values[$newlen] = 0; $newlen = $newlen + 1; } } $length = $newlen; $result = $originalSequence[$divide] . $result; } while ($newlen > 0); return $result; } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Internals/StringUncaseReplacer.php
src/CfdiUtils/Internals/StringUncaseReplacer.php
<?php declare(strict_types=1); namespace CfdiUtils\Internals; /** @internal */ final class StringUncaseReplacer { /** * @param array<string, array<string, true>> $replacements */ private function __construct(private array $replacements = []) { } /** * @param array<string, array<string>> $replacements */ public static function create(array $replacements): self { $replacer = new self(); foreach ($replacements as $replacement => $needles) { $replacer->addReplacement($replacement, ...$needles); } return $replacer; } private function addReplacement(string $replacement, string ...$needle): void { $needle[] = $replacement; // also include the replacement itself foreach ($needle as $entry) { $entry = mb_strtolower($entry); // normalize url to compare $this->replacements[$replacement][$entry] = true; } } public function findReplacement(string $url): string { $url = mb_strtolower($url); // normalize url to compare foreach ($this->replacements as $replacement => $entries) { if (isset($entries[$url])) { return $replacement; } } return ''; } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Internals/XmlReaderTrait.php
src/CfdiUtils/Internals/XmlReaderTrait.php
<?php namespace CfdiUtils\Internals; use CfdiUtils\Nodes\NodeInterface; use CfdiUtils\Nodes\XmlNodeUtils; use CfdiUtils\QuickReader\QuickReader; use CfdiUtils\QuickReader\QuickReaderImporter; use CfdiUtils\Utils\Xml; use DOMDocument; use DOMElement; /** @internal */ trait XmlReaderTrait { private DOMDocument $document; private string $version; private ?string $source = null; private ?NodeInterface $node = null; private ?QuickReader $quickReader = null; /** @throws \UnexpectedValueException */ private static function checkRootElement( DOMDocument $document, string $expectedNamespace, string $expectedNsPrefix, string $expectedRootBaseNodeName, ): DOMElement { $rootElement = Xml::documentElement($document); /** * is not documented: lookupPrefix returns NULL instead of string when not found * this is why we are casting the value to string * @var string|null $lookupPrefixResult */ $lookupPrefixResult = $document->lookupPrefix($expectedNamespace); $nsPrefix = (string)$lookupPrefixResult; if ('' === $nsPrefix) { throw new \UnexpectedValueException( sprintf('Document does not implement namespace %s', $expectedNamespace) ); } if ($expectedNsPrefix !== $nsPrefix) { throw new \UnexpectedValueException( sprintf('Prefix for namespace %s is not "%s"', $expectedNamespace, $expectedNsPrefix) ); } $expectedRootNodeName = $expectedNsPrefix . ':' . $expectedRootBaseNodeName; if ($rootElement->tagName !== $expectedRootNodeName) { throw new \UnexpectedValueException(sprintf('Root element is not %s', $expectedRootNodeName)); } return $rootElement; } /** * Create a CFDI object from a xml string */ public static function newFromString(string $content): self { $document = Xml::newDocumentContent($content); // populate source since it is already available, in this way we avoid the conversion from document to string $cfdi = new self($document); $cfdi->source = $content; return $cfdi; } /** * Obtain the version from the document, if the version was not detected returns an empty string */ public function getVersion(): string { return $this->version; } /** * Get a clone of the local DOM Document */ public function getDocument(): DOMDocument { return clone $this->document; } /** * Get the XML string source */ public function getSource(): string { if (null === $this->source) { // pass the document element to avoid xml header $this->source = (string) $this->document->saveXML(Xml::documentElement($this->document)); } return $this->source; } /** * Get the node object to iterate through the document */ public function getNode(): NodeInterface { if (null === $this->node) { $this->node = XmlNodeUtils::nodeFromXmlElement(Xml::documentElement($this->document)); } return $this->node; } /** * Get the quick reader object to iterate through the document */ public function getQuickReader(): QuickReader { if (null === $this->quickReader) { $this->quickReader = (new QuickReaderImporter())->importDocument($this->document); } return $this->quickReader; } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Internals/CommandTemplate.php
src/CfdiUtils/Internals/CommandTemplate.php
<?php namespace CfdiUtils\Internals; /** * Build a command array from a template * * NOTE: Changes will not be considering a breaking compatibility change since this utility is for internal usage only * @internal */ class CommandTemplate { public function create(string $template, array $arguments): array { $command = []; $parts = array_filter(explode(' ', $template), fn (string $part): bool => '' !== $part); $argumentPosition = 0; foreach ($parts as $value) { if ('?' === $value) { // argument insert $value = $arguments[$argumentPosition] ?? ''; $argumentPosition = $argumentPosition + 1; } $command[] = $value; } return $command; } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Internals/NormalizeLineEndingsTrait.php
src/CfdiUtils/Internals/NormalizeLineEndingsTrait.php
<?php namespace CfdiUtils\Internals; /** * NormalizeLineEndingsTrait contains a private function normalizeLineEndings * This help the implementer class to work with EOL * * NOTE: Changes will not be considering a bracking compatibility change since this utility is for internal usage only * @internal */ trait NormalizeLineEndingsTrait { /** * Changes EOL CRLF or LF to PHP_EOL. * This won't alter CR that are not at EOL. * This won't alter LFCR used in old Mac style * * @internal */ private function normalizeLineEndings(string $content): string { // move '\r\n' or '\n' to PHP_EOL // first substitution '\r\n' -> '\n' // second substitution '\n' -> PHP_EOL // remove any EOL at the EOF return rtrim(str_replace(["\r\n", "\n"], ["\n", PHP_EOL], $content), PHP_EOL); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Internals/TemporaryFile.php
src/CfdiUtils/Internals/TemporaryFile.php
<?php namespace CfdiUtils\Internals; /** * Utility to work with the creation of temporary files. * * NOTE: Changes will not be considering a bracking compatibility change since this utility is for internal usage only * @internal */ final class TemporaryFile implements \Stringable { private function __construct(private string $filename) { } public static function create(string $directory = ''): self { if ('' === $directory) { $directory = sys_get_temp_dir(); if (in_array($directory, ['', '.'], true)) { throw new \RuntimeException('System has an invalid default temp dir'); } } $previousErrorLevel = error_reporting(0); $filename = strval(tempnam($directory, '')); error_reporting($previousErrorLevel); // must check realpath since windows can return different paths for same location if (realpath(dirname($filename)) !== realpath($directory)) { unlink($filename); $filename = ''; } if ('' === $filename) { throw new \RuntimeException('Unable to create a temporary file'); } return new self($filename); } public function getPath(): string { return $this->filename; } public function retriveContents(): string { return strval(file_get_contents($this->filename)); } public function storeContents(string $contents): void { file_put_contents($this->filename, $contents); } public function remove(): void { $filename = $this->getPath(); if (file_exists($filename)) { unlink($filename); } } public function __toString(): string { return $this->getPath(); } public function runAndRemove(\Closure $fn) { try { return $fn(); } finally { $this->remove(); } } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Elements/Pagos10/Impuestos.php
src/CfdiUtils/Elements/Pagos10/Impuestos.php
<?php namespace CfdiUtils\Elements\Pagos10; use CfdiUtils\Elements\Common\AbstractElement; class Impuestos extends AbstractElement { public function getElementName(): string { return 'pago10:Impuestos'; } public function getChildrenOrder(): array { return ['pago10:Retenciones', 'pago10:Traslados']; } public function getTraslados(): Traslados { return $this->helperGetOrAdd(new Traslados()); } public function getRetenciones(): Retenciones { return $this->helperGetOrAdd(new Retenciones()); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Elements/Pagos10/Traslado.php
src/CfdiUtils/Elements/Pagos10/Traslado.php
<?php namespace CfdiUtils\Elements\Pagos10; use CfdiUtils\Elements\Common\AbstractElement; class Traslado extends AbstractElement { public function getElementName(): string { return 'pago10:Traslado'; } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Elements/Pagos10/Pagos.php
src/CfdiUtils/Elements/Pagos10/Pagos.php
<?php namespace CfdiUtils\Elements\Pagos10; use CfdiUtils\Elements\Common\AbstractElement; class Pagos extends AbstractElement { public function addPago(array $attributes = []): Pago { $pago = new Pago($attributes); $this->addChild($pago); return $pago; } public function multiPago(array ...$elementAttributes): self { foreach ($elementAttributes as $attributes) { $this->addPago($attributes); } return $this; } public function getElementName(): string { return 'pago10:Pagos'; } public function getFixedAttributes(): array { return [ 'xmlns:pago10' => 'http://www.sat.gob.mx/Pagos', 'xsi:schemaLocation' => 'http://www.sat.gob.mx/Pagos' . ' http://www.sat.gob.mx/sitio_internet/cfd/Pagos/Pagos10.xsd', 'Version' => '1.0', ]; } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Elements/Pagos10/Traslados.php
src/CfdiUtils/Elements/Pagos10/Traslados.php
<?php namespace CfdiUtils\Elements\Pagos10; use CfdiUtils\Elements\Common\AbstractElement; class Traslados extends AbstractElement { public function getElementName(): string { return 'pago10:Traslados'; } public function addTraslado(array $attributes = []): Traslado { $traslado = new Traslado($attributes); $this->addChild($traslado); return $traslado; } public function multiTraslado(array ...$elementAttributes): self { foreach ($elementAttributes as $attributes) { $this->addTraslado($attributes); } return $this; } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Elements/Pagos10/DoctoRelacionado.php
src/CfdiUtils/Elements/Pagos10/DoctoRelacionado.php
<?php namespace CfdiUtils\Elements\Pagos10; use CfdiUtils\Elements\Common\AbstractElement; class DoctoRelacionado extends AbstractElement { public function getElementName(): string { return 'pago10:DoctoRelacionado'; } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Elements/Pagos10/Retencion.php
src/CfdiUtils/Elements/Pagos10/Retencion.php
<?php namespace CfdiUtils\Elements\Pagos10; use CfdiUtils\Elements\Common\AbstractElement; class Retencion extends AbstractElement { public function getElementName(): string { return 'pago10:Retencion'; } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Elements/Pagos10/Pago.php
src/CfdiUtils/Elements/Pagos10/Pago.php
<?php namespace CfdiUtils\Elements\Pagos10; use CfdiUtils\Elements\Common\AbstractElement; class Pago extends AbstractElement { public function addDoctoRelacionado(array $attributes = []): DoctoRelacionado { $doctoRelacionado = new DoctoRelacionado($attributes); $this->addChild($doctoRelacionado); return $doctoRelacionado; } public function multiDoctoRelacionado(array ...$elementAttributes): self { foreach ($elementAttributes as $attributes) { $this->addDoctoRelacionado($attributes); } return $this; } public function addImpuestos(array $attributes = []): Impuestos { $impuestos = new Impuestos($attributes); $this->addChild($impuestos); return $impuestos; } public function getElementName(): string { return 'pago10:Pago'; } public function getChildrenOrder(): array { return ['pago10:DoctoRelacionado', 'pago10:Impuestos']; } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Elements/Pagos10/Retenciones.php
src/CfdiUtils/Elements/Pagos10/Retenciones.php
<?php namespace CfdiUtils\Elements\Pagos10; use CfdiUtils\Elements\Common\AbstractElement; class Retenciones extends AbstractElement { public function getElementName(): string { return 'pago10:Retenciones'; } public function addRetencion(array $attributes = []): Retencion { $retencion = new Retencion($attributes); $this->addChild($retencion); return $retencion; } public function multiRetencion(array ...$elementAttributes): self { foreach ($elementAttributes as $attributes) { $this->addRetencion($attributes); } return $this; } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Elements/CartaPorte10/Carro.php
src/CfdiUtils/Elements/CartaPorte10/Carro.php
<?php namespace CfdiUtils\Elements\CartaPorte10; use CfdiUtils\Elements\Common\AbstractElement; class Carro extends AbstractElement { public function getElementName(): string { return 'cartaporte:Carro'; } public function addContenedor(array $attributes = []): Contenedor { $contenedor = new Contenedor($attributes); $this->addChild($contenedor); return $contenedor; } public function multiContenedor(array ...$elementAttributes): self { foreach ($elementAttributes as $attributes) { $this->addContenedor($attributes); } return $this; } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Elements/CartaPorte10/Ubicacion.php
src/CfdiUtils/Elements/CartaPorte10/Ubicacion.php
<?php namespace CfdiUtils\Elements\CartaPorte10; use CfdiUtils\Elements\Common\AbstractElement; class Ubicacion extends AbstractElement { public function getElementName(): string { return 'cartaporte:Ubicacion'; } public function getChildrenOrder(): array { return ['cartaporte:Origen', 'cartaporte:Destino', 'cartaporte:Domicilio']; } public function getOrigen(): Origen { /** @noinspection PhpIncompatibleReturnTypeInspection */ return $this->helperGetOrAdd(new Origen()); } public function addOrigen(array $attributes = []): Origen { $origen = $this->getOrigen(); $origen->addAttributes($attributes); return $origen; } public function getDestino(): Destino { /** @noinspection PhpIncompatibleReturnTypeInspection */ return $this->helperGetOrAdd(new Destino()); } public function addDestino(array $attributes = []): Destino { $destino = $this->getDestino(); $destino->addAttributes($attributes); return $destino; } public function getDomicilio(): Domicilio { /** @noinspection PhpIncompatibleReturnTypeInspection */ return $this->helperGetOrAdd(new Domicilio()); } public function addDomicilio(array $attributes = []): Domicilio { $domicilio = $this->getDomicilio(); $domicilio->addAttributes($attributes); return $domicilio; } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Elements/CartaPorte10/Domicilio.php
src/CfdiUtils/Elements/CartaPorte10/Domicilio.php
<?php namespace CfdiUtils\Elements\CartaPorte10; use CfdiUtils\Elements\Common\AbstractElement; class Domicilio extends AbstractElement { public function getElementName(): string { return 'cartaporte:Domicilio'; } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Elements/CartaPorte10/Remolques.php
src/CfdiUtils/Elements/CartaPorte10/Remolques.php
<?php namespace CfdiUtils\Elements\CartaPorte10; use CfdiUtils\Elements\Common\AbstractElement; class Remolques extends AbstractElement { public function getElementName(): string { return 'cartaporte:Remolques'; } public function addRemolque(array $attributes = []): Remolque { $remolque = new Remolque($attributes); $this->addChild($remolque); return $remolque; } public function multiRemolque(array ...$elementAttributes): self { foreach ($elementAttributes as $attributes) { $this->addRemolque($attributes); } return $this; } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Elements/CartaPorte10/CantidadTransporta.php
src/CfdiUtils/Elements/CartaPorte10/CantidadTransporta.php
<?php namespace CfdiUtils\Elements\CartaPorte10; use CfdiUtils\Elements\Common\AbstractElement; class CantidadTransporta extends AbstractElement { public function getElementName(): string { return 'cartaporte:CantidadTransporta'; } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Elements/CartaPorte10/AutotransporteFederal.php
src/CfdiUtils/Elements/CartaPorte10/AutotransporteFederal.php
<?php namespace CfdiUtils\Elements\CartaPorte10; use CfdiUtils\Elements\Common\AbstractElement; class AutotransporteFederal extends AbstractElement { public function getElementName(): string { return 'cartaporte:AutotransporteFederal'; } public function addIdentificacionVehicular(array $attributes = []): IdentificacionVehicular { $identificacionVehicular = new IdentificacionVehicular($attributes); $this->addChild($identificacionVehicular); return $identificacionVehicular; } public function getIdentificacionVehicular(): IdentificacionVehicular { /** @noinspection PhpIncompatibleReturnTypeInspection */ return $this->helperGetOrAdd(new IdentificacionVehicular()); } public function addRemolques(array $attributes = []): Remolques { $remolques = new Remolques($attributes); $this->addChild($remolques); return $remolques; } public function getRemolques(): Remolques { /** @noinspection PhpIncompatibleReturnTypeInspection */ return $this->helperGetOrAdd(new Remolques()); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Elements/CartaPorte10/Arrendatario.php
src/CfdiUtils/Elements/CartaPorte10/Arrendatario.php
<?php namespace CfdiUtils\Elements\CartaPorte10; use CfdiUtils\Elements\Common\AbstractElement; class Arrendatario extends AbstractElement { public function getElementName(): string { return 'cartaporte:Arrendatario'; } public function getDomicilio(): Domicilio { /** @noinspection PhpIncompatibleReturnTypeInspection */ return $this->helperGetOrAdd(new Domicilio()); } public function addDomicilio(array $attributes = []): Domicilio { $domicilio = $this->getDomicilio(); $domicilio->addAttributes($attributes); return $domicilio; } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Elements/CartaPorte10/TransporteFerroviario.php
src/CfdiUtils/Elements/CartaPorte10/TransporteFerroviario.php
<?php namespace CfdiUtils\Elements\CartaPorte10; use CfdiUtils\Elements\Common\AbstractElement; class TransporteFerroviario extends AbstractElement { public function getElementName(): string { return 'cartaporte:TransporteFerroviario'; } public function addDerechosDePaso(array $attributes = []): DerechosDePaso { $derechosDePaso = new DerechosDePaso($attributes); $this->addChild($derechosDePaso); return $derechosDePaso; } public function multiDerechosDePaso(array ...$elementAttributes): self { foreach ($elementAttributes as $attributes) { $this->addDerechosDePaso($attributes); } return $this; } public function addCarro(array $attributes = []): Carro { $carro = new Carro($attributes); $this->addChild($carro); return $carro; } public function multiCarro(array ...$elementAttributes): self { foreach ($elementAttributes as $attributes) { $this->addCarro($attributes); } return $this; } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Elements/CartaPorte10/DerechosDePaso.php
src/CfdiUtils/Elements/CartaPorte10/DerechosDePaso.php
<?php namespace CfdiUtils\Elements\CartaPorte10; use CfdiUtils\Elements\Common\AbstractElement; class DerechosDePaso extends AbstractElement { public function getElementName(): string { return 'cartaporte:DerechosDePaso'; } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Elements/CartaPorte10/CartaPorte.php
src/CfdiUtils/Elements/CartaPorte10/CartaPorte.php
<?php namespace CfdiUtils\Elements\CartaPorte10; use CfdiUtils\Elements\Common\AbstractElement; class CartaPorte extends AbstractElement { public function getElementName(): string { return 'cartaporte:CartaPorte'; } public function getChildrenOrder(): array { return [ 'cartaporte:Ubicaciones', 'cartaporte:Mercancias', 'cartaporte:FiguraTransporte', ]; } public function getFixedAttributes(): array { return [ 'xmlns:cartaporte' => 'http://www.sat.gob.mx/cartaporte', 'xsi:schemaLocation' => 'http://www.sat.gob.mx/cartaporte' . ' http://www.sat.gob.mx/sitio_internet/cfd/CartaPorte/CartaPorte.xsd', 'Version' => '1.0', ]; } public function getUbicaciones(): Ubicaciones { /** @noinspection PhpIncompatibleReturnTypeInspection */ return $this->helperGetOrAdd(new Ubicaciones()); } public function addUbicaciones(array $attributes = []): Ubicaciones { $ubicaciones = $this->getUbicaciones(); $ubicaciones->addAttributes($attributes); return $ubicaciones; } public function getMercancias(): Mercancias { /** @noinspection PhpIncompatibleReturnTypeInspection */ return $this->helperGetOrAdd(new Mercancias()); } public function addMercancias(array $attributes = []): Mercancias { $mercancias = $this->getMercancias(); $mercancias->addAttributes($attributes); return $mercancias; } public function getFiguraTransporte(): FiguraTransporte { /** @noinspection PhpIncompatibleReturnTypeInspection */ return $this->helperGetOrAdd(new FiguraTransporte()); } public function addFiguraTransporte(array $attributes = []): FiguraTransporte { $figuraTransporte = $this->getFiguraTransporte(); $figuraTransporte->addAttributes($attributes); return $figuraTransporte; } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Elements/CartaPorte10/Propietario.php
src/CfdiUtils/Elements/CartaPorte10/Propietario.php
<?php namespace CfdiUtils\Elements\CartaPorte10; use CfdiUtils\Elements\Common\AbstractElement; class Propietario extends AbstractElement { public function getElementName(): string { return 'cartaporte:Propietario'; } public function getDomicilio(): Domicilio { /** @noinspection PhpIncompatibleReturnTypeInspection */ return $this->helperGetOrAdd(new Domicilio()); } public function addDomicilio(array $attributes = []): Domicilio { $domicilio = $this->getDomicilio(); $domicilio->addAttributes($attributes); return $domicilio; } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Elements/CartaPorte10/Mercancias.php
src/CfdiUtils/Elements/CartaPorte10/Mercancias.php
<?php namespace CfdiUtils\Elements\CartaPorte10; use CfdiUtils\Elements\Common\AbstractElement; class Mercancias extends AbstractElement { public function getElementName(): string { return 'cartaporte:Mercancias'; } public function addMercancia(array $attributes = []): Mercancia { $mercancia = new Mercancia($attributes); $this->addChild($mercancia); return $mercancia; } public function multiMercancia(array ...$elementAttributes): self { foreach ($elementAttributes as $attributes) { $this->addMercancia($attributes); } return $this; } public function addAutotransporteFederal(array $attributes = []): AutotransporteFederal { $autotransporteFederal = new AutotransporteFederal($attributes); $this->addChild($autotransporteFederal); return $autotransporteFederal; } public function addTransporteMaritimo(array $attributes = []): TransporteMaritimo { $transporteMaritimo = new TransporteMaritimo($attributes); $this->addChild($transporteMaritimo); return $transporteMaritimo; } public function addTransporteAereo(array $attributes = []): TransporteAereo { $transporteAereo = new TransporteAereo($attributes); $this->addChild($transporteAereo); return $transporteAereo; } public function addTransporteFerroviario(array $attributes = []): TransporteFerroviario { $transporteFerroviario = new TransporteFerroviario($attributes); $this->addChild($transporteFerroviario); return $transporteFerroviario; } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Elements/CartaPorte10/Remolque.php
src/CfdiUtils/Elements/CartaPorte10/Remolque.php
<?php namespace CfdiUtils\Elements\CartaPorte10; use CfdiUtils\Elements\Common\AbstractElement; class Remolque extends AbstractElement { public function getElementName(): string { return 'cartaporte:Remolque'; } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Elements/CartaPorte10/Notificado.php
src/CfdiUtils/Elements/CartaPorte10/Notificado.php
<?php namespace CfdiUtils\Elements\CartaPorte10; use CfdiUtils\Elements\Common\AbstractElement; class Notificado extends AbstractElement { public function getElementName(): string { return 'cartaporte:Notificado'; } public function getDomicilio(): Domicilio { /** @noinspection PhpIncompatibleReturnTypeInspection */ return $this->helperGetOrAdd(new Domicilio()); } public function addDomicilio(array $attributes = []): Domicilio { $domicilio = $this->getDomicilio(); $domicilio->addAttributes($attributes); return $domicilio; } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Elements/CartaPorte10/Ubicaciones.php
src/CfdiUtils/Elements/CartaPorte10/Ubicaciones.php
<?php namespace CfdiUtils\Elements\CartaPorte10; use CfdiUtils\Elements\Common\AbstractElement; class Ubicaciones extends AbstractElement { public function getElementName(): string { return 'cartaporte:Ubicaciones'; } public function addUbicacion(array $attributes = []): Ubicacion { $ubicacion = new Ubicacion($attributes); $this->addChild($ubicacion); return $ubicacion; } public function multiUbicacion(array ...$elementAttributes): self { foreach ($elementAttributes as $attributes) { $this->addUbicacion($attributes); } return $this; } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Elements/CartaPorte10/DetalleMercancia.php
src/CfdiUtils/Elements/CartaPorte10/DetalleMercancia.php
<?php namespace CfdiUtils\Elements\CartaPorte10; use CfdiUtils\Elements\Common\AbstractElement; class DetalleMercancia extends AbstractElement { public function getElementName(): string { return 'cartaporte:DetalleMercancia'; } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Elements/CartaPorte10/FiguraTransporte.php
src/CfdiUtils/Elements/CartaPorte10/FiguraTransporte.php
<?php namespace CfdiUtils\Elements\CartaPorte10; use CfdiUtils\Elements\Common\AbstractElement; class FiguraTransporte extends AbstractElement { public function getElementName(): string { return 'cartaporte:FiguraTransporte'; } public function addOperadores(array $attributes = []): Operadores { $operadores = new Operadores($attributes); $this->addChild($operadores); return $operadores; } public function multiOperadores(array ...$elementAttributes): self { foreach ($elementAttributes as $attributes) { $this->addOperadores($attributes); } return $this; } public function addPropietario(array $attributes = []): Propietario { $propietario = new Propietario($attributes); $this->addChild($propietario); return $propietario; } public function multiPropietario(array ...$elementAttributes): self { foreach ($elementAttributes as $attributes) { $this->addPropietario($attributes); } return $this; } public function addArrendatario(array $attributes = []): Arrendatario { $arrendatario = new Arrendatario($attributes); $this->addChild($arrendatario); return $arrendatario; } public function multiArrendatario(array ...$elementAttributes): self { foreach ($elementAttributes as $attributes) { $this->addArrendatario($attributes); } return $this; } public function addNotificado(array $attributes = []): Notificado { $arrendatario = new Notificado($attributes); $this->addChild($arrendatario); return $arrendatario; } public function multiNotificado(array ...$elementAttributes): self { foreach ($elementAttributes as $attributes) { $this->addNotificado($attributes); } return $this; } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Elements/CartaPorte10/Operadores.php
src/CfdiUtils/Elements/CartaPorte10/Operadores.php
<?php namespace CfdiUtils\Elements\CartaPorte10; use CfdiUtils\Elements\Common\AbstractElement; class Operadores extends AbstractElement { public function getElementName(): string { return 'cartaporte:Operadores'; } public function addOperador(array $attributes = []): Operador { $operador = new Operador($attributes); $this->addChild($operador); return $operador; } public function multiOperador(array ...$elementAttributes): self { foreach ($elementAttributes as $attributes) { $this->addOperador($attributes); } return $this; } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Elements/CartaPorte10/IdentificacionVehicular.php
src/CfdiUtils/Elements/CartaPorte10/IdentificacionVehicular.php
<?php namespace CfdiUtils\Elements\CartaPorte10; use CfdiUtils\Elements\Common\AbstractElement; class IdentificacionVehicular extends AbstractElement { public function getElementName(): string { return 'cartaporte:IdentificacionVehicular'; } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Elements/CartaPorte10/Origen.php
src/CfdiUtils/Elements/CartaPorte10/Origen.php
<?php namespace CfdiUtils\Elements\CartaPorte10; use CfdiUtils\Elements\Common\AbstractElement; class Origen extends AbstractElement { public function getElementName(): string { return 'cartaporte:Origen'; } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Elements/CartaPorte10/Destino.php
src/CfdiUtils/Elements/CartaPorte10/Destino.php
<?php namespace CfdiUtils\Elements\CartaPorte10; use CfdiUtils\Elements\Common\AbstractElement; class Destino extends AbstractElement { public function getElementName(): string { return 'cartaporte:Destino'; } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Elements/CartaPorte10/Contenedor.php
src/CfdiUtils/Elements/CartaPorte10/Contenedor.php
<?php namespace CfdiUtils\Elements\CartaPorte10; use CfdiUtils\Elements\Common\AbstractElement; class Contenedor extends AbstractElement { public function getElementName(): string { return 'cartaporte:Contenedor'; } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Elements/CartaPorte10/Mercancia.php
src/CfdiUtils/Elements/CartaPorte10/Mercancia.php
<?php namespace CfdiUtils\Elements\CartaPorte10; use CfdiUtils\Elements\Common\AbstractElement; class Mercancia extends AbstractElement { public function getElementName(): string { return 'cartaporte:Mercancia'; } public function addCantidadTransporta(array $attributes = []): CantidadTransporta { $cantidadTransporta = new CantidadTransporta($attributes); $this->addChild($cantidadTransporta); return $cantidadTransporta; } public function multiCantidadTransporta(array ...$elementAttributes): self { foreach ($elementAttributes as $attributes) { $this->addCantidadTransporta($attributes); } return $this; } public function addDetalleMercancia(array $attributes = []): DetalleMercancia { $detalleMercancia = new DetalleMercancia($attributes); $this->addChild($detalleMercancia); return $detalleMercancia; } public function getDetalleMercancia(): DetalleMercancia { /** @noinspection PhpIncompatibleReturnTypeInspection */ return $this->helperGetOrAdd(new DetalleMercancia()); } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Elements/CartaPorte10/TransporteAereo.php
src/CfdiUtils/Elements/CartaPorte10/TransporteAereo.php
<?php namespace CfdiUtils\Elements\CartaPorte10; use CfdiUtils\Elements\Common\AbstractElement; class TransporteAereo extends AbstractElement { public function getElementName(): string { return 'cartaporte:TransporteAereo'; } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Elements/CartaPorte10/Operador.php
src/CfdiUtils/Elements/CartaPorte10/Operador.php
<?php namespace CfdiUtils\Elements\CartaPorte10; use CfdiUtils\Elements\Common\AbstractElement; class Operador extends AbstractElement { public function getElementName(): string { return 'cartaporte:Operador'; } public function getDomicilio(): Domicilio { /** @noinspection PhpIncompatibleReturnTypeInspection */ return $this->helperGetOrAdd(new Domicilio()); } public function addDomicilio(array $attributes = []): Domicilio { $domicilio = $this->getDomicilio(); $domicilio->addAttributes($attributes); return $domicilio; } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Elements/CartaPorte10/TransporteMaritimo.php
src/CfdiUtils/Elements/CartaPorte10/TransporteMaritimo.php
<?php namespace CfdiUtils\Elements\CartaPorte10; use CfdiUtils\Elements\Common\AbstractElement; class TransporteMaritimo extends AbstractElement { public function getElementName(): string { return 'cartaporte:TransporteMaritimo'; } public function addContenedor(array $attributes = []): Contenedor { $contenedores = new Contenedor($attributes); $this->addChild($contenedores); return $contenedores; } public function multiContenedor(array ...$elementAttributes): self { foreach ($elementAttributes as $attributes) { $this->addContenedor($attributes); } return $this; } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Elements/Retenciones20/Addenda.php
src/CfdiUtils/Elements/Retenciones20/Addenda.php
<?php namespace CfdiUtils\Elements\Retenciones20; use CfdiUtils\Elements\Common\AbstractElement; use CfdiUtils\Nodes\NodeInterface; class Addenda extends AbstractElement { public function getElementName(): string { return 'retenciones:Addenda'; } public function add(NodeInterface $child): self { $this->children()->add($child); return $this; } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Elements/Retenciones20/CfdiRetenRelacionados.php
src/CfdiUtils/Elements/Retenciones20/CfdiRetenRelacionados.php
<?php namespace CfdiUtils\Elements\Retenciones20; use CfdiUtils\Elements\Common\AbstractElement; class CfdiRetenRelacionados extends AbstractElement { public function getElementName(): string { return 'retenciones:CfdiRetenRelacionados'; } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Elements/Retenciones20/Extranjero.php
src/CfdiUtils/Elements/Retenciones20/Extranjero.php
<?php namespace CfdiUtils\Elements\Retenciones20; use CfdiUtils\Elements\Common\AbstractElement; class Extranjero extends AbstractElement { public function getElementName(): string { return 'retenciones:Extranjero'; } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Elements/Retenciones20/Receptor.php
src/CfdiUtils/Elements/Retenciones20/Receptor.php
<?php namespace CfdiUtils\Elements\Retenciones20; use CfdiUtils\Elements\Common\AbstractElement; class Receptor extends AbstractElement { public function getElementName(): string { return 'retenciones:Receptor'; } public function getNacional(): Nacional { $nacional = $this->helperGetOrAdd(new Nacional()); $this->children()->removeAll(); $this->addChild($nacional); $this['NacionalidadR'] = 'Nacional'; return $nacional; } public function addNacional(array $attributes = []): Nacional { $nacional = $this->getNacional(); $nacional->addAttributes($attributes); return $nacional; } public function getExtranjero(): Extranjero { $nacional = $this->helperGetOrAdd(new Extranjero()); $this->children()->removeAll(); $this->addChild($nacional); $this['NacionalidadR'] = 'Extranjero'; return $nacional; } public function addExtranjero(array $attributes = []): Extranjero { $extranjero = $this->getExtranjero(); $extranjero->addAttributes($attributes); return $extranjero; } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Elements/Retenciones20/Totales.php
src/CfdiUtils/Elements/Retenciones20/Totales.php
<?php namespace CfdiUtils\Elements\Retenciones20; use CfdiUtils\Elements\Common\AbstractElement; class Totales extends AbstractElement { public function getElementName(): string { return 'retenciones:Totales'; } public function addImpRetenidos(array $attributes = [], array $children = []): ImpRetenidos { $impRetenidos = new ImpRetenidos($attributes, $children); $this->addChild($impRetenidos); return $impRetenidos; } public function multiImpRetenidos(array ...$elementAttributes): self { foreach ($elementAttributes as $attributes) { $this->addImpRetenidos($attributes); } return $this; } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Elements/Retenciones20/Periodo.php
src/CfdiUtils/Elements/Retenciones20/Periodo.php
<?php namespace CfdiUtils\Elements\Retenciones20; use CfdiUtils\Elements\Common\AbstractElement; class Periodo extends AbstractElement { public function getElementName(): string { return 'retenciones:Periodo'; } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Elements/Retenciones20/ImpRetenidos.php
src/CfdiUtils/Elements/Retenciones20/ImpRetenidos.php
<?php namespace CfdiUtils\Elements\Retenciones20; use CfdiUtils\Elements\Common\AbstractElement; class ImpRetenidos extends AbstractElement { public function getElementName(): string { return 'retenciones:ImpRetenidos'; } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Elements/Retenciones20/Nacional.php
src/CfdiUtils/Elements/Retenciones20/Nacional.php
<?php namespace CfdiUtils\Elements\Retenciones20; use CfdiUtils\Elements\Common\AbstractElement; class Nacional extends AbstractElement { public function getElementName(): string { return 'retenciones:Nacional'; } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Elements/Retenciones20/Emisor.php
src/CfdiUtils/Elements/Retenciones20/Emisor.php
<?php namespace CfdiUtils\Elements\Retenciones20; use CfdiUtils\Elements\Common\AbstractElement; class Emisor extends AbstractElement { public function getElementName(): string { return 'retenciones:Emisor'; } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Elements/Retenciones20/Complemento.php
src/CfdiUtils/Elements/Retenciones20/Complemento.php
<?php namespace CfdiUtils\Elements\Retenciones20; use CfdiUtils\Elements\Common\AbstractElement; use CfdiUtils\Nodes\NodeInterface; class Complemento extends AbstractElement { public function getElementName(): string { return 'retenciones:Complemento'; } public function add(NodeInterface $child): self { $this->children()->add($child); return $this; } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Elements/Retenciones20/Retenciones.php
src/CfdiUtils/Elements/Retenciones20/Retenciones.php
<?php namespace CfdiUtils\Elements\Retenciones20; use CfdiUtils\Elements\Common\AbstractElement; use CfdiUtils\Nodes\NodeInterface; class Retenciones extends AbstractElement { public function getElementName(): string { return 'retenciones:Retenciones'; } public function getCfdiRetenRelacionados(): CfdiRetenRelacionados { return $this->helperGetOrAdd(new CfdiRetenRelacionados()); } public function addCfdiRetenRelacionados(array $attributes = []): CfdiRetenRelacionados { $cfdiRelacionado = $this->getCfdiRetenRelacionados(); $cfdiRelacionado->addAttributes($attributes); return $cfdiRelacionado; } public function getEmisor(): Emisor { return $this->helperGetOrAdd(new Emisor()); } public function addEmisor(array $attributes = []): Emisor { $emisor = $this->getEmisor(); $emisor->addAttributes($attributes); return $emisor; } public function getReceptor(): Receptor { return $this->helperGetOrAdd(new Receptor()); } public function addReceptor(array $attributes = []): Receptor { $receptor = $this->getReceptor(); $receptor->addAttributes($attributes); return $receptor; } public function getPeriodo(): Periodo { return $this->helperGetOrAdd(new Periodo()); } public function addPeriodo(array $attributes = []): Periodo { $periodo = $this->getPeriodo(); $periodo->addAttributes($attributes); return $periodo; } public function getTotales(): Totales { return $this->helperGetOrAdd(new Totales()); } public function addTotales(array $attributes = []): Totales { $totales = $this->getTotales(); $totales->addAttributes($attributes); return $totales; } public function addImpRetenidos(array $attributes = []): ImpRetenidos { return $this->getTotales()->addImpRetenidos($attributes); } public function multiImpRetenidos(array ...$elementAttributes): self { $this->getTotales()->multiImpRetenidos(...$elementAttributes); return $this; } public function getComplemento(): Complemento { return $this->helperGetOrAdd(new Complemento()); } public function addComplemento(NodeInterface $children): self { $this->getComplemento()->add($children); return $this; } public function getAddenda(): Addenda { return $this->helperGetOrAdd(new Addenda()); } public function addAddenda(NodeInterface $children): self { $this->getAddenda()->add($children); return $this; } public function getChildrenOrder(): array { return [ 'retenciones:CfdiRetenRelacionados', 'retenciones:Emisor', 'retenciones:Receptor', 'retenciones:Periodo', 'retenciones:Totales', 'retenciones:Complemento', 'retenciones:Addenda', ]; } public function getFixedAttributes(): array { return [ 'xmlns:retenciones' => 'http://www.sat.gob.mx/esquemas/retencionpago/2', 'xmlns:xsi' => 'http://www.w3.org/2001/XMLSchema-instance', 'xsi:schemaLocation' => vsprintf('%s %s', [ 'http://www.sat.gob.mx/esquemas/retencionpago/2', 'http://www.sat.gob.mx/esquemas/retencionpago/2/retencionpagov2.xsd', ]), 'Version' => '2.0', ]; } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Elements/Nomina12/Deducciones.php
src/CfdiUtils/Elements/Nomina12/Deducciones.php
<?php namespace CfdiUtils\Elements\Nomina12; use CfdiUtils\Elements\Common\AbstractElement; class Deducciones extends AbstractElement { public function getElementName(): string { return 'nomina12:Deducciones'; } public function addDeduccion(array $attributes = []): Deduccion { $deduccion = new Deduccion($attributes); $this->addChild($deduccion); return $deduccion; } public function multiDeduccion(array ...$elementAttributes): self { foreach ($elementAttributes as $attributes) { $this->addDeduccion($attributes); } return $this; } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Elements/Nomina12/Percepciones.php
src/CfdiUtils/Elements/Nomina12/Percepciones.php
<?php namespace CfdiUtils\Elements\Nomina12; use CfdiUtils\Elements\Common\AbstractElement; class Percepciones extends AbstractElement { public function getElementName(): string { return 'nomina12:Percepciones'; } public function getChildrenOrder(): array { return [ 'nomina12:Percepcion', 'nomina12:JubilacionPensionRetiro', 'nomina12:SeparacionIndemnizacion', ]; } public function addPercepcion(array $attributes, array $children = []): Percepcion { $percepcion = new Percepcion($attributes, $children); $this->addChild($percepcion); return $percepcion; } public function multiPercepcion(array ...$elementAttributes): self { foreach ($elementAttributes as $attributes) { $this->addPercepcion($attributes); } return $this; } public function getJubilacionPensionRetiro(): JubilacionPensionRetiro { /** @noinspection PhpIncompatibleReturnTypeInspection */ return $this->helperGetOrAdd(new JubilacionPensionRetiro()); } public function addJubilacionPensionRetiro(array $attributes = []): JubilacionPensionRetiro { $jubilacionPensionRetiro = $this->getJubilacionPensionRetiro(); $jubilacionPensionRetiro->addAttributes($attributes); return $jubilacionPensionRetiro; } public function getSeparacionIndemnizacion(): SeparacionIndemnizacion { /** @noinspection PhpIncompatibleReturnTypeInspection */ return $this->helperGetOrAdd(new SeparacionIndemnizacion()); } public function addSeparacionIndemnizacion(array $attributes = []): SeparacionIndemnizacion { $separacionIndemnizacion = $this->getSeparacionIndemnizacion(); $separacionIndemnizacion->addAttributes($attributes); return $separacionIndemnizacion; } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Elements/Nomina12/JubilacionPensionRetiro.php
src/CfdiUtils/Elements/Nomina12/JubilacionPensionRetiro.php
<?php namespace CfdiUtils\Elements\Nomina12; use CfdiUtils\Elements\Common\AbstractElement; class JubilacionPensionRetiro extends AbstractElement { public function getElementName(): string { return 'nomina12:JubilacionPensionRetiro'; } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Elements/Nomina12/EntidadSNCF.php
src/CfdiUtils/Elements/Nomina12/EntidadSNCF.php
<?php namespace CfdiUtils\Elements\Nomina12; use CfdiUtils\Elements\Common\AbstractElement; class EntidadSNCF extends AbstractElement { public function getElementName(): string { return 'nomina12:EntidadSNCF'; } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Elements/Nomina12/HorasExtra.php
src/CfdiUtils/Elements/Nomina12/HorasExtra.php
<?php namespace CfdiUtils\Elements\Nomina12; use CfdiUtils\Elements\Common\AbstractElement; class HorasExtra extends AbstractElement { public function getElementName(): string { return 'nomina12:HorasExtra'; } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Elements/Nomina12/Receptor.php
src/CfdiUtils/Elements/Nomina12/Receptor.php
<?php namespace CfdiUtils\Elements\Nomina12; use CfdiUtils\Elements\Common\AbstractElement; class Receptor extends AbstractElement { public function getElementName(): string { return 'nomina12:Receptor'; } public function addSubContratacion(array $attributes = []): SubContratacion { $subContratacion = new SubContratacion($attributes); $this->addChild($subContratacion); return $subContratacion; } public function multiSubContratacion(array ...$elementAttributes): self { foreach ($elementAttributes as $attributes) { $this->addSubContratacion($attributes); } return $this; } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Elements/Nomina12/CompensacionSaldosAFavor.php
src/CfdiUtils/Elements/Nomina12/CompensacionSaldosAFavor.php
<?php namespace CfdiUtils\Elements\Nomina12; use CfdiUtils\Elements\Common\AbstractElement; class CompensacionSaldosAFavor extends AbstractElement { public function getElementName(): string { return 'nomina12:CompensacionSaldosAFavor'; } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false
eclipxe13/CfdiUtils
https://github.com/eclipxe13/CfdiUtils/blob/6786b3ee34831ef0d633302226414682a7a35aca/src/CfdiUtils/Elements/Nomina12/SubContratacion.php
src/CfdiUtils/Elements/Nomina12/SubContratacion.php
<?php namespace CfdiUtils\Elements\Nomina12; use CfdiUtils\Elements\Common\AbstractElement; class SubContratacion extends AbstractElement { public function getElementName(): string { return 'nomina12:SubContratacion'; } }
php
MIT
6786b3ee34831ef0d633302226414682a7a35aca
2026-01-05T04:57:52.988826Z
false