1 | <?php |
||
10 | trait AskAndValidate |
||
11 | { |
||
12 | /** |
||
13 | * @param string $question |
||
14 | * @param string $field |
||
15 | * @return string |
||
16 | */ |
||
17 | 2 | protected function askWithValidation(string $question, string $field): string |
|
18 | { |
||
19 | // Ask the question and get the answer |
||
20 | 2 | $input = $this->ask($question); |
|
|
|||
21 | |||
22 | // Populate the model |
||
23 | 2 | $this->getEntity()->fill([ |
|
24 | 2 | $field => $input, |
|
25 | ]); |
||
26 | |||
27 | // Validate the model data |
||
28 | 2 | $validator = $this->getEntity()->getValidator(); |
|
29 | 2 | if ($validator->fails()) { |
|
30 | // Get error message for the field |
||
31 | $message = (string) $validator->errors()->first($field); |
||
32 | // Display warning message if exists |
||
33 | if (!empty($message)) { |
||
34 | $this->warn($message); |
||
35 | // Ask the question again |
||
36 | return $this->askWithValidation($question, $field); |
||
37 | } |
||
38 | } |
||
39 | |||
40 | 2 | return (string) $input; |
|
41 | } |
||
42 | |||
43 | /** |
||
44 | * Required method to return the entity/model that contains the validation rules |
||
45 | * |
||
46 | * @return Model |
||
47 | */ |
||
48 | abstract protected function getEntity(): Model; |
||
49 | } |
||
50 |
This check looks for methods that are used by a trait but not required by it.
To illustrate, let’s look at the following code example
The trait
Idable
provides a methodequalsId
that in turn relies on the methodgetId()
. If this method does not exist on a class mixing in this trait, the method will fail.Adding the
getId()
as an abstract method to the trait will make sure it is available.