Passed
Push — master ( e9d973...038fa0 )
by Fran
03:28
created

AdminServices::parseAdmins()   B

Complexity

Conditions 7
Paths 6

Size

Total Lines 17
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 30.7665

Importance

Changes 0
Metric Value
cc 7
eloc 10
nc 6
nop 1
dl 0
loc 17
ccs 3
cts 14
cp 0.2143
crap 30.7665
rs 8.2222
c 0
b 0
f 0
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;
8
    use Symfony\Component\Finder\Finder;
9
10
    class AdminServices extends Service{
11
12
        /**
13
         * @Inyectable
14
         * @var \PSFS\base\config\Config Servicio de configuración
15
         */
16
        protected $config;
17
        /**
18
         * @Inyectable
19
         * @var \PSFS\base\Security Servicio de autenticación
20
         */
21
        protected $security;
22
        /**
23
         * @Inyectable
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 _("Zona restringida");
38
            exit();
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 1
            {
50
                if(!$this->security->checkAdmin())
51
                {
52
                    $this->setAdminHeaders();
53
                }
54
            }
55 1
            $this->parseAdmins($admins);
56 1
            return $admins;
57
        }
58
59
        /**
60
         * Servicio que parsea los administradores para mostrarlos en la gestión de usuarios
61
         * @param array $admins
62
         */
63 1
        private function parseAdmins(&$admins)
64
        {
65 1
            if(!empty($admins)) foreach($admins as &$admin)
66
            {
67
                if(isset($admin["profile"]))
68
                {
69
                    switch($admin["profile"]) {
70
                        case Security::MANAGER_ID_TOKEN: $admin['class'] = 'warning'; break;
0 ignored issues
show
Coding Style introduced by
The case body in a switch statement must start on the line following the statement.

According to the PSR-2, the body of a case statement must start on the line immediately following the case statement.

switch ($expr) {
case "A":
    doSomething(); //right
    break;
case "B":

    doSomethingElse(); //wrong
    break;

}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
Coding Style introduced by
Terminating statement must be on a line by itself

As per the PSR-2 coding standard, the break (or other terminating) statement must be on a line of its own.

switch ($expr) {
     case "A":
         doSomething();
         break; //wrong
     case "B":
         doSomething();
         break; //right
     case "C:":
         doSomething();
         return true; //right
 }

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
71
                        case Security::ADMIN_ID_TOKEN: $admin['class'] = 'info'; break;
0 ignored issues
show
Coding Style introduced by
The case body in a switch statement must start on the line following the statement.

According to the PSR-2, the body of a case statement must start on the line immediately following the case statement.

switch ($expr) {
case "A":
    doSomething(); //right
    break;
case "B":

    doSomethingElse(); //wrong
    break;

}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
Coding Style introduced by
Terminating statement must be on a line by itself

As per the PSR-2 coding standard, the break (or other terminating) statement must be on a line of its own.

switch ($expr) {
     case "A":
         doSomething();
         break; //wrong
     case "B":
         doSomething();
         break; //right
     case "C:":
         doSomething();
         return true; //right
 }

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
72
                        default:
73
                        case Security::USER_ID_TOKEN: $admin['class'] = 'primary'; break;
0 ignored issues
show
Coding Style introduced by
The case body in a switch statement must start on the line following the statement.

According to the PSR-2, the body of a case statement must start on the line immediately following the case statement.

switch ($expr) {
case "A":
    doSomething(); //right
    break;
case "B":

    doSomethingElse(); //wrong
    break;

}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
Coding Style introduced by
Terminating statement must be on a line by itself

As per the PSR-2 coding standard, the break (or other terminating) statement must be on a line of its own.

switch ($expr) {
     case "A":
         doSomething();
         break; //wrong
     case "B":
         doSomething();
         break; //right
     case "C:":
         doSomething();
         return true; //right
 }

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
74
                    }
75
                }else{
76
                    $admin["class"] = "primary";
77
                }
78
            }
79 1
        }
80
81
        /**
82
         * Servicio que lee los logs y los formatea para listarlos
83
         * @return array
84
         */
85
        public function getLogFiles()
86
        {
87
            $files = new Finder();
88
            $files->files()->in(LOG_DIR)->name("*.log")->sortByModifiedTime();
89
            $logs = array();
90
            /** @var \SplFileInfo $file */
91
            foreach($files as $file)
92
            {
93
                $size = $file->getSize() / 8 / 1024;
94
                $time = date("c", $file->getMTime());
95
                $dateTime = new \DateTime($time);
96
                if(!isset($logs[$dateTime->format("Y")])) $logs[$dateTime->format("Y")] = array();
97
                $logs[$dateTime->format("Y")][$dateTime->format("m")][$time] = array(
98
                    "filename" => $file->getFilename(),
99
                    "size" => round($size, 3)
100
                );
101
                krsort($logs[$dateTime->format("Y")][$dateTime->format("m")]);
102
                krsort($logs[$dateTime->format("Y")]);
103
            }
104
            return $logs;
105
        }
106
107
        /**
108
         * Servicio que parsea el fichero de log seleccionado
109
         * @param string|null $selectedLog
110
         *
111
         * @return array
0 ignored issues
show
Documentation introduced by
Consider making the return type a bit more specific; maybe use array<array|string|null>.

This check looks for the generic type array as a return type and suggests a more specific type. This type is inferred from the actual code.

Loading history...
112
         */
113
        public function formatLogFile($selectedLog)
114
        {
115
            $monthOpen = null;
116
            $files = new Finder();
117
            $files->files()->in(LOG_DIR)->name($selectedLog);
118
            $file = null;
119
            $log = array();
120
            foreach($files as $match)
121
            {
122
                $file = $match;
123
                break;
124
            }
125
            /** @var \SplFileInfo $file */
126
            if(!empty($file))
127
            {
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);
133
                $detailLog = array();
134
                foreach($content as &$line)
135
                {
136
                    list($line, $detail) = $this->parseLogLine($line, $match);
137
                    $detailLog[] = array_merge(array(
138
                        "log" => $line,
139
                    ), $detail);
140
                    if(count($detailLog) >= 1000) break;
141
                }
142
                $log = $detailLog;
143
            }
144
            return array($log, $monthOpen);
145
        }
146
147
        /**
148
         * Servicio que trata la línea del log para procesarle en el front end
149
         * @param $line
150
         * @param $match
151
         *
152
         * @return array
153
         */
154
        private function parseLogLine($line, $match)
155
        {
156
            $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);
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 168 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
157
            preg_match_all('/\{(.*)\}/', $line, $match);
158
            try {
159
                if (!empty($match[0])) {
160
                    $line = str_replace('[]', '', str_replace($match[0][0], '', $line));
161
162
                    $detail = json_decode($match[0][0], TRUE);
163
                }
164
                if (empty($detail)) $detail = array();
165
                preg_match_all('/\>\ (.*):/i', $line, $match);
166
167
                $type = (isset($match[1][0])) ? $match[1][0] : '';
168
                $type = explode(".", $type);
169
                $type = count($type)>1 ? $type[1] : $type[0];
170
                switch ($type) {
171
                    case 'INFO':
172
                        $detail["type"] = "success";
173
                        break;
174
                    case 'DEBUG':
175
                        $detail["type"] = "info";
176
                        break;
177
                    case 'ERROR':
178
                        $detail["type"] = "danger";
179
                        break;
180
                    case 'WARN':
181
                        $detail["type"] = "warning";
182
                        break;
183
                }
184
185
            } catch (\Exception $e) {
186
                $detail = array(
187
                    "type" => "danger",
188
                );
189
190
            }
191
192
            return array($line, $detail);
193
        }
194
    }
195