Accept::hasAllowed()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 14
rs 9.2
c 0
b 0
f 0
cc 4
eloc 7
nc 4
nop 1
1
<?php
2
3
namespace Dafiti\Silex\Response;
4
5
use Dafiti\Silex\Exception\AcceptNotAllowed;
6
7
class Accept
8
{
9
    /**
10
     * @var array
11
     */
12
    private $availablesAccepts = [];
13
14
    /**
15
     * @var string
16
     */
17
    private $default;
18
19
    /**
20
     * @param string $defaultAccept
21
     * @param array  $availablesAccepts
22
     */
23
    public function __construct($defaultAccept, array $availablesAccepts = [])
24
    {
25
        $this->default = $defaultAccept;
26
        $this->availablesAccepts = $availablesAccepts;
27
    }
28
29
    /**
30
     * @return string
31
     */
32
    public function getDefault()
33
    {
34
        return $this->default;
35
    }
36
37
    /**
38
     * @param array $accepts
39
     *
40
     * @return string
41
     *
42
     * @throws AcceptNotAllowed
43
     */
44
    public function getBest(array $accepts)
45
    {
46
        if (empty($accepts)) {
47
            return $this->getDefault();
48
        }
49
50
        foreach ($accepts as $accept) {
51
            if ($this->isAllowed($accept)) {
52
                return $accept;
53
            }
54
        }
55
56
        throw new AcceptNotAllowed($accepts);
57
    }
58
59
    /**
60
     * @param string $accept
61
     *
62
     * @return bool
63
     */
64
    public function isAllowed($accept)
65
    {
66
        if (!in_array($accept, $this->availablesAccepts)) {
67
            return false;
68
        }
69
70
        return true;
71
    }
72
73
    public function hasAllowed(array $accepts)
74
    {
75
        if (empty($accepts)) {
76
            return false;
77
        }
78
79
        foreach ($accepts as $accept) {
80
            if ($this->isAllowed($accept)) {
81
                return true;
82
            }
83
        }
84
85
        return false;
86
    }
87
}
88