Failed Conditions
Push — v7 ( 2109ab...348606 )
by Florent
02:23
created

CompressionMethodManager::add()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 9
rs 9.6666
c 0
b 0
f 0
cc 2
eloc 5
nc 2
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * The MIT License (MIT)
7
 *
8
 * Copyright (c) 2014-2017 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\Encryption\Compression;
15
16
final class CompressionMethodManager
17
{
18
    /**
19
     * @var CompressionMethodInterface[]
20
     */
21
    private $compressionMethods = [];
22
23
    /**
24
     * @param CompressionMethodInterface[] $methods
25
     *
26
     * @return CompressionMethodManager
27
     */
28
    public static function create(array $methods): CompressionMethodManager
29
    {
30
        $manager = new self();
31
        foreach ($methods as $method) {
32
            $manager->add($method);
33
        }
34
35
        return $manager;
36
    }
37
38
    /**
39
     * @param CompressionMethodInterface $compressionMethod
40
     */
41
    private function add(CompressionMethodInterface $compressionMethod)
42
    {
43
        $name = $compressionMethod->name();
44
        if ($this->has($name)) {
45
            throw new \InvalidArgumentException(sprintf('The compression method "%s" is already supported.', $name));
46
        }
47
48
        $this->compressionMethods[$name] = $compressionMethod;
49
    }
50
51
    /**
52
     * @param string $name
53
     *
54
     * @return bool
55
     */
56
    public function has(string $name): bool
57
    {
58
        return array_key_exists($name, $this->compressionMethods);
59
    }
60
61
    /**
62
     * This method will try to find a CompressionInterface object able to support the compression method.
63
     *
64
     * @param string $name The name of the compression method
65
     *
66
     * @return CompressionMethodInterface
67
     */
68
    public function get(string $name): CompressionMethodInterface
69
    {
70
        if (!$this->has($name)) {
71
            throw new \InvalidArgumentException(sprintf('The compression method "%s" is not supported.', $name));
72
        }
73
74
        return $this->compressionMethods[$name];
75
    }
76
77
    /**
78
     * @return string[]
79
     */
80
    public function list(): array
81
    {
82
        return array_keys($this->compressionMethods);
83
    }
84
}
85