Completed
Push — master ( 8146b2...061ea8 )
by Ryan
03:02
created

AbstractMiddleware::get()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 3
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * Copyright (c) 2017–2018 Ryan Parman <http://ryanparman.com>.
4
 * Copyright (c) 2017–2018 Contributors.
5
 *
6
 * http://opensource.org/licenses/Apache2.0
7
 */
8
declare(strict_types=1);
9
10
namespace SimplePie\Middleware;
11
12
use SimplePie\Configuration as C;
13
use SimplePie\Mixin as Tr;
14
15
/**
16
 * The base middleware class that all other middleware classes extend from. It handles low-level functionality that is
17
 * shared across all middleware classes.
18
 */
19
abstract class AbstractMiddleware implements C\SetLoggerInterface
20
{
21
    use Tr\LoggerTrait;
22
23
    /**
24
     * A callable which is used to determine whether or not to run this middleware.
25
     *
26
     * @var callable
27
     */
28
    protected $fn;
29
30
    /**
31
     * Constructs a new instance of this class.
32
     *
33
     * Accepts a callable with the following function signature:
34
     *
35
     * ```
36
     * function () {}
37
     * ```
38
     *
39
     * @param callable|null $fn A callable which is used to determine whether or not to run this
40
     *                          middleware. A value of `true` means that the middleware should run.
41
     *                          A value of `false` means that the middleware should NOT run, By
42
     *                          default, the middleware will run.
43
     */
44
    public function __construct(?callable $fn = null)
45
    {
46
        $this->fn = $fn ?: static function () {
47
            return true;
48
        };
49
    }
50
51
    /**
52
     * Checks whether or not a particular property exists on an object, and if not, instantiates it as an array.
53
     *
54
     * @param mixed  $object   An object that you can add ad-hoc properties to. Preferably a `stdClass` object.
55
     * @param string $property The name of the property to check and/or add.
56
     */
57
    public function addArrayProperty(&$object, string $property): void
58
    {
59
        if (!isset($object->{$property})) {
60
            $object->{$property} = [];
61
        }
62
    }
63
64
    /**
65
     * Return the value of an associative array key, if it exists. If not, return $default.
66
     *
67
     * @param array  $arr     The associative array to check.
68
     * @param string $key     The key in the associative array to return the value for.
69
     * @param mixed  $default The default value to return if there is no value. The default value is `null`.
70
     *
71
     * @return mixed
72
     */
73
    public function get(array $arr, string $key, $default = null)
74
    {
75
        return $arr[$key]
76
            ?? $default;
77
    }
78
}
79