AlgorithmManager::has()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * The MIT License (MIT)
7
 *
8
 * Copyright (c) 2014-2019 Spomky-Labs
9
 *
10
 * This software may be modified and distributed under the terms
11
 * of the MIT license.  See the LICENSE file for details.
12
 */
13
14
namespace Jose\Component\Core;
15
16
use InvalidArgumentException;
17
18
class AlgorithmManager
19
{
20
    /**
21
     * @var array
22
     */
23
    private $algorithms = [];
24
25
    /**
26
     * @param Algorithm[] $algorithms
27
     */
28
    public function __construct(array $algorithms)
29
    {
30
        foreach ($algorithms as $algorithm) {
31
            $this->add($algorithm);
32
        }
33
    }
34
35
    /**
36
     * Returns true if the algorithm is supported.
37
     *
38
     * @param string $algorithm The algorithm
39
     */
40
    public function has(string $algorithm): bool
41
    {
42
        return \array_key_exists($algorithm, $this->algorithms);
43
    }
44
45
    /**
46
     * Returns the list of names of supported algorithms.
47
     *
48
     * @return string[]
49
     */
50
    public function list(): array
51
    {
52
        return array_keys($this->algorithms);
53
    }
54
55
    /**
56
     * Returns the algorithm if supported, otherwise throw an exception.
57
     *
58
     * @param string $algorithm The algorithm
59
     *
60
     * @throws InvalidArgumentException if the algorithm is not supported
61
     */
62
    public function get(string $algorithm): Algorithm
63
    {
64
        if (!$this->has($algorithm)) {
65
            throw new InvalidArgumentException(sprintf('The algorithm "%s" is not supported.', $algorithm));
66
        }
67
68
        return $this->algorithms[$algorithm];
69
    }
70
71
    /**
72
     * Adds an algorithm to the manager.
73
     */
74
    private function add(Algorithm $algorithm): void
75
    {
76
        $name = $algorithm->name();
77
        $this->algorithms[$name] = $algorithm;
78
    }
79
}
80