Completed
Pull Request — master (#14)
by Simon
02:02
created

DeprecatedLogFormatter   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 62
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 2

Importance

Changes 0
Metric Value
wmc 9
lcom 0
cbo 2
dl 0
loc 62
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A formatLegacyEntry() 0 13 2
B createLegacyEntry() 0 20 6
A extractValues() 0 8 1
1
<?php
2
3
namespace SilverLeague\LogViewer\Helper;
4
5
use SilverStripe\Core\Convert;
6
7
/**
8
 * Class DeprecatedLogFormatter is used to format entries that are not full JSON.
9
 * This is to support older formatting that's not used anymore
10
 * @description purely exists to support older log formatting
11
 * @package SilverLeague\LogViewer\Deprecated
12
 *
13
 * @deprecated
14
 */
15
class DeprecatedLogFormatter
16
{
17
18
    /**
19
     * @param string $text
20
     * @return string
21
     */
22
    public static function formatLegacyEntry($text)
23
    {
24
        // Extract all the JSON-blocks from the message. Anything from `{"` to `} `
25
        preg_match_all("/(\{\".*?}+)\s/", $text, $matches);
26
        $entry = '';
27
        if (count($matches[1])) {
28
            $entry .= self::createLegacyEntry($matches, $text, $entry);
29
        } else {
30
            $entry .= '<p>' . $text . '</p>';
31
        }
32
33
        return $entry;
34
    }
35
36
    /**
37
     * @param array $matches
38
     * @param string $text
39
     * @param string $entry
40
     * @return string
41
     */
42
    private static function createLegacyEntry($matches, $text, $entry)
43
    {
44
        foreach ($matches[1] as $key => $match) {
45
            list($pretext, $matchToArray, $text) = self::extractValues($text, $match);
46
            $entry .= ($key > 0 ? "\n" : '') . trim($pretext) . ': ';
47
            if (is_array($matchToArray)) {
48
                $entry .= LogFormatter::entryToUl($matchToArray);
49
            } else {
50
                $entry .= "\n" . $match;
51
            }
52
        }
53
        $leftOver = Convert::json2array(trim($text));
54
        if (is_array($leftOver)) {
55
            $entry .= "\nOther: " . LogFormatter::entryToUl($leftOver);
56
        } elseif (strlen(trim($text))) { // add the leftover if there is any
57
            $entry .= "\nOther:\n" . $text;
58
        }
59
60
        return $entry;
61
    }
62
63
    /**
64
     * @param string $text
65
     * @param string $match
66
     * @return array
67
     */
68
    private static function extractValues($text, $match)
69
    {
70
        $pretext = substr($text, 0, strpos($text, $match)); // Header of the error
71
        $matchToArray = Convert::json2array($match); // Convert the rest to array
72
        $text = substr($text, strlen($pretext . $match)); // Prepare for the next entry
73
74
        return array($pretext, $matchToArray, $text);
75
    }
76
}