Passed
Push — master ( be88e3...87c6b6 )
by Fran
04:17
created

AdminServices   A

Complexity

Total Complexity 29

Size/Duplication

Total Lines 182
Duplicated Lines 0 %

Test Coverage

Coverage 8.59%

Importance

Changes 0
Metric Value
eloc 95
dl 0
loc 182
ccs 8
cts 93
cp 0.0859
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 18 7
A formatLogFile() 0 29 5
B parseLogLine() 0 39 10
A getLogFiles() 0 19 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 PSFS\controller\Admin;
0 ignored issues
show
Bug introduced by
The type PSFS\controller\Admin was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
8
use Symfony\Component\Finder\Finder;
9
10
class AdminServices extends Service
11
{
12
13
    /**
14
     * @Injectable
15
     * @var \PSFS\base\config\Config Servicio de configuración
16
     */
17
    protected $config;
18
    /**
19
     * @Injectable
20
     * @var \PSFS\base\Security Servicio de autenticación
21
     */
22
    protected $security;
23
    /**
24
     * @Injectable
25
     * @var \PSFS\base\Template Servicio de gestión de plantillas
26
     */
27
    protected $tpl;
28
29
    /**
30
     * Servicio que devuelve las cabeceras de autenticación
31
     * @return string HTML
32
     */
33
    public function setAdminHeaders()
34
    {
35
        $platform = trim(Config::getInstance()->get("platform.name"));
36
        header('HTTP/1.1 401 Unauthorized');
37
        header('WWW-Authenticate: Basic Realm="' . $platform . '"');
38
        echo _("Zona restringida");
39
        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...
40
    }
41
42
    /**
43
     * Servicio que devuelve los administradores de la plataforma
44
     * @return array|mixed
45
     */
46 1
    public function getAdmins()
47
    {
48 1
        $admins = $this->security->getAdmins();
49 1
        if (!empty($admins)) {
50
            if (!$this->security->checkAdmin()) {
51
                $this->setAdminHeaders();
52
            }
53
        }
54 1
        $this->parseAdmins($admins);
55 1
        return $admins;
56
    }
57
58
    /**
59
     * Servicio que parsea los administradores para mostrarlos en la gestión de usuarios
60
     * @param array $admins
61
     */
62 1
    private function parseAdmins(&$admins)
63
    {
64 1
        if (!empty($admins)) 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 1
    }
83
84
    /**
85
     * Servicio que lee los logs y los formatea para listarlos
86
     * @return array
87
     */
88
    public function getLogFiles()
89
    {
90
        $files = new Finder();
91
        $files->files()->in(LOG_DIR)->name("*.log")->sortByModifiedTime();
92
        $logs = array();
93
        /** @var \SplFileInfo $file */
94
        foreach ($files as $file) {
95
            $size = $file->getSize() / 8 / 1024;
96
            $time = date("c", $file->getMTime());
97
            $dateTime = new \DateTime($time);
98
            if (!isset($logs[$dateTime->format("Y")])) $logs[$dateTime->format("Y")] = array();
99
            $logs[$dateTime->format("Y")][$dateTime->format("m")][$time] = array(
100
                "filename" => $file->getFilename(),
101
                "size" => round($size, 3)
102
            );
103
            krsort($logs[$dateTime->format("Y")][$dateTime->format("m")]);
104
            krsort($logs[$dateTime->format("Y")]);
105
        }
106
        return $logs;
107
    }
108
109
    /**
110
     * Servicio que parsea el fichero de log seleccionado
111
     * @param string|null $selectedLog
112
     *
113
     * @return array
114
     */
115
    public function formatLogFile($selectedLog)
116
    {
117
        $monthOpen = null;
118
        $files = new Finder();
119
        $files->files()->in(LOG_DIR)->name($selectedLog);
120
        $file = null;
121
        $log = array();
122
        foreach ($files as $match) {
123
            $file = $match;
124
            break;
125
        }
126
        /** @var \SplFileInfo $file */
127
        if (!empty($file)) {
0 ignored issues
show
introduced by
The condition empty($file) is always false.
Loading history...
128
            $time = date("c", $file->getMTime());
129
            $dateTime = new \DateTime($time);
130
            $monthOpen = $dateTime->format("m");
131
            $content = file($file->getPath() . DIRECTORY_SEPARATOR . $file->getFilename());
132
            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

132
            krsort(/** @scrutinizer ignore-type */ $content);
Loading history...
133
            $detailLog = array();
134
            foreach ($content as &$line) {
135
                list($line, $detail) = $this->parseLogLine($line, $match);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $match does not seem to be defined for all execution paths leading up to this point.
Loading history...
136
                $detailLog[] = array_merge(array(
137
                    "log" => $line,
138
                ), $detail);
139
                if (count($detailLog) >= 1000) break;
140
            }
141
            $log = $detailLog;
142
        }
143
        return array($log, $monthOpen);
144
    }
145
146
    /**
147
     * Servicio que trata la línea del log para procesarle en el front end
148
     * @param $line
149
     * @param $match
150
     *
151
     * @return array
152
     */
153
    private function parseLogLine($line, $match)
154
    {
155
        $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);
156
        preg_match_all('/\{(.*)\}/', $line, $match);
157
        try {
158
            if (!empty($match[0])) {
159
                $line = str_replace('[]', '', str_replace($match[0][0], '', $line));
160
161
                $detail = json_decode($match[0][0], TRUE);
162
            }
163
            if (empty($detail)) $detail = array();
164
            preg_match_all('/\>\ (.*):/i', $line, $match);
165
166
            $type = (isset($match[1][0])) ? $match[1][0] : '';
167
            $type = explode(".", $type);
168
            $type = count($type) > 1 ? $type[1] : $type[0];
169
            switch ($type) {
170
                case 'INFO':
171
                    $detail["type"] = "success";
172
                    break;
173
                case 'DEBUG':
174
                    $detail["type"] = "info";
175
                    break;
176
                case 'ERROR':
177
                    $detail["type"] = "danger";
178
                    break;
179
                case 'WARN':
180
                    $detail["type"] = "warning";
181
                    break;
182
            }
183
184
        } catch (\Exception $e) {
185
            $detail = array(
186
                "type" => "danger",
187
            );
188
189
        }
190
191
        return array($line, $detail);
192
    }
193
}
194