Completed
Push — caching ( 6c9b2f )
by Nate
03:39
created

GetByClosure::__sleep()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 1
c 0
b 0
f 0
dl 0
loc 3
rs 10
cc 1
nc 1
nop 0
1
<?php
2
/*
3
 * Copyright (c) Nate Brunette.
4
 * Distributed under the MIT License (http://opensource.org/licenses/MIT)
5
 */
6
7
declare(strict_types=1);
8
9
namespace Tebru\Gson\Internal\AccessorStrategy;
10
11
use Closure;
12
use Tebru\Gson\Internal\GetterStrategy;
13
14
/**
15
 * Class GetByClosure
16
 *
17
 * Get data from an object by binding a closure to the class
18
 *
19
 * @author Nate Brunette <[email protected]>
20
 */
21
final class GetByClosure implements GetterStrategy
22
{
23
    /**
24
     * The name of the property
25
     *
26
     * @var string
27
     */
28
    public $propertyName;
29
30
    /**
31
     * The name of the class
32
     *
33
     * @var string
34
     */
35
    public $className;
36
37
    /**
38
     * The cached closure
39
     *
40
     * @var Closure
41
     */
42
    public $getter;
43
44
    /**
45
     * Constructor
46
     *
47
     * @param string $propertyName
48
     * @param string $className
49
     */
50
    public function __construct(string $propertyName, string $className)
51
    {
52
        $this->propertyName = $propertyName;
53
        $this->className = $className;
54
    }
55
56
    /**
57
     * Get object value by binding a closure to the class
58
     *
59
     * @param object $object
60
     * @return mixed
61
     */
62
    public function get($object)
63
    {
64
        if (null === $this->getter) {
65
            $this->getter = Closure::bind(static function ($object, string $propertyName) {
66
                return $object->{$propertyName};
67
            }, null, $this->className);
68
        }
69
70
        $getter = $this->getter;
71
72
        return $getter($object, $this->propertyName);
73
    }
74
75
    public function __sleep()
76
    {
77
        return ['propertyName', 'className'];
78
    }
79
}
80