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

LogEntry::entryToUl()   B

Complexity

Conditions 5
Paths 12

Size

Total Lines 16
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 16
rs 8.8571
cc 5
eloc 11
nc 12
nop 2
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)) {
66
                /** @deprecated We're falling back to the legacy text-only error */
67
                $entry = $this->convertLegacy($text);
0 ignored issues
show
Documentation Bug introduced by
The method convertLegacy does not exist on object<SilverLeague\LogViewer\Model\LogEntry>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
68
            } else {
69
                $asArray = Convert::json2array($text);
70
                $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 69 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...
71
            }
72
            $entry = nl2br("<pre>" . $entry . "</pre>");
73
            $fields->addFieldToTab('Root.Main', LiteralField::create('FormattedEntry', $entry));
74
        } else { // Just move the field after the Level
75
            $entryField = $fields->dataFieldByName('Entry');
76
            $fields->insertAfter('Level', $entryField);
0 ignored issues
show
Bug introduced by
It seems like $entryField defined by $fields->dataFieldByName('Entry') on line 75 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...
77
        }
78
79
        return $fields;
80
    }
81
82
    /**
83
     * Recursive method, will call itself if a sub element is an array
84
     * @param array $data
85
     * @param bool $first start with an opening bracket? if true, skip (counterintuitive, but naming)
86
     * @return string formatted <ul><li> of the array;
87
     */
88
    private function entryToUl($data, $first = false)
89
    {
90
        $out = $first ? '' : '[';
91
        $out .= '<ul style="margin-bottom: 0">';
92
        foreach ($data as $key => $arrayItem) {
93
            if (!is_array($arrayItem)) {
94
                $out .= '<li  class="list-unstyled"><span>' . $key . ' => ' . $arrayItem . '</span></li>';
95
            } else {
96
                $out .= '<li class="list-unstyled"><span>' . $key . ' => </span>' . $this->entryToUl($arrayItem) . '</li>';
97
            }
98
        }
99
        $out .= '</ul>';
100
        $out .= $first ? '' : ']';
101
102
        return $out;
103
    }
104
105
    /**
106
     * @param $text
107
     * @return string
108
     * @deprecated This method exists to make sure non-JSONFormatted messages won't break the flow
109
     */
110
    protected function formatLegacyEntry($text)
111
    {
112
        $entry = '';
113
        preg_match_all("/(\{\".*?}+)\s/", $text, $matches);
114
        if (count($matches[1])) {
115
            $entry .= "<h2>Entry</h2>";
116
            foreach ($matches[1] as $key => $match) {
117
                $pretext = substr($text, 0, strpos($text, $match)); // Header of the error
118
                $asArray = Convert::json2array($match); // Convert the rest to array
119
                $text = substr($text, strlen($pretext . $match)); // Prepare for the next entry
120
                $entry .= ($key > 0 ? "\n" : '') . trim($pretext) . ' => ';
121
                $entry .= $this->entryToUl($asArray);
0 ignored issues
show
Bug introduced by
It seems like $asArray defined by \SilverStripe\Core\Convert::json2array($match) on line 118 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...
122
            }
123
            if (json_decode(trim($text)) !== null) {
124
                $text = Convert::json2array($text);
125
                $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 124 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
            } elseif (strlen(trim($text))) { // add the leftover if there is any
127
                $entry .= "\nOther:\n" . $text;
128
            }
129
        }
130
131
        return $entry;
132
    }
133
134
    /**
135
     * @param int $length Length of the summary
136
     * @return string shortened string of the entry if too long.
137
     */
138
    public function getGridfieldSummary($length = 300)
139
    {
140
        $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...
141
142
        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...
143
    }
144
}
145