Completed
Push — master ( 6b77c2...0b4fa8 )
by Andrii
04:43
created

AbstractPage::setText()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 4
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 2
1
<?php
2
/**
3
 * Yii2 Pages Module
4
 *
5
 * @link      https://github.com/hiqdev/yii2-module-pages
6
 * @package   yii2-module-pages
7
 * @license   BSD-3-Clause
8
 * @copyright Copyright (c) 2016-2017, HiQDev (http://hiqdev.com/)
9
 */
10
11
namespace hiqdev\yii2\modules\pages\models;
12
13
use hiqdev\yii2\modules\pages\storage\FileSystemStorage;
14
use hiqdev\yii2\modules\pages\interfaces\StorageInterface;
15
use Symfony\Component\Yaml\Yaml;
16
use Yii;
17
18
abstract class AbstractPage extends \yii\base\BaseObject
19
{
20
    /** @var \yii\web\View */
21
    protected $view;
22
23
    public $layout;
24
25
    /** @var string */
26
    public $title;
27
28
    /** @var null|string */
29
    protected $path;
30
31
    /** @var string */
32
    protected $text;
33
34
    /** @var array  */
35
    protected $data = [];
36
37
    /** @var string */
38
    protected $url;
39
40
    /** @var StorageInterface  */
41
    protected $storage;
42
43
    public function __construct($path = null, StorageInterface $storage = null, $config = [])
44
    {
45
        if ($path) {
46
            $this->storage = $storage;
47
            list($data, $text) = $this->extractData($path);
48
49
            $this->path = $path;
50
            $this->text = $text;
51
            $this->setData($data);
52
        }
53
54
        $this->view = Yii::$app->view;
55
        parent::__construct($config);
56
    }
57
58
    public function setData($data)
59
    {
60
        if (!is_array($data)) {
61
            return;
62
        }
63
        $this->data = $data;
64
        foreach (['title', 'layout', 'url'] as $key) {
65
            if (isset($data[$key])) {
66
                $this->{$key} = $data[$key];
67
            }
68
        }
69
    }
70
71
    public function getData()
72
    {
73
        return $this->data;
74
    }
75
76
    public function getPath()
77
    {
78
        return $this->path;
79
    }
80
81
    public function getDate()
82
    {
83
        return $this->data['date'];
84
    }
85
86
    public function getUrl()
87
    {
88
        return $this->url ?: ['/pages/render/index', 'page' => $this->getPath()];
89
    }
90
91
    public static function createFromFile($path, FileSystemStorage $storage)
92
    {
93
        $extension = pathinfo($path)['extension'];
94
        $class = $storage->findPageClass($extension);
95
96
        return new $class($path, $storage);
97
    }
98
99 View Code Duplication
    public function extractData($path)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
100
    {
101
        $lines = $this->storage->readArray($path);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface hiqdev\yii2\modules\page...rfaces\StorageInterface as the method readArray() does only exist in the following implementations of said interface: hiqdev\yii2\modules\page...orage\FileSystemStorage.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
102
        $yaml = $this->readQuotedLines($lines, '/^---$/', '/^---$/');
103
        if (empty($yaml)) {
104
            $data = [];
105
            $text = $lines;
106
        } else {
107
            $data = $this->readYaml($yaml);
108
            $text = array_slice($lines, count($yaml));
109
        }
110
111
        return [$data, implode("\n", $text)];
112
    }
113
114
    public function readFrontMatter($lines)
115
    {
116
        $yaml = $this->readQuotedLines($lines, '/^---$/', '/^---$/');
117
        if (empty($yaml)) {
118
            return [];
119
        }
120
121
        return empty($yaml) ? [] : $this->readYaml($yaml);
122
    }
123
124
    public function readYaml($lines)
125
    {
126
        $data = Yaml::parse(implode("\n", $lines));
127
        if (is_int($data['date'])) {
128
            $data['date'] = date('c', $data['date']);
129
        }
130
131
        return $data;
132
    }
133
134
    public function readQuotedLines($lines, $headMarker, $tailMarker)
135
    {
136
        $line = array_shift($lines);
137
        if (!preg_match($headMarker, $line, $matches)) {
138
            return null;
139
        }
140
        $res[] = ltrim(substr($line, strlen($matches[0])));
0 ignored issues
show
Coding Style Comprehensibility introduced by
$res was never initialized. Although not strictly required by PHP, it is generally a good practice to add $res = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
141
        while ($line) {
142
            $line = array_shift($lines);
143
            if (preg_match($tailMarker, $line, $matches)) {
144
                $res[] = rtrim(substr($line, 0, -strlen($matches[0])));
145
                break;
146
            }
147
            $res[] = $line;
148
        }
149
150
        return $res;
151
    }
152
153
    /**
154
     * Renders the page with given params.
155
     *
156
     * @param array $params
157
     * @abstract
158
     */
159
    abstract public function render(array $params = []);
160
161
    /**
162
     * @param string $text
163
     */
164
    public function setText(string $text): void
165
    {
166
        $this->text = $text;
167
    }
168
169
    /**
170
     * @param string $url
171
     */
172
    public function setUrl(string $url): void
173
    {
174
        $this->url = $url;
175
    }
176
}
177