Passed
Push — master ( 7a0c63...f52afb )
by Aimeos
06:05
created

Standard::scale()   C

Complexity

Conditions 15
Paths 7

Size

Total Lines 132
Code Lines 31

Duplication

Lines 0
Ratio 0 %

Importance

Changes 8
Bugs 0 Features 0
Metric Value
eloc 31
c 8
b 0
f 0
dl 0
loc 132
rs 5.9166
cc 15
nc 7
nop 2

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
/**
4
 * @license LGPLv3, https://opensource.org/licenses/LGPL-3.0
5
 * @copyright Metaways Infosystems GmbH, 2011
6
 * @copyright Aimeos (aimeos.org), 2015-2024
7
 * @package MShop
8
 * @subpackage Media
9
 */
10
11
12
namespace Aimeos\MShop\Media\Manager;
13
14
use \Psr\Http\Message\UploadedFileInterface;
0 ignored issues
show
Bug introduced by
The type \Psr\Http\Message\UploadedFileInterface was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
15
16
17
/**
18
 * Default media manager implementation.
19
 *
20
 * @package MShop
21
 * @subpackage Media
22
 */
23
class Standard
24
	extends Base
25
	implements \Aimeos\MShop\Media\Manager\Iface, \Aimeos\MShop\Common\Manager\Factory\Iface
26
{
27
	/** mshop/media/manager/name
28
	 * Class name of the used media manager implementation
29
	 *
30
	 * Each default manager can be replace by an alternative imlementation.
31
	 * To use this implementation, you have to set the last part of the class
32
	 * name as configuration value so the manager factory knows which class it
33
	 * has to instantiate.
34
	 *
35
	 * For example, if the name of the default class is
36
	 *
37
	 *  \Aimeos\MShop\Media\Manager\Standard
38
	 *
39
	 * and you want to replace it with your own version named
40
	 *
41
	 *  \Aimeos\MShop\Media\Manager\Mymanager
42
	 *
43
	 * then you have to set the this configuration option:
44
	 *
45
	 *  mshop/media/manager/name = Mymanager
46
	 *
47
	 * The value is the last part of your own class name and it's case sensitive,
48
	 * so take care that the configuration value is exactly named like the last
49
	 * part of the class name.
50
	 *
51
	 * The allowed characters of the class name are A-Z, a-z and 0-9. No other
52
	 * characters are possible! You should always start the last part of the class
53
	 * name with an upper case character and continue only with lower case characters
54
	 * or numbers. Avoid chamel case names like "MyManager"!
55
	 *
56
	 * @param string Last part of the class name
57
	 * @since 2014.03
58
	 * @category Developer
59
	 */
60
61
	/** mshop/media/manager/decorators/excludes
62
	 * Excludes decorators added by the "common" option from the media manager
63
	 *
64
	 * Decorators extend the functionality of a class by adding new aspects
65
	 * (e.g. log what is currently done), executing the methods of the underlying
66
	 * class only in certain conditions (e.g. only for logged in users) or
67
	 * modify what is returned to the caller.
68
	 *
69
	 * This option allows you to remove a decorator added via
70
	 * "mshop/common/manager/decorators/default" before they are wrapped
71
	 * around the media manager.
72
	 *
73
	 *  mshop/media/manager/decorators/excludes = array( 'decorator1' )
74
	 *
75
	 * This would remove the decorator named "decorator1" from the list of
76
	 * common decorators ("\Aimeos\MShop\Common\Manager\Decorator\*") added via
77
	 * "mshop/common/manager/decorators/default" for the media manager.
78
	 *
79
	 * @param array List of decorator names
80
	 * @since 2014.03
81
	 * @category Developer
82
	 * @see mshop/common/manager/decorators/default
83
	 * @see mshop/media/manager/decorators/global
84
	 * @see mshop/media/manager/decorators/local
85
	 */
86
87
	/** mshop/media/manager/decorators/global
88
	 * Adds a list of globally available decorators only to the media manager
89
	 *
90
	 * Decorators extend the functionality of a class by adding new aspects
91
	 * (e.g. log what is currently done), executing the methods of the underlying
92
	 * class only in certain conditions (e.g. only for logged in users) or
93
	 * modify what is returned to the caller.
94
	 *
95
	 * This option allows you to wrap global decorators
96
	 * ("\Aimeos\MShop\Common\Manager\Decorator\*") around the media manager.
97
	 *
98
	 *  mshop/media/manager/decorators/global = array( 'decorator1' )
99
	 *
100
	 * This would add the decorator named "decorator1" defined by
101
	 * "\Aimeos\MShop\Common\Manager\Decorator\Decorator1" only to the media
102
	 * manager.
103
	 *
104
	 * @param array List of decorator names
105
	 * @since 2014.03
106
	 * @category Developer
107
	 * @see mshop/common/manager/decorators/default
108
	 * @see mshop/media/manager/decorators/excludes
109
	 * @see mshop/media/manager/decorators/local
110
	 */
111
112
	/** mshop/media/manager/decorators/local
113
	 * Adds a list of local decorators only to the media manager
114
	 *
115
	 * Decorators extend the functionality of a class by adding new aspects
116
	 * (e.g. log what is currently done), executing the methods of the underlying
117
	 * class only in certain conditions (e.g. only for logged in users) or
118
	 * modify what is returned to the caller.
119
	 *
120
	 * This option allows you to wrap local decorators
121
	 * ("\Aimeos\MShop\Media\Manager\Decorator\*") around the media manager.
122
	 *
123
	 *  mshop/media/manager/decorators/local = array( 'decorator2' )
124
	 *
125
	 * This would add the decorator named "decorator2" defined by
126
	 * "\Aimeos\MShop\Media\Manager\Decorator\Decorator2" only to the media
127
	 * manager.
128
	 *
129
	 * @param array List of decorator names
130
	 * @since 2014.03
131
	 * @category Developer
132
	 * @see mshop/common/manager/decorators/default
133
	 * @see mshop/media/manager/decorators/excludes
134
	 * @see mshop/media/manager/decorators/global
135
	 */
136
137
138
	use \Aimeos\MShop\Common\Manager\PropertyRef\Traits;
139
	use \Aimeos\MShop\Common\Manager\ListsRef\Traits;
140
	use \Aimeos\MShop\Upload;
141
	use Preview;
142
143
144
	private array $searchConfig = array(
145
		'media.id' => array(
146
			'label' => 'ID',
147
			'code' => 'media.id',
148
			'internalcode' => 'mmed."id"',
149
			'type' => 'int',
150
		),
151
		'media.siteid' => array(
152
			'label' => 'Site ID',
153
			'code' => 'media.siteid',
154
			'internalcode' => 'mmed."siteid"',
155
			'public' => false,
156
		),
157
		'media.type' => array(
158
			'label' => 'Type',
159
			'code' => 'media.type',
160
			'internalcode' => 'mmed."type"',
161
		),
162
		'media.label' => array(
163
			'label' => 'Label',
164
			'code' => 'media.label',
165
			'internalcode' => 'mmed."label"',
166
		),
167
		'media.domain' => array(
168
			'label' => 'Domain',
169
			'code' => 'media.domain',
170
			'internalcode' => 'mmed."domain"',
171
		),
172
		'media.languageid' => array(
173
			'label' => 'Language code',
174
			'code' => 'media.languageid',
175
			'internalcode' => 'mmed."langid"',
176
		),
177
		'media.mimetype' => array(
178
			'label' => 'Mime type',
179
			'code' => 'media.mimetype',
180
			'internalcode' => 'mmed."mimetype"',
181
		),
182
		'media.url' => array(
183
			'label' => 'URL',
184
			'code' => 'media.url',
185
			'internalcode' => 'mmed."link"',
186
		),
187
		'media.preview' => array(
188
			'label' => 'Preview URLs as JSON encoded string',
189
			'code' => 'media.preview',
190
			'internalcode' => 'mmed."preview"',
191
		),
192
		'media.filesystem' => array(
193
			'label' => 'File sytem name',
194
			'code' => 'media.filesystem',
195
			'internalcode' => 'mmed."fsname"',
196
		),
197
		'media.status' => array(
198
			'label' => 'Status',
199
			'code' => 'media.status',
200
			'internalcode' => 'mmed."status"',
201
			'type' => 'int',
202
		),
203
		'media.ctime' => array(
204
			'code' => 'media.ctime',
205
			'internalcode' => 'mmed."ctime"',
206
			'label' => 'Create date/time',
207
			'type' => 'datetime',
208
			'public' => false,
209
		),
210
		'media.mtime' => array(
211
			'code' => 'media.mtime',
212
			'internalcode' => 'mmed."mtime"',
213
			'label' => 'Modify date/time',
214
			'type' => 'datetime',
215
			'public' => false,
216
		),
217
		'media.editor' => array(
218
			'code' => 'media.editor',
219
			'internalcode' => 'mmed."editor"',
220
			'label' => 'Editor',
221
			'public' => false,
222
		),
223
		'media:has' => array(
224
			'code' => 'media:has()',
225
			'internalcode' => ':site AND :key AND mmedli."id"',
226
			'internaldeps' => ['LEFT JOIN "mshop_media_list" AS mmedli ON ( mmedli."parentid" = mmed."id" )'],
227
			'label' => 'Media has list item, parameter(<domain>[,<list type>[,<reference ID>)]]',
228
			'type' => 'null',
229
			'public' => false,
230
		),
231
		'media:prop' => array(
232
			'code' => 'media:prop()',
233
			'internalcode' => ':site AND :key AND mmedpr."id"',
234
			'internaldeps' => ['LEFT JOIN "mshop_media_property" AS mmedpr ON ( mmedpr."parentid" = mmed."id" )'],
235
			'label' => 'Media has property item, parameter(<property type>[,<language code>[,<property value>]])',
236
			'type' => 'null',
237
			'public' => false,
238
		),
239
	);
240
241
	private ?string $languageId;
242
243
244
	/**
245
	 * Initializes the object.
246
	 *
247
	 * @param \Aimeos\MShop\ContextIface $context Context object
248
	 */
249
	public function __construct( \Aimeos\MShop\ContextIface $context )
250
	{
251
		parent::__construct( $context );
252
253
		/** mshop/media/manager/resource
254
		 * Name of the database connection resource to use
255
		 *
256
		 * You can configure a different database connection for each data domain
257
		 * and if no such connection name exists, the "db" connection will be used.
258
		 * It's also possible to use the same database connection for different
259
		 * data domains by configuring the same connection name using this setting.
260
		 *
261
		 * @param string Database connection name
262
		 * @since 2023.04
263
		 */
264
		$this->setResourceName( $context->config()->get( 'mshop/media/manager/resource', 'db-media' ) );
265
		$this->languageId = $context->locale()->getLanguageId();
266
267
		$level = \Aimeos\MShop\Locale\Manager\Base::SITE_ALL;
268
		$level = $context->config()->get( 'mshop/media/manager/sitemode', $level );
269
270
271
		$this->searchConfig['media:has']['function'] = function( &$source, array $params ) use ( $level ) {
272
273
			$keys = [];
274
275
			foreach( (array) ( $params[1] ?? '' ) as $type ) {
276
				foreach( (array) ( $params[2] ?? '' ) as $id ) {
277
					$keys[] = $params[0] . '|' . ( $type ? $type . '|' : '' ) . $id;
278
				}
279
			}
280
281
			$sitestr = $this->siteString( 'mmedli."siteid"', $level );
282
			$keystr = $this->toExpression( 'mmedli."key"', $keys, ( $params[2] ?? null ) ? '==' : '=~' );
283
			$source = str_replace( [':site', ':key'], [$sitestr, $keystr], $source );
284
285
			return $params;
286
		};
287
288
289
		$this->searchConfig['media:prop']['function'] = function( &$source, array $params ) use ( $level ) {
290
291
			$keys = [];
292
			$langs = array_key_exists( 1, $params ) ? ( $params[1] ?? 'null' ) : '';
293
294
			foreach( (array) $langs as $lang ) {
295
				foreach( (array) ( $params[2] ?? '' ) as $val ) {
296
					$keys[] = substr( $params[0] . '|' . ( $lang === null ? 'null|' : ( $lang ? $lang . '|' : '' ) ) . $val, 0, 255 );
297
				}
298
			}
299
300
			$sitestr = $this->siteString( 'mmedpr."siteid"', $level );
301
			$keystr = $this->toExpression( 'mmedpr."key"', $keys, ( $params[2] ?? null ) ? '==' : '=~' );
302
			$source = str_replace( [':site', ':key'], [$sitestr, $keystr], $source );
303
304
			return $params;
305
		};
306
	}
307
308
309
	/**
310
	 * Removes old entries from the storage.
311
	 *
312
	 * @param iterable $siteids List of IDs for sites whose entries should be deleted
313
	 * @return \Aimeos\MShop\Media\Manager\Iface Manager object for chaining method calls
314
	 */
315
	public function clear( iterable $siteids ) : \Aimeos\MShop\Common\Manager\Iface
316
	{
317
		$path = 'mshop/media/manager/submanagers';
318
		$default = ['lists', 'property', 'type'];
319
320
		foreach( $this->context()->config()->get( $path, $default ) as $domain ) {
321
			$this->object()->getSubManager( $domain )->clear( $siteids );
322
		}
323
324
		return $this->clearBase( $siteids, 'mshop/media/manager/delete' );
325
	}
326
327
328
	/**
329
	 * Copies the media item and the referenced files
330
	 *
331
	 * @param \Aimeos\MShop\Media\Item\Iface $item Media item whose files should be copied
332
	 * @return \Aimeos\MShop\Media\Item\Iface Copied media item with new files
333
	 */
334
	public function copy( \Aimeos\MShop\Media\Item\Iface $item ) : \Aimeos\MShop\Media\Item\Iface
335
	{
336
		$item = ( clone $item )->setId( null );
337
338
		$path = $item->getUrl();
339
		$mime = $item->getMimeType();
340
		$domain = $item->getDomain();
341
		$previews = $item->getPreviews();
342
		$fsname = $item->getFileSystem();
343
		$fs = $this->context()->fs( $fsname );
344
345
		if( $fs->has( $path ) )
346
		{
347
			$newPath = $this->path( substr( basename( $path ), 9 ), $mime, $domain );
348
			$fs->copy( $path, $newPath );
349
			$item->setUrl( $newPath );
350
		}
351
352
		if( empty( $previews ) ) {
353
			return $this->scale( $item, true );
354
		}
355
356
		foreach( $previews as $size => $preview )
357
		{
358
			if( $fsname !== 'fs-mimeicon' && $fs->has( $preview ) )
359
			{
360
				$newPath = $this->path( substr( basename( $preview ), 9 ), $mime, $domain );
361
				$fs->copy( $preview, $newPath );
362
				$previews[$size] = $newPath;
363
			}
364
		}
365
366
		return $item->setPreviews( $previews );
367
	}
368
369
370
	/**
371
	 * Creates a new empty item instance
372
	 *
373
	 * @param array $values Values the item should be initialized with
374
	 * @return \Aimeos\MShop\Media\Item\Iface New media item object
375
	 */
376
	public function create( array $values = [] ) : \Aimeos\MShop\Common\Item\Iface
377
	{
378
		$values['media.siteid'] = $values['media.siteid'] ?? $this->context()->locale()->getSiteId();
379
		return $this->createItemBase( $values );
380
	}
381
382
383
	/**
384
	 * Removes multiple items.
385
	 *
386
	 * @param \Aimeos\MShop\Common\Item\Iface[]|string[] $items List of item objects or IDs of the items
387
	 * @return \Aimeos\MShop\Media\Manager\Iface Manager object for chaining method calls
388
	 */
389
	public function delete( $items ) : \Aimeos\MShop\Common\Manager\Iface
390
	{
391
		/** mshop/media/manager/delete/mysql
392
		 * Deletes the items matched by the given IDs from the database
393
		 *
394
		 * @see mshop/media/manager/delete/ansi
395
		 */
396
397
		/** mshop/media/manager/delete/ansi
398
		 * Deletes the items matched by the given IDs from the database
399
		 *
400
		 * Removes the records specified by the given IDs from the media database.
401
		 * The records must be from the site that is configured via the
402
		 * context item.
403
		 *
404
		 * The ":cond" placeholder is replaced by the name of the ID column and
405
		 * the given ID or list of IDs while the site ID is bound to the question
406
		 * mark.
407
		 *
408
		 * The SQL statement should conform to the ANSI standard to be
409
		 * compatible with most relational database systems. This also
410
		 * includes using double quotes for table and column names.
411
		 *
412
		 * @param string SQL statement for deleting items
413
		 * @since 2014.03
414
		 * @category Developer
415
		 * @see mshop/media/manager/insert/ansi
416
		 * @see mshop/media/manager/update/ansi
417
		 * @see mshop/media/manager/newid/ansi
418
		 * @see mshop/media/manager/search/ansi
419
		 * @see mshop/media/manager/count/ansi
420
		 */
421
		$cfgpath = 'mshop/media/manager/delete';
422
423
		foreach( map( $items ) as $item )
424
		{
425
			if( $item instanceof \Aimeos\MShop\Media\Item\Iface && $item->getFileSystem() === 'fs-media' )
426
			{
427
				$this->deletePreviews( $item, $item->getPreviews() );
428
				$this->deleteFile( $item->getUrl(), 'fs-media' );
429
			}
430
		}
431
432
		return $this->deleteItemsBase( $items, $cfgpath )->deleteRefItems( $items );
433
	}
434
435
436
	/**
437
	 * Creates a filter object.
438
	 *
439
	 * @param bool|null $default Add default criteria or NULL for relaxed default criteria
440
	 * @param bool $site TRUE for adding site criteria to limit items by the site of related items
441
	 * @return \Aimeos\Base\Criteria\Iface Returns the filter object
442
	 */
443
	public function filter( ?bool $default = false, bool $site = false ) : \Aimeos\Base\Criteria\Iface
444
	{
445
		if( $default !== false )
446
		{
447
			$object = $this->filterBase( 'media', $default );
448
			$langid = $this->context()->locale()->getLanguageId();
449
450
			if( $langid !== null )
451
			{
452
				$temp = array(
453
					$object->compare( '==', 'media.languageid', $langid ),
454
					$object->compare( '==', 'media.languageid', null ),
455
				);
456
457
				$expr = array(
458
					$object->getConditions(),
459
					$object->or( $temp ),
460
				);
461
462
				$object->setConditions( $object->and( $expr ) );
463
			}
464
465
			return $object;
466
		}
467
468
		return parent::filter();
469
	}
470
471
472
	/**
473
	 * Returns an item for the given ID.
474
	 *
475
	 * @param string $id ID of the item that should be retrieved
476
	 * @param string[] $ref List of domains to fetch list items and referenced items for
477
	 * @param bool|null $default Add default criteria or NULL for relaxed default criteria
478
	 * @return \Aimeos\MShop\Media\Item\Iface Returns the media item of the given id
479
	 * @throws \Aimeos\MShop\Exception If item couldn't be found
480
	 */
481
	public function get( string $id, array $ref = [], ?bool $default = false ) : \Aimeos\MShop\Common\Item\Iface
482
	{
483
		return $this->getItemBase( 'media.id', $id, $ref, $default );
484
	}
485
486
487
	/**
488
	 * Returns the available manager types
489
	 *
490
	 * @param bool $withsub Return also the resource type of sub-managers if true
491
	 * @return string[] Type of the manager and submanagers, subtypes are separated by slashes
492
	 */
493
	public function getResourceType( bool $withsub = true ) : array
494
	{
495
		$path = 'mshop/media/manager/submanagers';
496
		$default = ['lists', 'property'];
497
498
		return $this->getResourceTypeBase( 'media', $path, $default, $withsub );
499
	}
500
501
502
	/**
503
	 * Returns the attributes that can be used for searching.
504
	 *
505
	 * @param bool $withsub Return also attributes of sub-managers if true
506
	 * @return \Aimeos\Base\Criteria\Attribute\Iface[] List of search attribute items
507
	 */
508
	public function getSearchAttributes( bool $withsub = true ) : array
509
	{
510
		/** mshop/media/manager/submanagers
511
		 * List of manager names that can be instantiated by the media manager
512
		 *
513
		 * Managers provide a generic interface to the underlying storage.
514
		 * Each manager has or can have sub-managers caring about particular
515
		 * aspects. Each of these sub-managers can be instantiated by its
516
		 * parent manager using the getSubManager() method.
517
		 *
518
		 * The search keys from sub-managers can be normally used in the
519
		 * manager as well. It allows you to search for items of the manager
520
		 * using the search keys of the sub-managers to further limit the
521
		 * retrieved list of items.
522
		 *
523
		 * @param array List of sub-manager names
524
		 * @since 2014.03
525
		 * @category Developer
526
		 */
527
		$path = 'mshop/media/manager/submanagers';
528
529
		return $this->getSearchAttributesBase( $this->searchConfig, $path, [], $withsub );
530
	}
531
532
533
	/**
534
	 * Returns a new manager for media extensions
535
	 *
536
	 * @param string $manager Name of the sub manager type in lower case
537
	 * @param string|null $name Name of the implementation, will be from configuration (or Default) if null
538
	 * @return \Aimeos\MShop\Common\Manager\Iface Manager for different extensions, e.g stock, tags, locations, etc.
539
	 */
540
	public function getSubManager( string $manager, string $name = null ) : \Aimeos\MShop\Common\Manager\Iface
541
	{
542
		return $this->getSubManagerBase( 'media', $manager, $name );
543
	}
544
545
546
	/**
547
	 * Adds a new item to the storage or updates an existing one.
548
	 *
549
	 * @param \Aimeos\MShop\Media\Item\Iface $item New item that should be saved to the storage
550
	 * @param bool $fetch True if the new ID should be returned in the item
551
	 * @return \Aimeos\MShop\Media\Item\Iface $item Updated item including the generated ID
552
	 */
553
	protected function saveItem( \Aimeos\MShop\Media\Item\Iface $item, bool $fetch = true ) : \Aimeos\MShop\Media\Item\Iface
554
	{
555
		if( !$item->isModified() )
556
		{
557
			$item = $this->savePropertyItems( $item, 'media', $fetch );
558
			return $this->saveListItems( $item, 'media', $fetch );
559
		}
560
561
		$context = $this->context();
562
		$conn = $context->db( $this->getResourceName() );
563
564
		$id = $item->getId();
565
		$columns = $this->object()->getSaveAttributes();
566
567
		if( $id === null )
568
		{
569
			/** mshop/media/manager/insert/mysql
570
			 * Inserts a new media record into the database table
571
			 *
572
			 * @see mshop/media/manager/insert/ansi
573
			 */
574
575
			/** mshop/media/manager/insert/ansi
576
			 * Inserts a new media record into the database table
577
			 *
578
			 * Items with no ID yet (i.e. the ID is NULL) will be created in
579
			 * the database and the newly created ID retrieved afterwards
580
			 * using the "newid" SQL statement.
581
			 *
582
			 * The SQL statement must be a string suitable for being used as
583
			 * prepared statement. It must include question marks for binding
584
			 * the values from the media item to the statement before they are
585
			 * sent to the database server. The number of question marks must
586
			 * be the same as the number of columns listed in the INSERT
587
			 * statement. The order of the columns must correspond to the
588
			 * order in the save() method, so the correct values are
589
			 * bound to the columns.
590
			 *
591
			 * The SQL statement should conform to the ANSI standard to be
592
			 * compatible with most relational database systems. This also
593
			 * includes using double quotes for table and column names.
594
			 *
595
			 * @param string SQL statement for inserting records
596
			 * @since 2014.03
597
			 * @category Developer
598
			 * @see mshop/media/manager/update/ansi
599
			 * @see mshop/media/manager/newid/ansi
600
			 * @see mshop/media/manager/delete/ansi
601
			 * @see mshop/media/manager/search/ansi
602
			 * @see mshop/media/manager/count/ansi
603
			 */
604
			$path = 'mshop/media/manager/insert';
605
			$sql = $this->addSqlColumns( array_keys( $columns ), $this->getSqlConfig( $path ) );
0 ignored issues
show
Bug introduced by
It seems like $this->getSqlConfig($path) can also be of type array; however, parameter $sql of Aimeos\MShop\Common\Manager\Base::addSqlColumns() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

605
			$sql = $this->addSqlColumns( array_keys( $columns ), /** @scrutinizer ignore-type */ $this->getSqlConfig( $path ) );
Loading history...
606
		}
607
		else
608
		{
609
			/** mshop/media/manager/update/mysql
610
			 * Updates an existing media record in the database
611
			 *
612
			 * @see mshop/media/manager/update/ansi
613
			 */
614
615
			/** mshop/media/manager/update/ansi
616
			 * Updates an existing media record in the database
617
			 *
618
			 * Items which already have an ID (i.e. the ID is not NULL) will
619
			 * be updated in the database.
620
			 *
621
			 * The SQL statement must be a string suitable for being used as
622
			 * prepared statement. It must include question marks for binding
623
			 * the values from the media item to the statement before they are
624
			 * sent to the database server. The order of the columns must
625
			 * correspond to the order in the save() method, so the
626
			 * correct values are bound to the columns.
627
			 *
628
			 * The SQL statement should conform to the ANSI standard to be
629
			 * compatible with most relational database systems. This also
630
			 * includes using double quotes for table and column names.
631
			 *
632
			 * @param string SQL statement for updating records
633
			 * @since 2014.03
634
			 * @category Developer
635
			 * @see mshop/media/manager/insert/ansi
636
			 * @see mshop/media/manager/newid/ansi
637
			 * @see mshop/media/manager/delete/ansi
638
			 * @see mshop/media/manager/search/ansi
639
			 * @see mshop/media/manager/count/ansi
640
			 */
641
			$path = 'mshop/media/manager/update';
642
			$sql = $this->addSqlColumns( array_keys( $columns ), $this->getSqlConfig( $path ), false );
643
		}
644
645
		$idx = 1;
646
		$stmt = $this->getCachedStatement( $conn, $path, $sql );
647
648
		foreach( $columns as $name => $entry ) {
649
			$stmt->bind( $idx++, $item->get( $name ), \Aimeos\Base\Criteria\SQL::type( $entry->getType() ) );
650
		}
651
652
		$stmt->bind( $idx++, $item->getLanguageId() );
653
		$stmt->bind( $idx++, $item->getType() );
654
		$stmt->bind( $idx++, $item->getLabel() );
655
		$stmt->bind( $idx++, $item->getMimeType() );
656
		$stmt->bind( $idx++, $item->getUrl() );
657
		$stmt->bind( $idx++, $item->getStatus(), \Aimeos\Base\DB\Statement\Base::PARAM_INT );
658
		$stmt->bind( $idx++, $item->getFileSystem() );
659
		$stmt->bind( $idx++, $item->getDomain() );
660
		$stmt->bind( $idx++, json_encode( $item->getPreviews(), JSON_FORCE_OBJECT ) );
661
		$stmt->bind( $idx++, $context->datetime() ); // mtime
662
		$stmt->bind( $idx++, $context->editor() );
663
664
		if( $id !== null ) {
665
			$stmt->bind( $idx++, $context->locale()->getSiteId() . '%' );
666
			$stmt->bind( $idx++, $id, \Aimeos\Base\DB\Statement\Base::PARAM_INT );
667
		} else {
668
			$stmt->bind( $idx++, $this->siteId( $item->getSiteId(), \Aimeos\MShop\Locale\Manager\Base::SITE_SUBTREE ) );
669
			$stmt->bind( $idx++, $context->datetime() ); // ctime
670
		}
671
672
		$stmt->execute()->finish();
673
674
		if( $id === null )
675
		{
676
			/** mshop/media/manager/newid/mysql
677
			 * Retrieves the ID generated by the database when inserting a new record
678
			 *
679
			 * @see mshop/media/manager/newid/ansi
680
			 */
681
682
			/** mshop/media/manager/newid/ansi
683
			 * Retrieves the ID generated by the database when inserting a new record
684
			 *
685
			 * As soon as a new record is inserted into the database table,
686
			 * the database server generates a new and unique identifier for
687
			 * that record. This ID can be used for retrieving, updating and
688
			 * deleting that specific record from the table again.
689
			 *
690
			 * For MySQL:
691
			 *  SELECT LAST_INSERT_ID()
692
			 * For PostgreSQL:
693
			 *  SELECT currval('seq_mmed_id')
694
			 * For SQL Server:
695
			 *  SELECT SCOPE_IDENTITY()
696
			 * For Oracle:
697
			 *  SELECT "seq_mmed_id".CURRVAL FROM DUAL
698
			 *
699
			 * There's no way to retrive the new ID by a SQL statements that
700
			 * fits for most database servers as they implement their own
701
			 * specific way.
702
			 *
703
			 * @param string SQL statement for retrieving the last inserted record ID
704
			 * @since 2014.03
705
			 * @category Developer
706
			 * @see mshop/media/manager/insert/ansi
707
			 * @see mshop/media/manager/update/ansi
708
			 * @see mshop/media/manager/delete/ansi
709
			 * @see mshop/media/manager/search/ansi
710
			 * @see mshop/media/manager/count/ansi
711
			 */
712
			$path = 'mshop/media/manager/newid';
713
			$id = $this->newId( $conn, $path );
714
		}
715
716
		$item->setId( $id );
717
718
		$item = $this->savePropertyItems( $item, 'media', $fetch );
719
		return $this->saveListItems( $item, 'media', $fetch );
720
	}
721
722
723
	/**
724
	 * Rescales the original file to preview files referenced by the media item
725
	 *
726
	 * The height/width configuration for scaling
727
	 * - mshop/media/<files|preview>/maxheight
728
	 * - mshop/media/<files|preview>/maxwidth
729
	 * - mshop/media/<files|preview>/force-size
730
	 *
731
	 * @param \Aimeos\MShop\Media\Item\Iface $item Media item whose files should be scaled
732
	 * @param bool $force True to enforce creating new preview images
733
	 * @return \Aimeos\MShop\Media\Item\Iface Rescaled media item
734
	 */
735
	public function scale( \Aimeos\MShop\Media\Item\Iface $item, bool $force = false ) : \Aimeos\MShop\Media\Item\Iface
736
	{
737
		$mime = $item->getMimeType();
738
739
		if( empty( $url = $item->getUrl() )
740
			|| $item->getFileSystem() === 'fs-mimeicon'
741
			|| strncmp( 'data:', $url, 5 ) === 0
742
			|| strncmp( 'image/svg', $mime, 9 ) === 0
743
			|| strncmp( 'image/', $mime, 6 ) !== 0
744
		) {
745
			return $item;
746
		}
747
748
		$fs = $this->context()->fs( $item->getFileSystem() );
749
		$is = ( $fs instanceof \Aimeos\Base\Filesystem\MetaIface ? true : false );
750
751
		if( !$force
752
			&& !empty( $item->getPreviews() )
753
			&& preg_match( '#^[a-zA-Z]{2,6}://#', $url ) !== 1
754
			&& ( $is && date( 'Y-m-d H:i:s', $fs->time( $url ) ) < $item->getTimeModified() || $fs->has( $url ) )
755
		) {
756
			return $item;
757
		}
758
759
		$domain = $item->getDomain() ?: '-';
760
		$config = $this->context()->config();
761
762
		/** mshop/media/manager/previews/common
763
		 * Scaling options for preview images
764
		 *
765
		 * For responsive images, several preview images of different sizes are
766
		 * generated. This setting controls how many preview images are generated,
767
		 * what's their maximum width and height and if the given width/height is
768
		 * enforced by cropping images that doesn't fit.
769
		 *
770
		 * The setting must consist of a list image size definitions like:
771
		 *
772
		 *  [
773
		 *    ['maxwidth' => 240, 'maxheight' => 320, 'force-size' => 2],
774
		 *    ['maxwidth' => 720, 'maxheight' => 960, 'force-size' => 1],
775
		 *    ['maxwidth' => 2160, 'maxheight' => 2880, 'force-size' => 0],
776
		 *  ]
777
		 *
778
		 * "maxwidth" sets the maximum allowed width of the image whereas
779
		 * "maxheight" does the same for the maximum allowed height. If both
780
		 * values are given, the image is scaled proportionally so it fits into
781
		 * the box defined by both values.
782
		 *
783
		 * In case the image has different proportions than the specified ones
784
		 * and "force-size" is "0", the image is resized to fit entirely into
785
		 * the specified box. One side of the image will be shorter than it
786
		 * would be possible by the specified box.
787
		 *
788
		 * If "force-size" is "1", scaled images that doesn't fit into the
789
		 * given maximum width/height are centered and then filled with the
790
		 * background color.
791
		 *
792
		 * The value of "2" will center the image while the given maxwidth and
793
		 * maxheight are fully covered and crop the parts of the image which
794
		 * are outside the box created by maxwidth and maxheight.
795
		 *
796
		 * By default, images aren't padded or cropped, only scaled.
797
		 *
798
		 * The values for "maxwidth" and "maxheight" can also be null or not
799
		 * used. In that case, the width or height or both is unbound. If none
800
		 * of the values are given, the image won't be scaled at all. If only
801
		 * one value is set, the image will be scaled exactly to the given width
802
		 * or height and the other side is scaled proportionally.
803
		 *
804
		 * You can also define different preview sizes for different domains (e.g.
805
		 * for catalog images) and for different types (e.g. catalog stage images).
806
		 * Use configuration settings like
807
		 *
808
		 *  mshop/media/manager/previews/previews/<domain>/
809
		 *  mshop/media/manager/previews/previews/<domain>/<type>/
810
		 *
811
		 * for example:
812
		 *
813
		 *  mshop/media/manager/previews/catalog/previews => [
814
		 *    ['maxwidth' => 240, 'maxheight' => 320, 'force-size' => true],
815
		 *  ]
816
		 *  mshop/media/manager/previews/catalog/previews => [
817
		 *    ['maxwidth' => 400, 'maxheight' => 300, 'force-size' => false]
818
		 *  ]
819
		 *  mshop/media/manager/previews/catalog/stage/previews => [
820
		 *    ['maxwidth' => 360, 'maxheight' => 320, 'force-size' => true],
821
		 *    ['maxwidth' => 720, 'maxheight' => 480, 'force-size' => true]
822
		 *  ]
823
		 *
824
		 * These settings will create two preview images for catalog stage images,
825
		 * one with a different size for all other catalog images and all images
826
		 * from other domains will be sized to 240x320px. The available domains
827
		 * which can have images are:
828
		 *
829
		 * * attribute
830
		 * * catalog
831
		 * * product
832
		 * * service
833
		 * * supplier
834
		 *
835
		 * There are a few image types included per domain ("default" is always
836
		 * available). You can also add your own types in the admin backend and
837
		 * extend the frontend to display them where you need them.
838
		 *
839
		 * @param array List of image size definitions
840
		 * @category Developer
841
		 * @category User
842
		 * @since 2019.07
843
		 */
844
		$sizes = $config->get( 'mshop/media/manager/previews/common', [] );
845
		$sizes = $config->get( 'mshop/media/manager/previews/' . $domain, $sizes );
846
		$sizes = $config->get( 'mshop/media/manager/previews/' . $domain . '/' . $item->getType(), $sizes );
847
848
		$image = $this->image( $url );
849
		$quality = $this->quality();
850
		$old = $item->getPreviews();
851
		$previews = [];
852
853
		foreach( $this->createPreviews( $image, $sizes ) as $width => $image )
854
		{
855
			$path = $old[$width] ?? $this->path( $url, 'image/webp', $domain );
856
			$fs->write( $path, (string) $image->toWebp( $quality ) );
857
858
			$previews[$width] = $path;
859
			unset( $old[$width] );
860
		}
861
862
		$item = $this->deletePreviews( $item, $old )->setPreviews( $previews );
863
864
		$this->call( 'scaled', $item, $image );
865
866
		return $item;
867
	}
868
869
870
	/**
871
	 * Returns the item objects matched by the given search criteria.
872
	 *
873
	 * @param \Aimeos\Base\Criteria\Iface $search Search criteria object
874
	 * @param string[] $ref List of domains to fetch list items and referenced items for
875
	 * @param int|null &$total Number of items that are available in total
876
	 * @return \Aimeos\Map List of items implementing \Aimeos\MShop\Media\Item\Iface with ids as keys
877
	 */
878
	public function search( \Aimeos\Base\Criteria\Iface $search, array $ref = [], int &$total = null ) : \Aimeos\Map
879
	{
880
		$map = [];
881
		$context = $this->context();
882
		$conn = $context->db( $this->getResourceName() );
883
884
		$required = array( 'media' );
885
886
		/** mshop/media/manager/sitemode
887
		 * Mode how items from levels below or above in the site tree are handled
888
		 *
889
		 * By default, only items from the current site are fetched from the
890
		 * storage. If the ai-sites extension is installed, you can create a
891
		 * tree of sites. Then, this setting allows you to define for the
892
		 * whole media domain if items from parent sites are inherited,
893
		 * sites from child sites are aggregated or both.
894
		 *
895
		 * Available constants for the site mode are:
896
		 * * 0 = only items from the current site
897
		 * * 1 = inherit items from parent sites
898
		 * * 2 = aggregate items from child sites
899
		 * * 3 = inherit and aggregate items at the same time
900
		 *
901
		 * You also need to set the mode in the locale manager
902
		 * (mshop/locale/manager/sitelevel) to one of the constants.
903
		 * If you set it to the same value, it will work as described but you
904
		 * can also use different modes. For example, if inheritance and
905
		 * aggregation is configured the locale manager but only inheritance
906
		 * in the domain manager because aggregating items makes no sense in
907
		 * this domain, then items wil be only inherited. Thus, you have full
908
		 * control over inheritance and aggregation in each domain.
909
		 *
910
		 * @param int Constant from Aimeos\MShop\Locale\Manager\Base class
911
		 * @category Developer
912
		 * @since 2018.01
913
		 * @see mshop/locale/manager/sitelevel
914
		 */
915
		$level = \Aimeos\MShop\Locale\Manager\Base::SITE_ALL;
916
		$level = $context->config()->get( 'mshop/media/manager/sitemode', $level );
917
918
		/** mshop/media/manager/search/mysql
919
		 * Retrieves the records matched by the given criteria in the database
920
		 *
921
		 * @see mshop/media/manager/search/ansi
922
		 */
923
924
		/** mshop/media/manager/search/ansi
925
		 * Retrieves the records matched by the given criteria in the database
926
		 *
927
		 * Fetches the records matched by the given criteria from the media
928
		 * database. The records must be from one of the sites that are
929
		 * configured via the context item. If the current site is part of
930
		 * a tree of sites, the SELECT statement can retrieve all records
931
		 * from the current site and the complete sub-tree of sites.
932
		 *
933
		 * As the records can normally be limited by criteria from sub-managers,
934
		 * their tables must be joined in the SQL context. This is done by
935
		 * using the "internaldeps" property from the definition of the ID
936
		 * column of the sub-managers. These internal dependencies specify
937
		 * the JOIN between the tables and the used columns for joining. The
938
		 * ":joins" placeholder is then replaced by the JOIN strings from
939
		 * the sub-managers.
940
		 *
941
		 * To limit the records matched, conditions can be added to the given
942
		 * criteria object. It can contain comparisons like column names that
943
		 * must match specific values which can be combined by AND, OR or NOT
944
		 * operators. The resulting string of SQL conditions replaces the
945
		 * ":cond" placeholder before the statement is sent to the database
946
		 * server.
947
		 *
948
		 * If the records that are retrieved should be ordered by one or more
949
		 * columns, the generated string of column / sort direction pairs
950
		 * replaces the ":order" placeholder. Columns of
951
		 * sub-managers can also be used for ordering the result set but then
952
		 * no index can be used.
953
		 *
954
		 * The number of returned records can be limited and can start at any
955
		 * number between the begining and the end of the result set. For that
956
		 * the ":size" and ":start" placeholders are replaced by the
957
		 * corresponding values from the criteria object. The default values
958
		 * are 0 for the start and 100 for the size value.
959
		 *
960
		 * The SQL statement should conform to the ANSI standard to be
961
		 * compatible with most relational database systems. This also
962
		 * includes using double quotes for table and column names.
963
		 *
964
		 * @param string SQL statement for searching items
965
		 * @since 2014.03
966
		 * @category Developer
967
		 * @see mshop/media/manager/insert/ansi
968
		 * @see mshop/media/manager/update/ansi
969
		 * @see mshop/media/manager/newid/ansi
970
		 * @see mshop/media/manager/delete/ansi
971
		 * @see mshop/media/manager/count/ansi
972
		 */
973
		$cfgPathSearch = 'mshop/media/manager/search';
974
975
		/** mshop/media/manager/count/mysql
976
		 * Counts the number of records matched by the given criteria in the database
977
		 *
978
		 * @see mshop/media/manager/count/ansi
979
		 */
980
981
		/** mshop/media/manager/count/ansi
982
		 * Counts the number of records matched by the given criteria in the database
983
		 *
984
		 * Counts all records matched by the given criteria from the media
985
		 * database. The records must be from one of the sites that are
986
		 * configured via the context item. If the current site is part of
987
		 * a tree of sites, the statement can count all records from the
988
		 * current site and the complete sub-tree of sites.
989
		 *
990
		 * As the records can normally be limited by criteria from sub-managers,
991
		 * their tables must be joined in the SQL context. This is done by
992
		 * using the "internaldeps" property from the definition of the ID
993
		 * column of the sub-managers. These internal dependencies specify
994
		 * the JOIN between the tables and the used columns for joining. The
995
		 * ":joins" placeholder is then replaced by the JOIN strings from
996
		 * the sub-managers.
997
		 *
998
		 * To limit the records matched, conditions can be added to the given
999
		 * criteria object. It can contain comparisons like column names that
1000
		 * must match specific values which can be combined by AND, OR or NOT
1001
		 * operators. The resulting string of SQL conditions replaces the
1002
		 * ":cond" placeholder before the statement is sent to the database
1003
		 * server.
1004
		 *
1005
		 * Both, the strings for ":joins" and for ":cond" are the same as for
1006
		 * the "search" SQL statement.
1007
		 *
1008
		 * Contrary to the "search" statement, it doesn't return any records
1009
		 * but instead the number of records that have been found. As counting
1010
		 * thousands of records can be a long running task, the maximum number
1011
		 * of counted records is limited for performance reasons.
1012
		 *
1013
		 * The SQL statement should conform to the ANSI standard to be
1014
		 * compatible with most relational database systems. This also
1015
		 * includes using double quotes for table and column names.
1016
		 *
1017
		 * @param string SQL statement for counting items
1018
		 * @since 2014.03
1019
		 * @category Developer
1020
		 * @see mshop/media/manager/insert/ansi
1021
		 * @see mshop/media/manager/update/ansi
1022
		 * @see mshop/media/manager/newid/ansi
1023
		 * @see mshop/media/manager/delete/ansi
1024
		 * @see mshop/media/manager/search/ansi
1025
		 */
1026
		$cfgPathCount = 'mshop/media/manager/count';
1027
1028
		$results = $this->searchItemsBase( $conn, $search, $cfgPathSearch, $cfgPathCount, $required, $total, $level );
1029
1030
		while( $row = $results->fetch() )
1031
		{
1032
			if( ( $row['media.preview'] = json_decode( $row['media.preview'], true ) ) === null ) {
1033
				$row['media.preview'] = [];
1034
			}
1035
1036
			$map[$row['media.id']] = $row;
1037
		}
1038
1039
		$propItems = []; $name = 'media/property';
1040
		if( isset( $ref[$name] ) || in_array( $name, $ref, true ) )
1041
		{
1042
			$propTypes = isset( $ref[$name] ) && is_array( $ref[$name] ) ? $ref[$name] : null;
1043
			$propItems = $this->getPropertyItems( array_keys( $map ), 'media', $propTypes );
1044
		}
1045
1046
		return $this->buildItems( $map, $ref, 'media', $propItems );
1047
	}
1048
1049
1050
	/**
1051
	 * Stores the uploaded file and returns the updated item
1052
	 *
1053
	 * @param \Aimeos\MShop\Media\Item\Iface $item Media item for storing the file meta data, "domain" must be set
1054
	 * @param \Psr\Http\Message\UploadedFileInterface|null $file Uploaded file object
1055
	 * @param \Psr\Http\Message\UploadedFileInterface|null $preview Uploaded preview image
1056
	 * @return \Aimeos\MShop\Media\Item\Iface Updated media item including file and preview paths
1057
	 */
1058
	public function upload( \Aimeos\MShop\Media\Item\Iface $item, ?UploadedFileInterface $file, UploadedFileInterface $preview = null ) : \Aimeos\MShop\Media\Item\Iface
1059
	{
1060
		$domain = $item->getDomain() ?: '-';
1061
		$fsname = $item->getFileSystem() ?: 'fs-media';
1062
		$fs = $this->context()->fs( $fsname );
1063
1064
		if( $file && $file->getError() !== UPLOAD_ERR_NO_FILE && $this->isAllowed( $mime = $this->mimetype( $file ) ) )
1065
		{
1066
			try
1067
			{
1068
				$oldpath = $item->getUrl();
1069
1070
				$path = $this->path( $file->getClientFilename(), $mime, $domain );
1071
				$fs->write( $path, $this->sanitize( $file->getStream()->getContents(), $mime ) );
1072
1073
				$item->setLabel( $file->getClientFilename() )
1074
					->setMimetype( $mime )
1075
					->setUrl( $path );
1076
1077
				if( !$preview ) {
1078
					$this->scale( $item, true );
1079
				}
1080
1081
				if( !empty( $oldpath ) && $fs->has( $oldpath ) ) {
1082
					$fs->rm( $oldpath );
1083
				}
1084
			}
1085
			catch( \Exception $e )
1086
			{
1087
				if( !empty( $path ) && $fs->has( $path ) ) {
1088
					$fs->rm( $path );
1089
				}
1090
1091
				throw $e;
1092
			}
1093
		}
1094
1095
		if( $preview && $preview->getError() !== UPLOAD_ERR_NO_FILE && $this->isAllowed( $mime = $this->mimetype( $preview ) ) )
1096
		{
1097
			$path = $this->path( $preview->getClientFilename(), $mime, $domain );
1098
			$fs->write( $path, $this->sanitize( $preview->getStream()->getContents(), $mime ) );
1099
1100
			$item->setPreview( $path );
1101
		}
1102
1103
		return $item;
1104
	}
1105
1106
1107
	/**
1108
	 * Creates a new media item instance.
1109
	 *
1110
	 * @param array $values Associative list of key/value pairs
1111
	 * @param \Aimeos\MShop\Common\Item\Lists\Iface[] $listItems List of list items
1112
	 * @param \Aimeos\MShop\Common\Item\Iface[] $refItems List of items referenced
1113
	 * @param \Aimeos\MShop\Common\Item\Property\Iface[] $propItems List of property items
1114
	 * @return \Aimeos\MShop\Media\Item\Iface New media item
1115
	 */
1116
	protected function createItemBase( array $values = [], array $listItems = [], array $refItems = [],
1117
		array $propItems = [] ) : \Aimeos\MShop\Common\Item\Iface
1118
	{
1119
		$values['.languageid'] = $this->languageId;
1120
1121
		return new \Aimeos\MShop\Media\Item\Standard( $values, $listItems, $refItems, $propItems );
1122
	}
1123
}
1124