Test Failed
Push — master ( e3c39f...fe570d )
by Mihail
07:20
created

Model/Front/Content/FormNarrowContentUpdate.php (1 issue)

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\Helper\Crypt;
10
use Ffcms\Core\Helper\FileSystem\Directory;
11
use Ffcms\Core\Helper\FileSystem\Normalize;
12
use Ffcms\Core\Helper\Type\Any;
13
use Ffcms\Core\Helper\Type\Str;
14
use Gregwar\Image\Image;
15
16
class FormNarrowContentUpdate extends Model
17
{
18
    public $title = [];
19
    public $text = [];
20
    public $path;
21
    public $categoryId;
22
    /** @var \Symfony\Component\HttpFoundation\File\UploadedFile $poster */
23
    public $poster;
24
25
    public $authorId;
26
27
    /** @var Content */
28
    private $_record;
29
    /** @var array */
30
    private $_configs;
31
32
    private $_new = false;
33
34
    /**
35
     * FormNarrowContentUpdate constructor. Pass record object inside.
36
     * @param Content $record
37
     * @param array $configs
38
     */
39
    public function __construct(Content $record, $configs)
40
    {
41
        $this->_record = $record;
42
        $this->_configs = $configs;
43
        parent::__construct();
44
    }
45
46
    /**
47
    * Set default values from database record
48
    */
49
    public function before()
50
    {
51
        // set data from db record
52
        $this->title = $this->_record->title;
53
        $this->text = $this->_record->text;
54
        $this->path = $this->_record->path;
55
        $this->categoryId = $this->_record->category_id;
56
57
        // set current user id
58
        $this->authorId = App::$User->identity()->getId();
59
        // set true if it is a new content item
60
        if ($this->_record->id === null || (int)$this->_record->id < 1) {
61
            $this->_new = true;
62
        }
63
64
        // set random path slug if not defined
65
        if ($this->path === null || Str::likeEmpty($this->path)) {
66
            $randPath = date('d-m-Y') . '-' . Str::randomLatin(mt_rand(8, 12));
67
            $this->path = Str::lowerCase($randPath);
68
        }
69
    }
70
71
    /**
72
     * Form field input sources: post/get/file
73
     * {@inheritDoc}
74
     * @see \Ffcms\Core\Arch\Model::sources()
75
     */
76
    public function sources(): array
77
    {
78
        return [
79
            'poster' => 'file',
80
            'title' => 'post',
81
            'text' => 'post',
82
            'path' => 'post',
83
            'categoryId' => 'post'
84
        ];
85
    }
86
87
    /**
88
    * Form labels
89
    * @return array
90
    */
91
    public function labels(): array
92
    {
93
        return [
94
            'title' => __('Title'),
95
            'text' => __('Text'),
96
            'path' => __('Path slug'),
97
            'categoryId' => __('Category'),
98
            'poster' => __('Poster')
99
        ];
100
    }
101
102
    /**
103
    * Content update form validation rules
104
    * @return array
105
    */
106
    public function rules(): array
107
    {
108
        $r = [
109
            [['path', 'categoryId'], 'required'],
110
            ['title.' . App::$Request->getLanguage(), 'required'],
111
            ['text.' . App::$Request->getLanguage(), 'required', null, true, true],
112
            ['text', 'used', null, true, true],
113
            ['path', 'direct_match', '/^[a-zA-Z0-9\-]+$/'],
114
            ['categoryId', 'in', $this->categoryIds()],
115
            ['path', 'Apps\Model\Front\Content\FormNarrowContentUpdate::validatePath'],
116
            ['poster', 'used'],
117
            ['poster', 'isFile', ['jpg', 'png', 'gif', 'jpeg']],
118
            ['poster', 'sizeFile', (int)$this->_configs['gallerySize'] * 1024] // in bytes
119
        ];
120
121
        foreach (App::$Properties->get('languages') as $lang) {
122
            $r[] = ['title.' . $lang, 'length_max', 120, null, true, true];
123
            $r[] = ['keywords.' . $lang, 'length_max', 150];
124
            $r[] = ['description.' . $lang, 'length_max', 250];
125
        }
126
127
        return $r;
128
    }
129
130
    /**
131
     * Set attribute validation types
132
     * @return array
133
     */
134
    public function types(): array
135
    {
136
        return [
137
            'text' => 'html'
138
        ];
139
    }
140
141
    /**
142
     * Save input data to database
143
     */
144
    public function make()
145
    {
146
        // save data to db
147
        $this->_record->title = $this->title;
148
        $this->_record->text = $this->text;
149
        $this->_record->path = $this->path;
150
        $this->_record->category_id = (int)$this->categoryId;
151
        $this->_record->display = 0; // set to premoderation
0 ignored issues
show
Documentation Bug introduced by
The property $display was declared of type boolean, but 0 is of type integer. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
152
        $this->_record->author_id = (int)$this->authorId;
153
        $this->_record->save();
154
155
        // work with poster data
156
        if ($this->poster !== null) {
157
            // lets move poster from tmp to gallery
158
            $originDir = '/upload/gallery/' . $this->_record->id . '/orig/';
159
            $thumbDir = '/upload/gallery/' . $this->_record->id . '/thumb/';
160
            if (!Directory::exist($originDir)) {
161
                Directory::create($originDir);
162
            }
163
164
            if (!Directory::exist($thumbDir)) {
165
                Directory::create($thumbDir);
166
            }
167
168
            $fileName = App::$Security->simpleHash($this->poster->getClientOriginalName() . $this->poster->getSize());
169
            $newFullName = $fileName . '.' . $this->poster->guessExtension();
170
            // move poster to upload gallery directory
171
            $this->poster->move(Normalize::diskFullPath($originDir), $newFullName);
172
            // initialize image resizer
173
            $thumb = new Image();
174
            $thumb->setCacheDir(root . '/Private/Cache/images');
175
176
            // open original file, resize it and save
177
            $thumbSaveName = Normalize::diskFullPath($thumbDir) . '/' . $fileName . '.jpg';
178
            $thumb->open(Normalize::diskFullPath($originDir) . DIRECTORY_SEPARATOR . $newFullName)
179
                ->cropResize($this->_configs['galleryResize'])
180
                ->save($thumbSaveName, 'jpg', 90);
181
            $thumb = null;
182
183
            // update poster in database
184
            $this->_record->poster = $newFullName;
185
            $this->_record->save();
186
        }
187
    }
188
189
    /**
190
     * Get allowed category ids as array
191
     * @return array
192
     */
193
    public function categoryIds()
194
    {
195
        $data = ContentCategory::getSortedCategories();
196
        return array_keys($data);
197
    }
198
199
    /**
200
     * Validate content item pathway
201
     * @return bool
202
     */
203
    public function validatePath()
204
    {
205
        // try to find this item
206
        $find = Content::where('path', '=', $this->path);
207
        // exclude self id
208
        if ($this->_record->id && Any::isInt($this->_record->id)) {
209
            $find->where('id', '!=', $this->_record->id);
210
        }
211
212
        // limit only current category id
213
        $find->where('category_id', '=', $this->categoryId);
214
215
        return $find->count() < 1;
216
    }
217
}
218