Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[PropertyInfo] Allow fetching of types from @method annotations on class #28974

Open
raresserban opened this issue Oct 25, 2018 · 0 comments

Comments

Projects
None yet
2 participants
@raresserban
Copy link

commented Oct 25, 2018

Description
Allow the PropertyInfo component to also fetch type information from @method annotations on the class.This is useful when using DTO class which implement the __call method for setters/getters and when using the serializer.

Example
Given this trait:

trait DTOTrait
{
    protected $objectData = [];

    public function __call($name, $arguments)
    {
        if ('get' === substr($name, 0, 3)) {
            return $this->objectData[$this->getProperty($name)] ?? null;
        } elseif ('set' === substr($name, 0, 3) && array_key_exists(0, $arguments)) {
            $this->objectData[$this->getProperty($name)] = $arguments[0];

            return $this;
        }
    }

    public function __isset($name)
    {
        return array_key_exists($name, $this->objectData);
    }

    /**
     * From \JsonSerializable interface.
     *
     * Specify data which should be serialized to JSON
     * @link https://php.net/manual/en/jsonserializable.jsonserialize.php
     * @return mixed data which can be serialized by <b>json_encode</b>,
     * which is a value of any type other than a resource.
     */
    public function jsonSerialize()
    {
        return $this->objectData;
    }

    private function getProperty($name)
    {
        return lcfirst(substr($name, 3));
    }
}

And a class that uses it:

/**
 * @method self setData(DealDataDTO[] $data)
 * @method string getOrder()
 * @method self setOrder(?string $order)
 * @method \DateTime getEndDate()
 * @method self setEndDate(?\DateTime $endDate)
 */
class DealDTO implements \JsonSerializable
{
    use DTOTrait;
}

When serializing/deserializing the class, the Symfony Serializer, which uses the PropertyAccess component could use the information from the @method self setEndDate(?\DateTime $endDate) annotation to transform the $endDate property to a \DateTime, instead of just calling the setEndDate function with a string.
Keep in mind that I am also using the magic_call option from the PropertyAccess component.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.