Passed
Push — master ( b534e3...17b30a )
by Mihail
19:51
created

EntityContentRead::before()   F

Complexity

Conditions 21
Paths 289

Size

Total Lines 124
Code Lines 72

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 21
eloc 72
nc 289
nop 0
dl 0
loc 124
rs 3.6155
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Apps\Model\Front\Content;
4
5
use Apps\ActiveRecord\Content;
6
use Apps\ActiveRecord\ContentCategory;
7
use Ffcms\Core\App;
8
use Ffcms\Core\Arch\Model;
9
use Ffcms\Core\Exception\ForbiddenException;
10
use Ffcms\Core\Helper\Date;
11
use Ffcms\Core\Helper\FileSystem\Directory;
12
use Ffcms\Core\Helper\FileSystem\File;
13
use Ffcms\Core\Helper\Type\Any;
14
use Ffcms\Core\Helper\Type\Arr;
15
use Ffcms\Core\Helper\Type\Obj;
16
use Ffcms\Core\Helper\Type\Str;
17
18
/**
19
 * Class EntityContentRead. Prepare record object data to display.
20
 * @package Apps\Model\Front\Content
21
 */
22
class EntityContentRead extends Model
23
{
24
    public $id;
25
    public $title;
26
    public $path;
27
    public $text;
28
    public $display;
29
    public $createDate;
30
    public $editDate;
31
    public $catName;
32
    public $catPath;
33
    public $authorId;
34
    public $authorName;
35
    public $views;
36
    public $catNesting = [];
37
    public $source;
38
    public $posterThumb;
39
    public $posterFull;
40
    public $rating;
41
    public $canRate;
42
43
    public $metaTitle;
44
    public $metaDescription;
45
    public $metaKeywords;
46
47
    // gallery image key-value array as thumb->full
48
    public $galleryItems;
49
50
    // private activerecord relation objects
51
    private $_category;
52
    private $_content;
53
54
    /**
55
     * EntityContentRead constructor. Pass active record objects
56
     * @param ContentCategory $category
57
     * @param Content $content
58
     */
59
    public function __construct(ContentCategory $category, Content $content)
60
    {
61
        $this->_category = $category;
62
        $this->_content = $content;
63
        parent::__construct();
64
    }
65
66
    /**
67
     * Prepare model attributes from passed objects
68
     * @throws ForbiddenException
69
    */
70
    public function before()
71
    {
72
        $this->id = $this->_content->id;
73
        $this->title = $this->_content->getLocaled('title');
74
        $this->text = $this->_content->getLocaled('text');
75
        $this->display = (bool)$this->_content->display;
76
77
        // check if title and text are exists
78
        if (Str::length($this->title) < 1 || Str::length($this->text) < 1) {
0 ignored issues
show
Bug introduced by
It seems like $this->title can also be of type array or null; however, Ffcms\Core\Helper\Type\Str::length() does only seem to accept string, 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...
Bug introduced by
It seems like $this->text can also be of type array or null; however, Ffcms\Core\Helper\Type\Str::length() does only seem to accept string, 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...
79
            throw new ForbiddenException('Content of this page is empty!');
80
        }
81
82
        // get meta data
83
        $this->metaTitle = $this->_content->getLocaled('meta_title');
84
        if (Any::isEmpty($this->metaTitle)) {
85
            $this->metaTitle = $this->title;
86
        }
87
88
        $this->metaDescription = $this->_content->getLocaled('meta_description');
89
        $tmpKeywords = $this->_content->getLocaled('meta_keywords');
90
        $this->metaKeywords = explode(',', $tmpKeywords);
91
92
        // set content date, category data
93
        $this->createDate = Date::humanize($this->_content->created_at);
0 ignored issues
show
Security Bug introduced by
It seems like $this->_content->created_at can also be of type false; however, Ffcms\Core\Helper\Date::humanize() does only seem to accept string|integer, did you maybe forget to handle an error condition?
Loading history...
94
        $this->catName = $this->_category->getLocaled('title');
95
        $this->catPath = $this->_category->path;
96
97
        // set user data
98
        if (App::$User->isExist($this->_content->author_id)) {
99
            $this->authorId = $this->_content->author_id;
100
            $profile = App::$User->identity($this->authorId)->profile;
101
            $this->authorName = $profile->getNickname();
102
        }
103
104
        $this->source = $this->_content->source;
105
        $this->views = $this->_content->views+1;
106
        // check for dependence, add '' for general cat, ex: general/depend1/depend2/.../depend-n
107
        $catNestingArray = Arr::merge([0 => ''], explode('/', $this->catPath));
108
        if ($catNestingArray > 1) {
109
            // latest element its a current nesting level, lets cleanup it
110
            array_pop($catNestingArray);
111
            $catNestingPath = null;
112
            foreach ($catNestingArray as $cPath) {
113
                $catNestingPath .= $cPath;
114
115
                // try to find category by path in db
116
                $record = ContentCategory::getByPath($catNestingPath);
117
                if ($record !== null && $record->count() > 0) {
118
                    // if founded - add to nesting data
119
                    $this->catNesting[] = [
120
                        'name' => $record->getLocaled('title'),
121
                        'path' => $record->path
122
                    ];
123
                }
124
                if (!Str::likeEmpty($catNestingPath)) {
125
                    $catNestingPath .= '/';
126
                }
127
            }
128
        }
129
130
        // build array of category nesting level
131
        $this->catNesting[] = [
132
            'name' => $this->catName,
133
            'path' => $this->catPath
134
        ];
135
136
        // get gallery images and poster data
137
        $galleryPath = '/upload/gallery/' . $this->_content->id;
138
        // check if gallery folder is exist
139
        if (Directory::exist($galleryPath)) {
140
            $originImages = File::listFiles($galleryPath . '/orig/', ['.jpg', '.png', '.gif', '.jpeg', '.bmp', '.webp'], true);
141
            // generate poster data
142
            if (Arr::in($this->_content->poster, $originImages)) {
143
                // original poster
144
                $posterName = $this->_content->poster;
145
                $this->posterFull = $galleryPath . '/orig/' . $posterName;
146
                if (!File::exist($this->posterFull)) {
147
                    $this->posterFull = null;
148
                }
149
150
                // thumb poster
151
                $posterSplit = explode('.', $posterName);
152
                array_pop($posterSplit);
153
                $posterCleanName = implode('.', $posterSplit);
154
                $this->posterThumb = $galleryPath . '/thumb/' . $posterCleanName . '.jpg';
155
                if (!File::exist($this->posterThumb)) {
156
                    $this->posterThumb = null;
157
                }
158
            }
159
160
            // generate full gallery
161
            foreach ($originImages as $image) {
162
                $imageSplit = explode('.', $image);
163
                array_pop($imageSplit);
164
                $imageClearName = implode('.', $imageSplit);
165
                // skip image used in poster
166
                if (Str::startsWith($imageClearName, $this->_content->poster)) {
167
                    continue;
168
                }
169
170
                $thumbPath = $galleryPath . '/thumb/' . $imageClearName . '.jpg';
171
                if (File::exist($thumbPath)) {
172
                    $this->galleryItems[$thumbPath] = $galleryPath . '/orig/' . $image;
173
                }
174
            }
175
        }
176
        
177
        // set rating data
178
        $this->rating = $this->_content->rating;
179
        $ignoredRate = App::$Session->get('content.rate.ignore');
180
        $this->canRate = true;
181
        if (Any::isArray($ignoredRate) && Arr::in((string)$this->id, $ignoredRate)) {
182
            $this->canRate = false;
183
        }
184
        if (!App::$User->isAuth()) {
185
            $this->canRate = false;
186
        } elseif ($this->authorId === App::$User->identity()->getId()) {
187
            $this->canRate = false;
188
        }
189
        
190
        // update views count
191
        $this->_content->views += 1;
192
        $this->_content->save();
193
    }
194
195
    /**
196
     * Get content record obj
197
     * @return Content
198
     */
199
    public function getRecord()
200
    {
201
        return $this->_content;
202
    }
203
204
    /**
205
     * Get category relation of this content
206
     * @return ContentCategory
207
     */
208
    public function getCategory()
209
    {
210
        return $this->_category;
211
    }
212
}
213