ArgumentValueBuilder::build()   C
last analyzed

Complexity

Conditions 11
Paths 12

Size

Total Lines 39
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 39
rs 5.2653
c 0
b 0
f 0
cc 11
eloc 22
nc 12
nop 2

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php declare(strict_types=1);
2
3
/*
4
 * This file is part of the pinepain/js-sandbox PHP library.
5
 *
6
 * Copyright (c) 2016-2017 Bogdan Padalko <[email protected]>
7
 *
8
 * Licensed under the MIT license: http://opensource.org/licenses/MIT
9
 *
10
 * For the full copyright and license information, please view the
11
 * LICENSE file that was distributed with this source or visit
12
 * http://opensource.org/licenses/MIT
13
 */
14
15
16
namespace Pinepain\JsSandbox\Specs\Builder;
17
18
19
use Pinepain\JsSandbox\Specs\Builder\Exceptions\ArgumentValueBuilderException;
20
21
22
class ArgumentValueBuilder implements ArgumentValueBuilderInterface
23
{
24
    /**
25
     * {@inheritdoc}
26
     */
27
    public function build(string $definition, bool $with_literal)
28
    {
29
        if (is_numeric($definition)) {
30
            if (false !== strpos($definition, '.')) {
31
                return (float)$definition;
32
            }
33
34
            return (int)$definition;
35
        }
36
37
        switch (strtolower($definition)) {
38
            case 'null':
39
                return null;
40
            case 'true':
41
                return true;
42
            case 'false':
43
                return false;
44
        }
45
46
        if ($this->wrappedWith($definition, '[', ']')) {
47
            return [];
48
        }
49
50
        if ($this->wrappedWith($definition, '{', '}')) {
51
            return [];
52
        }
53
54
        foreach (['"', "'"] as $quote) {
55
            if ($this->wrappedWith($definition, $quote, $quote)) {
56
                return trim($definition, $quote);
57
            }
58
        }
59
60
        if (!$with_literal) {
61
            throw new ArgumentValueBuilderException("Unknown value format '{$definition}'");
62
        }
63
64
        return $definition;
65
    }
66
67
    private function wrappedWith(string $definition, string $starts, $ends)
68
    {
69
        if (strlen($definition) < 2) {
70
            return false;
71
        }
72
73
        return $starts == $definition[0] && $ends == $definition[-1];
74
    }
75
}
76