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

LogEntry::formatLegacyEntry()   C

Complexity

Conditions 7
Paths 4

Size

Total Lines 28
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 28
rs 6.7272
cc 7
eloc 21
nc 4
nop 1
1
<?php
2
3
namespace SilverLeague\LogViewer\Model;
4
5
use SilverStripe\Core\Convert;
6
use SilverStripe\Forms\LiteralField;
7
use SilverStripe\ORM\DataObject;
8
9
/**
10
 * A LogEntry is a set of data provided from Monolog via the DataObjectHandler
11
 *
12
 * @package silverstripe-logviewer
13
 * @author  Robbie Averill <[email protected]>
14
 * @author  Simon Erkelens <[email protected]>
15
 *
16
 * @property string $Entry
17
 * @property string $Level
18
 */
19
class LogEntry extends DataObject
20
{
21
    /**
22
     * {@inheritDoc}
23
     */
24
    private static $table_name = 'LogEntry';
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
Unused Code introduced by
The property $table_name is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
25
26
27
    /**
28
     * @var bool
29
     */
30
    private static $format_entry = true;
0 ignored issues
show
Unused Code introduced by
The property $format_entry is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
31
32
    /**
33
     * {@inheritDoc}
34
     */
35
    private static $db = [
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
Unused Code introduced by
The property $db is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
36
        'Entry' => 'Text',
37
        'Level' => 'Varchar'
38
    ];
39
40
    /**
41
     * {@inheritDoc}
42
     */
43
    private static $summary_fields = [
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
Unused Code introduced by
The property $summary_fields is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
44
        'GridfieldSummary' => 'Entry',
45
        'Created'          => 'Created',
46
        'Level'            => 'Level'
47
    ];
48
49
    /**
50
     * We should never need to edit log entries
51
     *
52
     * {@inheritDoc}
53
     */
54
    public function canEdit($member = false, $context = [])
0 ignored issues
show
Unused Code introduced by
The parameter $context is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
55
    {
56
        return false;
57
    }
58
59
    /**
60
     * @inheritdoc
61
     * @return \SilverStripe\Forms\FieldList
62
     */
63
    public function getCMSFields()
64
    {
65
        $config = self::config()->get('format_entry');
66
        $fields = parent::getCMSFields();
67
        if ($config) { // Default setting, format the entry
68
            $fields->removeByName(array('Entry'));
69
            $text = $this->Entry;
70
            $asArray = Convert::json2array($text);
71
            if (!is_array($asArray)) {
72
                /** @deprecated We're falling back to the legacy text-only error */
73
                $entry = $this->formatLegacyEntry($text);
0 ignored issues
show
Deprecated Code introduced by
The method SilverLeague\LogViewer\M...ry::formatLegacyEntry() has been deprecated with message: This method exists to make sure non-JSONFormatted messages won't break the flow

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
74
            } else {
75
                $entry = $this->entryToUl($asArray, true);
76
            }
77
            $entry = nl2br("<pre>" . $entry . "</pre>");
78
            $fields->addFieldToTab('Root.Main', LiteralField::create('FormattedEntry', $entry));
79
        } else { // Just move the field after the Level
80
            $entryField = $fields->dataFieldByName('Entry');
81
            if ($entryField !== null) {
82
                $fields->insertAfter('Level', $entryField);
83
            }
84
        }
85
86
        return $fields;
87
    }
88
89
    /**
90
     * Recursive method, will call itself if a sub element is an array
91
     * @param array $data
92
     * @param bool $first start with an opening bracket? if true, skip (counterintuitive, but naming)
93
     * @return string formatted <ul><li> of the array;
94
     */
95
    private function entryToUl($data, $first = false)
96
    {
97
        $out = $first ? '' : '[';
98
        $out .= '<ul style="margin-bottom: 0">';
99
        foreach ($data as $key => $arrayItem) {
100
            if (!is_array($arrayItem)) {
101
                $out .= '<li  class="list-unstyled"><span>' . $key . ' => ' . $arrayItem . '</span></li>';
102
            } else {
103
                $out .= '<li class="list-unstyled"><span>' . $key . ' => </span>' . $this->entryToUl($arrayItem) . '</li>';
104
            }
105
        }
106
        $out .= '</ul>';
107
        $out .= $first ? '' : ']';
108
109
        return $out;
110
    }
111
112
    /**
113
     * @param string $text
114
     * @return string
115
     * @deprecated This method exists to make sure non-JSONFormatted messages won't break the flow
116
     */
117
    private function formatLegacyEntry($text)
118
    {
119
        preg_match_all("/(\{\".*?}+)\s/", $text, $matches);
120
        $entry = "<h2>Entry</h2>";
121
        if (count($matches[1])) {
122
            foreach ($matches[1] as $key => $match) {
123
                $pretext = substr($text, 0, strpos($text, $match)); // Header of the error
124
                $asArray = Convert::json2array($match); // Convert the rest to array
125
                $text = substr($text, strlen($pretext . $match)); // Prepare for the next entry
126
                $entry .= ($key > 0 ? "\n" : '') . trim($pretext) . ' => ';
127
                if (is_array($asArray)) {
128
                    $entry .= $this->entryToUl($asArray);
129
                } else {
130
                    $entry .= "\n" . $match;
131
                }
132
            }
133
            $leftOver = Convert::json2array(trim($text));
134
            if ($leftOver !== null) {
135
                $entry .= "\nOther => " . $this->entryToUl($leftOver);
0 ignored issues
show
Bug introduced by
It seems like $leftOver defined by \SilverStripe\Core\Conve...json2array(trim($text)) on line 133 can also be of type boolean; however, SilverLeague\LogViewer\Model\LogEntry::entryToUl() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
136
            } elseif (strlen(trim($text))) { // add the leftover if there is any
137
                $entry .= "\nOther:\n" . $text;
138
            }
139
        } else {
140
            $entry = '<p>' . $text . '</p>';
141
        }
142
143
        return $entry;
144
    }
145
146
    /**
147
     * @param int $length Length of the summary
148
     * @return string shortened string of the entry if too long.
149
     */
150
    public function getGridfieldSummary($length = 300)
151
    {
152
        $elipsis = strlen($this->Entry) > $length ? '...' : '';
153
154
        return substr($this->Entry, 0, $length) . $elipsis;
155
    }
156
}
157