Passed
Push — master ( 37fbce...eb9638 )
by Mihail
09:07
created

Content::actionRss()   B

Complexity

Conditions 5
Paths 3

Size

Total Lines 46
Code Lines 23

Duplication

Lines 3
Ratio 6.52 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 3
loc 46
rs 8.4751
cc 5
eloc 23
nc 3
nop 0
1
<?php
2
3
namespace Apps\Controller\Front;
4
5
use Apps\ActiveRecord\ContentCategory;
6
use Apps\ActiveRecord\Content as ContentEntity;
7
use Apps\Model\Front\Content\EntityContentSearch;
8
use Extend\Core\Arch\FrontAppController;
9
use Ffcms\Core\App;
10
use Apps\Model\Front\Content\EntityCategoryList;
11
use Ffcms\Core\Exception\ForbiddenException;
12
use Ffcms\Core\Exception\NotFoundException;
13
use Apps\Model\Front\Content\EntityContentRead;
14
use Ffcms\Core\Helper\HTML\SimplePagination;
15
use Ffcms\Core\Helper\Serialize;
16
use Ffcms\Core\Helper\Type\Str;
17
use Suin\RSSWriter\Channel;
18
use Suin\RSSWriter\Feed;
19
use Suin\RSSWriter\Item;
20
21
/**
22
 * Class Content. Controller of content app - content and categories.
23
 * @package Apps\Controller\Front
24
 */
25
class Content extends FrontAppController
26
{
27
    const TAG_PER_PAGE = 50;
28
29
    /**
30
     * Index is forbidden
31
     * @throws NotFoundException
32
     */
33
    public function actionIndex()
34
    {
35
        throw new NotFoundException();
36
    }
37
38
    /**
39
     * List category content
40
     * @throws NotFoundException
41
     * @throws \Ffcms\Core\Exception\SyntaxException
42
     * @throws \Ffcms\Core\Exception\NativeException
43
     * @return string
44
     */
45
    public function actionList()
46
    {
47
        $path = App::$Request->getPathWithoutControllerAction();
48
        $configs = $this->getConfigs();
49
        $page = (int)App::$Request->query->get('page');
50
        $itemCount = (int)$configs['itemPerCategory'];
51
52
        // build special model with content list and category list information
53
        $model = new EntityCategoryList($path, $configs, $page);
54
55
        // build pagination
56
        $pagination = new SimplePagination([
57
            'url' => ['content/list', $path],
58
            'page' => $page,
59
            'step' => $itemCount,
60
            'total' => $model->getContentCount()
61
        ]);
62
63
        // drow response view
64
        return App::$View->render('list', [
65
            'model' => $model,
66
            'pagination' => $pagination,
67
            'configs' => $configs,
68
        ]);
69
    }
70
71
    /**
72
     * Show content item
73
     * @throws NotFoundException
74
     * @throws \Ffcms\Core\Exception\SyntaxException
75
     * @throws \Ffcms\Core\Exception\NativeException
76
     * @return string
77
     */
78
    public function actionRead()
79
    {
80
        // get raw path without controller-action
81
        $rawPath = App::$Request->getPathWithoutControllerAction();
82
        $arrayPath = explode('/', $rawPath);
83
        // get category and content item path as string
84
        $contentPath = array_pop($arrayPath);
85
        $categoryPath = implode('/', $arrayPath);
86
87
        // try to find category object by string pathway
88
        $categoryRecord = ContentCategory::getByPath($categoryPath);
89
90
        // if no categories are available for this path - throw exception
91
        if ($categoryRecord === null || $categoryRecord->count() < 1) {
92
            throw new NotFoundException();
93
        }
94
95
        // try to find content entity record
96
        $contentRecord = ContentEntity::where('path', '=', $contentPath)->where('category_id', '=', $categoryRecord->id);
97
        $trash = false;
98
99
        // if no entity is founded for this path lets try to find on trashed
100
        if ($contentRecord === null || $contentRecord->count() !== 1) {
101
            // check if user can access to content list on admin panel
102 View Code Duplication
            if (!App::$User->isAuth() || !App::$User->identity()->getRole()->can('Admin/Content/Index')) {
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...
103
                throw new NotFoundException();
104
            }
105
            // lets try to find in trashed
106
            $contentRecord->withTrashed();
107
            // no way, lets throw exception
108
            if ($contentRecord->count() !== 1) {
109
                throw new NotFoundException();
110
            }
111
            // set trashed marker for this item
112
            $trash = true;
113
        }
114
115
        // lets init entity model for content transfer to view
116
        $model = new EntityContentRead($categoryRecord, $contentRecord->first());
117
        $search = null;
118
        // check if similar search is enabled for item category
119
        if ((int)$model->getCategory()->getProperty('showSimilar') === 1 && $trash === false) {
120
            $search = new EntityContentSearch($model->title, $model->id);
121
        }
122
123
        return App::$View->render('read', [
124
            'model' => $model,
125
            'search' => $search,
126
            'trash' => $trash,
127
            'configs' => $this->getConfigs()
128
        ]);
129
    }
130
131
    /**
132
     * List latest by created_at content items contains tag name
133
     * @param string $tagName
134
     * @return string
135
     * @throws NotFoundException
136
     * @throws \Ffcms\Core\Exception\SyntaxException
137
     */
138
    public function actionTag($tagName)
139
    {
140
        $configs = $this->getConfigs();
141
        // check if tags is enabled
142
        if ((int)$configs['keywordsAsTags'] !== 1) {
143
            throw new NotFoundException(__('Tag system is disabled'));
144
        }
145
146
        // remove spaces and other shits
147
        $tagName = trim($tagName);
148
149
        // check if tag is not empty
150
        if (Str::likeEmpty($tagName) || Str::length($tagName) < 2) {
151
            throw new NotFoundException(__('Tag is empty or is too short!'));
152
        }
153
154
        // get equal rows order by creation date
155
        $records = ContentEntity::where('meta_keywords', 'like', '%' . $tagName . '%')->orderBy('created_at', 'DESC')->take(self::TAG_PER_PAGE);
156
        // check if result is not empty
157
        if ($records->count() < 1) {
158
            throw new NotFoundException(__('Nothing founded'));
159
        }
160
161
        // render response
162
        return App::$View->render('tag', [
163
            'records' => $records->get(),
164
            'tag' => App::$Security->strip_tags($tagName)
165
        ]);
166
    }
167
168
    /**
169
     * Display rss feeds from content category
170
     * @return string
171
     * @throws ForbiddenException
172
     */
173
    public function actionRss()
174
    {
175
        $path = App::$Request->getPathWithoutControllerAction();
176
        $configs = $this->getConfigs();
177
178
        // build model data
179
        $model = new EntityCategoryList($path, $configs, 0);
180
        // remove global layout
181
        $this->layout = null;
182
183
        // check if rss display allowed for this category
184 View Code Duplication
        if ((int)$model->category['configs']['showRss'] !== 1) {
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...
185
            throw new ForbiddenException(__('Rss feed is disabled for this category'));
186
        }
187
188
        // initialize rss feed objects
189
        $feed = new Feed();
190
        $channel = new Channel();
191
192
        // set channel data
193
        $channel->title($model->category['title'])
0 ignored issues
show
Bug introduced by
It seems like $model->category['title'] can also be of type array; however, Suin\RSSWriter\Channel::title() 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...
194
            ->description($model->category['description'])
0 ignored issues
show
Bug introduced by
It seems like $model->category['description'] can also be of type array; however, Suin\RSSWriter\Channel::description() 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...
195
            ->url(App::$Alias->baseUrl . '/content/list/' . $model->category['path'])
196
            ->appendTo($feed);
197
198
        // add content data
199
        if ($model->getContentCount() > 0) {
200
            foreach ($model->items as $row) {
201
                $item = new Item();
202
                // add title, short text, url
203
                $item->title($row['title'])
0 ignored issues
show
Bug introduced by
It seems like $row['title'] can also be of type array; however, Suin\RSSWriter\Item::title() 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...
204
                    ->description($row['text'])
205
                    ->url(App::$Alias->baseUrl . $row['uri']);
206
                // add poster
207
                if ($row['thumb'] !== null) {
208
                    $item->enclosure(App::$Alias->scriptUrl . $row['thumb'], $row['thumbSize'], 'image/jpeg');
209
                }
210
211
                // append response to channel
212
                $item->appendTo($channel);
213
            }
214
        }
215
216
        // render response from feed object
217
        return $feed->render();
218
    }
219
}
220