Created
September 29, 2021 16:54
-
-
Save Gummibeer/6092b295b3e84cffcfe20c3ddb6828f4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Exceptions; | |
use ArrayIterator; | |
use Closure; | |
use Countable; | |
use Exception; | |
use Illuminate\Support\Collection; | |
use IteratorAggregate; | |
use Illuminate\Contracts\Support\Arrayable; | |
use Illuminate\Contracts\Support\Jsonable; | |
use JsonSerializable; | |
use Stringable; | |
use Throwable; | |
use Traversable; | |
class BagException extends Exception implements Arrayable, Jsonable, JsonSerializable, Stringable, Countable, IteratorAggregate | |
{ | |
/** | |
* @param Throwable[] $exceptions | |
*/ | |
public function __construct(protected array $exceptions = []) | |
{ | |
parent::__construct(); | |
} | |
public function add(Throwable $exception): static | |
{ | |
$this->exceptions[] = $exception; | |
return $this; | |
} | |
public function addIf($condition, Throwable|Closure $exception): static | |
{ | |
return $condition | |
? $this->add(value($exception)) | |
: $this; | |
} | |
public function first(Closure|string|null $filter = null): ?Throwable | |
{ | |
if ($filter === null) { | |
return $this->exceptions()->first(); | |
} | |
return $this->filter($filter)->first(); | |
} | |
public function filter(Closure|string $filter = null): Collection | |
{ | |
if ($filter instanceof Closure) { | |
return $this->exceptions()->filter($filter); | |
} | |
return $this->exceptions() | |
->filter(fn (Throwable $exception): bool => $exception instanceof $filter); | |
} | |
public function isEmpty(): bool | |
{ | |
return ! $this->any(); | |
} | |
public function isNotEmpty(): bool | |
{ | |
return $this->any(); | |
} | |
public function any(): bool | |
{ | |
return $this->count() > 0; | |
} | |
public function count(): int | |
{ | |
return count($this->exceptions); | |
} | |
public function exceptions(): Collection | |
{ | |
return collect($this->exceptions); | |
} | |
public function getExceptions(): Collection | |
{ | |
return $this->exceptions(); | |
} | |
public function toArray(): array | |
{ | |
return $this->getExceptions()->all(); | |
} | |
public function jsonSerialize(): array | |
{ | |
return $this->toArray(); | |
} | |
public function toJson($options = 0): string | |
{ | |
return json_encode($this->jsonSerialize(), $options); | |
} | |
public function __toString(): string | |
{ | |
return $this->toJson(); | |
} | |
public function getIterator(): Traversable | |
{ | |
return new ArrayIterator($this->exceptions); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment