82 lines
1.7 KiB
PHP
82 lines
1.7 KiB
PHP
<?php
|
|
|
|
namespace App\Services\Cadastro\Localizacao;
|
|
|
|
use App\Models\Cadastro\Localizacao\Endereco;
|
|
|
|
class EnderecoSaveService
|
|
{
|
|
private $endereco;
|
|
private $params;
|
|
|
|
public function __construct(array $params)
|
|
{
|
|
$this->params = $params;
|
|
|
|
$this->treatParams();
|
|
$this->setEndereco();
|
|
}
|
|
|
|
private function treatParams()
|
|
{
|
|
if (array_key_exists('complemento', $this->params)
|
|
&& is_string($this->params['complemento'])
|
|
) {
|
|
|
|
$this->params['complemento'] = mb_strtoupper($this->params['complemento']);
|
|
}
|
|
}
|
|
|
|
private function setEndereco()
|
|
{
|
|
$this->endereco = Endereco::where([
|
|
'logradouro_id' => $this->params['logradouro_id'],
|
|
'numero' => $this->params['numero'] ?? null,
|
|
'complemento' => $this->params['complemento'] ?? null
|
|
])->first();
|
|
}
|
|
|
|
public function save()
|
|
{
|
|
if ($this->exists()) {
|
|
|
|
$this->endereco->update($this->getParamsToSave());
|
|
|
|
return $this->endereco->fresh();
|
|
}
|
|
|
|
return Endereco::create($this->getParamsToSave());
|
|
}
|
|
|
|
private function exists()
|
|
{
|
|
return !is_null($this->endereco);
|
|
}
|
|
|
|
private function getParamsToSave()
|
|
{
|
|
$params = [];
|
|
|
|
$keys = [
|
|
'logradouro_id',
|
|
'numero',
|
|
'complemento',
|
|
'latitude',
|
|
'longitude',
|
|
'referencia',
|
|
'zona_id',
|
|
'loteamento_id'
|
|
];
|
|
|
|
foreach ($keys as $key) {
|
|
|
|
if (array_key_exists($key, $this->params)) {
|
|
|
|
$params[$key] = $this->params[$key];
|
|
}
|
|
}
|
|
|
|
return $params;
|
|
}
|
|
}
|