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

LogEntry::getCMSFields()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 21
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 21
rs 9.3142
c 1
b 0
f 0
cc 3
eloc 16
nc 3
nop 0
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
 */
15
class LogEntry extends DataObject
16
{
17
    /**
18
     * {@inheritDoc}
19
     */
20
    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...
21
22
    /**
23
     * @var bool
24
     */
25
    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...
26
27
    /**
28
     * {@inheritDoc}
29
     */
30
    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...
31
        'Entry' => 'Text',
32
        'Level' => 'Varchar'
33
    ];
34
35
    /**
36
     * {@inheritDoc}
37
     */
38
    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...
39
        'GridfieldSummary' => 'Entry',
40
        'Created' => 'Created',
41
        'Level' => 'Level'
42
    ];
43
44
    /**
45
     * We should never need to edit log entries
46
     *
47
     * {@inheritDoc}
48
     */
49
    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...
50
    {
51
        return false;
52
    }
53
54
    /**
55
     * @inheritdoc
56
     * @return \SilverStripe\Forms\FieldList
57
     */
58
    public function getCMSFields()
59
    {
60
        $config = self::config()->get('format_entry');
61
        $fields = parent::getCMSFields();
62
        if ($config) { // Default setting, format the entry
63
            $fields->removeByName(array('Entry'));
64
            $text = $this->Entry;
0 ignored issues
show
Documentation introduced by
The property Entry does not exist on object<SilverLeague\LogViewer\Model\LogEntry>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
65
            if (!Convert::json2array($text)) { /** @deprecated We're falling back to the legacy text-only error */
66
                $entry = $this->convertLegacy($text);
0 ignored issues
show
Deprecated Code introduced by
The method SilverLeague\LogViewer\M...gEntry::convertLegacy() 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...
67
            } else {
68
                $asArray = Convert::json2array($text);
69
                $entry = $this->entryToUl($asArray, true);
0 ignored issues
show
Bug introduced by
It seems like $asArray defined by \SilverStripe\Core\Convert::json2array($text) on line 68 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...
70
            }
71
            $fields->addFieldToTab('Root.Main', LiteralField::create('FormattedEntry', nl2br("<pre>" . $entry . "</pre>")));
72
        } else { // Just move the field after the Level
73
            $entryField = $fields->dataFieldByName('Entry');
74
            $fields->insertAfter('Level', $entryField);
0 ignored issues
show
Bug introduced by
It seems like $entryField defined by $fields->dataFieldByName('Entry') on line 73 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...
75
        }
76
77
        return $fields;
78
    }
79
80
    /**
81
     * Recursive method, will call itself if a sub element is an array
82
     * @param array $data
83
     * @param bool $first start with an opening bracket? if true, skip (counterintuitive, but naming)
84
     * @return string formatted <ul><li> of the array;
85
     */
86
    private function entryToUl($data, $first = false)
87
    {
88
        $out = $first ? '' : '[';
89
        $out .= '<ul style="margin-bottom: 0">';
90
        foreach ($data as $key => $arrayItem) {
91
            if (!is_array($arrayItem)) {
92
                $out .= '<li  class="list-unstyled"><span>' . $key . ' => ' . $arrayItem . '</span></li>';
93
            } else {
94
                $out .= '<li class="list-unstyled"><span>' . $key . ' => </span>' . $this->entryToUl($arrayItem) . '</li>';
95
            }
96
        }
97
        $out .= '</ul>';
98
        $out .= $first ? '' : ']';
99
100
        return $out;
101
    }
102
103
    /**
104
     * @param $text
105
     * @return string
106
     * @deprecated This method exists to make sure non-JSONFormatted messages won't break the flow
107
     */
108
    protected function convertLegacy($text)
109
    {
110
        $entry = '';
111
        preg_match_all("/(\{\".*?}+)\s/", $text, $matches);
112
        if (count($matches[1])) {
113
            $entry .= "<h2>Entry</h2>";
114
            foreach ($matches[1] as $key => $match) {
115
                $pretext = substr($text, 0, strpos($text, $match)); // Header of the error
116
                $asArray = Convert::json2array($match); // Convert the rest to array
117
                $text = substr($text, strlen($pretext . $match)); // Prepare for the next entry
118
                $entry .= ($key > 0 ? "\n" : '') . trim($pretext) . ' => ';
119
                $entry .= $this->entryToUl($asArray);
0 ignored issues
show
Bug introduced by
It seems like $asArray defined by \SilverStripe\Core\Convert::json2array($match) on line 116 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...
120
            }
121
            if (json_decode(trim($text)) !== null) {
122
                $text = Convert::json2array($text);
123
                $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 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...
124
            } elseif(strlen(trim($text))) { // add the leftover if there is any
0 ignored issues
show
Coding Style introduced by
Expected 1 space after ELSEIF keyword; 0 found
Loading history...
125
                $entry .= "\nOther:\n" . $text;
126
            }
127
        }
128
129
        return $entry;
130
    }
131
132
    /**
133
     * @param int $length Length of the summary
134
     * @return string shortened string of the entry if too long.
135
     */
136
    public function GridfieldSummary($length = 300)
0 ignored issues
show
Coding Style introduced by
Method name "LogEntry::GridfieldSummary" is not in camel caps format
Loading history...
137
    {
138
        $elipsis = strlen($this->Entry) > $length ? '...' : '';
0 ignored issues
show
Documentation introduced by
The property Entry does not exist on object<SilverLeague\LogViewer\Model\LogEntry>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
139
140
        return substr($this->Entry, 0, $length) . $elipsis;
0 ignored issues
show
Documentation introduced by
The property Entry does not exist on object<SilverLeague\LogViewer\Model\LogEntry>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
141
    }
142
}
143