<?php declare(strict_types=1);

namespace Newland\Toubiz\Sync\Neos\Tests\Unit\ErrorHandling;

use Neos\Error\Messages\Error;
use Neos\Error\Messages\Result;
use Neos\Flow\Validation\Validator\ValidatorInterface;
use Newland\Toubiz\Sync\Neos\ErrorHandling\Validator\NullableValidator;
use PHPUnit\Framework\TestCase;

class NullableValidatorTest extends TestCase implements ValidatorInterface
{
    /** @var bool */
    private $innerValidationFails;

    /** @var bool */
    private $innerValidatorCalled;

    /** @var NullableValidator */
    private $subject;

    public function setUp(): void
    {
        parent::setUp();

        $this->innerValidationFails = true;
        $this->innerValidatorCalled = 0;
        $this->subject = new NullableValidator($this);
    }

    public function testIsAlwaysValidIfNull(): void
    {
        $this->innerValidationFails = true;
        $this->assertFalse($this->subject->validate(null)->hasErrors());
    }

    public function testCallsWrappedValidatorIfNotNull(): void
    {
        $this->innerValidationFails = false;
        $this->assertFalse($this->subject->validate('foo')->hasErrors());
        $this->assertEquals(1, $this->innerValidatorCalled);

        $this->innerValidationFails = true;
        $this->assertTrue($this->subject->validate('foo')->hasErrors());
        $this->assertEquals(2, $this->innerValidatorCalled);
    }


    public function validate($value)
    {
        $this->innerValidatorCalled++;
        $result = new Result();
        if ($this->innerValidationFails) {
            $result->addError(new Error('Test Error'));
        }
        return $result;
    }


    public function getOptions()
    {
        // Mock of ValidatorInterface
    }
}
