1 <?php
2
3 namespace Docoflow\Traits;
4
5 use Carbon\Carbon;
6
7 8 9 10 11 12
13 trait Validable
14 {
15 16 17 18 19
20 protected $validUntil;
21
22 23 24 25 26
27 public function validUntil()
28 {
29 if ($validUntil = $this->getAttribute('expired_at')) {
30 if ($this->validUntil) {
31 return $this->validUntil;
32 }
33
34 $this->validUntil = new Carbon($validUntil);
35
36 return $this->validUntil;
37 }
38 }
39
40 41 42 43 44
45 public function valid()
46 {
47 if ($validUntil = $this->validUntil()) {
48 return !$validUntil->isPast();
49 }
50
51 return true;
52 }
53
54 55 56 57 58
59 public function status()
60 {
61 if (is_null($status = (int) $this->getAttribute('status'))) {
62 $status = 0;
63 }
64
65 switch ($status) {
66 case 0:
67 return static::UNPROCESSED;
68 break;
69 case 1:
70 return static::APPROVED;
71 break;
72 case 2:
73 return static::PARTIAL;
74 break;
75 case 3:
76 return static::REJECTED;
77 break;
78 default:
79 return static::INVALID;
80 break;
81 }
82 }
83
84 85 86 87 88
89 public function approve()
90 {
91 $this->setAttribute('status', static::APPROVED);
92
93 return $this;
94 }
95
96 97 98 99 100
101 public function approveIf()
102 {
103 if (! $this->valid()) {
104 throw new LogicException('Cannot be approved, because validation process is expired.');
105 }
106
107 return $this->approve();
108 }
109
110 111 112 113 114
115 public function reject()
116 {
117 $this->setAttribute('status', static::REJECTED);
118
119 return $this;
120 }
121
122 123 124 125 126
127 public function rejectIf()
128 {
129 if (! $this->valid()) {
130 throw new LogicException('Cannot be rejected, because validation process is expired.');
131 }
132
133 return $this->reject();
134 }
135
136 137 138 139 140
141 public function reset()
142 {
143 $this->setAttribute('status', static::UNPROCESSED);
144
145 return $this;
146 }
147
148 149 150 151 152
153 public function resetIf()
154 {
155 if (! $this->valid()) {
156 throw new LogicException('Cannot be reseted, because validation process is expired.');
157 }
158
159 return $this->resetIf();
160 }
161 }
162