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

LogEntry::getGridfieldSummary()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 6
rs 9.4285
cc 2
eloc 3
nc 2
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 /** @noinspection PhpUnusedPrivateFieldInspection */
31
        $format_entry = true;
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $format_entry.

The PSR-2 coding standard requires that all properties in a class have their visibility explicitly declared. If you declare a property using

class A {
    var $property;
}

the property is implicitly global.

To learn more about the PSR-2, please see the PHP-FIG site on the PSR-2.

Loading history...
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...
32
33
    /**
34
     * {@inheritDoc}
35
     */
36
    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...
37
        'Entry' => 'Text',
38
        'Level' => 'Varchar'
39
    ];
40
41
    /**
42
     * {@inheritDoc}
43
     */
44
    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...
45
        'GridfieldSummary' => 'Entry',
46
        'Created'          => 'Created',
47
        'Level'            => 'Level'
48
    ];
49
50
    /**
51
     * We should never need to edit log entries
52
     *
53
     * {@inheritDoc}
54
     */
55
    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...
56
    {
57
        return false;
58
    }
59
60
    /**
61
     * @inheritdoc
62
     * @return \SilverStripe\Forms\FieldList
63
     */
64
    public function getCMSFields()
65
    {
66
        $config = self::config()->get('format_entry');
67
        $fields = parent::getCMSFields();
68
        if ($config) { // Default setting, format the entry
69
            $fields->removeByName(array('Entry'));
70
            $text = $this->Entry;
71
            $asArray = Convert::json2array($text);
72
            if (!is_array($asArray)) {
73
                /** @deprecated We're falling back to the legacy text-only error */
74
                $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...
75
            } else {
76
                $entry = $this->entryToUl($asArray, true);
77
            }
78
            $entry = nl2br("<pre>" . $entry . "</pre>");
79
            $fields->addFieldToTab('Root.Main', LiteralField::create('FormattedEntry', $entry));
80
        } else { // Just move the field after the Level
81
            $entryField = $fields->dataFieldByName('Entry');
82
            if ($entryField !== null) {
83
                $fields->insertAfter('Level', $entryField);
84
            }
85
        }
86
87
        return $fields;
88
    }
89
90
    /**
91
     * Recursive method, will call itself if a sub element is an array
92
     * @param array $data
93
     * @param bool $first start with an opening bracket? if true, skip (counterintuitive, but naming)
94
     * @return string formatted <ul><li> of the array;
95
     */
96
    private function entryToUl($data, $first = false)
97
    {
98
        $out = $first ? '' : '[';
99
        $out .= '<ul style="margin-bottom: 0">';
100
        foreach ($data as $key => $arrayItem) {
101
            if (!is_array($arrayItem)) {
102
                $out .= '<li  class="list-unstyled"><span>' . $key . ' => ' . $arrayItem . '</span></li>';
103
            } else {
104
                $out .= '<li class="list-unstyled"><span>' . $key . ' => </span>' . $this->entryToUl($arrayItem) . '</li>';
105
            }
106
        }
107
        $out .= '</ul>';
108
        $out .= $first ? '' : ']';
109
110
        return $out;
111
    }
112
113
    /**
114
     * @param string $text
115
     * @return string
116
     * @deprecated This method exists to make sure non-JSONFormatted messages won't break the flow
117
     */
118
    private function formatLegacyEntry($text)
119
    {
120
        preg_match_all("/(\{\".*?}+)\s/", $text, $matches);
121
        $entry = "<h2>Entry</h2>";
122
        if (count($matches[1])) {
123
            foreach ($matches[1] as $key => $match) {
124
                $pretext = substr($text, 0, strpos($text, $match)); // Header of the error
125
                $asArray = Convert::json2array($match); // Convert the rest to array
126
                $text = substr($text, strlen($pretext . $match)); // Prepare for the next entry
127
                $entry .= ($key > 0 ? "\n" : '') . trim($pretext) . ' => ';
128
                if (is_array($asArray)) {
129
                    $entry .= $this->entryToUl($asArray);
130
                } else {
131
                    $entry .= "\n" . $match;
132
                }
133
            }
134
            if (json_decode(trim($text)) !== null) {
135
                $text = Convert::json2array($text);
136
                $entry .= "\nOther => " . $this->entryToUl($text);
0 ignored issues
show
Bug introduced by
It seems like $text defined by \SilverStripe\Core\Convert::json2array($text) on line 135 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...
137
            } elseif (strlen(trim($text))) { // add the leftover if there is any
138
                $entry .= "\nOther:\n" . $text;
139
            }
140
        } else {
141
            $entry = '<p>' . $text . '</p>';
142
        }
143
144
        return $entry;
145
    }
146
147
    /**
148
     * @param int $length Length of the summary
149
     * @return string shortened string of the entry if too long.
150
     */
151
    public function getGridfieldSummary($length = 300)
152
    {
153
        $elipsis = strlen($this->Entry) > $length ? '...' : '';
154
155
        return substr($this->Entry, 0, $length) . $elipsis;
156
    }
157
}
158