Completed
Push — dev-master ( 86aae1...377172 )
by Vijay
03:33
created

Pages::pageImageUrlPath()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 5
nc 2
nop 1
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace FFCMS\Mappers;
4
5
/**
6
 * Pages Mapper Class.
7
 *
8
 * @author Vijay Mahrra <[email protected]>
9
 * @copyright (c) Copyright 2016 Vijay Mahrra
10
 * @license GPLv3 (http://www.gnu.org/licenses/gpl-3.0.html)
11
 *
12
 * @property int    $id
13
 * @property string $uuid
14
 * @property string $users_uuid
15
 * @property string $key
16
 * @property string $author
17
 * @property string $language
18
 * @property string $status
19
 * @property string $slug
20
 * @property string $path
21
 * @property string $keywords
22
 * @property string $description
23
 * @property string $title
24
 * @property string $summary
25
 * @property string $body
26
 * @property string $scopes
27
 * @property string $category
28
 * @property string $tags
29
 * @property string $metadata
30
 * @property string $created
31
 * @property string $published
32
 * @property string $updated
33
 * @property boolean $robots
34
 */
35
class Pages extends Mapper
36
{
37
    /**
38
     * Fields and their visibility to clients, boolean or string of visible field name
39
     *
40
     * @var array $fieldsVisible
41
     * @link https://github.com/Wixel/GUMP
42
     */
43
    public $fieldsVisible = [
44
        'uuid'         => 'id',
45
        'users_uuid'   => 'user_id',
46
    ];
47
48
    /**
49
     * Fields that are editable to clients, boolean or string of visible field name
50
     *
51
     * @var array $fieldsEditable
52
     */
53
    protected $fieldsEditable = [
54
        'key',
55
        'author',
56
        'language',
57
        'status',
58
        'slug',
59
        'path',
60
        'keywords',
61
        'description',
62
        'title',
63
        'summary',
64
        'body',
65
        'scopes',
66
        'category',
67
        'tags',
68
        'metadata',
69
        'published',
70
        'robots',
71
    ];
72
73
    /**
74
     * Filter rules for fields
75
     *
76
     * @var array $filterRules
77
     * @link https://github.com/Wixel/GUMP
78
     */
79
    public $filterRules = [
80
        'uuid'        => 'trim|sanitize_string|lower',
81
        'users_uuid'  => 'trim|sanitize_string|lower',
82
        'key'         => 'trim|sanitize_string|lower|slug',
83
        'author'      => 'trim|sanitize_string',
84
        'language'    => 'trim|sanitize_string|lower',
85
        'status'      => 'trim|sanitize_string|lower',
86
        'slug'        => 'trim|sanitize_string|lower|slug',
87
        'path'        => 'trim|sanitize_string|lower',
88
        'keywords'    => 'trim|sanitize_string|lower',
89
        'description' => 'trim|sanitize_string',
90
        'title'       => 'trim|sanitize_string',
91
        'summary'     => 'trim|sanitize_string',
92
        'body'        => 'trim|sanitize_string',
93
        'scopes'      => 'trim|sanitize_string|lower',
94
        'category'    => 'trim|sanitize_string|lower',
95
        'tags'        => 'trim|sanitize_string|lower',
96
        'metadata'    => 'trim',
97
        'created'     => 'trim|sanitize_string',
98
        'published'   => 'trim|sanitize_string',
99
        'updated'     => 'trim|sanitize_string',
100
        'robots'      => 'trim|sanitize_numbers|whole_number',
101
    ];
102
103
    /**
104
     * Validation rules for fields
105
     *
106
     * @var array $validationRules
107
     * @link https://github.com/Wixel/GUMP
108
     */
109
    public $validationRules = [
110
        'uuid'        => 'alpha_dash',
111
        'users_uuid'  => 'alpha_dash',
112
        'robots'      => 'numeric',
113
    ];
114
115
    /**
116
     * Path in assets folder to user page images
117
     *
118
     * @var string $pageImagePath
119
     */
120
    protected $pageImagePath = '/img/pages/';
121
122
    /**
123
     * Default page image name
124
     *
125
     * @var string $pageImageFileName
126
     */
127
    protected $pageImageFileName = 'page.png';
128
129
    /**
130
     * Return the on-the-fly dynamic image generation URL path
131
     *
132
     * @param array $params params to url
133
     * @return string return the url path or false if not exists
134
     */
135
    public function pageImageUrlDynamic(array $params = [])
136
    {
137
        $f3 = \Base::instance();
138
        return Helpers\Url::internal($f3->alias('page_image', 'key=' . $params['key']), $params);
0 ignored issues
show
Documentation introduced by
'key=' . $params['key'] is of type string, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
139
    }
140
141
    /**
142
     * Return the URL path to the image if exists or false
143
     *
144
     * @return string return the url path or false if not exists
145
     */
146
    public function pageImageUrlPath($filename = null): string
147
    {
148
        if (empty($filename)) {
149
            $filename = $this->pageImageFileName;
150
        }
151
        $assetsModel = Models\Assets::instance();
152
        return $assetsModel->assetUrlPath($this->pageImagePath . $this->uuid . '/' . $filename);
153
    }
154
155
    /**
156
     * Create if needed, and return the dir to the page image
157
     *
158
     * @return string $dir to the page image
159
     */
160
    public function pageImageDirPath(): string
161
    {
162
        $assetsModel = Models\Assets::instance();
163
        return $assetsModel->assetDirPath($this->pageImagePath . $this->uuid);
164
    }
165
166
    /**
167
     * Create if needed, and return the path to the page image
168
     *
169
     * @param null|string $filename filename for image
170
     * @return string $path to the page image
171
     */
172
    public function pageImageFilePath($filename = null): string
173
    {
174
        if (empty($filename)) {
175
            $filename = $this->pageImageFileName;
176
        }
177
        return $this->pageImageDirPath() . $filename;
178
    }
179
180
    /**
181
     * Return the URL path to the image if exists or false
182
     *
183
     * @return boolean $path to the page image
184
     * @return boolean true if the page image exists
185
     */
186
    public function pageImageExists($filename = null)
187
    {
188
        return file_exists($this->pageImageFilePath($filename));
189
    }
190
191
    /**
192
     * Return the URL path to the image if exists or false
193
     *
194
     * @param string $filename
0 ignored issues
show
Documentation introduced by
Should the type for parameter $filename not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
195
     * @return false|string return the url path or false if not exists
196
     */
197
    public function pageImageUrl($filename = null)
198
    {
199
        $url = $this->pageImageExists($filename) ? $this->pageImageUrlPath($filename) : false;
200
        if (empty($url)) {
201
            return false;
202
        }
203
        return $url . '?' . filesize($this->pageImageFilePath($filename));
204
    }
205
206
207
    /**
208
     * Create page image from given file
209
     *
210
     * @param string $file path to file
211
     * @return boolean if the file was written and and asset record created
0 ignored issues
show
Documentation introduced by
Should the return type not be false|array? Also, consider making the array more specific, something like array<String>, or String[].

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

If the return type contains the type array, this check recommends the use of a more specific type like String[] or array<String>.

Loading history...
212
     */
213
    public function pageImageCreate($file)
214
    {
215
        if (!file_exists($file)) {
216
            throw new Exceptions\Exception('Page image creation file does not exist.');
217
        }
218
        $f3 = \Base::instance();
219
220
        // read exif metadata
221
        $reader = \PHPExif\Reader\Reader::factory(\PHPExif\Reader\Reader::TYPE_NATIVE);
222
        $exif = $reader->read($file);
223
        $metadata = $exif->getData();
224
        unset($exif);
225
226
        // load image
227
        $img = new \Image($file);
228
229
        // make sure maximum width/height not exceeded
230
        $max    = $f3->get('assets.image.max');
231
        $height = $img->height();
232
        $width  = $img->width();
233 View Code Duplication
        if ($width > $max['width'] || $height > $max['height']) {
234
            $height = $height > $max['height'] ? $max['height'] : $height;
235
            $width  = $width > $max['width'] ? $max['width'] : $width;
236
            $img->resize($width, $height);
237
        }
238
239
        // remove pre-existing cached-images
240
        $dirPath = $this->pageImageDirPath();
241
        foreach (glob($dirPath . '/*.jpg') as $file) {
242
            unlink($file);
243
        }
244
245
        // convert to .png, create new page image file, overwrites existing
246
        $pageImagePath = $this->pageImageFilePath();
247
        if (!$f3->write($pageImagePath, $img->dump('png', $f3->get('assets.image.default.quality.png')))) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $f3->write($pageImagePat...default.quality.png'))) of type integer|false is loosely compared to false; this is ambiguous if the integer can be zero. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
248
            return false;
249
        }
250
251
        // create asset table entry
252
        $asset = new Assets;
253
254
        // load pre existing asset
255
        $asset->load(['users_uuid = ? AND ' . $this->db->quoteKey('key') . ' = ? AND category = ?', $this->uuid, $this->key, 'page']);
256
257
        // set values
258
        $asset->users_uuid = $this->uuid;
259
        $asset->filename = $pageImagePath;
260
        $asset->name = $this-title;
261
        $asset->description = $this->description;
262
        $asset->size = filesize($pageImagePath);
263
        $asset->url = $this->url($this->pageImageUrl());
0 ignored issues
show
Bug introduced by
The method url() does not seem to exist on object<FFCMS\Mappers\Pages>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
264
        $asset->type = 'image/png';
265
        $asset->key = $this->key;
266
        $asset->groups = 'public';
267
        $asset->category = 'page';
0 ignored issues
show
Documentation introduced by
The property category does not exist on object<FFCMS\Mappers\Assets>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
268
        $asset->tags = 'pages,page';
269
        $asset->metadata = json_encode($metadata, JSON_PRETTY_PRINT);
270
271
        return $asset->save();
272
    }
273
}
274