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

LogEntry::formatLegacyEntry()   B

Complexity

Conditions 6
Paths 4

Size

Total Lines 23
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 23
rs 8.5906
cc 6
eloc 17
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
     * @var bool
28
     */
29
    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...
30
31
    /**
32
     * {@inheritDoc}
33
     */
34
    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...
35
        'Entry' => 'Text',
36
        'Level' => 'Varchar'
37
    ];
38
39
    /**
40
     * {@inheritDoc}
41
     */
42
    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...
43
        'GridfieldSummary' => 'Entry',
44
        'Created'          => 'Created',
45
        'Level'            => 'Level'
46
    ];
47
48
    /**
49
     * We should never need to edit log entries
50
     *
51
     * {@inheritDoc}
52
     */
53
    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...
54
    {
55
        return false;
56
    }
57
58
    /**
59
     * @inheritdoc
60
     * @return \SilverStripe\Forms\FieldList
61
     */
62
    public function getCMSFields()
63
    {
64
        $config = self::config()->get('format_entry');
65
        $fields = parent::getCMSFields();
66
        if ($config) { // Default setting, format the entry
67
            $fields->removeByName(array('Entry'));
68
            $text = $this->Entry;
69
            $asArray = Convert::json2array($text);
70
            if (!is_array($asArray)) {
71
                /** @deprecated We're falling back to the legacy text-only error */
72
                $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...
73
            } else {
74
                $entry = $this->entryToUl($asArray, true);
75
            }
76
            $entry = nl2br("<pre>" . $entry . "</pre>");
77
            $fields->addFieldToTab('Root.Main', LiteralField::create('FormattedEntry', $entry));
78
        } else { // Just move the field after the Level
79
            $entryField = $fields->dataFieldByName('Entry');
80
            $fields->insertAfter('Level', $entryField);
0 ignored issues
show
Bug introduced by
It seems like $entryField defined by $fields->dataFieldByName('Entry') on line 79 can be null; however, SilverStripe\Forms\FieldList::insertAfter() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
81
        }
82
83
        return $fields;
84
    }
85
86
    /**
87
     * Recursive method, will call itself if a sub element is an array
88
     * @param array $data
89
     * @param bool $first start with an opening bracket? if true, skip (counterintuitive, but naming)
90
     * @return string formatted <ul><li> of the array;
91
     */
92
    private function entryToUl($data, $first = false)
93
    {
94
        $out = $first ? '' : '[';
95
        $out .= '<ul style="margin-bottom: 0">';
96
        foreach ($data as $key => $arrayItem) {
97
            if (!is_array($arrayItem)) {
98
                $out .= '<li  class="list-unstyled"><span>' . $key . ' => ' . $arrayItem . '</span></li>';
99
            } else {
100
                $out .= '<li class="list-unstyled"><span>' . $key . ' => </span>' . $this->entryToUl($arrayItem) . '</li>';
101
            }
102
        }
103
        $out .= '</ul>';
104
        $out .= $first ? '' : ']';
105
106
        return $out;
107
    }
108
109
    /**
110
     * @param $text
111
     * @return string
112
     * @deprecated This method exists to make sure non-JSONFormatted messages won't break the flow
113
     */
114
    protected function formatLegacyEntry($text)
115
    {
116
        $entry = '';
117
        preg_match_all("/(\{\".*?}+)\s/", $text, $matches);
118
        if (count($matches[1])) {
119
            $entry .= "<h2>Entry</h2>";
120
            foreach ($matches[1] as $key => $match) {
121
                $pretext = substr($text, 0, strpos($text, $match)); // Header of the error
122
                $asArray = Convert::json2array($match); // Convert the rest to array
123
                $text = substr($text, strlen($pretext . $match)); // Prepare for the next entry
124
                $entry .= ($key > 0 ? "\n" : '') . trim($pretext) . ' => ';
125
                $entry .= $this->entryToUl($asArray);
0 ignored issues
show
Bug introduced by
It seems like $asArray defined by \SilverStripe\Core\Convert::json2array($match) on line 122 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...
126
            }
127
            if (json_decode(trim($text)) !== null) {
128
                $text = Convert::json2array($text);
129
                $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 128 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...
130
            } elseif (strlen(trim($text))) { // add the leftover if there is any
131
                $entry .= "\nOther:\n" . $text;
132
            }
133
        }
134
135
        return $entry;
136
    }
137
138
    /**
139
     * @param int $length Length of the summary
140
     * @return string shortened string of the entry if too long.
141
     */
142
    public function getGridfieldSummary($length = 300)
143
    {
144
        $elipsis = strlen($this->Entry) > $length ? '...' : '';
145
146
        return substr($this->Entry, 0, $length) . $elipsis;
147
    }
148
}
149