<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\MockObject;

use function array_merge;
use PHPUnit\Framework\MockObject\Generator\Generator;
use PHPUnit\Framework\MockObject\Generator\ReflectionException;
use ReflectionClass;

/**
 * @template T of object
 *
 * @no-named-arguments Parameter names are not covered by the backward compatibility promise for PHPUnit
 */
abstract class TestDoubleBuilder
{
    /**
     * @var class-string<T>
     */
    protected readonly string $type;

    /**
     * @var list<non-empty-string>
     */
    protected array $methods          = [];
    protected bool $emptyMethodsArray = false;

    /**
     * @var array<mixed>
     */
    protected array $constructorArgs      = [];
    protected bool $originalConstructor   = true;
    protected bool $originalClone         = true;
    protected bool $returnValueGeneration = true;

    /**
     * @var list<non-empty-string>
     */
    protected array $doubledProperties = [];

    /**
     * @param class-string<T> $type
     */
    public function __construct(string $type)
    {
        $this->type = $type;
    }

    /**
     * Specifies the subset of methods to mock, requiring each to exist in the class.
     *
     * @param list<non-empty-string> $methods
     *
     * @throws CannotUseOnlyMethodsException
     * @throws ReflectionException
     *
     * @return $this
     */
    public function onlyMethods(array $methods): static
    {
        if ($methods === []) {
            $this->emptyMethodsArray = true;

            return $this;
        }

        try {
            $reflector = new ReflectionClass($this->type);

            // @codeCoverageIgnoreStart
        } catch (\ReflectionException $e) {
            throw new ReflectionException(
                $e->getMessage(),
                $e->getCode(),
                $e,
            );
            // @codeCoverageIgnoreEnd
        }

        foreach ($methods as $method) {
            if (!$reflector->hasMethod($method)) {
                throw new CannotUseOnlyMethodsException($this->type, $method);
            }
        }

        $this->methods = array_merge($this->methods, $methods);

        return $this;
    }

    /**
     * Specifies properties that do not declare property hooks for which property hooks should be doubled.
     *
     * @param list<non-empty-string> $properties
     *
     * @throws PropertyCannotBeDoubledException
     * @throws ReflectionException
     *
     * @return $this
     */
    public function doubleProperties(array $properties): static
    {
        try {
            $reflector = new ReflectionClass($this->type);

            // @codeCoverageIgnoreStart
        } catch (\ReflectionException $e) {
            throw new ReflectionException(
                $e->getMessage(),
                $e->getCode(),
                $e,
            );
            // @codeCoverageIgnoreEnd
        }

        foreach ($properties as $propertyName) {
            if (!$reflector->hasProperty($propertyName)) {
                throw new PropertyCannotBeDoubledException($this->type, $propertyName, 'it does not exist');
            }

            $property = $reflector->getProperty($propertyName);

            if (!$property->isPublic()) {
                throw new PropertyCannotBeDoubledException($this->type, $propertyName, 'it is not public');
            }

            if ($property->isStatic()) {
                throw new PropertyCannotBeDoubledException($this->type, $propertyName, 'it is static');
            }

            if ($property->isReadOnly()) {
                throw new PropertyCannotBeDoubledException($this->type, $propertyName, 'it is readonly');
            }

            if ($property->isFinal()) {
                throw new PropertyCannotBeDoubledException($this->type, $propertyName, 'it is final');
            }

            if (!$property->hasType()) {
                throw new PropertyCannotBeDoubledException($this->type, $propertyName, 'it does not declare a type');
            }
        }

        $this->doubledProperties = array_merge($this->doubledProperties, $properties);

        return $this;
    }

    /**
     * Specifies the arguments for the constructor.
     *
     * @param array<mixed> $arguments
     *
     * @return $this
     */
    public function setConstructorArgs(array $arguments): static
    {
        $this->constructorArgs = $arguments;

        return $this;
    }

    /**
     * Disables the invocation of the original constructor.
     *
     * @return $this
     */
    public function disableOriginalConstructor(): static
    {
        $this->originalConstructor = false;

        return $this;
    }

    /**
     * Enables the invocation of the original constructor.
     *
     * @return $this
     */
    public function enableOriginalConstructor(): static
    {
        $this->originalConstructor = true;

        return $this;
    }

    /**
     * Disables the invocation of the original clone constructor.
     *
     * @return $this
     */
    public function disableOriginalClone(): static
    {
        $this->originalClone = false;

        return $this;
    }

    /**
     * Enables the invocation of the original clone constructor.
     *
     * @return $this
     */
    public function enableOriginalClone(): static
    {
        $this->originalClone = true;

        return $this;
    }

    /**
     * @return $this
     */
    public function enableAutoReturnValueGeneration(): static
    {
        $this->returnValueGeneration = true;

        return $this;
    }

    /**
     * @return $this
     */
    public function disableAutoReturnValueGeneration(): static
    {
        $this->returnValueGeneration = false;

        return $this;
    }

    protected function getTestDouble(?string $testDoubleClassName, bool $mockObject): MockObject|Stub
    {
        return (new Generator)->testDouble(
            $this->type,
            $mockObject,
            !$this->emptyMethodsArray ? $this->methods : null,
            $this->constructorArgs,
            $testDoubleClassName ?? '',
            $this->originalConstructor,
            $this->originalClone,
            $this->returnValueGeneration,
            $this->doubledProperties,
        );
    }
}
