ActionLogParsedCache::get()   B
last analyzed

Complexity

Conditions 11
Paths 29

Size

Total Lines 58
Code Lines 32

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 26
CRAP Score 11

Importance

Changes 0
Metric Value
eloc 32
c 0
b 0
f 0
dl 0
loc 58
ccs 26
cts 26
cp 1
rs 7.3166
cc 11
nc 29
nop 1
crap 11

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * This file is part of the Shieldon package.
4
 *
5
 * (c) Terry L. <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 *
10
 * php version 7.1.0
11
 *
12
 * @category  Web-security
13
 * @package   Shieldon
14
 * @author    Terry Lin <[email protected]>
15
 * @copyright 2019 terrylinooo
16
 * @license   https://github.com/terrylinooo/shieldon/blob/2.x/LICENSE MIT
17
 * @link      https://github.com/terrylinooo/shieldon
18
 * @see       https://shieldon.io
19
 */
20
21
declare(strict_types=1);
22
23
namespace Shieldon\Firewall\Log;
24
25
use function date;
26
use function file_get_contents;
27
use function file_put_contents;
28
use function json_encode;
29
use function rtrim;
30
use function strtotime;
31
use function time;
32
use const JSON_PRETTY_PRINT;
33
34
/**
35
 * Cache the data parsed by ActionLogParser.
36
 */
37
final class ActionLogParsedCache
38
{
39
    /**
40
     * $directory The directory where to store the logs in.
41
     *
42
     * @var string
43
     */
44
    protected $directory = '';
45
46
    /**
47
     * Constructer.
48
     *
49
     * @param string $directory The directory where to store the logs in.
50
     */
51 4
    public function __construct(string $directory = '')
52
    {
53 4
        $this->directory = $directory;
54
    }
55
56
    /**
57
     * Save the data into a cache file.
58
     *
59
     * @param string $type The period type of action logs.
60
     * @param string $data The parsed data of action logs.
61
     *                     The keys are `time`, `ip_details`, `period_data`.
62
     *
63
     * @return self
64
     */
65 2
    public function save(string $type = 'today', array $data = []): self
66
    {
67 2
        $data['time'] = time();
68
69 2
        $filePath = rtrim($this->directory, '/') . '/cache_' . $type . '.json';
70
71 2
        file_put_contents($filePath, json_encode($data, JSON_PRETTY_PRINT));
72
73 2
        return $this;
74
    }
75
76
    /**
77
     * Get the data from a cache file.
78
     *
79
     * @param string $type The period type of action logs.
80
     *
81
     * @return array
82
     */
83 3
    public function get(string $type = 'today'): array
84
    {
85 3
        $data = [];
86
        $filePath = rtrim($this->directory, '/') . '/cache_' . $type . '.json';
87 3
88
        if (file_exists($filePath)) {
89 3
            $content = file_get_contents($filePath);
90 2
            $data = json_decode($content, true);
91 2
92
            $cacheTime = $data['time'];
93 2
94
            $keepCache = true;
95 2
96
            switch ($type) {
97
                case 'yesterday':
98
                case 'past_seven_days':
99 2
100 2
                    // Update cache file daily.
101
                    $endTime = strtotime(date('Y-m-d', strtotime('-1 day')));
102
                    $beginTime = strtotime(date('Y-m-d', strtotime('-2 days')));
103 1
                    break;
104 1
105 1
                case 'last_month':
106
107 2
                    // Update cache file monthly.
108
                    $endTime = strtotime(date('Y-m-d', strtotime('-1 month')));
109
                    $beginTime = strtotime(date('Y-m-d', strtotime('-2 months')));
110 1
                    break;
111 1
112 1
                case 'this_month':
113
114 2
                    // Update cache file daily.
115
                    $endTime = strtotime(date('Y-m-d', strtotime('-1 day')));
116
                    $beginTime = strtotime(date('Y-m') . '-01');
117 1
                    break;
118 1
119 1
                case 'past_seven_hours':
120
                case 'today':
121 2
                default:
122 2
                    // Update cache file hourly.
123
                    $endTime = strtotime(date('Y-m-d H:00:00', time()));
124
                    $beginTime = strtotime(date('Y-m-d H:00:00', strtotime('-1 hour')));
125
                    break;
126 2
            }
127 2
128 2
            // The cacheTime is between beginTime and endTime.
129
            // @codeCoverageIgnoreStart
130
            if (($beginTime < $cacheTime) && ($endTime > $cacheTime)) {
131
                $keepCache = false;
132
            }
133
134
            if (!$keepCache) {
135
                $data = [];
136
            }
137
            // @codeCoverageIgnoreEnd
138
        }
139
140
        return $data;
141
    }
142
}
143