Completed
Pull Request — 2.x (#2161)
by Christian
03:47
created

ExceptionValueMap::resolveFromClassName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 1
1
<?php
2
3
/*
4
 * This file is part of the FOSRestBundle package.
5
 *
6
 * (c) FriendsOfSymfony <http://friendsofsymfony.github.com/>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace FOS\RestBundle\Util;
13
14
/**
15
 * Stores map of values mapped to exception class
16
 * Resolves value by exception.
17
 *
18
 * @author Mikhail Shamin <[email protected]>
19
 *
20
 * @internal since 2.8
21
 */
22
class ExceptionValueMap
23
{
24
    /**
25
     * Map of values mapped to exception class
26
     * key => exception class
27
     * value => value associated with exception.
28
     */
29
    private $map;
30
31
    /**
32
     * @param array<string,bool>|array<string,int> $map
33
     */
34 43
    public function __construct(array $map)
35
    {
36 43
        $this->map = $map;
37 43
    }
38
39
    /**
40
     * Resolves the value corresponding to an exception object.
41
     *
42
     * @return bool|int|false Value found or false is not found
43
     */
44 3
    public function resolveException(\Exception $exception)
45
    {
46 3
        return $this->resolveThrowable($exception);
47
    }
48
49
    /**
50
     * Resolves the value corresponding to an exception object.
51
     *
52
     * @return bool|int|false Value found or false is not found
53
     *
54
     * @internal since 2.8
55
     */
56 16
    public function resolveThrowable(\Throwable $exception)
57
    {
58 16
        return $this->doResolveClass(get_class($exception));
59
    }
60
61
    /**
62
     * @internal
63
     */
64 11
    public function resolveFromClassName(string $className)
65
    {
66 11
        return $this->doResolveClass($className);
67
    }
68
69
    /**
70
     * @return bool|int|false if not found
71
     */
72 27
    private function doResolveClass(string $class)
73
    {
74 27
        foreach ($this->map as $mapClass => $value) {
75 24
            if (!$value) {
76 1
                continue;
77
            }
78
79 24
            if ($class === $mapClass || is_subclass_of($class, $mapClass)) {
0 ignored issues
show
Bug introduced by
Due to PHP Bug #53727, is_subclass_of might return inconsistent results on some PHP versions if $mapClass can be an interface. If so, you could instead use ReflectionClass::implementsInterface.
Loading history...
80 18
                return $value;
81
            }
82
        }
83
84 13
        return false;
85
    }
86
}
87