Passed
Push — master ( 87c6b6...f17d15 )
by Fran
02:49
created

AdminServices   A

Complexity

Total Complexity 29

Size/Duplication

Total Lines 190
Duplicated Lines 0 %

Test Coverage

Coverage 8.16%

Importance

Changes 0
Metric Value
eloc 100
dl 0
loc 190
ccs 8
cts 98
cp 0.0816
rs 10
c 0
b 0
f 0
wmc 29

6 Methods

Rating   Name   Duplication   Size   Complexity  
A getAdmins() 0 10 3
A setAdminHeaders() 0 7 1
B parseAdmins() 0 19 7
A formatLogFile() 0 32 5
B parseLogLine() 0 40 10
A getLogFiles() 0 21 3
1
<?php
2
namespace PSFS\services;
3
4
use PSFS\base\config\Config;
5
use PSFS\base\Security;
6
use PSFS\base\Service;
7
use Symfony\Component\Finder\Finder;
8
9
class AdminServices extends Service
10
{
11
12
    /**
13
     * @Injectable
14
     * @var \PSFS\base\config\Config Servicio de configuración
15
     */
16
    protected $config;
17
    /**
18
     * @Injectable
19
     * @var \PSFS\base\Security Servicio de autenticación
20
     */
21
    protected $security;
22
    /**
23
     * @Injectable
24
     * @var \PSFS\base\Template Servicio de gestión de plantillas
25
     */
26
    protected $tpl;
27
28
    /**
29
     * Servicio que devuelve las cabeceras de autenticación
30
     * @return string HTML
31
     */
32
    public function setAdminHeaders()
33
    {
34
        $platform = trim(Config::getInstance()->get('platform.name'));
35
        header('HTTP/1.1 401 Unauthorized');
36
        header('WWW-Authenticate: Basic Realm="' . $platform . '"');
37
        echo t('Zona restringida');
38
        exit();
1 ignored issue
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
39
    }
40
41
    /**
42
     * Servicio que devuelve los administradores de la plataforma
43
     * @return array|mixed
44
     */
45 1
    public function getAdmins()
46
    {
47 1
        $admins = $this->security->getAdmins();
48 1
        if (!empty($admins)) {
49
            if (!$this->security->checkAdmin()) {
50
                $this->setAdminHeaders();
51
            }
52
        }
53 1
        $this->parseAdmins($admins);
54 1
        return $admins;
55
    }
56
57
    /**
58
     * Servicio que parsea los administradores para mostrarlos en la gestión de usuarios
59
     * @param array $admins
60
     */
61 1
    private function parseAdmins(&$admins)
62
    {
63 1
        if (!empty($admins)) {
64
            foreach ($admins as &$admin) {
65
                if (isset($admin['profile'])) {
66
                    switch ($admin['profile']) {
67
                        case Security::MANAGER_ID_TOKEN:
68
                            $admin['class'] = 'warning';
69
                            break;
70
                        case Security::ADMIN_ID_TOKEN:
71
                            $admin['class'] = 'info';
72
                            break;
73
                        default:
74
                        case Security::USER_ID_TOKEN:
75
                            $admin['class'] = 'primary';
76
                            break;
77
                    }
78
                } else {
79
                    $admin['class'] = 'primary';
80
                }
81
            }
82
        }
83 1
    }
84
85
    /**
86
     * Servicio que lee los logs y los formatea para listarlos
87
     * @return array
88
     */
89
    public function getLogFiles()
90
    {
91
        $files = new Finder();
92
        $files->files()->in(LOG_DIR)->name('*.log')->sortByModifiedTime();
93
        $logs = array();
94
        /** @var \SplFileInfo $file */
95
        foreach ($files as $file) {
96
            $size = $file->getSize() / 8 / 1024;
97
            $time = date('c', $file->getMTime());
98
            $dateTime = new \DateTime($time);
99
            if (!isset($logs[$dateTime->format('Y')])) {
100
                $logs[$dateTime->format('Y')] = [];
101
            }
102
            $logs[$dateTime->format('Y')][$dateTime->format('m')][$time] = [
103
                'filename' => $file->getFilename(),
104
                'size' => round($size, 3),
105
            ];
106
            krsort($logs[$dateTime->format('Y')][$dateTime->format('m')]);
107
            krsort($logs[$dateTime->format('Y')]);
108
        }
109
        return $logs;
110
    }
111
112
    /**
113
     * Servicio que parsea el fichero de log seleccionado
114
     * @param string|null $selectedLog
115
     *
116
     * @return array
117
     */
118
    public function formatLogFile($selectedLog)
119
    {
120
        $monthOpen = null;
121
        $files = new Finder();
122
        $files->files()->in(LOG_DIR)->name($selectedLog);
123
        $file = null;
124
        $log = array();
125
        foreach($files as $match) {
126
            $file = $match;
127
            break;
128
        }
129
        /** @var \SplFileInfo $file */
130
        if (null !== $file) {
131
            $time = date('c', $file->getMTime());
132
            $dateTime = new \DateTime($time);
133
            $monthOpen = $dateTime->format('m');
134
            $content = file($file->getPath() . DIRECTORY_SEPARATOR . $file->getFilename());
135
            krsort($content);
0 ignored issues
show
Bug introduced by
It seems like $content can also be of type false; however, parameter $array of krsort() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

135
            krsort(/** @scrutinizer ignore-type */ $content);
Loading history...
136
            $detailLog = array();
137
            foreach ($content as &$line) {
138
                list($line, $detail) = $this->parseLogLine($line, $file);
139
                $detailLog[] = array_merge([
140
                    'log' => $line,
141
                ], $detail);
142
                if (count($detailLog) >= 1000) {
143
                    break;
144
                }
145
            }
146
            unset($line);
147
            $log = $detailLog;
148
        }
149
        return [$log, $monthOpen];
150
    }
151
152
    /**
153
     * Servicio que trata la línea del log para procesarle en el front end
154
     * @param $line
155
     * @param $match
156
     *
157
     * @return array
158
     */
159
    private function parseLogLine($line, $match)
160
    {
161
        $line = preg_replace(array('/^\[(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})\]/'), '<span class="label label-success">$4:$5:$6  $3-$2-$1</span>', $line);
162
        preg_match_all('/\{(.*)\}/', $line, $match);
163
        try {
164
            if (!empty($match[0])) {
165
                $line = str_replace('[]', '', str_replace($match[0][0], '', $line));
166
167
                $detail = json_decode($match[0][0], TRUE);
168
            }
169
            if (empty($detail)) {
170
                $detail = array();
171
            }
172
            preg_match_all('/\>\ (.*):/', $line, $match);
173
174
            $type = isset($match[1][0]) ? $match[1][0] : '';
175
            $type = explode('.', $type);
176
            $type = count($type) > 1 ? $type[1] : $type[0];
177
            switch ($type) {
178
                case 'INFO':
179
                    $detail['type'] = 'success';
180
                    break;
181
                case 'DEBUG':
182
                    $detail['type'] = 'info';
183
                    break;
184
                case 'ERROR':
185
                    $detail['type'] = 'danger';
186
                    break;
187
                case 'WARN':
188
                    $detail['type'] = 'warning';
189
                    break;
190
            }
191
192
        } catch (\Exception $e) {
193
            $detail = [
194
                'type' => 'danger',
195
            ];
196
        }
197
198
        return [$line, $detail];
199
    }
200
}
201