95 lines
2.3 KiB
PHP
95 lines
2.3 KiB
PHP
<?php
|
|
|
|
namespace App\Rules;
|
|
|
|
use App\Models\Cadastro\SujeitoAtencao\Cidadao;
|
|
|
|
use Illuminate\Contracts\Validation\Rule;
|
|
|
|
class CpfDuplication implements Rule
|
|
{
|
|
private $params;
|
|
private $id;
|
|
|
|
public function __construct(array $params = [])
|
|
{
|
|
$this->params = $params;
|
|
$this->id = $params['id'] ?? null;
|
|
}
|
|
/**
|
|
* Determine if the validation rule passes.
|
|
*
|
|
* @param string $attribute
|
|
* @param mixed $value
|
|
* @return bool
|
|
*/
|
|
public function passes($attribute, $value)
|
|
{
|
|
$cpf = $this->params['cpf'] ?? null;
|
|
|
|
if (empty($cpf))
|
|
return true;
|
|
|
|
if (!$this->isCpfDuplicated($this->id, $cpf))
|
|
return true;
|
|
|
|
$cpfNaoPertenceAoCidadao = $this->params['cpf_nao_pertence_ao_cidadao'] ?? null;
|
|
|
|
if ($cpfNaoPertenceAoCidadao) {
|
|
|
|
$motivo = $this->params['motivo_duplicidade_cpf_id'] ?? null;
|
|
|
|
if ((int)$motivo > 0) {
|
|
|
|
$nome = trim($this->params['nome']);
|
|
|
|
if (!$this->thereIsCidadaoWithSameNameAndCpf($nome, $cpf))
|
|
return true;
|
|
}
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
private function isCpfDuplicated($id, $cpf)
|
|
{
|
|
if (is_null($id)) {
|
|
return Cidadao::where([['cpf', $cpf], ['motivo_duplicidade_cpf_id', null]])
|
|
->whereHas('paciente', function ($query) {
|
|
$query->whereNull('deleted_at');
|
|
})
|
|
->exists();
|
|
}
|
|
|
|
return Cidadao::where([
|
|
['cpf', $cpf],
|
|
['id', '<>', $id],
|
|
['motivo_duplicidade_cpf_id', null]
|
|
])
|
|
->whereHas('paciente', function ($query) {
|
|
$query->whereNull('deleted_at');
|
|
})
|
|
->exists();
|
|
}
|
|
|
|
private function thereIsCidadaoWithSameNameAndCpf($name, $cpf)
|
|
{
|
|
if (is_null($this->id))
|
|
$cidadaos = Cidadao::where([['nome', $name], ['cpf', $cpf]])->get();
|
|
else
|
|
$cidadaos = Cidadao::where([['nome', $name], ['cpf', $cpf], ['id', '<>', $this->id]])->get();
|
|
|
|
return $cidadaos->count() > 0;
|
|
}
|
|
|
|
/**
|
|
* Get the validation error message.
|
|
*
|
|
* @return string
|
|
*/
|
|
public function message()
|
|
{
|
|
return 'CPF já cadastrado para outro cidadão.';
|
|
}
|
|
}
|