init commit
All checks were successful
build-api-image / build (push) Successful in 51s

This commit is contained in:
Antonio Lopes dos Santos
2026-08-04 16:52:02 -03:00
commit afec302c3e
11594 changed files with 1636728 additions and 0 deletions

View File

@@ -0,0 +1,32 @@
<?php
namespace App\Utils\AtencaoBasica;
class EsusUtil
{
/**
* @return string
*/
public static function v4UUID()
{
return sprintf(
'%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
// 32 bits for "time_low"
mt_rand(0, 0xffff),
mt_rand(0, 0xffff),
// 16 bits for "time_mid"
mt_rand(0, 0xffff),
// 16 bits for "time_hi_and_version",
// four most significant bits holds version number 4
mt_rand(0, 0x0fff) | 0x4000,
// 16 bits, 8 bits for "clk_seq_hi_res",
// 8 bits for "clk_seq_low",
// two most significant bits holds zero and one for variant DCE1.1
mt_rand(0, 0x3fff) | 0x8000,
// 48 bits for "node"
mt_rand(0, 0xffff),
mt_rand(0, 0xffff),
mt_rand(0, 0xffff)
);
}
}

View File

@@ -0,0 +1,20 @@
<?php
namespace App\Utils\Calculations;
class Week
{
public static function sub(int $minuendo, int $subtraendo): int
{
$result = $minuendo - $subtraendo;
return $result < 1 ? 7 - abs($result) : $result;
}
public static function sum(int $firstPortion, int $secondPortion): int
{
$result = $firstPortion + $secondPortion;
return $result > 7 ? $result - 7 : $result;
}
}

View File

@@ -0,0 +1,16 @@
<?php
namespace App\Utils;
class ComposerJson
{
public static function getVersion()
{
return self::getJson()->version;
}
public static function getJson()
{
return json_decode(file_get_contents(base_path('composer.json')));
}
}

View File

@@ -0,0 +1,36 @@
<?php
namespace App\Utils;
class ConversaoUnidadeMedidaUtil
{
public static function gramasParaQuilogramas($gramas)
{
return $gramas / 1000;
}
public static function quilogramasParaGramas($quilogramas)
{
return $quilogramas * 1000;
}
public static function centimetrosParaMetros($centimetros)
{
return $centimetros / 100;
}
public static function metrosParaCentimetros($metros)
{
return $metros * 100;
}
public static function milimetrosDeMercurioParaCentimetrosDeMercurio($milimetrosDeMercurio)
{
return $milimetrosDeMercurio / 10;
}
public static function centimetrosDeMercurioParaMilimetrosDeMercurio($centimetrosDeMercurio)
{
return $centimetrosDeMercurio * 10;
}
}

91
api/app/Utils/Crypt.php Normal file
View File

@@ -0,0 +1,91 @@
<?php
namespace App\Utils;
class Crypt
{
private static $key = 'd82499ef6072d87a2f547ba57aa38825';
private static $rounds = 1001;
private static $customCharset = '-._~0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
public static function XORCrypt($text)
{
$data = self::addPadding($text, 32);
$encryptedData = self::convertToCustomCharset($data);
$key = self::convertToCustomCharset(self::$key);
$keyLength = strlen($key);
for ($j = 0; $j < self::$rounds; $j++) {
$encryptedData = strrev($encryptedData);
$start = ($j * 12) % $keyLength;
$keyPart = substr($key, $start, 12);
$encryptedData = self::applyXOREncryption($encryptedData, $keyPart);
}
return $encryptedData;
}
private static function addPadding($text, $blockSize)
{
$paddingLength = $blockSize - (strlen($text) % $blockSize) - 1;
$padding = self::generateRandomPadding($paddingLength);
return $text . '.' . $padding;
}
private static function convertToCustomCharset($inputString)
{
$output = '';
for ($i = 0; $i < strlen($inputString); $i++) {
$char = $inputString[$i];
$charIndex = strpos(self::$customCharset, $char);
if ($charIndex === false) {
$output .= '~';
} else {
$output .= $char;
}
}
return $output;
}
private static function generateRandomPadding($length)
{
$padding = '';
$charsetLength = strlen(self::$customCharset);
for ($i = 0; $i < $length; $i++) {
$randomIndex = rand(0, $charsetLength - 1);
$padding .= self::$customCharset[$randomIndex];
}
return $padding;
}
private static function applyXOREncryption($data, $key, $decrypt = false)
{
$result = '';
$keyLength = strlen($key);
$charsetLength = strlen(self::$customCharset);
for ($i = 0; $i < strlen($data); $i++) {
$char = $data[$i];
$keyChar = $key[$i % $keyLength];
$charIndex = strpos(self::$customCharset, $char);
$keyIndex = strpos(self::$customCharset, $keyChar);
if ($charIndex !== false && $keyIndex !== false) {
$encryptedIndex = $decrypt ? ($charIndex - $keyIndex + $charsetLength) % $charsetLength : ($charIndex + $keyIndex) % $charsetLength;
$result .= self::$customCharset[$encryptedIndex];
} else {
$result .= '~';
}
}
return $result;
}
}

View File

@@ -0,0 +1,58 @@
<?php
namespace App\Utils;
use Illuminate\Support\Str;
class DataUtil
{
public static function isStringBoolean($string)
{
return !is_null($string) && !is_null(filter_var($string, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE));
}
public static function isStringTrue($string)
{
return !is_null($string) && filter_var($string, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE) === true;
}
public static function isStringFalse($string)
{
return !is_null($string) && filter_var($string, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE) === false;
}
public static function getBooleanValueFromStringBoolean($string)
{
return filter_var($string, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
}
public static function hasData(?array $data)
{
if (is_null($data)) {
return false;
}
foreach ($data as $item) {
if (isset($item)) {
return true;
}
}
return false;
}
public static function getSimOuNao(?bool $isTrue, bool $uppercase = false)
{
$response = $isTrue ? 'Sim' : 'Não';
if ($uppercase) {
$response = Str::upper($response);
}
return $response;
}
}

View File

@@ -0,0 +1,37 @@
<?php
namespace App\Utils;
use DateTime;
class DateTimeUtil
{
public static function isDate($string)
{
$string = str_replace('/', '-', $string);
$stamp = strtotime($string);
if (is_numeric($stamp)) {
$month = date('m', $stamp);
$day = date('d', $stamp);
$year = date('Y', $stamp);
return checkdate($month, $day, $year);
}
return false;
}
public static function isFormattedCorrectly($date, $format = 'Y-m-d H:i:s')
{
if (self::isDate($date)) {
$createdDate = DateTime::createFromFormat($format, $date);
return $createdDate && $createdDate->format($format) === $date;
}
return false;
}
}

13
api/app/Utils/Email.php Normal file
View File

@@ -0,0 +1,13 @@
<?php
namespace App\Utils;
use Illuminate\Support\Facades\Mail;
class Email
{
public static function enviar($to, $subject)
{
Mail::to($to)->send($subject);
}
}

View File

@@ -0,0 +1,55 @@
<?php
namespace App\Utils\Exports;
use Dompdf\Dompdf;
use Dompdf\Options;
class Pdf
{
private Dompdf $dompdf;
public function __construct(Options $options = null)
{
$this->dompdf = new Dompdf($options ?? $this->getDefaultOptions());
$this->setPaper('A4', 'portrait');
}
private function getDefaultOptions() : Options
{
$options = new Options;
$options->set('isPhpEnabled', true);
return $options;
}
public function setPaper(string $type, string $orientation) : void
{
$this->dompdf->setPaper($type, $orientation);
}
public function stream(string $html, string $fileName = 'documento')
{
$this->dompdf->loadHtml($html);
$this->dompdf->render();
return response()->streamDownload(
function () {
echo $this->dompdf->output();
},
"{$fileName}.pdf",
['Content-Type' => 'Application/pdf']
);
}
public function output(string $html)
{
$this->dompdf->loadHtml($html);
$this->dompdf->render();
return $this->dompdf->output();
}
}

View File

@@ -0,0 +1,99 @@
<?php
namespace App\Utils\Exports;
use App\Models\Cadastro\SujeitoAtencao\Lotacao;
use App\Models\Intranet\Cliente;
use App\Utils\ComposerJson;
use App\Utils\MaskUtil;
use Barryvdh\Snappy\Facades\SnappyPdf;
use Carbon\Carbon;
class Pdf1
{
private const TEMPLATE_BASE_NAME = 'impressoes.template.';
private static function getCustomerData()
{
$cliente = Cliente::where('link', app('config')->get('database.default'))
->where('sistema_id', 1)
->firstOrFail();
$lotacao = Lotacao::findOrFail(auth()->payload()->get('lotacao_id'));
return [
'cliente' => [
'sistema' => [
'ramo_atividade' => [
'nome' => $cliente->sistema->ramoAtividade->nome ?? null,
],
'nome' => $cliente->sistema->nome ?? null,
'versao' => ComposerJson::getVersion(),
],
'municipio' => [
'estado' => [
'uf' => $cliente->municipio->estado->uf ?? null,
],
'nome' => $cliente->municipio->nome ?? null,
],
'nome' => $cliente->nome ?? null,
'email' => $cliente->email ?? null,
'site' => $cliente->site ?? null,
'logotipo' => $cliente->logotipo ? base64_encode(file_get_contents(storage_path('app/intranet/cliente/logotipo/' . $cliente->logotipo))) : null,
],
'infraestrutura' => [
'unidade' => [
'nome_fantasia' => $lotacao->infraestrutura->unidade->nome_fantasia ?? null,
'cnes' => $lotacao->infraestrutura->unidade->cnes ?? null,
],
'endereco' => [
'logradouro' => [
'municipio' => [
'estado' => [
'uf' => $lotacao->infraestrutura->endereco->logradouro->municipio->estado->uf ?? null,
],
'nome' => $lotacao->infraestrutura->endereco->logradouro->municipio->nome ?? null,
],
'bairro' => [
'nome' => $lotacao->infraestrutura->endereco->logradouro->bairro->nome ?? null,
],
'tipo' => [
'descricao' => $lotacao->infraestrutura->endereco->logradouro->tipo->descricao ?? null,
],
'nome' => $lotacao->infraestrutura->endereco->logradouro->nome ?? null,
'cep' => MaskUtil::getCepMasked($lotacao->infraestrutura->endereco->logradouro->cep) ?? null,
],
'numero' => $lotacao->infraestrutura->endereco->numero ?? null,
'referencia' => $lotacao->infraestrutura->endereco->referencia ?? null,
],
'telefone' => MaskUtil::getPhoneMasked($lotacao->infraestrutura->telefone) ?? null,
],
'usuario' => [
'cidadao' => [
'nome' => $lotacao->usuario->cidadao->nome ?? null,
'nome' => $lotacao->usuario->cidadao->nome ?? null,
]
],
'data_impressao' => Carbon::now()->format('d/m/Y H:i:s')
];
}
public static function generate($title, $template, $data, $orientation = 'portrait')
{
$data = array_merge($data, ['title' => $title], ['_data' => self::getCustomerData()]);
$snappyPdf = SnappyPdf::loadView(self::TEMPLATE_BASE_NAME . $template, $data)
->setOption('footer-html', view('impressoes.layout1.footer', $data)->render())
->setOption('header-html', view('impressoes.layout1.header', $data)->render())
->setOption('margin-bottom', 18)
->setOption('margin-left', 2)
->setOption('margin-right', 2)
->setOption('margin-top', 27)
->setPaper('a4')
->setOrientation($orientation);
$snappyPdf->setTimeout(300);
return $snappyPdf->inline();
}
}

View File

@@ -0,0 +1,97 @@
<?php
namespace App\Utils\Exports;
use App\Models\Cadastro\SujeitoAtencao\Lotacao;
use App\Models\Intranet\Cliente;
use App\Utils\ComposerJson;
use App\Utils\MaskUtil;
use Barryvdh\Snappy\Facades\SnappyPdf;
use Carbon\Carbon;
class Pdf1Externo
{
private const TEMPLATE_BASE_NAME = 'impressoes.template.';
private static function getCustomerData()
{
$cliente = Cliente::where('link', app('config')->get('database.default'))
->where('sistema_id', 1)
->firstOrFail();
return [
'cliente' => [
'sistema' => [
'ramo_atividade' => [
'nome' => $cliente->sistema->ramoAtividade->nome ?? null,
],
'nome' => $cliente->sistema->nome ?? null,
'versao' => ComposerJson::getVersion(),
],
'municipio' => [
'estado' => [
'uf' => $cliente->municipio->estado->uf ?? null,
],
'nome' => $cliente->municipio->nome ?? null,
],
'nome' => $cliente->nome ?? null,
'email' => $cliente->email ?? null,
'site' => $cliente->site ?? null,
'logotipo' => $cliente->logotipo ? base64_encode(file_get_contents(storage_path('app/intranet/cliente/logotipo/' . $cliente->logotipo))) : null,
],
'infraestrutura' => [
'unidade' => [
'nome_fantasia' => null,
'cnes' => null,
],
'endereco' => [
'logradouro' => [
'municipio' => [
'estado' => [
'uf' => null,
],
'nome' => null,
],
'bairro' => [
'nome' => null,
],
'tipo' => [
'descricao' => null,
],
'nome' => null,
'cep' => null,
],
'numero' => null,
'referencia' => null,
],
'telefone' => null,
],
'usuario' => [
'cidadao' => [
'nome' => null,
'nome' => null,
]
],
'data_impressao' => Carbon::now()->format('d/m/Y H:i:s')
];
}
public static function generate($title, $template, $data, $orientation = 'portrait')
{
$data = array_merge($data, ['title' => $title], ['_data' => self::getCustomerData()]);
$snappyPdf = SnappyPdf::loadView(self::TEMPLATE_BASE_NAME . $template, $data)
->setOption('footer-html', view('impressoes.layout1.footer', $data)->render())
->setOption('header-html', view('impressoes.layout1.header', $data)->render())
->setOption('margin-bottom', 18)
->setOption('margin-left', 2)
->setOption('margin-right', 2)
->setOption('margin-top', 27)
->setPaper('a4')
->setOrientation($orientation);
return $snappyPdf->inline();
}
}

View File

@@ -0,0 +1,97 @@
<?php
namespace App\Utils\Exports;
use App\Models\Cadastro\SujeitoAtencao\Lotacao;
use App\Models\Intranet\Cliente;
use App\Utils\ComposerJson;
use App\Utils\MaskUtil;
use Barryvdh\Snappy\Facades\SnappyPdf;
use Carbon\Carbon;
class PdfAtendimento
{
private const TEMPLATE_BASE_NAME = 'impressoes.template.';
private static function getCustomerData()
{
$cliente = Cliente::where('link', app('config')->get('database.default'))
->where('sistema_id', 1)
->firstOrFail();
$lotacao = Lotacao::findOrFail(auth()->payload()->get('lotacao_id'));
return [
'cliente' => [
'sistema' => [
'ramo_atividade' => [
'nome' => $cliente->sistema->ramoAtividade->nome ?? null,
],
'nome' => $cliente->sistema->nome ?? null,
'versao' => ComposerJson::getVersion(),
],
'municipio' => [
'estado' => [
'uf' => $cliente->municipio->estado->uf ?? null,
],
'nome' => $cliente->municipio->nome ?? null,
],
'nome' => $cliente->nome ?? null,
'email' => $cliente->email ?? null,
'site' => $cliente->site ?? null,
'logotipo' => $cliente->logotipo ? base64_encode(file_get_contents(storage_path('app/intranet/cliente/logotipo/' . $cliente->logotipo))) : null,
],
'infraestrutura' => [
'unidade' => [
'nome_fantasia' => $lotacao->infraestrutura->unidade->nome_fantasia ?? null,
'cnes' => $lotacao->infraestrutura->unidade->cnes ?? null,
],
'endereco' => [
'logradouro' => [
'municipio' => [
'estado' => [
'uf' => $lotacao->infraestrutura->endereco->logradouro->municipio->estado->uf ?? null,
],
'nome' => $lotacao->infraestrutura->endereco->logradouro->municipio->nome ?? null,
],
'bairro' => [
'nome' => $lotacao->infraestrutura->endereco->logradouro->bairro->nome ?? null,
],
'tipo' => [
'descricao' => $lotacao->infraestrutura->endereco->logradouro->tipo->descricao ?? null,
],
'nome' => $lotacao->infraestrutura->endereco->logradouro->nome ?? null,
'cep' => MaskUtil::getCepMasked($lotacao->infraestrutura->endereco->logradouro->cep) ?? null,
],
'numero' => $lotacao->infraestrutura->endereco->numero ?? null,
'referencia' => $lotacao->infraestrutura->endereco->referencia ?? null,
],
'telefone' => MaskUtil::getPhoneMasked($lotacao->infraestrutura->telefone) ?? null,
],
'usuario' => [
'cidadao' => [
'nome' => $lotacao->usuario->cidadao->nome ?? null,
'nome' => $lotacao->usuario->cidadao->nome ?? null,
]
],
'data_impressao' => Carbon::now()->format('d/m/Y H:i:s')
];
}
public static function generate($title, $template, $data, $orientation = 'portrait')
{
$data = array_merge($data, ['title' => $title], ['_data' => self::getCustomerData()]);
$snappyPdf = SnappyPdf::loadView(self::TEMPLATE_BASE_NAME . $template, $data)
->setOption('footer-html', view('impressoes.layout-atendimento.footer', $data)->render())
->setOption('header-html', view('impressoes.layout-atendimento.header', $data)->render())
->setOption('margin-bottom', 17)
->setOption('margin-left', 2)
->setOption('margin-right', 2)
->setOption('margin-top', 43)
->setPaper('a4')
->setOrientation($orientation);
return $snappyPdf->inline();
}
}

View File

@@ -0,0 +1,91 @@
<?php
namespace App\Utils\Exports;
use App\Models\Cadastro\SujeitoAtencao\Lotacao;
use App\Models\Intranet\Cliente;
use App\Utils\ComposerJson;
use App\Utils\MaskUtil;
use Barryvdh\Snappy\Facades\SnappyPdf;
use Carbon\Carbon;
class PdfCupom
{
private const TEMPLATE_BASE_NAME = 'impressoes.template.';
private static function getCustomerData()
{
$cliente = Cliente::where('link', app('config')->get('database.default'))->firstOrFail();
$lotacao = Lotacao::findOrFail(auth()->payload()->get('lotacao_id'));
return [
'cliente' => [
'sistema' => [
'ramo_atividade' => [
'nome' => $cliente->sistema->ramoAtividade->nome ?? null,
],
'nome' => $cliente->sistema->nome ?? null,
'versao' => ComposerJson::getVersion(),
],
'municipio' => [
'estado' => [
'uf' => $cliente->municipio->estado->uf ?? null,
],
'nome' => $cliente->municipio->nome ?? null,
],
'nome' => $cliente->nome ?? null,
'email' => $cliente->email ?? null,
'site' => $cliente->site ?? null,
'logotipo' => $cliente->logotipo ? base64_encode(file_get_contents(storage_path('app/intranet/cliente/logotipo/' . $cliente->logotipo))) : null,
],
'infraestrutura' => [
'unidade' => [
'nome_fantasia' => $lotacao->infraestrutura->unidade->nome_fantasia ?? null,
'cnes' => $lotacao->infraestrutura->unidade->cnes ?? null,
],
'endereco' => [
'logradouro' => [
'municipio' => [
'estado' => [
'uf' => $lotacao->infraestrutura->endereco->logradouro->municipio->estado->uf ?? null,
],
'nome' => $lotacao->infraestrutura->endereco->logradouro->municipio->nome ?? null,
],
'bairro' => [
'nome' => $lotacao->infraestrutura->endereco->logradouro->bairro->nome ?? null,
],
'tipo' => [
'descricao' => $lotacao->infraestrutura->endereco->logradouro->tipo->descricao ?? null,
],
'nome' => $lotacao->infraestrutura->endereco->logradouro->nome ?? null,
'cep' => MaskUtil::getCepMasked($lotacao->infraestrutura->endereco->logradouro->cep) ?? null,
],
'numero' => $lotacao->infraestrutura->endereco->numero ?? null,
'referencia' => $lotacao->infraestrutura->endereco->referencia ?? null,
],
'telefone' => MaskUtil::getPhoneMasked($lotacao->infraestrutura->telefone) ?? null,
],
'usuario' => [
'cidadao' => [
'nome' => $lotacao->usuario->cidadao->nome ?? null,
'nome_social' => $lotacao->usuario->cidadao->nome_social ?? null,
]
],
'data_impressao' => Carbon::now()->format('d/m/Y H:i:s')
];
}
public static function generate($title, $template, $data)
{
$data = array_merge($data, ['title' => $title], ['_data' => self::getCustomerData()]);
return SnappyPdf::loadView(self::TEMPLATE_BASE_NAME . $template, $data)
->setOption('header-html', view('impressoes.layout-cupom.header', $data)->render())
->setOption('margin-bottom', 25)
->setOption('margin-left', 2)
->setOption('margin-right', 2)
->setOption('margin-top', 33)
->setPaper('a4')
->inline();
}
}

View File

@@ -0,0 +1,91 @@
<?php
namespace App\Utils\Exports;
use App\Models\Cadastro\SujeitoAtencao\Lotacao;
use App\Models\Intranet\Cliente;
use App\Utils\ComposerJson;
use App\Utils\MaskUtil;
use Barryvdh\Snappy\Facades\SnappyPdf;
use Carbon\Carbon;
class PdfEtiqueta
{
private const TEMPLATE_BASE_NAME = 'impressoes.template.';
private static function getCustomerData()
{
$cliente = Cliente::where('link', app('config')->get('database.default'))->firstOrFail();
$lotacao = Lotacao::findOrFail(auth()->payload()->get('lotacao_id'));
return [
'cliente' => [
'sistema' => [
'ramo_atividade' => [
'nome' => $cliente->sistema->ramoAtividade->nome ?? null,
],
'nome' => $cliente->sistema->nome ?? null,
'versao' => ComposerJson::getVersion(),
],
'municipio' => [
'estado' => [
'uf' => $cliente->municipio->estado->uf ?? null,
],
'nome' => $cliente->municipio->nome ?? null,
],
'nome' => $cliente->nome ?? null,
'email' => $cliente->email ?? null,
'site' => $cliente->site ?? null,
'logotipo' => $cliente->logotipo ? base64_encode(file_get_contents(storage_path('app/intranet/cliente/logotipo/' . $cliente->logotipo))) : null,
],
'infraestrutura' => [
'unidade' => [
'nome_fantasia' => $lotacao->infraestrutura->unidade->nome_fantasia ?? null,
'cnes' => $lotacao->infraestrutura->unidade->cnes ?? null,
],
'endereco' => [
'logradouro' => [
'municipio' => [
'estado' => [
'uf' => $lotacao->infraestrutura->endereco->logradouro->municipio->estado->uf ?? null,
],
'nome' => $lotacao->infraestrutura->endereco->logradouro->municipio->nome ?? null,
],
'bairro' => [
'nome' => $lotacao->infraestrutura->endereco->logradouro->bairro->nome ?? null,
],
'tipo' => [
'descricao' => $lotacao->infraestrutura->endereco->logradouro->tipo->descricao ?? null,
],
'nome' => $lotacao->infraestrutura->endereco->logradouro->nome ?? null,
'cep' => MaskUtil::getCepMasked($lotacao->infraestrutura->endereco->logradouro->cep) ?? null,
],
'numero' => $lotacao->infraestrutura->endereco->numero ?? null,
'referencia' => $lotacao->infraestrutura->endereco->referencia ?? null,
],
'telefone' => MaskUtil::getPhoneMasked($lotacao->infraestrutura->telefone) ?? null,
],
'usuario' => [
'cidadao' => [
'nome' => $lotacao->usuario->cidadao->nome ?? null,
'nome' => $lotacao->usuario->cidadao->nome ?? null,
]
],
'data_impressao' => Carbon::now()->format('d/m/Y H:i:s')
];
}
public static function generate($template, $data)
{
$data = array_merge($data, ['_data' => self::getCustomerData()]);
return SnappyPdf::loadView(self::TEMPLATE_BASE_NAME . $template, $data)
->setOption('header-html', view('impressoes.layout-etiqueta.header', $data)->render())
->setOption('margin-bottom', 25)
->setOption('margin-left', 2)
->setOption('margin-right', 2)
->setOption('margin-top', 10)
->setPaper('a4')
->inline();
}
}

View File

@@ -0,0 +1,33 @@
<?php
namespace App\Utils\Exports;
use setasign\Fpdi\Fpdi;
use setasign\Fpdi\PdfParser\StreamReader;
class PhpMerge
{
public static function mergePdfDocuments($documentTitle, $pdfContents)
{
$pdf = new Fpdi();
foreach ($pdfContents as $pdfContent) {
$streamReader = StreamReader::createByString($pdfContent['data']);
$pageCount = $pdf->setSourceFile($streamReader);
for ($pageNo = 1; $pageNo <= $pageCount; $pageNo++) {
$templateId = $pdf->importPage($pageNo);
$pdf->AddPage($pdfContent['orientation'], 'A4');
$pdf->useTemplate($templateId);
}
}
return response($pdf->Output($documentTitle . '.pdf', 'S'))
->header('Content-Type', 'application/pdf')
->header('Content-Disposition', 'inline; filename="' . $documentTitle . '.pdf"')
->header('Cache-Control', 'no-cache, no-store, must-revalidate')
->header('Pragma', 'no-cache')
->header('Expires', '0');
}
}

View File

@@ -0,0 +1,140 @@
<?php
namespace App\Utils\Exports;
use App\Models\Cadastro\SujeitoAtencao\Lotacao;
use App\Models\Intranet\Cliente;
use App\Utils\ComposerJson;
use App\Utils\MaskUtil;
use Carbon\Carbon;
class Template
{
private const TEMPLATE_BASE_NAME = 'impressoes.template.';
private string $title;
private string $subtitle;
private string $template;
private array $data;
private bool $duplicate;
public static function make(string $title, string $template, $duplicate = false) : Template
{
return new self($title, $template, $duplicate);
}
private function __construct(string $title, string $template, $duplicate = false)
{
$this->title = trim($title);
$this->template = self::TEMPLATE_BASE_NAME . trim(trim(trim($template), '.'));
$this->duplicate = $duplicate;
}
public function withSubtitle(string $subtitle) : Template
{
$this->subtitle = trim($subtitle);
return $this;
}
public function withData(array $data) : Template
{
$this->data = $data;
return $this;
}
public function appendData(array $data) : Template
{
$this->data = array_merge($this->data, $data);
return $this;
}
public function getHtml()
{
$this->setGeneralData();
return view($this->template, $this->data)->render();
}
private function setGeneralData() : void
{
$data = [
'dataAtual' => [
'porExtenso' => Carbon::now()->translatedFormat('d \de F \de Y'),
],
'titulo' => $this->title,
'duplicate' => $this->duplicate,
];
if (!empty($this->subtitle)) {
$data['subtitulo'] = $this->subtitle;
}
$this->data['_data'] = array_merge($data, $this->getCustomerData());
}
private function getCustomerData() : array
{
$cliente = Cliente::where('link', app('config')->get('database.default'))->firstOrFail();
$lotacao = Lotacao::findOrFail(auth()->payload()->get('lotacao_id'));
return [
'cliente' => [
'sistema' => [
'ramo_atividade' => [
'nome' => $cliente->sistema->ramoAtividade->nome ?? null,
],
'nome' => $cliente->sistema->nome ?? null,
'versao' => ComposerJson::getVersion(),
],
'municipio' => [
'estado' => [
'uf' => $cliente->municipio->estado->uf ?? null,
],
'nome' => $cliente->municipio->nome ?? null,
],
'nome' => $cliente->nome ?? null,
'email' => $cliente->email ?? null,
'site' => $cliente->site ?? null,
'logotipo' => $cliente->logotipo ? base64_encode(file_get_contents(storage_path('app/intranet/cliente/logotipo/' . $cliente->logotipo))) : null,
],
'infraestrutura' => [
'unidade' => [
'nome_fantasia' => $lotacao->infraestrutura->unidade->nome_fantasia ?? null,
'cnes' => $lotacao->infraestrutura->unidade->cnes ?? null,
],
'endereco' => [
'logradouro' => [
'municipio' => [
'estado' => [
'uf' => $lotacao->infraestrutura->endereco->logradouro->municipio->estado->uf ?? null,
],
'nome' => $lotacao->infraestrutura->endereco->logradouro->municipio->nome ?? null,
],
'bairro' => [
'nome' => $lotacao->infraestrutura->endereco->logradouro->bairro->nome ?? null,
],
'tipo' => [
'descricao' => $lotacao->infraestrutura->endereco->logradouro->tipo->descricao ?? null,
],
'nome' => $lotacao->infraestrutura->endereco->logradouro->nome ?? null,
'cep' => MaskUtil::getCepMasked($lotacao->infraestrutura->endereco->logradouro->cep) ?? null,
],
'numero' => $lotacao->infraestrutura->endereco->numero ?? null,
'referencia' => $lotacao->infraestrutura->endereco->referencia ?? null,
],
'telefone' => MaskUtil::getPhoneMasked($lotacao->infraestrutura->telefone) ?? null,
],
'usuario' => [
'cidadao' => [
'nome' => $lotacao->usuario->cidadao->nome ?? null,
'nome' => $lotacao->usuario->cidadao->nome ?? null,
]
],
'data_impressao' => Carbon::now()->format('d/m/Y H:i:s')
];
}
}

20
api/app/Utils/Format.php Normal file
View File

@@ -0,0 +1,20 @@
<?php
namespace App\Utils;
class Format
{
public static function getProcedimentoFormated($procedimento)
{
return preg_replace(
'/(\d{2})(\d{2})(\d{2})(\d{3})(\d{1})/',
'$1.$2.$3.$4-$5',
self::getOnlyDigits($procedimento)
);
}
public static function getOnlyDigits(&$value)
{
return preg_replace('/[^\d]/', '', (string) $value);
}
}

View File

@@ -0,0 +1,11 @@
<?php
namespace App\Utils;
class ImportacaoCns
{
public static function regexValidacao()
{
return '/[^a-zA-Z0-9áéíóúâêîôûãõäëïöüçÁÉÍÓÚÂÊÎÔÛÃÕÄËÏÖÜÇ\'()\/,\s-]/';
}
}

186
api/app/Utils/MaskUtil.php Normal file
View File

@@ -0,0 +1,186 @@
<?php
namespace App\Utils;
use App\Enums\Geral\DocumentoTipo;
class MaskUtil
{
private const DOCUMENT_TYPES = [
DocumentoTipo::CNPJ => 'Cnpj',
DocumentoTipo::CPF => 'Cpf',
DocumentoTipo::RG => 'Rg',
DocumentoTipo::CNH => 'Cnh',
DocumentoTipo::CNS => 'Cns',
];
public static function getDocumentMasked(int $documentoTipoId, $numero)
{
return self::{'get' . self::DOCUMENT_TYPES[$documentoTipoId] . 'Masked'}($numero);
}
public static function getCpfMasked($cpf)
{
return preg_replace(
'/(\d{3})(\d{3})(\d{3})(\d{2})/',
'$1.$2.$3-$4',
self::getOnlyDigits($cpf)
);
}
public static function getCnpjMasked($cnpj)
{
return preg_replace(
'/(\d{2})(\d{3})(\d{3})(\d{4})(\d{2})/',
'$1.$2.$3/$4-$5',
self::getOnlyDigits($cnpj)
);
}
public static function getCnhMasked($cnh)
{
return $cnh;
}
public static function getCnsMasked($cns)
{
return preg_replace(
'/(\d{3})(\d{4})(\d{4})(\d{4})/',
'$1 $2 $3 $4',
self::getOnlyDigits($cns)
);
}
public static function getDnvMasked($cns)
{
return preg_replace(
'/(\d{2})(\d{8})(\d{1})/',
'$1-$2-$3',
self::getOnlyDigits($cns)
);
}
public static function getOnlyDigits(&$value)
{
return preg_replace('/[^\d]/', '', (string) $value);
}
public static function getPhoneMasked($number)
{
$number = self::getOnlyDigits($number);
switch (strlen($number)) {
case 10: {
return preg_replace(
'/(\d{2})(\d{4})(\d{4})/',
'($1) $2-$3',
$number
);
}
case 11: {
return preg_replace(
'/(\d{2})(\d{5})(\d{4})/',
'($1) $2-$3',
$number
);
}
default: {
return $number;
}
}
}
public static function getCepMasked($cep)
{
return preg_replace(
'/(\d{2})(\d{3})(\d{3})/',
'$1.$2-$3',
self::getOnlyDigits($cep)
);
}
public static function getNumeroCertidaoMasked($numero)
{
return preg_replace(
'/(\d{6})(\d{2})(\d{2})(\d{4})(\d{1})(\d{5})(\d{3})(\d{7})(\d{2})/',
'$1 $2 $3 $4 $5 $6 $7 $8 $9',
self::getOnlyDigits($numero)
);
}
public static function getProcedimentoMasked($procedimento)
{
return preg_replace(
'/(\d{2})(\d{2})(\d{2})(\d{3})(\d{1})/',
'$1.$2.$3.$4-$5',
$procedimento
);
}
public static function getCidMasked($cid)
{
return preg_replace(
'/(\w{3})(\w{1})/',
'$1.$2',
$cid
);
}
public static function getRgMasked($rg)
{
return $rg;
}
public static function getNumeroAutorizacaoFornecimentoMasked($numero)
{
return preg_replace(
'/(\d{5})(\d{4})/',
'$1/$2',
self::getOnlyDigits($numero)
);
}
public static function getPlacaMasked($placa)
{
return preg_replace(
'/([A-Z]{3})(([0-9]{4})|([0-1]{1}[A-Z]{1}[0-9]{2}))/',
'$1-$2',
self::getDataUnmasked($placa)
);
}
public static function getDataUnmasked($value)
{
return preg_replace('/[^\w]/', '', (string) $value);
}
public static function maskNome($nome)
{
$partes = preg_split('/\s+/', trim($nome));
$primeiro = array_shift($partes);
$iniciais = array_map(fn($p) => mb_substr($p, 0, 1) . '.', $partes);
return (substr($primeiro, 0, 3) . (strlen($primeiro) > 3 ? '.' : '')) . (count($iniciais) ? ' ' . implode(' ', $iniciais) : '');
}
public static function maskDocumento($valor)
{
if (empty($valor)) return null;
$tamanho = strlen($valor);
if ($tamanho <= 5) {
return $valor;
}
$inicio = substr($valor, 0, 3);
$fim = substr($valor, -2);
$oculto = str_repeat('*', $tamanho - 5);
return $inicio . $oculto . $fim;
}
}

View File

@@ -0,0 +1,26 @@
<?php
namespace App\Utils;
class MesesAnoUtil
{
public static function getNomeMes($numeroMes) : string
{
$meses = [
1 => 'JANEIRO',
2 => 'FEVEREIRO',
3 => 'MARÇO',
4 => 'ABRIL',
5 => 'MAIO',
6 => 'JUNHO',
7 => 'JULHO',
8 => 'AGOSTO',
9 => 'SETEMBRO',
10 => 'OUTUBRO',
11 => 'NOVEMBRO',
12 => 'DEZEMBRO'
];
return $meses[$numeroMes] ?? 'MÊS INVÁLIDO';
}
}

View File

@@ -0,0 +1,107 @@
<?php
namespace App\Utils;
class NumericUtil
{
public static function getPorExtenso(int $valor, array $params = [])
{
$bolExibirMoeda = $params['exibirMoeda'] ?? false;
$bolPalavraFeminina = $params['isPalavraFeminina'] ?? false;
$valor = self::removerFormatacaoNumero($valor);
$singular = null;
$plural = null;
if ( $bolExibirMoeda )
{
$singular = array("centavo", "real", "mil", "milhão", "bilhão", "trilhão", "quatrilhão");
$plural = array("centavos", "reais", "mil", "milhões", "bilhões", "trilhões","quatrilhões");
}
else
{
$singular = array("", "", "mil", "milhão", "bilhão", "trilhão", "quatrilhão");
$plural = array("", "", "mil", "milhões", "bilhões", "trilhões","quatrilhões");
}
$c = array("", "cem", "duzentos", "trezentos", "quatrocentos","quinhentos", "seiscentos", "setecentos", "oitocentos", "novecentos");
$d = array("", "dez", "vinte", "trinta", "quarenta", "cinquenta","sessenta", "setenta", "oitenta", "noventa");
$d10 = array("dez", "onze", "doze", "treze", "quatorze", "quinze","dezesseis", "dezesete", "dezoito", "dezenove");
$u = array("", "um", "dois", "três", "quatro", "cinco", "seis","sete", "oito", "nove");
if ( $bolPalavraFeminina )
{
if ($valor == 1)
$u = array("", "uma", "duas", "três", "quatro", "cinco", "seis","sete", "oito", "nove");
else
$u = array("", "um", "duas", "três", "quatro", "cinco", "seis","sete", "oito", "nove");
$c = array("", "cem", "duzentas", "trezentas", "quatrocentas","quinhentas", "seiscentas", "setecentas", "oitocentas", "novecentas");
}
$z = 0;
$valor = number_format( $valor, 2, ".", "." );
$inteiro = explode( ".", $valor );
for ( $i = 0; $i < count( $inteiro ); $i++ )
for ( $ii = mb_strlen( $inteiro[$i] ); $ii < 3; $ii++ )
$inteiro[$i] = "0" . $inteiro[$i];
// $fim identifica onde que deve se dar junção de centenas por "e" ou por "," ;)
$rt = null;
$fim = count( $inteiro ) - ($inteiro[count( $inteiro ) - 1] > 0 ? 1 : 2);
for ( $i = 0; $i < count( $inteiro ); $i++ )
{
$valor = $inteiro[$i];
$rc = (($valor > 100) && ($valor < 200)) ? "cento" : $c[$valor[0]];
$rd = ($valor[1] < 2) ? "" : $d[$valor[1]];
$ru = ($valor > 0) ? (($valor[1] == 1) ? $d10[$valor[2]] : $u[$valor[2]]) : "";
$r = $rc . (($rc && ($rd || $ru)) ? " e " : "") . $rd . (($rd && $ru) ? " e " : "") . $ru;
$t = count( $inteiro ) - 1 - $i;
$r .= $r ? " " . ($valor > 1 ? $plural[$t] : $singular[$t]) : "";
if ( $valor == "000")
$z++;
elseif ( $z > 0 )
$z--;
if ( ($t == 1) && ($z > 0) && ($inteiro[0] > 0) )
$r .= ( ($z > 1) ? " de " : "") . $plural[$t];
if ( $r )
$rt = $rt . ((($i > 0) && ($i <= $fim) && ($inteiro[0] > 0) && ($z < 1)) ? ( ($i < $fim) ? ", " : " e ") : " ") . $r;
}
$rt = mb_substr( $rt, 1 );
return($rt ? trim( $rt ) : "zero");
}
private static function removerFormatacaoNumero($strNumero)
{
$strNumero = trim( str_replace( "R$", null, $strNumero ) );
$vetVirgula = explode( ",", $strNumero );
if ( count( $vetVirgula ) == 1 )
{
$acentos = array(".");
$resultado = str_replace( $acentos, "", $strNumero );
return $resultado;
}
else if ( count( $vetVirgula ) != 2 )
{
return $strNumero;
}
$strNumero = $vetVirgula[0];
$strDecimal = mb_substr( $vetVirgula[1], 0, 2 );
$acentos = array(".");
$resultado = str_replace( $acentos, "", $strNumero );
$resultado = $resultado . "." . $strDecimal;
return $resultado;
}
}

View File

@@ -0,0 +1,11 @@
<?php
namespace App\Utils;
class RequestUtil
{
public static function isAcceptedBoolean($value)
{
return in_array($value, [true, false, 0, 1, '0', '1'], true);
}
}

13
api/app/Utils/Senha.php Normal file
View File

@@ -0,0 +1,13 @@
<?php
namespace App\Utils;
use Str;
class Senha
{
public static function gerar()
{
return Str::random(8);
}
}

View File

@@ -0,0 +1,12 @@
<?php
require(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'util' . DIRECTORY_SEPARATOR . 'ApiClassLoader.php');
$packages = array(
dirname(__FILE__) . DIRECTORY_SEPARATOR .'util',
dirname(__FILE__) . DIRECTORY_SEPARATOR .'rest-client',
dirname(__FILE__) . DIRECTORY_SEPARATOR .'model'
);
ApiClassLoader::register($packages);

View File

@@ -0,0 +1,84 @@
<?php
/**
* Classe responsável por fazer as conversões para o formato json utilizados no webservice.
*/
class JsonConverter {
/**
* Retorna a representação json de um envio simples.
* @param Sms $sms mensagem a ser enviada
* @param int $aggregateId id do agrupador
* @return string|null string no formato json
*/
public static function smsToJson($sms, $aggregateId=null){
$baseJson=self::getJsonBase($sms, $aggregateId);
$json = '{"sendSmsRequest":'.$baseJson.'}';
return $json;
}
/**
* Retorna a representação json de um envio múltiplo.
* @param array $smsList lista de mensagens SMS a serem enviadas.
* @param int $aggregateId id do agrupador
* @return string|null
*/
public static function smsListToJson($smsList, $aggregateId=null){
if(is_array($smsList)){
$json = '{"sendSmsMultiRequest":{';
if($aggregateId!=null){
$json .= '"aggregateId":'.$aggregateId.',';
}
$json .= '"sendSmsRequestList":[';
foreach($smsList as $sms){
$json .= self::getJsonBase($sms).',';
}
$json = rtrim($json, ',');
$json .= ']}}';
return $json;
}
return null;
}
/**
*
* @param Sms $sms
* @param int $aggregateId
* @return string
*/
private static function getJsonBase($sms, $aggregateId=null){
$obj = new stdClass();
if($sms->getId()!=null){
$obj->id=$sms->getId();
}
if($sms->getMsg()!=null){
$obj->msg=$sms->getMsg();
}
if($sms->getTo()!=null){
$obj->to=$sms->getTo();
}
if($sms->getCallbackOption()!=null){
$obj->callbackOption=$sms->getCallbackOption();
}
if($sms->getSchedule()!=null){
$obj->schedule=$sms->getSchedule();
}
if($sms->getFrom()!=null){
$obj->from=$sms->getFrom();
}
if($sms->getExpiryDate()!=null){
$obj->expiryDate=$sms->getExpiryDate();
}
if($sms->getTimeToLive()!=null){
$obj->timetoLive=$sms->getTimeToLive();
}
if($aggregateId!=null){
$obj->aggregateId=$aggregateId;
}
return json_encode($obj);
}
}

View File

@@ -0,0 +1,155 @@
<?php
/**
* Representa uma mensagem SMS.
*/
class Sms {
/**
* @var string Id da mensagem. Este atributo é opcional
*/
private $id=null;
/**
* @var string Celular de destino. Este atributo é obrigatório
*/
private $to=null;
/**
* @var string Mensagem a ser enviada. Este atributo é obrigatório
*/
private $msg=null;
/**
* @var string Remetente da mensagem. Este atributo é obrigatório para alguns tipos de conta
*/
private $from=null;
/**
* @var string Tipo do callback da mensagem, pode ser NONE(não será retornado nenhum callback de status para a mensagem)
* FINAL(serão retornados apenas os callbacks de status final para a mensagem) e
* ALL(todos os callbacks de status serão retornados para a mensagem).
*/
private $callbackOption=self::CALLBACK_NONE;
/**
* @var string Data do agendamento da mensagem no formato descrito na ISO 8601(yyyy-MM-dd'T'HH:mm:ss).
* Este atributo é opcional e caso não seja informado serão usados a data e a hora do momento do envio.
*/
private $schedule=null;
private $timeToLive=null;
private $expiryDate=null;
const CALLBACK_NONE="NONE";
const CALLBACK_FINAL="FINAL";
const CALLBACK_ALL="ALL";
/**
* Método de acesso ao id da mensagem.
* @return string Id da mesangem.
*/
public function getId() {
return $this->id;
}
/**
* Método modificador de acesso do id da mensagem.
* @param string $id Id da mensagem.
*/
public function setId($id) {
$this->id = $id;
}
/**
* Método de acesso ao remetente da mensagem.
* @return string Remetente da mensagem.
*/
public function getFrom() {
return $this->from;
}
/**
* Método modificador de acesso do remetente da mensagem.
* @param string $from Remetente da mensagem.
*/
public function setFrom($from) {
$this->from = $from;
}
/**
* Método de acesso ao celular de destino da mensagem.
* @return string Destino da mensagem
*/
public function getTo() {
return $this->to;
}
/**
* Método modificador de acesso do celular de destino da mensagem.
* @param string $to Destino da mensagem
*/
public function setTo($to) {
$this->to = $to;
}
/**
* Método de acesso ao conteúdo da mensagem.
* @return string Conteúdo da mensagem.
*/
public function getMsg() {
return $this->msg;
}
/**
* Método modificador de acesso do conteúdo da mensagem.
* @param string $msg Conteúdo da mensagem.
*/
public function setMsg($msg) {
$this->msg = $msg;
}
/**
* Método de acesso para a data de agendamento da mensagem.
* @return string Data de agendamento da mensagem no formato ISO 8601(yyyy-MM-dd'T'HH:mm:ss)
*/
public function getSchedule() {
return $this->schedule;
}
/**
* @param string $schedule método modificador de acesso para a data de agendamento da mensagem.
* O formato informado deverá ser o mesmo descrito na ISO 8601(yyyy-MM-dd'T'HH:mm:ss)
*/
public function setSchedule($schedule) {
$this->schedule = $schedule;
}
/**
* Método de acesso para o tipo de callback da mensagem.
* @return string Tipo do callback da mensagem.
*/
public function getCallbackOption() {
return $this->callbackOption;
}
/**
* Método modificador de acesso do tipo de callback da mensagem.
* @param string $callbackOption Tipo de do callback da mensagem.
* Poderá ser NONE, FINAL, ou ALL.
*/
public function setCallbackOption($callbackOption) {
$this->callbackOption = $callbackOption;
}
public function getTimeToLive() {
return $this->timeToLive;
}
public function setTimeToLive($timeToLive) {
$this->timeToLive = $timeToLive;
}
public function getExpiryDate() {
return $this->expiryDate;
}
public function setExpiryDate($expiryDate) {
$this->expiryDate = $expiryDate;
}
}

View File

@@ -0,0 +1,237 @@
<?php
/**
* Classe que serve como fachada para acesso ao webservice de envio e consulta de mensagens.
*/
class SmsFacade {
/**
* @var RestClient
*/
private $client;
/**
* @var string
*/
private $accountAlias;
/**
* @var string
*/
private $accountPassword;
/**
*
* @var string
*/
private $webServiceUrl;
const DEFAULT_WEBSERVICE_URL="https://api-rest.zenvia360.com.br";
/**
* @param string $accountAlias Alias da conta que será utilizada para autenticação no webservice.
* @param string $accountPassword Senha da conta que será utilizada para autenticação no webservice.
* @param string $webServiceUrl URL do webservice. Caso seja nulo será o usado o valor de @see SmsFacade::DEFAULT_WEBSERVICE_URL
*/
public function __construct($accountAlias, $accountPassword, $webServiceUrl=null) {
$this->accountAlias = $accountAlias;
$this->accountPassword = $accountPassword;
if($webServiceUrl==null){
$this->webServiceUrl=self::DEFAULT_WEBSERVICE_URL;
}
else{
$this->webServiceUrl=$webServiceUrl;
}
$this->client=new RestClient();
}
/**
* Faz um envio de mensagem simples.
* @param Sms $sms O SMS que deverá ser enviado. Este parâmetro é obrigatório
* @param int $aggregateId O id do agrupador que deverá ser relacionado ao envio.
* Este parâmetro será obrigatório apenas se a conta possuir a configuração de agrupador habilitada.
* @return SmsResponse Resposta com o status e o detalhe da mensagem enviada
* @throws RuntimeException
*/
public function send($sms, $aggregateId=null){
$headers = $this->getBaseHeaders();
$json = JsonConverter::smsToJson($sms, $aggregateId);
$client = $this->client;
$url=$this->webServiceUrl."/services/send-sms";
$response = $client->post($url, $json, $headers);
$this->checkResponse($response);
$obj = json_decode($response->getBody());
$sendSmsResponse=$obj->sendSmsResponse;
$smsResponse = new SmsResponse($sendSmsResponse->statusCode, $sendSmsResponse->statusDescription, $sendSmsResponse->detailCode, $sendSmsResponse->detailDescription);
return $smsResponse;
}
/**
* Faz um envio de mensagem múltiplo.
* @param array $smsList Array contendo uma lista de SMS para serem enviados.Este parâmetro é obrigatório
* @param int $aggregateId O id do agrupador que deverá ser relacionado ao envio.
* Este parâmetro será obrigatório apenas se a conta possuir a configuração de agrupador habilitada.
* @return array Lista de objetos do tipo SmsResponse.
* @throws RuntimeException
*/
public function sendMultiple($smsList, $aggregateId=null){
$headers = $this->getBaseHeaders();
$json = JsonConverter::smsListToJson($smsList, $aggregateId);
$client = $this->client;
$url=$this->webServiceUrl."/services/send-sms-multiple";
$response = $client->post($url, $json, $headers);
$this->checkResponse($response);
$obj = json_decode($response->getBody());
$responses = array();
if(is_object($obj)){
foreach($obj->sendSmsMultiResponse->sendSmsResponseList as $sendSmsResponse){
$smsResponse = new SmsResponse($sendSmsResponse->statusCode, $sendSmsResponse->statusDescription, $sendSmsResponse->detailCode, $sendSmsResponse->detailDescription);
array_push($responses, $smsResponse);
}
}
return $responses;
}
/**
* Faz o cancelamento de uma mensagem.
* @param string $id Id da mensagem que deverá ser cancelada. Este parâmetro é obrigatório.
* @return SmsResponse Resposta com o status e o detalhe da operação de cancelamento.
* @throws RuntimeException
*/
public function cancel($id){
$headers = $this->getBaseHeaders();
$client = $this->client;
$url=$this->webServiceUrl."/services/cancel-sms/".$id;
$response = $client->post($url, null, $headers);
$this->checkResponse($response);
$obj = json_decode($response->getBody());
$cancelSmsResp=$obj->cancelSmsResp;
$smsResponse = new SmsResponse($cancelSmsResp->statusCode, $cancelSmsResp->statusDescription, $cancelSmsResp->detailCode, $cancelSmsResp->detailDescription);
return $smsResponse;
}
/**
* Faz a consulta do status atual de uma mensagem enviada.
* @param string $id Id da mensagem a ser consultada. Este parâmetro é obrigatório.
* @return SmsStatusResponse Resposta com o status e o detalhe da mensagem a ser consultada.
* @throws RuntimeException
*/
public function getStatus($id){
$headers = $this->getBaseHeaders();
$headers['Content-Type']=null;
$client = $this->client;
$url=$this->webServiceUrl."/services/get-sms-status/".$id;
$response = $client->get($url, $headers);
$this->checkResponse($response);
$obj = json_decode($response->getBody());
$statusSms=$obj->getSmsStatusResp;
$statusResponse = new SmsStatusResponse();
$statusResponse->setStatusCode($statusSms->statusCode);
$statusResponse->setStatusDescription($statusSms->statusDescription);
$statusResponse->setDetailCode($statusSms->detailCode);
$statusResponse->setDetailDescription($statusSms->detailDescription);
$statusResponse->setId($statusSms->id);
$statusResponse->setReceived($statusSms->received);
$statusResponse->setShortCode($statusSms->shortcode);
$statusResponse->setMobileOperatorName($statusSms->mobileOperatorName);
return $statusResponse;
}
/**
* Faz a listagem de mensagens recebidas que ainda não foram consultadas.
* Os SMS recebidos retornados por esta consulta só poderão ser consultados apenas uma única vez
* de forma que se um SMS é retornado nesta consulta o mesmo não será listado novamente em uma consulta posterior.
* Caso seja necessário consultar as mesmas mensagens recebidas múltiplas vezes, deverá ser usado o método @see SmsFacade::searchMessagesReceived
* @return SmsReceivedResponse Resposta com as mensagens recebidas.
* @throws RuntimeException
*/
public function listMessagesReceived(){
$headers = $this->getBaseHeaders();
$client = $this->client;
$url=$this->webServiceUrl."/services/received/list";
$response = $client->post($url, null, $headers);
$this->checkResponse($response);
$smsResponse = $this->parseMoList($response->getBody());
return $smsResponse;
}
/**
* Faz a consulta de todas as mensagens recebidas no período informado. Este método deverá
* retornar todas as mensagens recebidas que coincidirem com o filtro passado
* independentemente se as mesmas já terem sido consultadas anteriormente.
* @param string $startPeriod Data inicial no formato descrito na ISO 8601(yyyy-MM-dd'T'HH:mm:ss). Este parâmetro é obrigatório.
* @param string $endPeriod Data final no formato descrito na ISO 8601(yyyy-MM-dd'T'HH:mm:ss). Este parâmetro é obrigatório.
* @param string $mobile Celular a ser utilizado na pesquisa de mensagens recebidas.
* @param $smsId $smsId Id da mensagem de origem a ser utilizado na pesquisa de mensagens recebidas.
* @return SmsReceivedResponse Resposta com as mensagens recebidas.
* @throws RuntimeException
*/
public function searchMessagesReceived($startPeriod, $endPeriod, $mobile=null, $smsId=null ){
$headers = $this->getBaseHeaders();
$headers['Content-Type']=null;
$client = $this->client;
$url=$this->webServiceUrl."/services/received/search/".rawurlencode($startPeriod).'/'.rawurlencode($endPeriod).'?';
if($mobile!=null){
$url .='mobile='.rawurlencode($mobile).'&';
}
if($smsId!=null){
$url .='mtId='.rawurlencode($smsId);
}
$url = rtrim($url, '&');
$response = $client->get($url, $headers);
$this->checkResponse($response);
$smsResponse = $this->parseMoList($response->getBody());
return $smsResponse;
}
/**
* Faz o parse do json de resposta com a representação da lista de mensagens recebidas do webservice para um objeto @see SmsReceivedResponse.
* @param string $jsonResponse Json retornado pelo webservice.
* @return SmsReceivedResponse Resposta com as mensagens recebidas.
*/
private function parseMoList($jsonResponse){
$obj = json_decode($jsonResponse);
$smsResponse = new SmsReceivedResponse($obj->receivedResponse->statusCode, $obj->receivedResponse->statusDescription, $obj->receivedResponse->detailCode, $obj->receivedResponse->detailDescription);
if( is_array($obj->receivedResponse->receivedMessages) && count($obj->receivedResponse->receivedMessages) > 0 ){
foreach($obj->receivedResponse->receivedMessages as $message){
$receivedMessage = new SmsReceived();
$receivedMessage->setBody($message->body);
$receivedMessage->setDateReceived($message->dateReceived);
$receivedMessage->setId($message->id);
$receivedMessage->setMobile($message->mobile);
$receivedMessage->setMobileOperatorName($message->mobileOperatorName);
$receivedMessage->setShortCode($message->shortcode);
$receivedMessage->setSmsOriginId($message->mtId);
$smsResponse->addReceivedMessage($receivedMessage);
}
}
return $smsResponse;
}
/**
* Verifica se o serviço retornou uma resposta válida.
* @param HttpResponse $response
* @throws RuntimeException Se o servidor restornou uma resposta inválida.
*/
private function checkResponse($response){
if($response->getHttpCode()>= 400){
$exceptionMessage=$response->getHttpCode().' - '.$response->getHttpDescription()." \nServer Response\n".$response->getBody()."."."\nApi Request\n[".$response->getRequestOrigin();
throw new RuntimeException($exceptionMessage);
}
}
/**
* Headers base para as requisições.
* @return array Array associativo com os headers comuns das requisições.
*/
private function getBaseHeaders(){
$accountAlias=$this->accountAlias;
$accountPassword=$this->accountPassword;
$headers = array(
'Accept'=>'application/json',
'Content-Type'=>'application/json; charset=UTF-8',
'Authorization'=> 'Basic '. base64_encode($accountAlias.':'.$accountPassword)
);
return $headers;
}
}

View File

@@ -0,0 +1,124 @@
<?php
/**
* Classe que representa uma mensagem recebida.
*/
class SmsReceived {
/**
* @var long Id da mensagem recebida.
*/
private $id;
/**
* @var string Data de recebimento da mensagem.
*/
private $dateReceived;
/**
* @var string Celular da mensagem recebida.
*/
private $mobile;
/**
* @var string Conteúdo da mensagem recebida.
*/
private $body;
/**
* @var string Shortcode da mensagem recebida.
*/
private $shortCode;
/**
* @var string Nome da operadora do celular da mensagem recebida.
*/
private $mobileOperatorName;
/**
* @var string Id da mensagem que originou a mensagem recebida.
*/
private $smsOriginId;
/**
* Método acessor ao id da mensagem.
* @return long Id da mensagem recebida
*/
public function getId() {
return $this->id;
}
/**
* Método acessor para a data de recebimento da mensagem.
* @return string Data de recebimento da mensagem no formato ISO 8601(yyyy-MM-dd'T'HH:mm:ss).
*/
public function getDateReceived() {
return $this->dateReceived;
}
/**
* Método acessor ao celular da mensagem recebida.
* @return string Celular da mensagem recebida
*/
public function getMobile() {
return $this->mobile;
}
/**
* Método acessor ao conteúdo da mensagem recebida.
* @return string Conteúdo da mensagem recebida
*/
public function getBody() {
return $this->body;
}
/**
* Método acessor ao Shortcode da mensagem recebida.
* @return string Shortcode da mensagem recebida
*/
public function getShortCode() {
return $this->shortCode;
}
/**
* Método acessor para a operadora do celular da mensagem recebida.
* @return string Operadora celular da mensagem recebida
*/
public function getMobileOperatorName() {
return $this->mobileOperatorName;
}
/**
* Método acessor ao id do SMS de origem da mensagem recebida.
* @return string Id do SMS de origem da mensagem recebida.
*/
public function getSmsOriginId() {
return $this->smsOriginId;
}
public function setId($id) {
$this->id = $id;
}
public function setDateReceived($dateReceived) {
$this->dateReceived = $dateReceived;
}
public function setMobile($mobile) {
$this->mobile = $mobile;
}
public function setBody($body) {
$this->body = $body;
}
public function setShortCode($shortCode) {
$this->shortCode = $shortCode;
}
public function setMobileOperatorName($mobileOperatorName) {
$this->mobileOperatorName = $mobileOperatorName;
}
public function setSmsOriginId($smsOriginId) {
$this->smsOriginId = $smsOriginId;
}
}

View File

@@ -0,0 +1,38 @@
<?php
/**
* Classe que representa uma resposta contendo um conjunto de mensagens recebidas.
*/
class SmsReceivedResponse extends SmsResponse{
/**
* @var array Lista com as mensagens recebidas na resposta.
*/
private $receivedMessages=array();
/**
* Verifica se há mensagens recebidas na resposta.
* @return bool
*/
public function hasMessages(){
return count($this->receivedMessages);
}
/**
* Adiciona uma mensagem recebida à lista de mensagens recebidas.
* @param SmsReceived $receivedMessage
*/
public function addReceivedMessage($receivedMessage){
array_push($this->receivedMessages, $receivedMessage);
}
/**
* Retorna a lista de mensagens recebidas da resposta.
* @return array Lista com as mensagens recebidas.
*/
public function getReceivedMessages(){
return $this->receivedMessages;
}
}

View File

@@ -0,0 +1,86 @@
<?php
/**
* Classe que representa uma resposta contendo o status de uma mensagem.
*/
class SmsResponse {
/**
* @var string Código do status da resposta
*/
private $statusCode;
/**
* @var string Descrição do status da resposta
*/
private $statusDescription;
/**
* @var string Código do detalhe do status da resposta
*/
private $detailCode;
/**
* @var string Descrição do detalhe do status da resposta
*/
private $detailDescription;
/**
* @param string $statusCode
* @param string $statusDescription
* @param string $detailCode
* @param string $detailDescription
*/
public function __construct($statusCode, $statusDescription, $detailCode, $detailDescription) {
$this->statusCode=$statusCode;
$this->statusDescription=$statusDescription;
$this->detailCode=$detailCode;
$this->detailDescription=$detailDescription;
}
/**
* Método acessor ao código do status retornado na resposta.
* @return string Código do status
*/
public function getStatusCode() {
return $this->statusCode;
}
/**
* Método acessor para a descrição do status retornado na resposta.
* @return string Descrição do status
*/
public function getStatusDescription() {
return $this->statusDescription;
}
/**
* Método acessor ao código do detalhe do status retornado na resposta.
* @return string Código do detalhe do status
*/
public function getDetailCode() {
return $this->detailCode;
}
/**
* Método acessor para a descrição do do detalhe do status retornado na resposta.
* @return string Descrição do detalhe do status
*/
public function getDetailDescription() {
return $this->detailDescription;
}
public function setStatusCode($statusCode) {
$this->statusCode = $statusCode;
}
public function setStatusDescription($statusDescription) {
$this->statusDescription = $statusDescription;
}
public function setDetailCode($detailCode) {
$this->detailCode = $detailCode;
}
public function setDetailDescription($detailDescription) {
$this->detailDescription = $detailDescription;
}
}

View File

@@ -0,0 +1,78 @@
<?php
/**
* Classe que representa uma resposta a uma consulta de status de uma mensagem.
*/
class SmsStatusResponse extends SmsResponse{
/**
* @var string Id da mensagem enviada.
*/
private $id;
/**
* @var string data de recebimento da mensagem no formato ISO 8601(yyyy-MM-dd'T'HH:mm:ss)
*/
private $received;
/**
* @var string Shortcode da mensagem consultada
*/
private $shortCode;
/**
* @var string Operadora da mensagem consultada.
*/
private $mobileOperatorName;
public function __construct($statusCode="", $statusDescription="", $detailCode="", $detailDescription="") {
parent::__construct($statusCode, $statusDescription, $detailCode, $detailDescription);
}
/**
* Método acessor ao id da mensagem consultada.
* @return string Id da mensagem consultada.
*/
public function getId() {
return $this->id;
}
/**
* Método acessor para a data de recebimento da mensagem consultada.
* @return string Data de recebimento da mensagem consultada.
*/
public function getReceived() {
return $this->received;
}
/**
* Método acessor ao shortcode da mensagem consultada.
* @return string Shortcode da mensagem consultada.
*/
public function getShortCode() {
return $this->shortCode;
}
/**
* Método acessor para a operadora da mensagem consultada.
* @return string Operadora da mensagem consultada.
*/
public function getMobileOperatorName() {
return $this->mobileOperatorName;
}
public function setId($id) {
$this->id = $id;
}
public function setReceived($received) {
$this->received = $received;
}
public function setShortCode($shortCode) {
$this->shortCode = $shortCode;
}
public function setMobileOperatorName($mobileOperatorName) {
$this->mobileOperatorName = $mobileOperatorName;
}
}

View File

@@ -0,0 +1,122 @@
<?php
class DefaultHttpClient implements HttpClient{
/**
* @param HttpRequest $request
* @param int $timeout
* @return HttpResponse
* @throws RuntimeException
*/
public function makeRequest($request, $timeout=null){
$response = null;
$httpSocket=null;
try{
$httpString = $this->parseRequest($request);
$httpSocket = $this->createSocket($request->getURL(), $timeout);
$this->makeHttpRequest($httpSocket, $httpString);
$responseString = $this->retrieveHttpResponse($httpSocket);
$response = $this->parseResponse($responseString, $request);
$this->closeSocket($httpSocket);
}catch(Exception $ex){
$this->closeSocket($httpSocket);
$exceptionMessage='Http Request Failed. Request['.$request.'], Response['.$response.'].';
throw new Exception($exceptionMessage, null, $ex);
}
return $response;
}
/**
*
* @param URL $url
* @param int $timeout
* @return resource
* @throws RuntimeException
*/
private function createSocket($url, $timeout=null){
$host=$url->getHost();
$port = $url->getPort() == null ? 80 : $url->getPort();
if($url->getScheme() == 'https'){
$host='ssl://'.$url->getHost();
$port = $url->getPort() == null ? 443 : $url->getPort();
}
$errorCode = null;
$errorDescription = null;
$socket = null;
if (is_null($timeout)){
$socket = fsockopen($host, $port, $errorCode, $errorDescription);
}
else{
$socket = fsockopen($host, $port, $errorCode, $errorDescription, $timeout);
}
if (!is_resource($socket)) {
throw new RuntimeException($errorCode . " (" . $errorDescription . ")");
}
return $socket;
}
private function closeSocket($socket){
if(is_resource($socket)){
fclose($socket);
}
}
private function makeHttpRequest($socket, $httpString){
$this->checkSocket($socket);
fwrite($socket, $httpString);
}
private function checkSocket($socket){
if(!is_resource($socket)){
throw new RuntimeException("Invalid socket resource.");
}
}
/**
*
* @param string $responseString
* @param HttpRequest $request
* @return HttpResponse
*/
private function parseResponse($responseString, $request){
$responseParser = new HttpResponseParser();
$response = $responseParser->parse($responseString);
$response->setRequestOrigin($request);
return $response;
}
/**
* @param HttpRequest $request
* @return string
*/
private function parseRequest($request){
$requestParser = new HttpRequestParser();
$httpString = $requestParser->parse($request);
return $httpString;
}
/**
*
* @param resource $socket
* @return string
* @throws RuntimeException Caso não seja possível ler o recurso do caminho de origem
*/
private function retrieveHttpResponse($socket){
$this->checkSocket($socket);
$responseContent = "";
$line="";
while (!feof($socket)) {
$line=fgets($socket, 128);
$responseContent .= $line;
}
if($responseContent==null || trim($responseContent) == "" ){
throw new RuntimeException("Resource requested not found. Try change the request path.");
}
return $responseContent;
}
}

View File

@@ -0,0 +1,11 @@
<?php
interface HttpClient {
/**
*
* @param HttpRequest $request
* @param int $timeout
* @return HttpResponse
*/
public function makeRequest($request, $timeout=null);
}

View File

@@ -0,0 +1,34 @@
<?php
class HttpHeader {
/**
* @var string
*/
private $name;
/**
* @var mixed
*/
private $value;
public function __construct($name, $value) {
$this->name = $name;
$this->value = $value;
}
public function getName() {
return $this->name;
}
public function getValue() {
return $this->value;
}
public function __toString() {
return "[name=".$this->name.', value='.$this->value.']';
}
}

View File

@@ -0,0 +1,90 @@
<?php
class HttpRequest {
const HTTP_GET="GET";
const HTTP_POST="POST";
const HTTP_PUT="PUT";
const HTTP_DELETE="DELETE";
/**
*
* @var URL
*/
private $url;
/**
* @var array
*/
private $headers=array();
/**
* @var string
*/
private $method;
/**
* @var string
*/
private $body;
public function getMethod() {
return $this->method;
}
public function setMethod($method) {
$this->method = $method;
}
public function getHeaders(){
return $this->headers;
}
/**
* @param HttpHeader $header
*/
public function addHeader($header){
array_push($this->headers, $header);
}
public function hasHeader($name){
$hasHeader = false;
foreach($this->headers as $header){
if($header->getName() == $name){
$hasHeader=true;
}
}
return $hasHeader;
}
/**
* @return URL
*/
public function getUrl() {
return $this->url;
}
public function setUrl($url) {
$this->url = $url;
}
public function getBody() {
return $this->body;
}
public function setBody($body) {
$this->body = $body;
}
public function __toString() {
$requestString = get_class($this).'[url='.$this->url.', method='.$this->method.', body='.$this->body;
return $requestString;
}
}

View File

@@ -0,0 +1,39 @@
<?php
class HttpRequestParser {
/**
*
* @param HttpRequest $request
* @return type
*/
public function parse($request){
$postData= $request->getBody();
$url = $request->getMethod() . " " . $request->getURL()->getUri().'?'.$request->getURL()->getQueryString();
$output = $url . " HTTP/1.1\r\n";
$output .= "Host: " . $request->getURL()->getHost() . "\r\n";
$output .= "User-Agent: Zenvia PHP API\r\n";
$output .= $this->parseCustomHeaders($request);
$output .= "Content-Length: " . strlen($postData) . "\r\n";
$output .= "Connection: close\r\n\r\n";
$output .= $postData;
return $output;
}
/**
* @param HttpRequest $request
* @return string
*/
private function parseCustomHeaders($request){
$headers = $request->getHeaders();
$output = "";
foreach($headers as $header){
$output .= sprintf("%s:%s \r\n", $header->getName(), $header->getValue());
}
$output .= "User-Agent: Zenvia PHP API\r\n";
return $output;
}
}

View File

@@ -0,0 +1,83 @@
<?php
class HttpResponse {
/**
* @var int
*/
private $httpCode;
/**
* @var string
*/
private $httpDescription;
/**
* @var array
*/
private $headers=array();
/**
* @var string
*/
private $body;
/**
* @var HttpRequest
*/
private $requestOrigin;
public function getHttpCode() {
return $this->httpCode;
}
public function getHttpDescription() {
return $this->httpDescription;
}
public function setHttpCode($httpCode) {
$this->httpCode = $httpCode;
}
public function setHttpDescription($httpDescription) {
$this->httpDescription = $httpDescription;
}
public function getHeaders() {
return $this->headers;
}
public function getBody() {
return $this->body;
}
public function getRequestOrigin() {
return $this->requestOrigin;
}
public function setBody($body) {
$this->body = $body;
}
/**
* @param HttpHeader $header
*/
public function addHeader($header){
array_push($this->headers, $header);
}
public function setRequestOrigin(HttpRequest $requestOrigin) {
$this->requestOrigin = $requestOrigin;
}
public function __toString() {
$headers=null;
if(is_array($this->headers)){
$headers = implode(", ", $this->headers);
}
$responseString = get_class($this)."[Http Code=".$this->httpCode.'-'.$this->httpDescription.", \nHeaders=".$headers.", \nBody=".$this->body.", Request Origin=".$this->requestOrigin."]";
return $responseString;
}
}

View File

@@ -0,0 +1,71 @@
<?php
class HttpResponseParser {
/**
* @param string
* @return HttpResponse
*/
public function parse($httpContent) {
$httpResponse = new HttpResponse();
$responseArray = explode("\r\n\r\n", $httpContent);
$headersData = $responseArray[0];
$headersArray = explode("\n", $headersData);
$totalHeaders = count($headersArray);
for ($i = 0; $i < $totalHeaders; $i++) {
$indexHttpHeader = strpos($headersArray[$i], "HTTP");
if ($indexHttpHeader !== false) {
//HTTP/1.1 200 OK
$httpCode = substr($headersArray[$i], $indexHttpHeader + 9, 3);
$httpDescription = substr($headersArray[$i], $indexHttpHeader + 13);
$httpResponse->setHttpCode(intval(trim($httpCode)));
$httpResponse->setHttpDescription(trim($httpDescription));
} else {
$httpResponse->addHeader($this->parseHeader($headersArray[$i]));
}
}
$bodyData = $this->getRequestBody($headersData, $responseArray[1]);
$httpResponse->setBody($bodyData);
return $httpResponse;
}
/**
*
* @param string $headerText
* @return HttpHeader
*/
private function parseHeader($headerText) {
$indexVal = strpos($headerText, ":");
$header=null;
if ($indexVal !== false) {
$headerName = substr($headerText, 0, $indexVal);
$headerValue = substr($headerText, $indexVal + 1);
$header = new HttpHeader($headerName, trim($headerValue));
} else {
$header = new HttpHeader("$i", trim($headerText));
}
return $header;
}
/**
*
* @param string $headersData
* @param string $bodyData
* @return string
*/
private function getRequestBody($headersData, $bodyData) {
$content = $bodyData;
if (!(strpos($headersData, "Transfer-Encoding: chunked") === false)) {
$aux = explode("\r\n", $bodyData);
$countAux = count($aux);
for ($i = 0; $i < $countAux; $i++) {
if ($i == 0 || ($i % 2) == 0) {
$aux[$i] = "";
}
}
$content = implode("", $aux);
}
return $content;
}
}

View File

@@ -0,0 +1,113 @@
<?php
class RestClient {
/**
* @var HttpClient
*/
private $httpClient = null;
const DEFAULT_CONTENT_TYPE="application/x-www-form-urlencoded;charset=UTF-8";
/**
*
* @param HttpClient $httpClient
*/
public function __construct($httpClient=null) {
if($httpClient==null){
$this->httpClient = new DefaultHttpClient();
}
else{
$this->httpClient = $httpClient;
}
}
/**
*
* @param string $url
* @param array $additionalHeaders
* @return HttpResponse
* @throws RuntimeException
*/
public function get($url, $additionalHeaders=array()){
$response = $this->request($url, HttpRequest::HTTP_GET, null, $additionalHeaders);
return $response;
}
/**
*
* @param string $url
* @param string|array $data
* @param array $additionalHeaders
* @return HttpResponse
* @throws RuntimeException
*/
public function post($url, $data=null, $additionalHeaders=array()){
$response = $this->request($url, HttpRequest::HTTP_POST, $data, $additionalHeaders);
return $response;
}
/**
*
* @param string $url
* @param string $method
* @param string|array $data
* @param string $additionalHeaders
* @return HttpResponse
* @throws RuntimeException
*/
private function request($url, $method, $data=null, $additionalHeaders=array()){
$request = $this->createRequest($url, $method, $this->serializeRequestBody($data), $additionalHeaders);
try{
$response = $this->httpClient->makeRequest($request);
}catch(Exception $ex){
throw new RuntimeException($ex);
}
return $response;
}
/**
*
* @param string $data
* return string
*/
private function serializeRequestBody($data){
$serializedData = null;
if($data!= null && is_array($data) ){
$serializedData = http_build_query($data);
}elseif ($data!= null && is_string($data)) {
$serializedData = $data;
}
return $serializedData;
}
/**
*
* @param string $url
* @param string $method
* @param string|array $data
* @param array $additionalHeaders
* @return HttpRequest
*/
private function createRequest($url, $method, $data=null, $additionalHeaders=array()){
$httpRequest = new HttpRequest();
$httpRequest->setUrl(new SMSURL($url));
$httpRequest->setMethod($method);
if(is_array($additionalHeaders) && count($additionalHeaders) > 0){
foreach($additionalHeaders as $headerName=>$headerValue){
$httpRequest->addHeader(new HttpHeader($headerName, $headerValue));
}
}
if(!$httpRequest->hasHeader('Content-Type')){
$httpRequest->addHeader(new HttpHeader('Content-Type', self::DEFAULT_CONTENT_TYPE));
}
$httpRequest->setBody($data);
return $httpRequest;
}
}

View File

@@ -0,0 +1,85 @@
<?php
class SMSURL {
/**
* @var string
*/
private $host;
/**
* @var string
*/
private $uri;
/**
* @var int
*/
private $port;
/**
* @var string
*/
private $queryString;
/**
* @var string
*/
private $scheme;
/**
* @param string $url
*/
public function __construct($url) {
$this->fill($url);
}
private function fill($url){
$parsedUrl = parse_url($url);
$this->host=$parsedUrl['host'];
$this->uri=$parsedUrl['path'];
$this->scheme=$parsedUrl['scheme'];
if(key_exists('port', $parsedUrl)){
$this->port=$parsedUrl['port'];
}
if(key_exists('query', $parsedUrl)){
$this->queryString=$parsedUrl['query'];
}
}
public function getHost() {
return $this->host;
}
public function getUri() {
return $this->uri;
}
public function getPort() {
return $this->port;
}
public function getQueryString() {
return $this->queryString;
}
public function getScheme() {
return $this->scheme;
}
public function __toString() {
$urlString=$this->host;
if($this->port!=null && $this->port!=80){
$urlString.=':'.$this->port;
}
if($this->uri!=null && $this->uri!=""){
$urlString.=$this->uri;
}
if($this->queryString!=null && $this->queryString!=""){
$urlString.='?'.$this->queryString;
}
return $urlString;
}
}

View File

@@ -0,0 +1,46 @@
<?php
class ApiClassLoader {
private static $packages = array();
/**
* @packages
*/
public static function register($packages) {
self::$packages=$packages;
return spl_autoload_register(array('ApiClassLoader', 'load'));
}
public static function load($classname) {
if ((class_exists($classname))) {
return false;
}
$filePhp = $classname . '.php';
foreach (self::$packages as $package) {
self::mapperClass($package, $filePhp);
}
}
private static function mapperClass($dir, $file) {
$pObjectFilePath = $dir . DIRECTORY_SEPARATOR . $file;
if ((file_exists($pObjectFilePath) === false) || (is_readable($pObjectFilePath) === false)) {
$itemHandler = opendir($dir);
while (($item = readdir($itemHandler)) !== false) {
if (trim($item) != "." && trim($item) != "..") {
$dirTmp = $dir . DIRECTORY_SEPARATOR . $item;
if (is_dir($dirTmp) && substr($item, 0, 1) != ".") {
if (self::mapperClass($dirTmp, $file)) {
return true;
}
}
}
}
return false;
} else {
require($pObjectFilePath);
return true;
}
}
}

View File

@@ -0,0 +1,107 @@
<?php
namespace App\Utils;
class StringUtil
{
public static function getWithoutAccents(string $string)
{
$transliteration = [
'IJ' => 'I', 'Ö' => 'O','Œ' => 'O','Ü' => 'U','ä' => 'a','æ' => 'a',
'ij' => 'i','ö' => 'o','œ' => 'o','ü' => 'u','ß' => 's','ſ' => 's',
'À' => 'A','Á' => 'A','Â' => 'A','Ã' => 'A','Ä' => 'A','Å' => 'A',
'Æ' => 'A','Ā' => 'A','Ą' => 'A','Ă' => 'A','Ç' => 'C','Ć' => 'C',
'Č' => 'C','Ĉ' => 'C','Ċ' => 'C','Ď' => 'D','Đ' => 'D','È' => 'E',
'É' => 'E','Ê' => 'E','Ë' => 'E','Ē' => 'E','Ę' => 'E','Ě' => 'E',
'Ĕ' => 'E','Ė' => 'E','Ĝ' => 'G','Ğ' => 'G','Ġ' => 'G','Ģ' => 'G',
'Ĥ' => 'H','Ħ' => 'H','Ì' => 'I','Í' => 'I','Î' => 'I','Ï' => 'I',
'Ī' => 'I','Ĩ' => 'I','Ĭ' => 'I','Į' => 'I','İ' => 'I','Ĵ' => 'J',
'Ķ' => 'K','Ľ' => 'K','Ĺ' => 'K','Ļ' => 'K','Ŀ' => 'K','Ł' => 'L',
'Ñ' => 'N','Ń' => 'N','Ň' => 'N','Ņ' => 'N','Ŋ' => 'N','Ò' => 'O',
'Ó' => 'O','Ô' => 'O','Õ' => 'O','Ø' => 'O','Ō' => 'O','Ő' => 'O',
'Ŏ' => 'O','Ŕ' => 'R','Ř' => 'R','Ŗ' => 'R','Ś' => 'S','Ş' => 'S',
'Ŝ' => 'S','Ș' => 'S','Š' => 'S','Ť' => 'T','Ţ' => 'T','Ŧ' => 'T',
'Ț' => 'T','Ù' => 'U','Ú' => 'U','Û' => 'U','Ū' => 'U','Ů' => 'U',
'Ű' => 'U','Ŭ' => 'U','Ũ' => 'U','Ų' => 'U','Ŵ' => 'W','Ŷ' => 'Y',
'Ÿ' => 'Y','Ý' => 'Y','Ź' => 'Z','Ż' => 'Z','Ž' => 'Z','à' => 'a',
'á' => 'a','â' => 'a','ã' => 'a','ā' => 'a','ą' => 'a','ă' => 'a',
'å' => 'a','ç' => 'c','ć' => 'c','č' => 'c','ĉ' => 'c','ċ' => 'c',
'ď' => 'd','đ' => 'd','è' => 'e','é' => 'e','ê' => 'e','ë' => 'e',
'ē' => 'e','ę' => 'e','ě' => 'e','ĕ' => 'e','ė' => 'e','ƒ' => 'f',
'ĝ' => 'g','ğ' => 'g','ġ' => 'g','ģ' => 'g','ĥ' => 'h','ħ' => 'h',
'ì' => 'i','í' => 'i','î' => 'i','ï' => 'i','ī' => 'i','ĩ' => 'i',
'ĭ' => 'i','į' => 'i','ı' => 'i','ĵ' => 'j','ķ' => 'k','ĸ' => 'k',
'ł' => 'l','ľ' => 'l','ĺ' => 'l','ļ' => 'l','ŀ' => 'l','ñ' => 'n',
'ń' => 'n','ň' => 'n','ņ' => 'n','ʼn' => 'n','ŋ' => 'n','ò' => 'o',
'ó' => 'o','ô' => 'o','õ' => 'o','ø' => 'o','ō' => 'o','ő' => 'o',
'ŏ' => 'o','ŕ' => 'r','ř' => 'r','ŗ' => 'r','ś' => 's','š' => 's',
'ť' => 't','ù' => 'u','ú' => 'u','û' => 'u','ū' => 'u','ů' => 'u',
'ű' => 'u','ŭ' => 'u','ũ' => 'u','ų' => 'u','ŵ' => 'w','ÿ' => 'y',
'ý' => 'y','ŷ' => 'y','ż' => 'z','ź' => 'z','ž' => 'z','Α' => 'A',
'Ά' => 'A','Ἀ' => 'A','Ἁ' => 'A','Ἂ' => 'A','Ἃ' => 'A','Ἄ' => 'A',
'Ἅ' => 'A','Ἆ' => 'A','Ἇ' => 'A','ᾈ' => 'A','ᾉ' => 'A','ᾊ' => 'A',
'ᾋ' => 'A','ᾌ' => 'A','ᾍ' => 'A','ᾎ' => 'A','ᾏ' => 'A','Ᾰ' => 'A',
'Ᾱ' => 'A','Ὰ' => 'A','ᾼ' => 'A','Β' => 'B','Γ' => 'G','Δ' => 'D',
'Ε' => 'E','Έ' => 'E','Ἐ' => 'E','Ἑ' => 'E','Ἒ' => 'E','Ἓ' => 'E',
'Ἔ' => 'E','Ἕ' => 'E','Ὲ' => 'E','Ζ' => 'Z','Η' => 'I','Ή' => 'I',
'Ἠ' => 'I','Ἡ' => 'I','Ἢ' => 'I','Ἣ' => 'I','Ἤ' => 'I','Ἥ' => 'I',
'Ἦ' => 'I','Ἧ' => 'I','ᾘ' => 'I','ᾙ' => 'I','ᾚ' => 'I','ᾛ' => 'I',
'ᾜ' => 'I','ᾝ' => 'I','ᾞ' => 'I','ᾟ' => 'I','Ὴ' => 'I','ῌ' => 'I',
'Θ' => 'T','Ι' => 'I','Ί' => 'I','Ϊ' => 'I','Ἰ' => 'I','Ἱ' => 'I',
'Ἲ' => 'I','Ἳ' => 'I','Ἴ' => 'I','Ἵ' => 'I','Ἶ' => 'I','Ἷ' => 'I',
'Ῐ' => 'I','Ῑ' => 'I','Ὶ' => 'I','Κ' => 'K','Λ' => 'L','Μ' => 'M',
'Ν' => 'N','Ξ' => 'K','Ο' => 'O','Ό' => 'O','Ὀ' => 'O','Ὁ' => 'O',
'Ὂ' => 'O','Ὃ' => 'O','Ὄ' => 'O','Ὅ' => 'O','Ὸ' => 'O','Π' => 'P',
'Ρ' => 'R','Ῥ' => 'R','Σ' => 'S','Τ' => 'T','Υ' => 'Y','Ύ' => 'Y',
'Ϋ' => 'Y','Ὑ' => 'Y','Ὓ' => 'Y','Ὕ' => 'Y','Ὗ' => 'Y','Ῠ' => 'Y',
'Ῡ' => 'Y','Ὺ' => 'Y','Φ' => 'F','Χ' => 'X','Ψ' => 'P','Ω' => 'O',
'Ώ' => 'O','Ὠ' => 'O','Ὡ' => 'O','Ὢ' => 'O','Ὣ' => 'O','Ὤ' => 'O',
'Ὥ' => 'O','Ὦ' => 'O','Ὧ' => 'O','ᾨ' => 'O','ᾩ' => 'O','ᾪ' => 'O',
'ᾫ' => 'O','ᾬ' => 'O','ᾭ' => 'O','ᾮ' => 'O','ᾯ' => 'O','Ὼ' => 'O',
'ῼ' => 'O','α' => 'a','ά' => 'a','ἀ' => 'a','ἁ' => 'a','ἂ' => 'a',
'ἃ' => 'a','ἄ' => 'a','ἅ' => 'a','ἆ' => 'a','ἇ' => 'a','ᾀ' => 'a',
'ᾁ' => 'a','ᾂ' => 'a','ᾃ' => 'a','ᾄ' => 'a','ᾅ' => 'a','ᾆ' => 'a',
'ᾇ' => 'a','ὰ' => 'a','ᾰ' => 'a','ᾱ' => 'a','ᾲ' => 'a','ᾳ' => 'a',
'ᾴ' => 'a','ᾶ' => 'a','ᾷ' => 'a','β' => 'b','γ' => 'g','δ' => 'd',
'ε' => 'e','έ' => 'e','ἐ' => 'e','ἑ' => 'e','ἒ' => 'e','ἓ' => 'e',
'ἔ' => 'e','ἕ' => 'e','ὲ' => 'e','ζ' => 'z','η' => 'i','ή' => 'i',
'ἠ' => 'i','ἡ' => 'i','ἢ' => 'i','ἣ' => 'i','ἤ' => 'i','ἥ' => 'i',
'ἦ' => 'i','ἧ' => 'i','ᾐ' => 'i','ᾑ' => 'i','ᾒ' => 'i','ᾓ' => 'i',
'ᾔ' => 'i','ᾕ' => 'i','ᾖ' => 'i','ᾗ' => 'i','ὴ' => 'i','ῂ' => 'i',
'ῃ' => 'i','ῄ' => 'i','ῆ' => 'i','ῇ' => 'i','θ' => 't','ι' => 'i',
'ί' => 'i','ϊ' => 'i','ΐ' => 'i','ἰ' => 'i','ἱ' => 'i','ἲ' => 'i',
'ἳ' => 'i','ἴ' => 'i','ἵ' => 'i','ἶ' => 'i','ἷ' => 'i','ὶ' => 'i',
'ῐ' => 'i','ῑ' => 'i','ῒ' => 'i','ῖ' => 'i','ῗ' => 'i','κ' => 'k',
'λ' => 'l','μ' => 'm','ν' => 'n','ξ' => 'k','ο' => 'o','ό' => 'o',
'ὀ' => 'o','ὁ' => 'o','ὂ' => 'o','ὃ' => 'o','ὄ' => 'o','ὅ' => 'o',
'ὸ' => 'o','π' => 'p','ρ' => 'r','ῤ' => 'r','ῥ' => 'r','σ' => 's',
'ς' => 's','τ' => 't','υ' => 'y','ύ' => 'y','ϋ' => 'y','ΰ' => 'y',
'ὐ' => 'y','ὑ' => 'y','ὒ' => 'y','ὓ' => 'y','ὔ' => 'y','ὕ' => 'y',
'ὖ' => 'y','ὗ' => 'y','ὺ' => 'y','ῠ' => 'y','ῡ' => 'y','ῢ' => 'y',
'ῦ' => 'y','ῧ' => 'y','φ' => 'f','χ' => 'x','ψ' => 'p','ω' => 'o',
'ώ' => 'o','ὠ' => 'o','ὡ' => 'o','ὢ' => 'o','ὣ' => 'o','ὤ' => 'o',
'ὥ' => 'o','ὦ' => 'o','ὧ' => 'o','ᾠ' => 'o','ᾡ' => 'o','ᾢ' => 'o',
'ᾣ' => 'o','ᾤ' => 'o','ᾥ' => 'o','ᾦ' => 'o','ᾧ' => 'o','ὼ' => 'o',
'ῲ' => 'o','ῳ' => 'o','ῴ' => 'o','ῶ' => 'o','ῷ' => 'o','А' => 'A',
'Б' => 'B','В' => 'V','Г' => 'G','Д' => 'D','Е' => 'E','Ё' => 'E',
'Ж' => 'Z','З' => 'Z','И' => 'I','Й' => 'I','К' => 'K','Л' => 'L',
'М' => 'M','Н' => 'N','О' => 'O','П' => 'P','Р' => 'R','С' => 'S',
'Т' => 'T','У' => 'U','Ф' => 'F','Х' => 'K','Ц' => 'T','Ч' => 'C',
'Ш' => 'S','Щ' => 'S','Ы' => 'Y','Э' => 'E','Ю' => 'Y','Я' => 'Y',
'а' => 'A','б' => 'B','в' => 'V','г' => 'G','д' => 'D','е' => 'E',
'ё' => 'E','ж' => 'Z','з' => 'Z','и' => 'I','й' => 'I','к' => 'K',
'л' => 'L','м' => 'M','н' => 'N','о' => 'O','п' => 'P','р' => 'R',
'с' => 'S','т' => 'T','у' => 'U','ф' => 'F','х' => 'K','ц' => 'T',
'ч' => 'C','ш' => 'S','щ' => 'S','ы' => 'Y','э' => 'E','ю' => 'Y',
'я' => 'Y','ð' => 'd','Ð' => 'D','þ' => 't','Þ' => 'T','ა' => 'a',
'ბ' => 'b','გ' => 'g','დ' => 'd','ე' => 'e','ვ' => 'v','ზ' => 'z',
'თ' => 't','ი' => 'i','კ' => 'k','ლ' => 'l','მ' => 'm','ნ' => 'n',
'ო' => 'o','პ' => 'p','ჟ' => 'z','რ' => 'r','ს' => 's','ტ' => 't',
'უ' => 'u','ფ' => 'p','ქ' => 'k','ღ' => 'g','ყ' => 'q','შ' => 's',
'ჩ' => 'c','ც' => 't','ძ' => 'd','წ' => 't','ჭ' => 'c','ხ' => 'k',
'ჯ' => 'j','ჰ' => 'h'
];
return str_replace(array_keys($transliteration), array_values($transliteration), $string);
}
}

47
api/app/Utils/ZipUtil.php Normal file
View File

@@ -0,0 +1,47 @@
<?php
namespace App\Utils;
use Exception;
use ZipArchive;
class ZipUtil
{
public static function extract($file, $destination)
{
$zipper = new ZipArchive();
if(!$zipper->open($file)) {
throw new Exception('Erro ao abrir o arquivo ZIP.');
}
if($zipper->numFiles == 0) {
throw new Exception('Arquivo vazio ou não encontrado.');
}
$zipper->extractTo($destination);
$zipper->close();
}
public static function compress($files, $destination)
{
$zipper = new ZipArchive();
$path = dirname($destination);
if (file_exists($path) === false) {
mkdir($path);
}
if ($zipper->open($destination, ZipArchive::CREATE) !== TRUE) {
throw new Exception('Erro ao abrir o diretório de destino do arquivo ZIP.');
}
foreach ($files as $file) {
$zipper->addFile($file['path'], $file['name']);
}
$zipper->close();
}
}