Skip to content

Instantly share code, notes, and snippets.

@Gummibeer
Created September 29, 2021 16:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Gummibeer/6092b295b3e84cffcfe20c3ddb6828f4 to your computer and use it in GitHub Desktop.
Save Gummibeer/6092b295b3e84cffcfe20c3ddb6828f4 to your computer and use it in GitHub Desktop.
<?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