1<?php
2
3namespace DeepCopy\Filter;
4
5use DeepCopy\Reflection\ReflectionHelper;
6
7/**
8 * @final
9 */
10class ReplaceFilter implements Filter
11{
12    /**
13     * @var callable
14     */
15    protected $callback;
16
17    /**
18     * @param callable $callable Will be called to get the new value for each property to replace
19     */
20    public function __construct(callable $callable)
21    {
22        $this->callback = $callable;
23    }
24
25    /**
26     * Replaces the object property by the result of the callback called with the object property.
27     *
28     * {@inheritdoc}
29     */
30    public function apply($object, $property, $objectCopier)
31    {
32        $reflectionProperty = ReflectionHelper::getProperty($object, $property);
33        $reflectionProperty->setAccessible(true);
34
35        $value = call_user_func($this->callback, $reflectionProperty->getValue($object));
36
37        $reflectionProperty->setValue($object, $value);
38    }
39}
40