Passed
Pull Request — master (#281)
by
unknown
05:45
created

NotificationParser::replace()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 3
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace Fenos\Notifynder\Parsers;
4
5
use Fenos\Notifynder\Models\NotificationCategory;
6
use Fenos\Notifynder\Exceptions\ExtraParamsException;
7
use Illuminate\Database\Eloquent\ModelNotFoundException;
8
use Fenos\Notifynder\Models\Notification as ModelNotification;
9
10
/**
11
 * Class NotificationParser.
12
 */
13
class NotificationParser
14
{
15
    /**
16
     * Regex-search-rule.
17
     */
18
    const RULE = '/\{([a-zA-Z0-9_\.]+)\}/m';
19
20
    /**
21
     * Parse a notification and return the body text.
22
     *
23
     * @param ModelNotification $notification
24
     * @param int $categoryId
25
     * @return string
26
     * @throws ExtraParamsException
27
     */
28
    public function parse($notification, $categoryId)
0 ignored issues
show
Unused Code introduced by
The parameter $categoryId 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...
29
    {
30
        $category = $notification->category;
0 ignored issues
show
Bug introduced by
The property category does not seem to exist. Did you mean category_id?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
31
        if (is_null($category)) {
32
            throw (new ModelNotFoundException)->setModel(
33
                NotificationCategory::class, $notification->category_id
34
            );
35
        }
36
        $text = $category->template_body;
37
38
        $specialValues = $this->getValues($text);
39
        if (count($specialValues) > 0) {
40
            $specialValues = array_filter($specialValues, function ($value) use ($notification) {
41
                return ((is_array($notification) && isset($notification[$value])) || (is_object($notification) && isset($notification->$value))) || starts_with($value, ['extra.', 'to.', 'from.']);
42
            });
43
44
            foreach ($specialValues as $replacer) {
45
                $replace = $this->mixedGet($notification, $replacer);
46
                if (empty($replace) && notifynder_config()->isStrict()) {
47
                    throw new ExtraParamsException("The following [$replacer] param required from your category is missing.");
48
                }
49
                $text = $this->replace($text, $replace, $replacer);
50
            }
51
        }
52
53
        return $text;
54
    }
55
56
    /**
57
     * Get an array of all placehodlers.
58
     *
59
     * @param string $body
60
     * @return array
61
     */
62
    protected function getValues($body)
63
    {
64
        $values = [];
65
        preg_match_all(self::RULE, $body, $values);
66
67
        return $values[1];
68
    }
69
70
    /**
71
     * Replace a single placeholder.
72
     *
73
     * @param string $body
74
     * @param string $valueMatch
75
     * @param string $replacer
76
     * @return string
77
     */
78
    protected function replace($body, $valueMatch, $replacer)
79
    {
80
        $body = str_replace('{'.$replacer.'}', $valueMatch, $body);
81
82
        return $body;
83
    }
84
85
    /**
86
     * @param array|object $object
87
     * @param string $key
88
     * @param null|mixed $default
89
     * @return mixed
90
     */
91
    protected function mixedGet($object, $key, $default = null)
92
    {
93
        if (is_null($key) || trim($key) == '') {
94
            return '';
95
        }
96
        foreach (explode('.', $key) as $segment) {
97
            if (is_object($object) && isset($object->{$segment})) {
98
                $object = $object->{$segment};
99
                continue;
100
            }
101 View Code Duplication
            if (is_object($object) && method_exists($object, '__get') && ! is_null($object->__get($segment))) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
102
                $object = $object->__get($segment);
103
                continue;
104
            }
105 View Code Duplication
            if (is_object($object) && method_exists($object, 'getAttribute') && ! is_null($object->getAttribute($segment))) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
106
                $object = $object->getAttribute($segment);
107
                continue;
108
            }
109
            if (is_array($object) && array_key_exists($segment, $object)) {
110
                $object = array_get($object, $segment, $default);
111
                continue;
112
            }
113
114
            return value($default);
115
        }
116
117
        return $object;
118
    }
119
}
120