Passed
Pull Request — 2.x (#1446)
by Harings
09:04
created

HandlesStubs::replaceConditionals()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 20
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 11
c 1
b 0
f 0
nc 3
nop 3
dl 0
loc 20
rs 9.9
1
<?php
2
3
namespace A17\Twill\Commands\Traits;
4
5
trait HandlesStubs
6
{
7
    /**
8
     * @param array $variables
9
     * @param string $stub
10
     * @param array|null $delimiters
11
     * @return string
12
     */
13
    public function replaceVariables($variables, $stub, $delimiters = null)
14
    {
15
        $delimiters = $delimiters ?: ['{{', '}}'];
16
17
        foreach ($variables as $key => $value) {
18
            $key = "{$delimiters[0]}{$key}{$delimiters[1]}";
19
20
            $stub = str_replace($key, $value, $stub);
21
        }
22
23
        return $stub;
24
    }
25
26
    /**
27
     * @param array $variables
28
     * @param string $stub
29
     * @param array|null $delimiters
30
     * @return string
31
     */
32
    public function replaceConditionals($conditionals, $stub, $delimiters = null)
33
    {
34
        $delimiters = $delimiters ?: ['{{', '}}'];
35
36
        foreach ($conditionals as $key => $value) {
37
            $start = "{$delimiters[0]}{$key}{$delimiters[1]}";
38
            $end = "{$delimiters[0]}\/{$key}{$delimiters[1]}";
39
40
            if ((bool)$value) {
41
                // replace delimiters only
42
                $stub = preg_replace("/$start/", '', $stub);
43
                $stub = preg_replace("/$end/", '', $stub);
44
            } else {
45
                // replace delimiters and everything between
46
                $anything = '[\s\S]+?';
47
                $stub = preg_replace("/{$start}{$anything}{$end}/", '', $stub);
48
            }
49
        }
50
51
        return $stub;
52
    }
53
54
    /**
55
     * @param string $stub
56
     * @return string
57
     */
58
    public function removeEmptyLinesWithOnlySpaces($stub)
59
    {
60
        return preg_replace('/^ +\n/m', '', $stub);
61
    }
62
}
63