Application::__async_show_edit()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 22
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 22
rs 9.2
cc 3
eloc 12
nc 3
nop 1
1
<?php
2
namespace samsoncms\app\gallery;
3
4
use samson\activerecord\Field;
5
use samsoncms\api\CMS;
6
use samsoncms\api\Material;
7
use samsoncms\api\MaterialField;
8
use samsonphp\event\Event;
9
use samsoncms\app\gallery\tab\Gallery;
10
use samsonframework\resource\ResourceMap;
11
12
/**
13
 * SamsonCMS application for interacting with material gallery
14
 * @author [email protected]
15
 */
16
class Application extends \samsoncms\Application
17
{
18
    /** Application name */
19
    public $name = 'Галлерея';
20
21
    /** Hide application access from main menu */
22
    public $hide = true;
23
24
    /** @var string Entity class name */
25
    protected $entity = '\samson\activerecord\gallery';
26
27
    /** Identifier */
28
    protected $id = 'gallery';
29
30
    /** @var \samsonphp\fs\FileService File service pointer */
31
    protected $fs;
32
33
    /**
34
     * Initialize module
35
     * @param array $params Collection of parameters
36
     * @return bool True if success
37
     */
38
    public function init(array $params = array())
39
    {
40
        // TODO: Should be change to DI in future
41
        // Set pointer to file service
42
        $this->fs = & $this->system->module('fs');
43
44
        // Subscribe to material form created event for custom tab rendering
45
        Event::subscribe('samsoncms.material.form.created', array($this, 'tabBuilder'));
46
47
        // Subscribe to event - add gallery field additional field type
48
        Event::subscribe('cms_field.select_create', array($this, 'fieldSelectCreate'));
49
50
        return parent::init($params);
51
    }
52
53
    /**
54
     * Render all gallery additional fields as material form tabs
55
     * @param \samsoncms\app\material\form\Form $form Material form insctance
56
     */
57
    public function tabBuilder(\samsoncms\app\material\form\Form & $form)
58
    {
59
        // If we have related structures
60
        if (count($form->navigationIDs)) {
61
            // Get all gallery additional field for material form structures
62
            $galleryFields = $this->query->entity(\samsoncms\api\Field::class)
63
                ->where('Type', 9)
64
                ->join('structurefield')
65
                ->where('structurefield_StructureID', $form->navigationIDs)
66
                ->exec();
67
68
            // Create tab for each additional gallery field
69
            foreach ($galleryFields as $field) {
70
                $form->tabs[] = new Gallery($this, $this->query, $form->entity, $field);
71
            }
72
        }
73
    }
74
75
    /** Field select creation event handler */
76
    public function fieldSelectCreate(&$list)
77
    {
78
        $list[t('Галлерея', true)] = 9;
0 ignored issues
show
Deprecated Code introduced by
The function t() has been deprecated with message: Should be used as $this->system->getContainer()->geti18n()->translate()|plural()

This function has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed from the class and what other function to use instead.

Loading history...
79
    }
80
81
    /**
82
     * Controller for deleting material image from gallery
83
     * @param string $imageId Gallery Image identifier
84
     * @return array Async response array
85
     */
86
    public function __async_delete($imageId, $materialFieldID = null)
0 ignored issues
show
Coding Style introduced by
Method name "Application::__async_delete" is not in camel caps format
Loading history...
87
    {
88
        // Async response
89
        $result = array();
90
91
        /** @var \samson\activerecord\gallery $image */
92
        $image = null;
93
94
        // Find gallery record in DB
95
        if ($this->findAsyncEntityByID($imageId, $image, $result)) {
96
            if ($image->Path != '') {
97
                // Get image path
98
                $imagePath = $this->formImagePath($image->Path, $image->Src);
99
                // Physically remove file from server
100
                if ($this->imageExists($imagePath)) {
101
                    $this->fs->delete($imagePath);
102
                }
103
104
                // Delete thumbnails
105
                if (class_exists('\samson\scale\ScaleController', false)) {
106
                    /** @var \samson\scale\ScaleController $scale */
107
                    $scale = $this->system->module('scale');
108
109
                    foreach (array_keys($scale->thumnails_sizes) as $folder) {
110
                        // Form image path for scale module
111
                        $imageScalePath = $this->formImagePath($image->Path . $folder . '/', $image->Src);
112
                        if ($this->imageExists($imageScalePath)) {
113
                            $this->fs->delete($imageScalePath);
114
                        }
115
                    }
116
                }
117
            }
118
119
            // Remove record from DB
120
            $image->delete();
121
        }
122
123
        return $this->__async_update($materialFieldID);
124
    }
125
126
    /**
127
     * Controller for rendering gallery images list
128
     * @param int $materialFieldId Gallery identifier, represented as materialfield id
129
     * @return array Async response array
130
     */
131
    public function __async_update($materialFieldId)
0 ignored issues
show
Coding Style introduced by
Method name "Application::__async_update" is not in camel caps format
Loading history...
132
    {
133
        return array('status' => true, 'html' => $this->getHTML($materialFieldId));
134
    }
135
136
	/**
137
     * Controller for getting quantity image in gallery.
138
     *
139
     * @param integer $materialFieldId identefier Table MaterialField
140
     * @return array Async response array with additional param count.
141
     */
142
    public function __async_getCount($materialFieldId)
0 ignored issues
show
Coding Style introduced by
Method name "Application::__async_getCount" is not in camel caps format
Loading history...
143
    {
144
        // @var array $result Result of asynchronous controller
145
        $response = array('status' => 1);
146
        // Getting quantity from DB by param materialFieldId
147
        $response['count'] = $this->query
148
            ->entity(CMS::MATERIAL_IMAGES_RELATION_ENTITY)
149
            ->where(MaterialField::F_PRIMARY, $materialFieldId)
150
            ->count();
151
152
        return $response;
153
    }
154
	
155
	/**
156
     *  Controller for update material image properties alt from gallery.
157
     *
158
     *  @param int $imageId Gallery image identifier
159
     *  @return array async response
160
     */
161
    public function __async_updateAlt($imageId)
0 ignored issues
show
Coding Style introduced by
Method name "Application::__async_updateAlt" is not in camel caps format
Loading history...
162
    {
163
        // @var array $result Result of asynchronous controller
164
        $result = array('status' => false);
165
        // @var \samson\activerecord\gallery $image Image to insert into editor
166
        $image = null;
167
        //get data from ajax
168
        $data = json_decode(file_get_contents('php://input'), true);
169
        //set input value
170
        $value = trim($data['value']);
171
172
173
        // Getting first field image
174
        if ($this->query->entity(CMS::MATERIAL_IMAGES_RELATION_ENTITY)
175
            ->where('PhotoID', $imageId)->first($image)) {
0 ignored issues
show
Unused Code introduced by
The call to QueryInterface::first() has too many arguments starting with $image.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
176
            // Update value alt
177
            $image->Description = $value;
178
            // Save result in datebase
179
            $image->save();
180
            // Set success status
181
            $result['status'] = true;
182
            // Reduce number of characters to 25
183
            $result['description'] = utf8_limit_string($value, 25, '...');
184
            // Return result value
185
            $result['value'] = $value;
186
        }
187
188
        return $result;
189
    }
190
	
191
    /**
192
     * Controller for image upload
193
     * @param string $materialFieldId Gallery identifier, represented as materialfield id
194
     * @return array Async response array
195
     */
196
    public function __async_upload($materialFieldId)
0 ignored issues
show
Coding Style introduced by
__async_upload uses the super-global variable $_SERVER which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
Coding Style introduced by
Method name "Application::__async_upload" is not in camel caps format
Loading history...
197
    {
198
        $result = array('status' => false);
199
200
        /** @var \samsonphp\upload\Upload $upload Pointer to uploader object */
201
        $upload = null;
202
        // Verify extension image
203
        if ($this->verifyExtensionFile()) {
204
            // Uploading file to server and path current material identifier
205
            if (uploadFile($upload, array(), $materialFieldId)) {
206
                /** @var \samson\activerecord\materialfield $materialField MaterialField object to identify gallery */
207
                $materialField = null;
208
//            /** @var array $children List of related materials */
209
//            $children = null;
210
                // Check if participant has not uploaded remix yet
211
                if (
212
                $this->query->entity(MaterialField::ENTITY)
213
                    ->where('MaterialFieldID', $materialFieldId)
214
                    ->where('Active', 1)
215
                    ->first($materialField)
0 ignored issues
show
Unused Code introduced by
The call to QueryInterface::first() has too many arguments starting with $materialField.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
216
                ) {
217
                    // Create empty db record
218
                    $photo = new \samson\activerecord\gallery(false);
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a null|object<samsonframew...\orm\DatabaseInterface>.

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...
219
                    $photo->Name = $upload->realName();
220
                    $photo->Src = $upload->name();
221
                    $photo->Path = $upload->path();
222
                    $photo->materialFieldId = $materialField->id;
0 ignored issues
show
Bug introduced by
The property materialFieldId does not seem to exist. Did you mean materialFieldID?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
223
                    $photo->MaterialID = $materialField->MaterialID;
224
                    $photo->size = $upload->size();
225
                    $photo->Active = 1;
0 ignored issues
show
Documentation Bug introduced by
The property $Active was declared of type boolean, but 1 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...
226
                    $photo->save();
227
228
229
                    // Call scale if it is loaded
230
                    if (class_exists('\samson\scale\ScaleController', false)) {
231
                        /** @var \samson\scale\ScaleController $scale */
232
                        $scale = $this->system->module('scale');
233
                        $scale->resize($upload->fullPath(), $upload->name(), $upload->uploadDir);
234
                    }
235
236
                    $result['status'] = true;
237
                }
238
            }
239
        } else {
240
            $errorText = "Файл ( " . urldecode($_SERVER['HTTP_X_FILE_NAME']) . " ) не является картинкой!";
241
            $result = array('status' => false, 'errorText' => $errorText);
242
        }
243
244
        return $result;
245
    }
246
247
    /**
248
     * method for verify extension file
249
     * @return boolean true - file is image, false - file not image
250
     * */
251
    private function verifyExtensionFile()
0 ignored issues
show
Coding Style introduced by
verifyExtensionFile uses the super-global variable $_SERVER which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
252
    {
253
        $supported_image = array(
254
            'gif',
255
            'jpg',
256
            'jpeg',
257
            'png'
258
        );
259
260
        $fileName = $_SERVER['HTTP_X_FILE_NAME'];
261
262
        $ext = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
263
        if (in_array($ext, $supported_image)) {
264
            return true;
265
        }
266
        return false;
267
    }
268
269
    /**
270
     * Function to save image priority
271
     * @return array Async response array
272
     */
273
    public function __async_priority()
0 ignored issues
show
Coding Style introduced by
__async_priority uses the super-global variable $_POST which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
Coding Style introduced by
Method name "Application::__async_priority" is not in camel caps format
Loading history...
274
    {
275
        $result = array('status' => true);
276
277
        // If we have changed priority of images
278
        if (isset($_POST['ids'])) {
279
            // For each received image id
280
            for ($i = 0; $i < count($_POST['ids']); $i++) {
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
281
                /** @var \samson\activerecord\gallery $photo Variable to store image info */
282
                $photo = null;
283
                // If we have such image in database
284
                if ($this->query->entity(CMS::MATERIAL_IMAGES_RELATION_ENTITY)->where('PhotoID', $_POST['ids'][$i])->first($photo)) {
0 ignored issues
show
Unused Code introduced by
The call to QueryInterface::first() has too many arguments starting with $photo.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
285
                    // Reset it's priority and save it
286
                    $photo->priority = $i;
287
                    $photo->save();
288
                } else {
289
                    $result['status'] = false;
290
                    $result['message'] = 'Can not find images with specified ids!';
291
                }
292
            }
293
        } else {
294
            $result['status'] = false;
295
            $result['message'] = 'There are no images to sort!';
296
        }
297
        return $result;
298
    }
299
300
    /**
301
     * Asynchronous function to get image editor
302
     * @param int $imageId Image identifier to insert into editor
303
     * @return array Result array
304
     */
305
    public function __async_show_edit($imageId)
0 ignored issues
show
Coding Style introduced by
Method name "Application::__async_show_edit" is not in camel caps format
Loading history...
306
    {
307
        /** @var array $result Result of asynchronous controller */
308
        $result = array('status' => false);
309
        /** @var \samson\activerecord\gallery $image Image to insert into editor */
310
        $image = null;
311
        if ($this->query->entity(CMS::MATERIAL_IMAGES_RELATION_ENTITY)->where('PhotoID', $imageId)->first($image)) {
0 ignored issues
show
Unused Code introduced by
The call to QueryInterface::first() has too many arguments starting with $image.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
312
313
            /** @var string $path Path to image */
314
            $path = $this->formImagePath($image->Path, $image->Src);
315
316
            // If there is image for this path
317
            if ($this->imageExists($path)) {
318
                $result['status'] = true;
319
                $result['html'] = $this->view('editor/index')
320
                    ->set($image, 'image')
321
                    ->set($path, 'path')
322
                    ->output();
323
            }
324
        }
325
        return $result;
326
    }
327
328
    /**
329
     * Applies all changes with the image and save it
330
     * @param int $imageId Edit image identifier
331
     * @return array
332
     */
333
    public function __async_edit($imageId)
0 ignored issues
show
Coding Style introduced by
Method name "Application::__async_edit" is not in camel caps format
Loading history...
334
    {
335
        /** @var array $result Result of asynchronous controller */
336
        $result = array('status' => false);
337
        /** @var \samson\activerecord\gallery $image Image to insert into editor */
338
        $image = null;
339
        /** @var resource $imageResource Copy of edit image */
340
        $imageResource = null;
341
        /** @var resource $croppedImage Resource of cropped image */
342
        $croppedImage = null;
343
344
        // If there is such image in database
345
        if ($this->query->entity(CMS::MATERIAL_IMAGES_RELATION_ENTITY)->where('PhotoID', $imageId)->first($image)) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
Unused Code introduced by
The call to QueryInterface::first() has too many arguments starting with $image.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
346
347
            // Form proper path
348
            $path = $this->formImagePath($image->Path, $image->Src);
349
350
            // Check image extension
351
            switch (pathinfo($path, PATHINFO_EXTENSION)) {
352
                case 'jpeg':
353
                case 'jpg':
354
                    $imageResource = imagecreatefromjpeg($path);
355
                    $croppedImage = $this->cropImage($imageResource);
0 ignored issues
show
Documentation Bug introduced by
The method cropImage does not exist on object<samsoncms\app\gallery\Application>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
356
                    $result['status'] = imagejpeg($croppedImage, $path);
357
                    break;
358 View Code Duplication
                case 'png':
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...
359
                    $imageResource = imagecreatefrompng($path);
360
                    $croppedImage = $this->cropTransparentImage($imageResource);
0 ignored issues
show
Documentation Bug introduced by
The method cropTransparentImage does not exist on object<samsoncms\app\gallery\Application>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
361
                    $result['status'] = imagepng($croppedImage, $path);
362
                    break;
363 View Code Duplication
                case 'gif':
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...
364
                    $imageResource = imagecreatefromgif($path);
365
                    $croppedImage = $this->cropTransparentImage($imageResource);
0 ignored issues
show
Documentation Bug introduced by
The method cropTransparentImage does not exist on object<samsoncms\app\gallery\Application>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
366
                    $result['status'] = imagegif($croppedImage, $path);
367
                    break;
368
            }
369
370
            // delete temporary images
371
            imagedestroy($croppedImage);
372
            imagedestroy($imageResource);
373
        }
374
        return $result;
375
    }
376
377
    /**
378
     * Render gallery images list
379
     * @param string $materialFieldId Material identifier
380
     * @return string html representation of image list
381
     */
382
    public function getHTML($materialFieldId)
383
    {
384
        // Get all material images
385
        $items_html = '';
386
        /** @var array $images List of gallery images */
387
        $images = null;
388
        // there are gallery images
389
        if ($this->query->entity(CMS::MATERIAL_IMAGES_RELATION_ENTITY)->where('materialFieldId', $materialFieldId)->orderBy('priority')->exec($images)) {
0 ignored issues
show
Unused Code introduced by
The call to QueryInterface::exec() has too many arguments starting with $images.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
390
            /** @var \samson\cms\CMSGallery $image */
391
            foreach ($images as $image) {
392
                // Get image size string
393
                $size = ', ';
394
                // Get image path
395
                $path = $this->formImagePath($image->Path, $image->Src);
396
397
                // if file doesn't exist
398
                if (!$this->imageExists($path)) {
399
                      $path = ResourceMap::find('www/img/no-img.png', $this);
0 ignored issues
show
Documentation introduced by
$this is of type this<samsoncms\app\gallery\Application>, but the function expects a object<samsonframework\resource\ResourceMap>|null.

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...
400
                }
401
402
                // set image size string representation, if it is not 0
403
                $size = ($image->size == 0) ? '' : $size . $this->humanFileSize($image->size);
404
405
                // Render gallery image tumb
406
                $items_html .= $this->view('tumbs/item')
407
                    ->set($image, 'image')
408
                    ->set(utf8_limit_string($image->Description, 25, '...'), 'description')
409
                    ->set(utf8_limit_string($image->Name, 18, '...'), 'name')
410
                    ->set($path, 'imgpath')
411
                    ->set($size, 'size')
412
                    ->set($materialFieldId, 'material_id')
413
                    ->output();
414
            }
415
        }
416
417
        // Render content into inner content html
418
        return $this->view('tumbs/index')
419
            ->set($items_html, 'images')
420
            ->set($materialFieldId, 'material_id')
421
            ->output();
422
    }
423
424
    /**
425
     * Function to form image size
426
     * @param int $bytes Bytes count
427
     * @param int $decimals Decimal part of number(count of numbers)
428
     * @return string Generated image size
429
     */
430
    public function humanFileSize($bytes, $decimals = 2)
431
    {
432
        /** @var string $sizeLetters Size shortcuts */
433
        $sizeLetters = 'BKBMBGBTBPB';
434
        $factor = (int)(floor((strlen($bytes) - 1) / 3));
435
        $sizeLetter = ($factor <= 0) ? substr($sizeLetters, 0, 1) : substr($sizeLetters, $factor * 2 - 1, 2);
436
        return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . $sizeLetter;
437
    }
438
439
    /**
440
     * Checks if image exists, supports old database structure
441
     * @param string $imagePath Path to image(Full or not)
442
     * @param string $imageSrc Image name, if it wasn't in $imagePath
443
     * @return bool
444
     */
445
    private function imageExists($imagePath, $imageSrc = null)
446
    {
447
        // If image name is sewhere parameter
448
        if (isset($imageSrc)) {
449
            // Form path to the image
450
            $imageFullPath = $this->formImagePath($imagePath, $imageSrc);
451
        } else {
452
            // Path was already set
453
            $imageFullPath = $imagePath;
454
        }
455
456
        // Call file service existence method
457
        return $this->fs->exists($imageFullPath);
458
    }
459
460
    /**
461
     * Function to form image path correctly, also supports old database structure
462
     * @param string $imagePath Path to the image
463
     * @param string $imageSrc Image name
464
     * @return string Full path to image
465
     */
466
    private function formImagePath($imagePath, $imageSrc)
467
    {
468
        // Get old-way image path, remove full path to check file
469
        if (empty($imagePath)) {
470
            $path = $imageSrc;
471
        } else { // Use new CORRECT way
472
            $path = $imagePath . $imageSrc;
473
        }
474
475
        // form relative path to the image
476
        $dir = quotemeta(__SAMSON_BASE__);
477
        // TODO: WTF? Why do we need this, need comments!!!
478
        if (strpos($path, 'http://') === false) {
479
            if ($dir == '/') {
480
                return substr($path, 1);
481
            } else {
482
                return preg_replace('/' . addcslashes($dir, '/') . '/', '', $path);
483
            }
484
        }
485
486
        return $path;
487
    }
488
}
489