1: <?php declare(strict_types=1);
2:
3: namespace Salient\Core\Concern;
4:
5: use Salient\Contract\Console\ConsoleMessageType as MessageType;
6: use Salient\Contract\Core\Exception\MultipleErrorExceptionInterface;
7: use Salient\Contract\Core\MessageLevel as Level;
8: use Salient\Core\Facade\Console;
9: use Salient\Utility\Arr;
10: use Salient\Utility\Format;
11: use Salient\Utility\Str;
12:
13: /**
14: * @phpstan-require-implements MultipleErrorExceptionInterface
15: */
16: trait MultipleErrorExceptionTrait
17: {
18: protected string $MessageWithoutErrors;
19: /** @var string[] */
20: protected array $Errors;
21: protected bool $HasUnreportedErrors = true;
22:
23: public function __construct(
24: string $message = '',
25: string ...$errors
26: ) {
27: $message = rtrim($message, ':');
28: $this->MessageWithoutErrors = $message;
29: $this->Errors = $errors;
30:
31: switch (count($errors)) {
32: case 0:
33: $this->HasUnreportedErrors = false;
34: break;
35:
36: case 1:
37: $separator = ': ';
38: $append = $errors[0];
39: // No break
40: default:
41: $message = Arr::implode(
42: $separator ?? ":\n",
43: [$message, $append ?? rtrim(Format::list($errors))],
44: ''
45: );
46: break;
47: }
48:
49: parent::__construct($message);
50: }
51:
52: public function getMessageWithoutErrors(): string
53: {
54: return Str::coalesce($this->MessageWithoutErrors, $this->message);
55: }
56:
57: /**
58: * @return string[]
59: */
60: public function getErrors(): array
61: {
62: return $this->Errors;
63: }
64:
65: /**
66: * @inheritDoc
67: */
68: public function reportErrors()
69: {
70: foreach ($this->Errors as $error) {
71: Console::message('__Error:__', $error, Level::ERROR, MessageType::UNFORMATTED);
72: }
73: $this->HasUnreportedErrors = false;
74: return $this;
75: }
76:
77: /**
78: * @inheritDoc
79: */
80: public function hasUnreportedErrors(): bool
81: {
82: return $this->HasUnreportedErrors;
83: }
84:
85: /**
86: * @inheritDoc
87: */
88: public function getMetadata(): array
89: {
90: return [
91: 'Errors' => $this->Errors
92: ? Format::list($this->Errors)
93: : '<none>',
94: ];
95: }
96: }
97: