Passed
Push — master ( 8ef71d...d04643 )
by Austin
03:30 queued 01:15
created

SecurityTxtHelper::__construct()   C

Complexity

Conditions 9
Paths 7

Size

Total Lines 48
Code Lines 32

Duplication

Lines 10
Ratio 20.83 %

Importance

Changes 0
Metric Value
dl 10
loc 48
rs 5.5102
c 0
b 0
f 0
cc 9
eloc 32
nc 7
nop 0
1
<?php
2
/**
3
 * src/SecurityTxtHelper.php.
4
 *
5
 * @author      Austin Heap <[email protected]>
6
 * @version     v0.3.0
7
 */
8
declare(strict_types=1);
9
10
namespace AustinHeap\Security\Txt;
11
12
/**
13
 * SecurityTxtHelper.
14
 *
15
 * @link        https://github.com/austinheap/laravel-security-txt
16
 * @link        https://packagist.org/packages/austinheap/laravel-security-txt
17
 * @link        https://austinheap.github.io/laravel-security-txt/classes/AustinHeap.Security.Txt.SecurityTxtHelper.html
18
 */
19
class SecurityTxtHelper
20
{
21
    /**
22
     * Internal version number.
23
     *
24
     * @var string
25
     */
26
    const VERSION = '0.3.0';
27
28
    /**
29
     * Internal SecurityTxt object.
30
     *
31
     * @var \AustinHeap\Security\Txt\Writer
32
     */
33
    protected $writer = null;
34
35
    /**
36
     * Internal array of log entries.
37
     *
38
     * @var array
39
     */
40
    protected $logEntries = [];
41
42
    /**
43
     * Enable built-in cache.
44
     *
45
     * @var bool
46
     */
47
    protected $cache = false;
48
49
    /**
50
     * Minutes to cache output.
51
     *
52
     * @var int
53
     */
54
    protected $cacheTime = null;
55
56
    /**
57
     * Cache key to use.
58
     *
59
     * @var string
60
     */
61
    protected $cacheKey = 'cache:AustinHeap\Security\Txt\SecurityTxt';
62
63
    /**
64
     * Create a new SecurityTxtHelper instance.
65
     *
66
     * @return \AustinHeap\Security\Txt\SecurityTxtHelper
67
     */
68
    public function __construct()
69
    {
70
        $this->writer = new Writer();
71
72
        $keys = [
73
            'security-txt.enabled'          => ['validator' => 'is_bool',       'setter' => 'setEnabled',           'self' => true],
74
            'security-txt.debug'            => ['validator' => 'is_bool',       'setter' => 'setDebug'],
75
            'security-txt.cache'            => ['validator' => 'is_bool',       'setter' => 'setCache',             'self' => true],
76
            'security-txt.cache-time'       => ['validator' => 'is_numeric',    'setter' => 'setCacheTime',         'self' => true],
77
            'security-txt.cache-key'        => ['validator' => 'is_string',     'setter' => 'setCacheKey',          'self' => true],
78
            'security-txt.comments'         => ['validator' => 'is_bool',       'setter' => 'setComments'],
79
            'security-txt.contacts'         => ['validator' => 'is_array',      'setter' => 'setContacts'],
80
            'security-txt.encryption'       => ['validator' => 'is_string',     'setter' => 'setEncryption'],
81
            'security-txt.disclosure'       => ['validator' => 'is_string',     'setter' => 'setDisclosure'],
82
            'security-txt.acknowledgement'  => ['validator' => 'is_string',     'setter' => 'setAcknowledgement'],
83
        ];
84
85
        foreach ($keys as $key => $mapping) {
86
            if (empty(config($key, null))) {
87
                $this->addLogEntry('"'.__CLASS__.'" cannot process empty value for key "'.$key.'".', 'notice');
88
                continue;
89
            }
90
91
            if (! $mapping['validator'](config($key))) {
92
                $this->addLogEntry('"'.__CLASS__.'" cannot find mapping "validator" method named "'.$mapping['setter'].'".', 'warning');
93
                continue;
94
            }
95
96
            if (array_key_exists('self', $mapping) &&
97
                is_bool($mapping['self']) &&
98
                $mapping['self'] === true) {
99 View Code Duplication
                if (! method_exists($this, $mapping['setter'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
100
                    $this->addLogEntry('"'.__CLASS__.'" cannot find mapping "setter" method on object "'.get_class($this).'" named "'.$mapping['setter'].'".', 'error');
101
                    continue;
102
                }
103
104
                $this->{$mapping['setter']}(config($key));
105
            } else {
106 View Code Duplication
                if (! method_exists($this->writer, $mapping['setter'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
107
                    $this->addLogEntry('"'.__CLASS__.'" cannot find mapping "setter" method on object "'.get_class($this->writer).'" named "'.$mapping['setter'].'".', 'error');
108
                    continue;
109
                }
110
111
                $this->writer->{$mapping['setter']}(config($key));
112
            }
113
        }
114
115
        return $this;
116
    }
117
118
    /**
119
     * Add log entry.
120
     *
121
     * @param  string       $text
122
     * @param  string       $level
123
     * @return \AustinHeap\Security\Txt\SecurityTxtHelper
124
     */
125
    public function addLogEntry(string $text, string $level = 'info'): SecurityTxtHelper
126
    {
127
        \Log::$level($text);
128
129
        $this->logEntries[] = ['text' => $text, 'level' => $level];
130
131
        return $this;
132
    }
133
134
    /**
135
     * Fetches the raw text of the document.
136
     *
137
     * @return \AustinHeap\Security\Txt\SecurityTxtHelper
138
     */
139
    public function fetch(): string
140
    {
141
        if ($this->cache) {
142
            $text = cache($this->cacheKey, null);
143
144
            if (! is_null($text)) {
145
                return $text;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $text could return the type Illuminate\Cache\CacheMa...tracts\Cache\Repository which is incompatible with the type-hinted return string. Consider adding an additional type-check to rule them out.
Loading history...
146
            }
147
        }
148
149
        $text = $this->writer
150
                     ->generate()
151
                     ->getText();
152
153
        if ($this->writer->getComments()) {
154
            $text .= '# Cache is '.($this->cache ? 'enabled with key "'.$this->cacheKey.'"' : 'disabled').'.'.PHP_EOL.
155
                     '#'.PHP_EOL;
156
        }
157
158
        if ($this->cache) {
159
            cache([$this->cacheKey => $text], now()->addMinutes($this->cacheTime));
160
        }
161
162
        return empty($text) ? '' : $text;
0 ignored issues
show
Bug Best Practice introduced by
The expression return empty($text) ? '' : $text returns the type string which is incompatible with the documented return type AustinHeap\Security\Txt\SecurityTxtHelper.
Loading history...
163
    }
164
165
    /**
166
     * Enable the enabled flag.
167
     *
168
     * @return \AustinHeap\Security\Txt\SecurityTxtHelper
169
     */
170
    public function enable(): SecurityTxtHelper
171
    {
172
        return $this->setEnabled(true);
173
    }
174
175
    /**
176
     * Disable the enabled flag.
177
     *
178
     * @return \AustinHeap\Security\Txt\SecurityTxtHelper
179
     */
180
    public function disable(): SecurityTxtHelper
181
    {
182
        return $this->setEnabled(false);
183
    }
184
185
    /**
186
     * Set the enabled flag.
187
     *
188
     * @param  bool         $enabled
189
     * @return \AustinHeap\Security\Txt\SecurityTxtHelper
190
     */
191
    public function setEnabled(bool $enabled): SecurityTxtHelper
192
    {
193
        $this->enabled = $enabled;
0 ignored issues
show
Bug Best Practice introduced by
The property enabled does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
194
195
        return $this;
196
    }
197
198
    /**
199
     * Get the enabled flag.
200
     *
201
     * @return bool
202
     */
203
    public function getEnabled(): bool
204
    {
205
        return $this->enabled;
206
    }
207
208
    /**
209
     * Enable the cache flag.
210
     *
211
     * @return \AustinHeap\Security\Txt\SecurityTxtHelper
212
     */
213
    public function enableCache(): SecurityTxtHelper
214
    {
215
        return $this->setCache(true);
216
    }
217
218
    /**
219
     * Disable the cache flag.
220
     *
221
     * @return \AustinHeap\Security\Txt\SecurityTxtHelper
222
     */
223
    public function disableCache(): SecurityTxtHelper
224
    {
225
        return $this->setCache(false);
226
    }
227
228
    /**
229
     * Set the cache flag.
230
     *
231
     * @param  bool         $cache
232
     * @return \AustinHeap\Security\Txt\SecurityTxtHelper
233
     */
234
    public function setCache(bool $cache): SecurityTxtHelper
235
    {
236
        $this->cache = $cache;
237
238
        return $this;
239
    }
240
241
    /**
242
     * Get the cache flag.
243
     *
244
     * @return bool
245
     */
246
    public function getCache(): bool
247
    {
248
        return $this->cache;
249
    }
250
251
    /**
252
     * Set the cache key.
253
     *
254
     * @param  string       $cacheKey
255
     * @return \AustinHeap\Security\Txt\SecurityTxtHelper
256
     */
257
    public function setCacheKey(string $cacheKey): SecurityTxtHelper
258
    {
259
        $this->cacheKey = $cacheKey;
260
261
        return $this;
262
    }
263
264
    /**
265
     * Get the cache key.
266
     *
267
     * @return string
268
     */
269
    public function getCacheKey(): string
270
    {
271
        return $this->cacheKey;
272
    }
273
274
    /**
275
     * Set the cache time.
276
     *
277
     * @param  int          $cacheTime
278
     * @return \AustinHeap\Security\Txt\SecurityTxtHelper
279
     */
280
    public function setCacheTime(int $cacheTime): SecurityTxtHelper
281
    {
282
        $this->cacheTime = $cacheTime;
283
284
        return $this;
285
    }
286
287
    /**
288
     * Get the cache time.
289
     *
290
     * @return int
291
     */
292
    public function getCacheTime(): int
293
    {
294
        return $this->cacheTime;
295
    }
296
}
297