Completed
Pull Request — master (#884)
by Robert
13:50
created

DefaultAccessorFinder::findSetter()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
c 0
b 0
f 0
rs 10
cc 1
eloc 2
nc 1
nop 2
1
<?php
2
3
namespace JMS\Serializer\Accessor\Guess;
4
5
/**
6
 * Find for accessors in "getFooBar" and "setFooBar" format.
7
 */
8
final class DefaultAccessorFinder implements AccessorFinderInterface
9
{
10
    /**
11
     * {@inheritDoc}
12
     */
13
    public function findGetter(\ReflectionClass $class, $propertyName)
14
    {
15
        return $this->findAccessor('get', $propertyName, $class);
16
    }
17
18
    /**
19
     * {@inheritDoc}
20
     */
21
    public function findSetter(\ReflectionClass $class, $propertyName)
22
    {
23
        return $this->findAccessor('set', $propertyName, $class);
24
    }
25
26
    /**
27
     * @param $prefix
28
     * @param $property
29
     * @param \ReflectionClass $class
30
     * @return null|string
31
     */
32
    private function findAccessor($prefix, $property, \ReflectionClass $class)
33
    {
34
        $method = $prefix . $this->toStudyCase($property);
35
36
        return $class->hasMethod($method) ? $method : null;
37
    }
38
39
    /**
40
     * @param string $value
41
     * @return string
42
     */
43
    private function toStudyCase($value)
44
    {
45
        // "foo-bar_baz" -> "fooBarBaz":
46
        $value = \preg_replace_callback('/[\-\_](?<letter>\w)/', function (array $matches) {
47
            return strtoupper($matches['letter']);
48
        }, $value);
49
50
        return ucfirst($value);
51
    }
52
}
53