<?php

declare(strict_types=1);

namespace GroundLevel\Testing\Traits;

/**
 * Class trait with utility functions for writing to private/protected properties.
 */
trait WritesProperties
{
    /**
     * Sets the value of a private or protected property of an object.
     *
     * @param  string|object $object        An instance of the class or the class name.
     * @param  string        $propertyName  The name of property for which to set the value.
     * @param  mixed         $propertyValue The value of property to set.
     * @return mixed
     */
    protected function setPropertyValue($object, string $propertyName, $propertyValue) // phpcs:ignore Squiz.Commenting.FunctionComment.TypeHintMissing -- `mixed` type hinting available from PHP 8.0+.
    {
        /*
         * @var ReflectionProperty $prop
         */
        $property = $this->getProperty($object, $propertyName);

        // Check if the property is static.
        if ($property->isStatic()) {
            // Use setStaticPropertyValue for static properties.
            $property->getDeclaringClass()->setStaticPropertyValue($propertyName, $propertyValue);
        } else {
            // Use setValue for non-static properties.
            $property->setValue($object, $propertyValue);
        }
    }
}
