blockStringValue()   C
last analyzed

Complexity

Conditions 14
Paths 80

Size

Total Lines 35
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 14
eloc 19
nc 80
nop 1
dl 0
loc 35
rs 6.2666
c 0
b 0
f 0

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
2
3
namespace Digia\GraphQL\Language;
4
5
/**
6
 * Produces the value of a block string from its parsed raw value, similar to
7
 * Coffeescript's block string, Python's docstring trim or Ruby's strip_heredoc.
8
 * This implements the GraphQL spec's BlockStringValue() static algorithm.
9
 *
10
 * @param string $rawString
11
 * @return string
12
 */
13
function blockStringValue(string $rawString): string
14
{
15
    $lines        = \preg_split("/\r\n|[\n\r]/", $rawString);
16
    $lines        = false === $lines ? [] : $lines;
17
    $lineCount    = \count($lines);
18
    $commonIndent = null;
19
20
    for ($i = 1; $i < $lineCount; $i++) {
21
        $line   = $lines[$i];
22
        $indent = leadingWhitespace($line);
23
24
        if ($indent < \mb_strlen($line) && (null === $commonIndent || $indent < $commonIndent)) {
25
            $commonIndent = $indent;
26
27
            if ($commonIndent === 0) {
28
                break;
29
            }
30
        }
31
    }
32
33
    if (null !== $commonIndent && $commonIndent > 0) {
34
        for ($i = 1; $i < $lineCount; $i++) {
35
            $lines[$i] = sliceString($lines[$i], $commonIndent);
36
        }
37
    }
38
39
    while (\count($lines) > 0 && isBlank($lines[0])) {
40
        \array_shift($lines);
41
    }
42
43
    while (($lineCount = \count($lines)) > 0 && isBlank($lines[$lineCount - 1])) {
44
        \array_pop($lines);
45
    }
46
47
    return \implode("\n", $lines);
48
}
49
50
/**
51
 * @param string $string
52
 * @return int
53
 */
54
function leadingWhitespace(string $string): int
55
{
56
    $i      = 0;
57
    $length = \mb_strlen($string);
58
59
    while ($i < $length && ($string[$i] === ' ' || $string[$i] === "\t")) {
60
        $i++;
61
    }
62
63
    return $i;
64
}
65
66
/**
67
 * @param string $string
68
 * @return bool
69
 */
70
function isBlank(string $string): bool
71
{
72
    return leadingWhitespace($string) === \mb_strlen($string);
73
}
74