| 1 |
<?php |
| 2 |
|
| 3 |
namespace App\Billingo\Traits; |
| 4 |
|
| 5 |
use App\Billingo\Error\BillingoError; |
| 6 |
use App\Billingo\Models\BillingoModel; |
| 7 |
use App\Billingo\Service\SelfTest; |
| 8 |
|
| 9 |
trait WithSelfControl |
| 10 |
{ |
| 11 |
|
| 12 |
public function hasError(): bool |
| 13 |
{ |
| 14 |
$checkNestedArray = function (array $array) use (&$checkNestedArray) { |
| 15 |
foreach ($array as $element) { |
| 16 |
if (is_array($element)) { |
| 17 |
if ($checkNestedArray($element)) { |
| 18 |
|
| 19 |
return true; |
| 20 |
} |
| 21 |
} else { |
| 22 |
if ($element instanceof BillingoError) { |
| 23 |
|
| 24 |
return true; |
| 25 |
} |
| 26 |
} |
| 27 |
} |
| 28 |
|
| 29 |
return false; |
| 30 |
}; |
| 31 |
|
| 32 |
return $checkNestedArray( |
| 33 |
is_array($this->getObjectCheck()) |
| 34 |
? $this->getObjectCheck() |
| 35 |
: [camelToSnake(classBasename($this)) => $this->getObjectCheck()] |
| 36 |
); |
| 37 |
} |
| 38 |
|
| 39 |
protected function hasBillingoModel(): bool |
| 40 |
{ |
| 41 |
foreach ($this->properties as $property) { |
| 42 |
if ($property instanceof BillingoModel) { |
| 43 |
|
| 44 |
return true; |
| 45 |
} |
| 46 |
} |
| 47 |
|
| 48 |
return false; |
| 49 |
} |
| 50 |
|
| 51 |
private function getObjectCheck(): BillingoError|string|array |
| 52 |
{ |
| 53 |
|
| 54 |
if (!is_null($this->getErrors())) { |
| 55 |
|
| 56 |
return $this->getErrors(); |
| 57 |
} |
| 58 |
|
| 59 |
if ($this->hasBillingoModel()) { |
| 60 |
|
| 61 |
$objectsChecks = []; |
| 62 |
|
| 63 |
foreach ($this->properties as $key => $property) { |
| 64 |
|
| 65 |
if ($property instanceof BillingoModel) { |
| 66 |
$objectsChecks[$key] = $property->getObjectCheck(); |
| 67 |
} |
| 68 |
} |
| 69 |
|
| 70 |
return $objectsChecks; |
| 71 |
} else { |
| 72 |
|
| 73 |
return 'OK'; |
| 74 |
} |
| 75 |
} |
| 76 |
|
| 77 |
public function getSelfTest(): SelfTest |
| 78 |
{ |
| 79 |
$controlTree = $this->getObjectCheck(); |
| 80 |
|
| 81 |
return new SelfTest( |
| 82 |
classBasename($this), |
| 83 |
$controlTree instanceof BillingoError |
| 84 |
? [classBasename($this) => $controlTree] |
| 85 |
: $controlTree |
| 86 |
); |
| 87 |
} |
| 88 |
} |
| 89 |
|