<?php
namespace Shared\Exception;

use Exception;
use JetBrains\PhpStorm\Pure;

class ValidationException extends Exception {
    protected array $errors;

    #[Pure] public function __construct(array $errors, $message = "Validation errors occurred", $code = 0, Exception $previous = null) {
        parent::__construct($message, $code, $previous);
        $this->errors = $errors;
    }

    public function getErrors(): array
    {
        return $this->errors;
    }

    public function __toString() {
        return __CLASS__ . ": [{$this->code}]: {$this->message}\n" . $this->formatErrors();
    }

    protected function formatErrors(): string
    {
        return implode("\n", array_map(function ($error) {
            return "- {$error}";
        }, $this->errors));
    }
}
