PhpFactoryFqcn   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 38
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 13
dl 0
loc 38
rs 10
c 1
b 0
f 0
wmc 7

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A ensureExtendsFactory() 0 4 2
A asInstance() 0 6 1
A ensureIsClassName() 0 4 2
A asString() 0 3 1
1
<?php
2
3
/**
4
 * This file is part of phiremock-codeception-extension.
5
 *
6
 * phiremock-codeception-extension is free software: you can redistribute it and/or modify
7
 * it under the terms of the GNU Lesser General Public License as published by
8
 * the Free Software Foundation, either version 3 of the License, or
9
 * (at your option) any later version.
10
 *
11
 * phiremock-codeception-extension is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with phiremock-codeception-extension.  If not, see <http://www.gnu.org/licenses/>.
18
 */
19
20
namespace Mcustiel\Phiremock\Server\Cli\Options;
21
22
use InvalidArgumentException;
23
use Mcustiel\Phiremock\Server\Factory\Factory;
24
use Mcustiel\Phiremock\Server\Utils\Config\Config;
25
26
class PhpFactoryFqcn
27
{
28
    private const CLASSNAME_REGEX = '~^(?:\\\\[a-z0-9_]+|[a-z0-9_]+)(?:\\\\[a-z0-9_]+)*$~i';
29
30
    /** @var string */
31
    private $className;
32
33
    public function __construct(string $className)
34
    {
35
        $this->ensureIsClassName($className);
36
        $this->ensureExtendsFactory($className);
37
        $this->className = $className;
38
    }
39
40
    public function asString(): string
41
    {
42
        return $this->className;
43
    }
44
45
    public function asInstance(Config $config): object
46
    {
47
        /** @var class-string<Factory> $className */
48
        $className = $this->className;
49
50
        return $className::createDefault($config);
51
    }
52
53
    private function ensureExtendsFactory(string $className): void
54
    {
55
        if (!is_a($className, Factory::class, true)) {
56
            throw new InvalidArgumentException(sprintf('Class %s does not extend %s', $className, Factory::class));
57
        }
58
    }
59
60
    private function ensureIsClassName(string $className): void
61
    {
62
        if (preg_match(self::CLASSNAME_REGEX, $className) !== 1) {
63
            throw new InvalidArgumentException('Invalid class name: ' . $className);
64
        }
65
    }
66
}
67