Stub   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 68
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 3
Bugs 0 Features 0
Metric Value
eloc 11
c 3
b 0
f 0
dl 0
loc 68
ccs 12
cts 12
cp 1
rs 10
wmc 6

4 Methods

Rating   Name   Duplication   Size   Complexity  
A path() 0 5 2
A get() 0 7 2
A replace() 0 5 1
A isCustom() 0 3 1
1
<?php
2
/*
3
 * This file is part of the "andrey-helldar/support" project.
4
 *
5
 * For the full copyright and license information, please view the LICENSE
6
 * file that was distributed with this source code.
7
 *
8
 * @author Andrey Helldar <[email protected]>
9
 *
10
 * @copyright 2021 Andrey Helldar
11
 *
12
 * @license MIT
13
 *
14
 * @see https://github.com/andrey-helldar/support
15
 */
16
17
namespace Helldar\Support\Tools;
18
19
use Helldar\Support\Exceptions\UnknownStubFileException;
20
use Helldar\Support\Facades\Helpers\Str;
21
22
class Stub
23
{
24
    public const PHP_ARRAY = 'php_array.stub';
25
26
    public const JSON = 'json.stub';
27
28
    /**
29
     * Replace the contents of the template file.
30
     *
31
     * @param  string  $stub_file
32
     * @param  array  $replace
33
     *
34
     * @throws \Helldar\Support\Exceptions\UnknownStubFileException
35
     *
36
     * @return string
37
     */
38 16
    public function replace(string $stub_file, array $replace): string
39
    {
40 16
        $content = $this->get($stub_file);
41
42 16
        return Str::replace($content, $replace);
43
    }
44
45
    /**
46
     * Receive the contents of the template file.
47
     *
48
     * @param  string  $filename
49
     *
50
     * @throws \Helldar\Support\Exceptions\UnknownStubFileException
51
     *
52
     * @return string
53
     */
54 24
    public function get(string $filename): string
55
    {
56 24
        if ($path = $this->path($filename)) {
57 22
            return file_get_contents($path);
58
        }
59
60 2
        throw new UnknownStubFileException($filename);
61
    }
62
63
    /**
64
     * Receive the path to the template file.
65
     *
66
     * @param  string  $filename
67
     *
68
     * @return string|null
69
     */
70 24
    protected function path(string $filename): ?string
71
    {
72 24
        $path = $this->isCustom($filename) ? $filename : __DIR__ . '/../../resources/stubs/' . $filename;
73
74 24
        return realpath($path);
75
    }
76
77
    /**
78
     * Returns a link to the template file.
79
     *
80
     * If the file exists under the specified link, it will return it,
81
     * otherwise it will search in the default folder.
82
     *
83
     * @param  string  $path
84
     *
85
     * @return bool
86
     */
87 24
    protected function isCustom(string $path): bool
88
    {
89 24
        return file_exists($path);
90
    }
91
}
92