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

HandlesStubs   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 56
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 18
c 1
b 0
f 0
dl 0
loc 56
rs 10
wmc 8

3 Methods

Rating   Name   Duplication   Size   Complexity  
A replaceConditionals() 0 20 4
A removeEmptyLinesWithOnlySpaces() 0 3 1
A replaceVariables() 0 11 3
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