1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Source\Models\Address; |
4
|
|
|
|
5
|
|
|
use Source\Core\Model; |
6
|
|
|
|
7
|
|
|
/** |
8
|
|
|
* @package Source\Models |
9
|
|
|
*/ |
10
|
|
|
class City extends Model |
11
|
|
|
{ |
12
|
|
|
/** |
13
|
|
|
* City constructor. |
14
|
|
|
*/ |
15
|
|
|
public function __construct() |
16
|
|
|
{ |
17
|
|
|
parent::__construct("city", ["id"], ["state_id", "ibge", "name"]); |
18
|
|
|
} |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* @param int $state_id |
22
|
|
|
* @param int $ibge |
23
|
|
|
* @param string $name |
24
|
|
|
* @return City |
25
|
|
|
*/ |
26
|
|
|
public function bootstrap(int $state_id, int $ibge, string $name): City |
27
|
|
|
{ |
28
|
|
|
$this->state_id = $state_id; |
|
|
|
|
29
|
|
|
$this->ibge = $ibge; |
|
|
|
|
30
|
|
|
$this->name = $name; |
|
|
|
|
31
|
|
|
return $this; |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* @param string $name |
36
|
|
|
* @param string $columns |
37
|
|
|
* @return null|City |
38
|
|
|
*/ |
39
|
|
|
public function findByName(string $name, string $columns = "*"): ?City |
40
|
|
|
{ |
41
|
|
|
$find = $this->find("name = :name", "name={$name}", $columns); |
42
|
|
|
|
43
|
|
|
return $find->fetch(); |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
/** |
47
|
|
|
* @return bool |
48
|
|
|
*/ |
49
|
|
|
public function save(): bool |
50
|
|
|
{ |
51
|
|
|
if (!$this->required()) { |
52
|
|
|
$this->error = "Faltam campos obrigatórios!"; |
53
|
|
|
return false; |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
/** City Update */ |
57
|
|
|
if (!empty($this->id)) { |
|
|
|
|
58
|
|
|
$cityId = $this->id; |
59
|
|
|
|
60
|
|
|
if ($this->find("name = :e AND state_id = :s AND id != :i", "e={$this->name}&i={$cityId}&s={$this->state_id}", "id")->fetch()) { |
61
|
|
|
$this->error = "A cidade informada já está cadastrada!"; |
62
|
|
|
return false; |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
$this->update($this->safe(), "id = :id", "id={$cityId}"); |
66
|
|
|
if ($this->fail()) { |
67
|
|
|
$this->error = "Erro ao atualizar, verifique os dados"; |
68
|
|
|
return false; |
69
|
|
|
} |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
/** City Create */ |
73
|
|
|
if (empty($this->id)) { |
74
|
|
|
if ($this->find("name = :e AND state_id = :s AND id != :i", "e={$this->name}&i={$this->id}&s={$this->state_id}", "id")->fetch()) { |
75
|
|
|
$this->error = "A cidade informada já está cadastrada!"; |
76
|
|
|
return false; |
77
|
|
|
} |
78
|
|
|
|
79
|
|
|
$cityId = $this->create($this->safe()); |
80
|
|
|
if ($this->fail()) { |
81
|
|
|
$this->error = "Erro ao cadastrar, verifique os dados"; |
82
|
|
|
return false; |
83
|
|
|
} |
84
|
|
|
} |
85
|
|
|
|
86
|
|
|
$this->data = ($this->findById($cityId))->data(); |
|
|
|
|
87
|
|
|
return true; |
88
|
|
|
} |
89
|
|
|
} |
90
|
|
|
|