Loop::foreach()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Murtukov\PHPCodeGenerator;
6
7
class Loop extends DependencyAwareGenerator implements BlockInterface
8
{
9
    use ScopedContentTrait;
10
11
    public const TYPE_WHILE = 'while';
12
    public const TYPE_FOR = 'for';
13
    public const TYPE_FOREACH = 'foreach';
14
    public const TYPE_DO_WHILE = 'doWhile';
15
16
    private string $condition;
17
    private string $type;
18
19 3
    public function __construct(string $condition = '', $type = self::TYPE_WHILE)
20
    {
21 3
        $this->condition = $condition;
22 3
        $this->type = $type;
23 3
    }
24
25 4
    public function generate(): string
26
    {
27
        // do ... while
28 4
        if (self::TYPE_DO_WHILE === $this->type) {
29
            return <<<CODE
30 1
            do {
31 1
            {$this->generateContent()}
32 1
            } while ($this->condition)
33
            CODE;
34
        }
35
36
        // Other loop types
37
        return <<<CODE
38 4
        $this->type ($this->condition) {
39 4
        {$this->generateContent()}
40
        }
41
        CODE;
42
    }
43
44 1
    public static function while(string $condition)
45
    {
46 1
        return new self($condition);
47
    }
48
49 1
    public static function for(string $condition)
50
    {
51 1
        return new self($condition, self::TYPE_FOR);
52
    }
53
54 3
    public static function foreach(string $condition)
55
    {
56 3
        return new self($condition, self::TYPE_FOREACH);
57
    }
58
59 1
    public static function doWhile(string $condition)
60
    {
61 1
        return new self($condition, self::TYPE_DO_WHILE);
62
    }
63
}
64