GetByClosure::get()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 6
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 11
ccs 6
cts 6
cp 1
crap 2
rs 10
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 3
    public function __construct(string $propertyName, string $className)
51
    {
52 3
        $this->propertyName = $propertyName;
53 3
        $this->className = $className;
54 3
    }
55
56
    /**
57
     * Get object value by binding a closure to the class
58
     *
59
     * @param object $object
60
     * @return mixed
61
     */
62 3
    public function get($object)
63
    {
64 3
        if (null === $this->getter) {
65
            $this->getter = Closure::bind(static function ($object, string $propertyName) {
66 3
                return $object->{$propertyName};
67 3
            }, null, $this->className);
68
        }
69
70 3
        $getter = $this->getter;
71
72 3
        return $getter($object, $this->propertyName);
73
    }
74
}
75