ValidationResult.php

Code Hygiene Score: 100

Keine Issues gefunden.

Klassen 1

Funktionen 7

Versionen 1

Code

<?php

declare(strict_types=1);

namespace Infrastructure\Validation;

// @responsibility: Value Object für Validierungsergebnisse (immutable)

final readonly class ValidationResult
{
    /**
     * @param bool        $valid Whether validation passed
     * @param string|null $error Error message if validation failed
     * @param mixed       $data  Additional data (e.g., validated value)
     */
    private function __construct(
        public bool $valid,
        public ?string $error,
        public mixed $data = null
    ) {
    }

    /**
     * Create a successful validation result.
     *
     * @param mixed $data Optional data to include (e.g., validated/normalized value)
     */
    public static function ok(mixed $data = null): self
    {
        return new self(true, null, $data);
    }

    /**
     * Create a failed validation result.
     *
     * @param string $message Error message describing the validation failure
     */
    public static function error(string $message): self
    {
        return new self(false, $message);
    }

    /**
     * Check if validation passed.
     */
    public function isValid(): bool
    {
        return $this->valid;
    }

    /**
     * Check if validation failed.
     */
    public function isError(): bool
    {
        return !$this->valid;
    }

    /**
     * Get error message or null if valid.
     */
    public function getError(): ?string
    {
        return $this->error;
    }

    /**
     * Get associated data.
     */
    public function getData(): mixed
    {
        return $this->data;
    }
}
← Übersicht Graph