Passed
Push — master ( e7c54b...4d1238 )
by Aimeos
07:37
created

Standard::insert()   A

Complexity

Conditions 3
Paths 32

Size

Total Lines 116
Code Lines 30

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 30
nc 32
nop 3
dl 0
loc 116
rs 9.44
c 0
b 0
f 0

How to fix   Long Method   

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-2020
7
 * @package MShop
8
 * @subpackage Locale
9
 */
10
11
12
namespace Aimeos\MShop\Locale\Manager\Site;
13
14
15
/**
16
 * Default implementation for managing sites.
17
 *
18
 * @package MShop
19
 * @subpackage Locale
20
 */
21
class Standard
22
	extends \Aimeos\MShop\Common\Manager\Base
23
	implements \Aimeos\MShop\Locale\Manager\Site\Iface, \Aimeos\MShop\Common\Manager\Factory\Iface
24
{
25
	private $cache = [];
26
27
	private $searchConfig = array(
28
		'locale.site.id' => array(
29
			'code' => 'locale.site.id',
30
			'internalcode' => 'mlocsi."id"',
31
			'internaldeps' => ['LEFT JOIN "mshop_locale_site" AS mlocsi ON (mloc."siteid" = mlocsi."siteid")'],
32
			'label' => 'Site ID',
33
			'type' => 'string',
34
			'internaltype' => \Aimeos\MW\DB\Statement\Base::PARAM_INT,
35
			'public' => false,
36
		),
37
		'locale.site.siteid' => array(
38
			'code' => 'locale.site.siteid',
39
			'internalcode' => 'mlocsi."siteid"',
40
			'label' => 'Unique site ID',
41
			'type' => 'string',
42
			'internaltype' => \Aimeos\MW\DB\Statement\Base::PARAM_STR,
43
			'public' => false,
44
		),
45
		'locale.site.label' => array(
46
			'code' => 'locale.site.label',
47
			'internalcode' => 'mlocsi."label"',
48
			'label' => 'Site label',
49
			'type' => 'string',
50
			'internaltype' => \Aimeos\MW\DB\Statement\Base::PARAM_STR,
51
		),
52
		'locale.site.code' => array(
53
			'code' => 'locale.site.code',
54
			'internalcode' => 'mlocsi."code"',
55
			'label' => 'Site code',
56
			'type' => 'string',
57
			'internaltype' => \Aimeos\MW\DB\Statement\Base::PARAM_STR,
58
		),
59
		'locale.site.status' => array(
60
			'code' => 'locale.site.status',
61
			'internalcode' => 'mlocsi."status"',
62
			'label' => 'Site status',
63
			'type' => 'integer',
64
			'internaltype' => \Aimeos\MW\DB\Statement\Base::PARAM_INT,
65
		),
66
		'locale.site.level' => array(
67
			'code' => 'locale.site.level',
68
			'internalcode' => 'mlocsi."level"',
69
			'label' => 'Site tree level',
70
			'type' => 'integer',
71
			'internaltype' => \Aimeos\MW\DB\Statement\Base::PARAM_INT,
72
			'public' => false,
73
		),
74
		'locale.site.config' => array(
75
			'code' => 'locale.site.config',
76
			'internalcode' => 'mlocsi."config"',
77
			'label' => 'Site config',
78
			'type' => 'string',
79
			'internaltype' => \Aimeos\MW\DB\Statement\Base::PARAM_STR,
80
			'public' => false,
81
		),
82
		'locale.site.ctime' => array(
83
			'code' => 'locale.site.ctime',
84
			'internalcode' => 'mlocsi."ctime"',
85
			'label' => 'Site create date/time',
86
			'type' => 'datetime',
87
			'internaltype' => \Aimeos\MW\DB\Statement\Base::PARAM_STR,
88
			'public' => false,
89
		),
90
		'locale.site.mtime' => array(
91
			'code' => 'locale.site.mtime',
92
			'internalcode' => 'mlocsi."mtime"',
93
			'label' => 'Site modify date/time',
94
			'type' => 'datetime',
95
			'internaltype' => \Aimeos\MW\DB\Statement\Base::PARAM_STR,
96
			'public' => false,
97
		),
98
		'locale.site.editor' => array(
99
			'code' => 'locale.site.editor',
100
			'internalcode' => 'mlocsi."editor"',
101
			'label' => 'Site editor',
102
			'type' => 'string',
103
			'internaltype' => \Aimeos\MW\DB\Statement\Base::PARAM_STR,
104
			'public' => false,
105
		),
106
	);
107
108
109
	/**
110
	 * Initializes the object.
111
	 *
112
	 * @param \Aimeos\MShop\Context\Item\Iface $context Context object
113
	 */
114
	public function __construct( \Aimeos\MShop\Context\Item\Iface $context )
115
	{
116
		parent::__construct( $context );
117
		$this->setResourceName( 'db-locale' );
118
	}
119
120
121
	/**
122
	 * Removes old entries from the storage.
123
	 *
124
	 * @param iterable $siteids List of IDs for sites whose entries should be deleted
125
	 * @return \Aimeos\MShop\Locale\Manager\Site\Iface Manager object for chaining method calls
126
	 */
127
	public function clear( iterable $siteids ) : \Aimeos\MShop\Common\Manager\Iface
128
	{
129
		if( empty( $siteids ) ) {
130
			return $this;
131
		}
132
133
		$context = $this->getContext();
134
		$config = $context->getConfig();
135
136
		/** mshop/locale/manager/site/cleanup/shop/domains
137
		 * List of madmin domains names whose items referring to the same site should be deleted as well
138
		 *
139
		 * As items for each domain can be stored in a separate database, the
140
		 * site manager needs a list of domain names used to connect to the
141
		 * correct database and to remove all items that belong the the deleted
142
		 * site.
143
		 *
144
		 * For each domain the cleanup will be done by the corresponding MShop
145
		 * manager. To keep records for old sites in the database even if the
146
		 * site was already deleted, you can configure a new list with the
147
		 * domains removed you would like to keep, e.g. the "order" domain to
148
		 * keep all orders ever placed.
149
		 *
150
		 * @param array List of domain names in lower case
151
		 * @since 2014.03
152
		 * @category Developer
153
		 * @see mshop/locale/manager/site/cleanup/admin/domains
154
		 */
155
		$path = 'mshop/locale/manager/site/cleanup/shop/domains';
156
		$default = array(
157
			'attribute', 'catalog', 'coupon', 'customer', 'index',
158
			'media', 'order', 'plugin', 'price', 'product', 'review',
159
			'tag', 'service', 'stock', 'subscription', 'supplier', 'text'
160
		);
161
162
		foreach( $config->get( $path, $default ) as $domain ) {
163
			\Aimeos\MShop::create( $context, $domain )->clear( $siteids );
164
		}
165
166
		/** mshop/locale/manager/site/cleanup/admin/domains
167
		 * List of mshop domains names whose items referring to the same site should be deleted as well
168
		 *
169
		 * As items for each domain can be stored in a separate database, the
170
		 * site manager needs a list of domain names used to connect to the
171
		 * correct database and to remove all items that belong the the deleted
172
		 * site.
173
		 *
174
		 * For each domain the cleanup will be done by the corresponding MAdmin
175
		 * manager. To keep records for old sites in the database even if the
176
		 * site was already deleted, you can configure a new list with the
177
		 * domains removed you would like to keep, e.g. the "log" domain to
178
		 * keep all log entries ever written.
179
		 *
180
		 * @param array List of domain names in lower case
181
		 * @since 2014.03
182
		 * @category Developer
183
		 * @see mshop/locale/manager/site/cleanup/shop/domains
184
		 */
185
		$path = 'mshop/locale/manager/site/cleanup/admin/domains';
186
		$default = array( 'job', 'log', 'cache' );
187
188
		foreach( $config->get( $path, $default ) as $domain ) {
189
			\Aimeos\MAdmin::create( $context, $domain )->clear( $siteids );
190
		}
191
192
		return $this;
193
	}
194
195
196
	/**
197
	 * Creates a new empty item instance
198
	 *
199
	 * @param array $values Values the item should be initialized with
200
	 * @return \Aimeos\MShop\Locale\Item\Site\Iface New locale site item object
201
	 */
202
	public function create( array $values = [] ) : \Aimeos\MShop\Common\Item\Iface
203
	{
204
		return $this->createItemBase( $values );
205
	}
206
207
208
	/**
209
	 * Adds a new site to the storage or updates an existing one.
210
	 *
211
	 * @param \Aimeos\MShop\Locale\Item\Site\Iface $item New site item for saving to the storage
212
	 * @param bool $fetch True if the new ID should be returned in the item
213
	 * @return \Aimeos\MShop\Locale\Item\Site\Iface $item Updated item including the generated ID
214
	 */
215
	public function saveItem( \Aimeos\MShop\Locale\Item\Site\Iface $item, bool $fetch = true ) : \Aimeos\MShop\Locale\Item\Site\Iface
216
	{
217
		if( $item->getId() === null ) {
218
			throw new \Aimeos\MShop\Locale\Exception( sprintf( 'Newly created site can not be saved using method "save()". Try using method "insert()" instead.' ) );
219
		}
220
221
		if( !$item->isModified() ) {
222
			return $item;
223
		}
224
225
		$context = $this->getContext();
226
227
		$dbm = $context->getDatabaseManager();
228
		$dbname = $this->getResourceName();
229
		$conn = $dbm->acquire( $dbname );
230
231
		try
232
		{
233
			$id = $item->getId();
234
			$columns = $this->getObject()->getSaveAttributes();
235
236
			/** mshop/locale/manager/site/update/mysql
237
			 * Updates an existing site record in the database
238
			 *
239
			 * @see mshop/locale/manager/site/update/ansi
240
			 */
241
242
			/** mshop/locale/manager/site/update/ansi
243
			 * Updates an existing site record in the database
244
			 *
245
			 * The SQL statement must be a string suitable for being used as
246
			 * prepared statement. It must include question marks for binding
247
			 * the values from the site item to the statement before they are
248
			 * sent to the database server. The order of the columns must
249
			 * correspond to the order in the save() method, so the
250
			 * correct values are bound to the columns.
251
			 *
252
			 * The SQL statement should conform to the ANSI standard to be
253
			 * compatible with most relational database systems. This also
254
			 * includes using double quotes for table and column names.
255
			 *
256
			 * @param string SQL statement for updating records
257
			 * @since 2014.03
258
			 * @category Developer
259
			 * @see mshop/locale/manager/site/insert/ansi
260
			 * @see mshop/locale/manager/site/delete/ansi
261
			 * @see mshop/locale/manager/site/search/ansi
262
			 * @see mshop/locale/manager/site/count/ansi
263
			 * @see mshop/locale/manager/site/newid/ansi
264
			 */
265
			$path = 'mshop/locale/manager/site/update';
266
			$sql = $this->addSqlColumns( array_keys( $columns ), $this->getSqlConfig( $path ), false );
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

266
			$sql = $this->addSqlColumns( array_keys( $columns ), /** @scrutinizer ignore-type */ $this->getSqlConfig( $path ), false );
Loading history...
267
268
			$idx = 1;
269
			$stmt = $this->getCachedStatement( $conn, $path, $sql );
270
271
			foreach( $columns as $name => $entry ) {
272
				$stmt->bind( $idx++, $item->get( $name ), $entry->getInternalType() );
273
			}
274
275
			$stmt->bind( $idx++, $item->getSiteId() );
276
			$stmt->bind( $idx++, $item->getCode() );
277
			$stmt->bind( $idx++, $item->getLabel() );
278
			$stmt->bind( $idx++, json_encode( $item->getConfig() ) );
279
			$stmt->bind( $idx++, $item->getStatus(), \Aimeos\MW\DB\Statement\Base::PARAM_INT );
280
			$stmt->bind( $idx++, $context->getEditor() );
281
			$stmt->bind( $idx++, date( 'Y-m-d H:i:s' ) ); // mtime
282
			$stmt->bind( $idx++, $id, \Aimeos\MW\DB\Statement\Base::PARAM_INT );
283
284
			$stmt->execute()->finish();
285
			$item->setId( $id ); // set Modified false
286
287
			$dbm->release( $conn, $dbname );
288
		}
289
		catch( \Exception $e )
290
		{
291
			$dbm->release( $conn, $dbname );
292
			throw $e;
293
		}
294
295
		return $item;
296
	}
297
298
299
	/**
300
	 * Removes multiple items.
301
	 *
302
	 * @param \Aimeos\MShop\Common\Item\Iface|array|string $items List of item objects or IDs of the items
303
	 * @return \Aimeos\MShop\Locale\Manager\Site\Iface Manager object for chaining method calls
304
	 */
305
	public function delete( $items ) : \Aimeos\MShop\Common\Manager\Iface
306
	{
307
		if( is_map( $items ) ) { $items = $items->toArray(); }
308
		if( !is_array( $items ) ) { $items = [$items]; }
309
		if( empty( $items ) ) { return $this; }
310
311
312
		$filter = $this->getObject()->filter()
313
			->add( ['locale.site.id' => $items] )
314
			->slice( 0, count( $items ) );
315
316
		$siteIds = $this->getObject()->search( $filter )->getSiteId()->toArray();
317
		$this->getObject()->clear( $siteIds );
318
319
320
		/** mshop/locale/manager/site/delete/mysql
321
		 * Deletes the items matched by the given IDs from the database
322
		 *
323
		 * @see mshop/locale/manager/site/delete/ansi
324
		 */
325
326
		/** mshop/locale/manager/site/delete/ansi
327
		 * Deletes the items matched by the given IDs from the database
328
		 *
329
		 * Removes the site records specified by the given IDs from the
330
		 * locale database. The records must be from the site that is configured
331
		 * via the context item.
332
		 *
333
		 * The ":cond" placeholder is replaced by the name of the ID column and
334
		 * the given ID or list of IDs while the site ID is bound to the question
335
		 * mark.
336
		 *
337
		 * The SQL statement should conform to the ANSI standard to be
338
		 * compatible with most relational database systems. This also
339
		 * includes using double quotes for table and column names.
340
		 *
341
		 * @param string SQL statement for deleting items
342
		 * @since 2014.03
343
		 * @category Developer
344
		 * @see mshop/locale/manager/site/insert/ansi
345
		 * @see mshop/locale/manager/site/update/ansi
346
		 * @see mshop/locale/manager/site/search/ansi
347
		 * @see mshop/locale/manager/site/count/ansi
348
		 * @see mshop/locale/manager/site/newid/ansi
349
		 */
350
		$path = 'mshop/locale/manager/site/delete';
351
352
		return $this->deleteItemsBase( $items, $path, false );
353
	}
354
355
356
	/**
357
	 * Returns the item specified by its code and domain/type if necessary
358
	 *
359
	 * @param string $code Code of the item
360
	 * @param string[] $ref List of domains to fetch list items and referenced items for
361
	 * @param string|null $domain Domain of the item if necessary to identify the item uniquely
362
	 * @param string|null $type Type code of the item if necessary to identify the item uniquely
363
	 * @param bool $default True to add default criteria
364
	 * @return \Aimeos\MShop\Common\Item\Iface Item object
365
	 */
366
	public function find( string $code, array $ref = [], string $domain = null, string $type = null,
367
		bool $default = false ) : \Aimeos\MShop\Common\Item\Iface
368
	{
369
		return $this->findBase( array( 'locale.site.code' => $code ), $ref, $default );
370
	}
371
372
373
	/**
374
	 * Returns the site item specified by its ID.
375
	 *
376
	 * @param string $id Unique ID of the site data in the storage
377
	 * @param string[] $ref List of domains to fetch list items and referenced items for
378
	 * @param bool $default Add default criteria
379
	 * @return \Aimeos\MShop\Locale\Item\Site\Iface Returns the site item of the given id
380
	 * @throws \Aimeos\MShop\Exception If the item couldn't be found
381
	 */
382
	public function get( string $id, array $ref = [], bool $default = false ) : \Aimeos\MShop\Common\Item\Iface
383
	{
384
		return $this->getItemBase( 'locale.site.id', $id, $ref, $default );
385
	}
386
387
388
	/**
389
	 * Returns the available manager types
390
	 *
391
	 * @param bool $withsub Return also the resource type of sub-managers if true
392
	 * @return string Type of the manager and submanagers, subtypes are separated by slashes
393
	 */
394
	public function getResourceType( bool $withsub = true ) : array
395
	{
396
		$path = 'mshop/locale/manager/site/submanagers';
397
398
		return $this->getResourceTypeBase( 'locale/site', $path, [], $withsub );
399
	}
400
401
402
	/**
403
	 * Returns the attributes that can be used for searching.
404
	 *
405
	 * @param bool $withsub Return also attributes of sub-managers if true
406
	 * @return \Aimeos\MW\Criteria\Attribute\Iface[] List of search attribute items
407
	 */
408
	public function getSearchAttributes( bool $withsub = true ) : array
409
	{
410
		/** mshop/locale/manager/site/submanagers
411
		 * List of manager names that can be instantiated by the locale site manager
412
		 *
413
		 * Managers provide a generic interface to the underlying storage.
414
		 * Each manager has or can have sub-managers caring about particular
415
		 * aspects. Each of these sub-managers can be instantiated by its
416
		 * parent manager using the getSubManager() method.
417
		 *
418
		 * The search keys from sub-managers can be normally used in the
419
		 * manager as well. It allows you to search for items of the manager
420
		 * using the search keys of the sub-managers to further limit the
421
		 * retrieved list of items.
422
		 *
423
		 * @param array List of sub-manager names
424
		 * @since 2014.03
425
		 * @category Developer
426
		 */
427
		$path = 'mshop/locale/manager/site/submanagers';
428
429
		return $this->getSearchAttributesBase( $this->searchConfig, $path, [], $withsub );
430
	}
431
432
433
	/**
434
	 * Returns a new sub manager of the given type and name.
435
	 *
436
	 * @param string $manager Name of the sub manager type in lower case
437
	 * @param string|null $name Name of the implementation, will be from configuration (or Default) if null
438
	 * @return \Aimeos\MShop\Common\Manager\Iface Sub manager
439
	 */
440
	public function getSubManager( string $manager, string $name = null ) : \Aimeos\MShop\Common\Manager\Iface
441
	{
442
		/** mshop/locale/manager/site/name
443
		 * Class name of the used locale site manager implementation
444
		 *
445
		 * Each default locale site manager can be replaced by an alternative imlementation.
446
		 * To use this implementation, you have to set the last part of the class
447
		 * name as configuration value so the manager factory knows which class it
448
		 * has to instantiate.
449
		 *
450
		 * For example, if the name of the default class is
451
		 *
452
		 *  \Aimeos\MShop\Locale\Manager\Site\Standard
453
		 *
454
		 * and you want to replace it with your own version named
455
		 *
456
		 *  \Aimeos\MShop\Locale\Manager\Site\Mysite
457
		 *
458
		 * then you have to set the this configuration option:
459
		 *
460
		 *  mshop/locale/manager/site/name = Mysite
461
		 *
462
		 * The value is the last part of your own class name and it's case sensitive,
463
		 * so take care that the configuration value is exactly named like the last
464
		 * part of the class name.
465
		 *
466
		 * The allowed characters of the class name are A-Z, a-z and 0-9. No other
467
		 * characters are possible! You should always start the last part of the class
468
		 * name with an upper case character and continue only with lower case characters
469
		 * or numbers. Avoid chamel case names like "MySite"!
470
		 *
471
		 * @param string Last part of the class name
472
		 * @since 2014.03
473
		 * @category Developer
474
		 */
475
476
		/** mshop/locale/manager/site/decorators/excludes
477
		 * Excludes decorators added by the "common" option from the locale site manager
478
		 *
479
		 * Decorators extend the functionality of a class by adding new aspects
480
		 * (e.g. log what is currently done), executing the methods of the underlying
481
		 * class only in certain conditions (e.g. only for logged in users) or
482
		 * modify what is returned to the caller.
483
		 *
484
		 * This option allows you to remove a decorator added via
485
		 * "mshop/common/manager/decorators/default" before they are wrapped
486
		 * around the locale site manager.
487
		 *
488
		 *  mshop/locale/manager/site/decorators/excludes = array( 'decorator1' )
489
		 *
490
		 * This would remove the decorator named "decorator1" from the list of
491
		 * common decorators ("\Aimeos\MShop\Common\Manager\Decorator\*") added via
492
		 * "mshop/common/manager/decorators/default" for the locale site manager.
493
		 *
494
		 * @param array List of decorator names
495
		 * @since 2014.03
496
		 * @category Developer
497
		 * @see mshop/common/manager/decorators/default
498
		 * @see mshop/locale/manager/site/decorators/global
499
		 * @see mshop/locale/manager/site/decorators/local
500
		 */
501
502
		/** mshop/locale/manager/site/decorators/global
503
		 * Adds a list of globally available decorators only to the locale site manager
504
		 *
505
		 * Decorators extend the functionality of a class by adding new aspects
506
		 * (e.g. log what is currently done), executing the methods of the underlying
507
		 * class only in certain conditions (e.g. only for logged in users) or
508
		 * modify what is returned to the caller.
509
		 *
510
		 * This option allows you to wrap global decorators
511
		 * ("\Aimeos\MShop\Common\Manager\Decorator\*") around the locale site
512
		 * manager.
513
		 *
514
		 *  mshop/locale/manager/site/decorators/global = array( 'decorator1' )
515
		 *
516
		 * This would add the decorator named "decorator1" defined by
517
		 * "\Aimeos\MShop\Common\Manager\Decorator\Decorator1" only to the locale
518
		 * site manager.
519
		 *
520
		 * @param array List of decorator names
521
		 * @since 2014.03
522
		 * @category Developer
523
		 * @see mshop/common/manager/decorators/default
524
		 * @see mshop/locale/manager/site/decorators/excludes
525
		 * @see mshop/locale/manager/site/decorators/local
526
		 */
527
528
		/** mshop/locale/manager/site/decorators/local
529
		 * Adds a list of local decorators only to the locale site manager
530
		 *
531
		 * Decorators extend the functionality of a class by adding new aspects
532
		 * (e.g. log what is currently done), executing the methods of the underlying
533
		 * class only in certain conditions (e.g. only for logged in users) or
534
		 * modify what is returned to the caller.
535
		 *
536
		 * This option allows you to wrap local decorators
537
		 * ("\Aimeos\MShop\Locale\Manager\Site\Decorator\*") around the locale site
538
		 * manager.
539
		 *
540
		 *  mshop/locale/manager/site/decorators/local = array( 'decorator2' )
541
		 *
542
		 * This would add the decorator named "decorator2" defined by
543
		 * "\Aimeos\MShop\Locale\Manager\Site\Decorator\Decorator2" only to the
544
		 * locale site manager.
545
		 *
546
		 * @param array List of decorator names
547
		 * @since 2014.03
548
		 * @category Developer
549
		 * @see mshop/common/manager/decorators/default
550
		 * @see mshop/locale/manager/site/decorators/excludes
551
		 * @see mshop/locale/manager/site/decorators/global
552
		 */
553
554
		return $this->getSubManagerBase( 'locale', 'site/' . $manager, $name );
555
	}
556
557
558
	/**
559
	 * Searches for site items matching the given criteria.
560
	 *
561
	 * @param \Aimeos\MW\Criteria\Iface $search Search criteria object
562
	 * @param string[] $ref List of domains to fetch list items and referenced items for
563
	 * @param int|null &$total Number of items that are available in total
564
	 * @return \Aimeos\Map List of items implementing \Aimeos\MShop\Locale\Item\Site\Iface with ids as keys
565
	 */
566
	public function search( \Aimeos\MW\Criteria\Iface $search, array $ref = [], int &$total = null ) : \Aimeos\Map
567
	{
568
		$items = [];
569
		$context = $this->getContext();
570
571
		$dbm = $context->getDatabaseManager();
572
		$dbname = $this->getResourceName();
573
		$conn = $dbm->acquire( $dbname );
574
575
		try
576
		{
577
			$attributes = $this->getObject()->getSearchAttributes();
578
			$translations = $this->getSearchTranslations( $attributes );
579
			$types = $this->getSearchTypes( $attributes );
580
			$columns = $this->getObject()->getSaveAttributes();
581
			$sortcols = $search->translate( $search->getSortations(), $translations );
582
583
			$colstring = '';
584
			foreach( $columns as $name => $entry ) {
585
				$colstring .= $entry->getInternalCode() . ', ';
586
			}
587
588
			$find = array( ':columns', ':cond', ':order', ':start', ':size' );
589
			$replace = array(
590
				$colstring . ( $sortcols ? join( ', ', $sortcols ) . ', ' : '' ),
591
				$search->getConditionSource( $types, $translations ),
592
				$search->getSortationSource( $types, $translations ),
593
				$search->getOffset(),
594
				$search->getLimit(),
595
			);
596
597
			/** mshop/locale/manager/site/search/mysql
598
			 * Retrieves the records matched by the given criteria in the database
599
			 *
600
			 * @see mshop/locale/manager/site/search/ansi
601
			 */
602
603
			/** mshop/locale/manager/site/search/ansi
604
			 * Retrieves the records matched by the given criteria in the database
605
			 *
606
			 * Fetches the records matched by the given criteria from the attribute
607
			 * database. The records must be from one of the sites that are
608
			 * configured via the context item. If the current site is part of
609
			 * a tree of sites, the SELECT statement can retrieve all records
610
			 * from the current site and the complete sub-tree of sites.
611
			 *
612
			 * As the records can normally be limited by criteria from sub-managers,
613
			 * their tables must be joined in the SQL context. This is done by
614
			 * using the "internaldeps" property from the definition of the ID
615
			 * column of the sub-managers. These internal dependencies specify
616
			 * the JOIN between the tables and the used columns for joining. The
617
			 * ":joins" placeholder is then replaced by the JOIN strings from
618
			 * the sub-managers.
619
			 *
620
			 * To limit the records matched, conditions can be added to the given
621
			 * criteria object. It can contain comparisons like column names that
622
			 * must match specific values which can be combined by AND, OR or NOT
623
			 * operators. The resulting string of SQL conditions replaces the
624
			 * ":cond" placeholder before the statement is sent to the database
625
			 * server.
626
			 *
627
			 * If the records that are retrieved should be ordered by one or more
628
			 * columns, the generated string of column / sort direction pairs
629
			 * replaces the ":order" placeholder. In case no ordering is required,
630
			 * the complete ORDER BY part including the "\/*-orderby*\/...\/*orderby-*\/"
631
			 * markers is removed to speed up retrieving the records. Columns of
632
			 * sub-managers can also be used for ordering the result set but then
633
			 * no index can be used.
634
			 *
635
			 * The number of returned records can be limited and can start at any
636
			 * number between the begining and the end of the result set. For that
637
			 * the ":size" and ":start" placeholders are replaced by the
638
			 * corresponding values from the criteria object. The default values
639
			 * are 0 for the start and 100 for the size value.
640
			 *
641
			 * The SQL statement should conform to the ANSI standard to be
642
			 * compatible with most relational database systems. This also
643
			 * includes using double quotes for table and column names.
644
			 *
645
			 * @param string SQL statement for searching items
646
			 * @since 2014.03
647
			 * @category Developer
648
			 * @see mshop/locale/manager/site/insert/ansi
649
			 * @see mshop/locale/manager/site/update/ansi
650
			 * @see mshop/locale/manager/site/delete/ansi
651
			 * @see mshop/locale/manager/site/count/ansi
652
			 * @see mshop/locale/manager/site/newid/ansi
653
			 */
654
			$path = 'mshop/locale/manager/site/search';
655
656
			$sql = $this->getSqlConfig( $path );
657
			$results = $this->getSearchResults( $conn, str_replace( $find, $replace, $sql ) );
658
659
			try
660
			{
661
				while( ( $row = $results->fetch() ) !== null )
662
				{
663
					$config = $row['locale.site.config'];
0 ignored issues
show
Unused Code introduced by
The assignment to $config is dead and can be removed.
Loading history...
664
665
					if( ( $row['locale.site.config'] = json_decode( $config = $row['locale.site.config'], true ) ) === null )
666
					{
667
						$msg = sprintf( 'Invalid JSON as result of search for ID "%2$s" in "%1$s": %3$s', 'mshop_locale_site.config', $row['locale.site.id'], $config );
668
						$this->getContext()->getLogger()->log( $msg, \Aimeos\MW\Logger\Base::WARN );
669
					}
670
671
					if( $item = $this->applyFilter( $this->createItemBase( $row ) ) ) {
672
						$items[$row['locale.site.id']] = $item;
673
					}
674
				}
675
			}
676
			catch( \Exception $e )
677
			{
678
				$results->finish();
679
				throw $e;
680
			}
681
682
			if( $total !== null ) {
683
				$total = $this->getTotal( $conn, $find, $replace );
684
			}
685
686
			$dbm->release( $conn, $dbname );
687
		}
688
		catch( \Exception $e )
689
		{
690
			$dbm->release( $conn, $dbname );
691
			throw $e;
692
		}
693
694
		return map( $items );
695
	}
696
697
698
	/**
699
	 * Creates a filter object.
700
	 *
701
	 * @param bool $default Add default criteria
702
	 * @param bool $site TRUE for adding site criteria to limit items by the site of related items
703
	 * @return \Aimeos\MW\Criteria\Iface Returns the filter object
704
	 */
705
	public function filter( bool $default = false, bool $site = false ) : \Aimeos\MW\Criteria\Iface
706
	{
707
		if( $default === true ) {
708
			$search = $this->filterBase( 'locale.site' );
709
		} else {
710
			$search = parent::filter( $default );
711
		}
712
713
		$expr = array(
714
			$search->compare( '==', 'locale.site.level', 0 ),
715
			$search->getConditions(),
716
		);
717
718
		$search->setConditions( $search->combine( '&&', $expr ) );
719
720
		return $search;
721
	}
722
723
724
	/**
725
	 * Returns a list of item IDs, that are in the path of given item ID.
726
	 *
727
	 * @param string $id ID of item to get the path for
728
	 * @param string[] $ref List of domains to fetch list items and referenced items for
729
	 * @return \Aimeos\Map List of IDs as keys and items implementing \Aimeos\MShop\Locale\Item\Site\Iface
730
	 */
731
	public function getPath( string $id, array $ref = [] ) : \Aimeos\Map
732
	{
733
		$item = $this->getTree( $id, $ref, \Aimeos\MW\Tree\Manager\Base::LEVEL_ONE );
734
		return map( [$item->getId() => $item] );
735
	}
736
737
738
	/**
739
	 * Returns a node and its descendants depending on the given resource.
740
	 *
741
	 * @param string|null $id Retrieve nodes starting from the given ID
742
	 * @param string[] $ref List of domains (e.g. text, media, etc.) whose referenced items should be attached to the objects
743
	 * @param int $level One of the level constants from \Aimeos\MW\Tree\Manager\Base
744
	 * @return \Aimeos\MShop\Locale\Item\Site\Iface Site item, maybe with subnodes
745
	 */
746
	public function getTree( string $id = null, array $ref = [], int $level = \Aimeos\MW\Tree\Manager\Base::LEVEL_TREE ) : \Aimeos\MShop\Locale\Item\Site\Iface
747
	{
748
		if( $id !== null )
749
		{
750
			if( count( $ref ) > 0 ) {
751
				return $this->getObject()->get( $id, $ref );
752
			}
753
754
			if( !isset( $this->cache[$id] ) ) {
755
				$this->cache[$id] = $this->getObject()->get( $id, $ref );
756
			}
757
758
			return $this->cache[$id];
759
		}
760
761
		$criteria = $this->getObject()->filter()->slice( 0, 1 );
762
		$criteria->setConditions( $criteria->compare( '==', 'locale.site.code', 'default' ) );
763
764
		if( ( $item = $this->getObject()->search( $criteria, $ref )->first() ) === null ) {
765
			throw new \Aimeos\MShop\Locale\Exception( sprintf( 'Tree root with code "%1$s" in "%2$s" not found', 'default', 'locale.site.code' ) );
766
		}
767
768
		$this->cache[$item->getId()] = $item;
769
770
		return $item;
771
	}
772
773
774
	/**
775
	 * Adds a new item object.
776
	 *
777
	 * @param \Aimeos\MShop\Locale\Item\Site\Iface $item Item which should be inserted
778
	 * @param string|null $parentId ID of the parent item where the item should be inserted into
779
	 * @param string|null $refId ID of the item where the item should be inserted before (null to append)
780
	 * @return \Aimeos\MShop\Locale\Item\Site\Iface $item Updated item including the generated ID
781
	 */
782
	public function insert( \Aimeos\MShop\Locale\Item\Site\Iface $item, string $parentId = null, string $refId = null ) : \Aimeos\MShop\Locale\Item\Site\Iface
783
	{
784
		$context = $this->getContext();
785
786
		$dbm = $context->getDatabaseManager();
787
		$dbname = $this->getResourceName();
788
		$conn = $dbm->acquire( $dbname );
789
790
		try
791
		{
792
			$date = date( 'Y-m-d H:i:s' );
793
			$columns = $this->getObject()->getSaveAttributes();
794
795
			/** mshop/locale/manager/site/insert/mysql
796
			 * Inserts a new currency record into the database table
797
			 *
798
			 * @see mshop/locale/manager/site/insert/ansi
799
			 */
800
801
			/** mshop/locale/manager/site/insert/ansi
802
			 * Inserts a new currency record into the database table
803
			 *
804
			 * The SQL statement must be a string suitable for being used as
805
			 * prepared statement. It must include question marks for binding
806
			 * the values from the site item to the statement before they are
807
			 * sent to the database server. The number of question marks must
808
			 * be the same as the number of columns listed in the INSERT
809
			 * statement. The order of the columns must correspond to the
810
			 * order in the save() method, so the correct values are
811
			 * bound to the columns.
812
			 *
813
			 * The SQL statement should conform to the ANSI standard to be
814
			 * compatible with most relational database systems. This also
815
			 * includes using double quotes for table and column names.
816
			 *
817
			 * @param string SQL statement for inserting records
818
			 * @since 2014.03
819
			 * @category Developer
820
			 * @see mshop/locale/manager/site/update/ansi
821
			 * @see mshop/locale/manager/site/delete/ansi
822
			 * @see mshop/locale/manager/site/search/ansi
823
			 * @see mshop/locale/manager/site/count/ansi
824
			 * @see mshop/locale/manager/site/newid/ansi
825
			 */
826
			$path = 'mshop/locale/manager/site/insert';
827
			$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

827
			$sql = $this->addSqlColumns( array_keys( $columns ), /** @scrutinizer ignore-type */ $this->getSqlConfig( $path ) );
Loading history...
828
829
			$idx = 1;
830
			$stmt = $this->getCachedStatement( $conn, $path, $sql );
831
832
			foreach( $columns as $name => $entry ) {
833
				$stmt->bind( $idx++, $item->get( $name ), $entry->getInternalType() );
834
			}
835
836
			$stmt->bind( $idx++, '' ); // site ID
837
			$stmt->bind( $idx++, $item->getCode() );
838
			$stmt->bind( $idx++, $item->getLabel() );
839
			$stmt->bind( $idx++, json_encode( $item->getConfig() ) );
840
			$stmt->bind( $idx++, $item->getStatus(), \Aimeos\MW\DB\Statement\Base::PARAM_INT );
841
			$stmt->bind( $idx++, $context->getEditor() );
842
			$stmt->bind( $idx++, $date ); // mtime
843
			$stmt->bind( $idx++, $date ); // ctime
844
845
			$stmt->execute()->finish();
846
847
			/** mshop/locale/manager/site/newid/mysql
848
			 * Retrieves the ID generated by the database when inserting a new record
849
			 *
850
			 * @see mshop/locale/manager/site/newid/ansi
851
			 */
852
853
			/** mshop/locale/manager/site/newid/ansi
854
			 * Retrieves the ID generated by the database when inserting a new record
855
			 *
856
			 * As soon as a new record is inserted into the database table,
857
			 * the database server generates a new and unique identifier for
858
			 * that record. This ID can be used for retrieving, updating and
859
			 * deleting that specific record from the table again.
860
			 *
861
			 * For MySQL:
862
			 *  SELECT LAST_INSERT_ID()
863
			 * For PostgreSQL:
864
			 *  SELECT currval('seq_matt_id')
865
			 * For SQL Server:
866
			 *  SELECT SCOPE_IDENTITY()
867
			 * For Oracle:
868
			 *  SELECT "seq_matt_id".CURRVAL FROM DUAL
869
			 *
870
			 * There's no way to retrive the new ID by a SQL statements that
871
			 * fits for most database servers as they implement their own
872
			 * specific way.
873
			 *
874
			 * @param string SQL statement for retrieving the last inserted record ID
875
			 * @since 2014.03
876
			 * @category Developer
877
			 * @see mshop/locale/manager/site/insert/ansi
878
			 * @see mshop/locale/manager/site/update/ansi
879
			 * @see mshop/locale/manager/site/delete/ansi
880
			 * @see mshop/locale/manager/site/search/ansi
881
			 * @see mshop/locale/manager/site/count/ansi
882
			 */
883
			$path = 'mshop/locale/manager/newid';
884
			$item->setId( $this->newId( $conn, $this->getSqlConfig( $path ) ) );
0 ignored issues
show
Bug introduced by
It seems like $this->getSqlConfig($path) can also be of type array; however, parameter $cfgpath of Aimeos\MShop\Common\Manager\Base::newId() 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

884
			$item->setId( $this->newId( $conn, /** @scrutinizer ignore-type */ $this->getSqlConfig( $path ) ) );
Loading history...
885
886
			$dbm->release( $conn, $dbname );
887
888
			// Add unique site identifier
889
			$item = $this->getObject()->save( $item->setSiteId( $item->getId() . '.' ) );
890
		}
891
		catch( \Exception $e )
892
		{
893
			$dbm->release( $conn, $dbname );
894
			throw $e;
895
		}
896
897
		return $item;
898
	}
899
900
901
	/**
902
	 * Moves an existing item to the new parent in the storage.
903
	 *
904
	 * @param string $id ID of the item that should be moved
905
	 * @param string|null $oldParentId ID of the old parent item which currently contains the item that should be removed
906
	 * @param string|null $newParentId ID of the new parent item where the item should be moved to
907
	 * @param string|null $refId ID of the item where the item should be inserted before (null to append)
908
	 * @return \Aimeos\MShop\Locale\Manager\Site\Iface Manager object for chaining method calls
909
	 */
910
	public function moveItem( string $id, string $oldParentId = null, string $newParentId = null,
911
		string $refId = null ) : \Aimeos\MShop\Locale\Manager\Site\Iface
912
	{
913
		throw new \Aimeos\MShop\Locale\Exception( sprintf( 'Method "%1$s" for locale site manager not available', 'moveItem()' ) );
914
	}
915
916
917
	/**
918
	 * Registers a new item filter for the given name
919
	 *
920
	 * Not used for site items but required for trees
921
	 *
922
	 * @param string $name Filter name
923
	 * @param \Closure $fcn Callback function
924
	 */
925
	public function registerItemFilter( string $name, \Closure $fcn ) : \Aimeos\MShop\Locale\Manager\Site\Iface
926
	{
927
		return $this;
928
	}
929
930
931
	/**
932
	 * Returns the search results for the given SQL statement.
933
	 *
934
	 * @param \Aimeos\MW\DB\Connection\Iface $conn Database connection
935
	 * @param string $sql SQL statement
936
	 * @return \Aimeos\MW\DB\Result\Iface Search result object
937
	 */
938
	protected function getSearchResults( \Aimeos\MW\DB\Connection\Iface $conn, string $sql ) : \Aimeos\MW\DB\Result\Iface
939
	{
940
		$time = microtime( true );
941
942
		$stmt = $conn->create( $sql );
943
		$result = $stmt->execute();
944
945
		$msg = 'Time: ' . ( microtime( true ) - $time ) * 1000 . "ms\n"
946
			. 'Class: ' . get_class( $this ) . "\n"
947
			. str_replace( ["\t", "\n\n"], ['', "\n"], trim( (string) $stmt ) );
948
949
		$this->getContext()->getLogger()->log( $msg, \Aimeos\MW\Logger\Base::DEBUG, 'core/sql' );
950
951
		return $result;
952
	}
953
954
955
	/**
956
	 * Create new item object initialized with given parameters.
957
	 *
958
	 * @param array $data Associative list of item key/value pairs
959
	 * @return \Aimeos\MShop\Locale\Item\Site\Iface Site item object
960
	 */
961
	protected function createItemBase( array $data = [] ) : \Aimeos\MShop\Locale\Item\Site\Iface
962
	{
963
		return new \Aimeos\MShop\Locale\Item\Site\Standard( $data );
964
	}
965
966
967
	/**
968
	 * Returns the raw search config array.
969
	 *
970
	 * @return array List of search config arrays
971
	 */
972
	protected function getSearchConfig() : array
973
	{
974
		return $this->searchConfig;
975
	}
976
977
978
	/**
979
	 * Returns the total number of items found for the conditions
980
	 *
981
	 * @param \Aimeos\MW\DB\Connection\Iface $conn Database connection
982
	 * @param string[] $find List of markers that should be replaced in the SQL statement
983
	 * @param string[] $replace List of replacements for the markers in the SQL statement
984
	 * @throws \Aimeos\MShop\Locale\Exception If no total value was found
985
	 * @return int Total number of found items
986
	 */
987
	protected function getTotal( \Aimeos\MW\DB\Connection\Iface $conn, array $find, array $replace ) : int
988
	{
989
		/** mshop/locale/manager/site/count/mysql
990
		 * Counts the number of records matched by the given criteria in the database
991
		 *
992
		 * @see mshop/locale/manager/site/count/ansi
993
		 */
994
995
		/** mshop/locale/manager/site/count/ansi
996
		 * Counts the number of records matched by the given criteria in the database
997
		 *
998
		 * Counts all records matched by the given criteria from the attribute
999
		 * database. The records must be from one of the sites that are
1000
		 * configured via the context item. If the current site is part of
1001
		 * a tree of sites, the statement can count all records from the
1002
		 * current site and the complete sub-tree of sites.
1003
		 *
1004
		 * As the records can normally be limited by criteria from sub-managers,
1005
		 * their tables must be joined in the SQL context. This is done by
1006
		 * using the "internaldeps" property from the definition of the ID
1007
		 * column of the sub-managers. These internal dependencies specify
1008
		 * the JOIN between the tables and the used columns for joining. The
1009
		 * ":joins" placeholder is then replaced by the JOIN strings from
1010
		 * the sub-managers.
1011
		 *
1012
		 * To limit the records matched, conditions can be added to the given
1013
		 * criteria object. It can contain comparisons like column names that
1014
		 * must match specific values which can be combined by AND, OR or NOT
1015
		 * operators. The resulting string of SQL conditions replaces the
1016
		 * ":cond" placeholder before the statement is sent to the database
1017
		 * server.
1018
		 *
1019
		 * Both, the strings for ":joins" and for ":cond" are the same as for
1020
		 * the "search" SQL statement.
1021
		 *
1022
		 * Contrary to the "search" statement, it doesn't return any records
1023
		 * but instead the number of records that have been found. As counting
1024
		 * thousands of records can be a long running task, the maximum number
1025
		 * of counted records is limited for performance reasons.
1026
		 *
1027
		 * The SQL statement should conform to the ANSI standard to be
1028
		 * compatible with most relational database systems. This also
1029
		 * includes using double quotes for table and column names.
1030
		 *
1031
		 * @param string SQL statement for counting items
1032
		 * @since 2014.03
1033
		 * @category Developer
1034
		 * @see mshop/locale/manager/site/insert/ansi
1035
		 * @see mshop/locale/manager/site/update/ansi
1036
		 * @see mshop/locale/manager/site/delete/ansi
1037
		 * @see mshop/locale/manager/site/search/ansi
1038
		 * @see mshop/locale/manager/site/newid/ansi
1039
		 */
1040
		$path = 'mshop/locale/manager/site/count';
1041
1042
		$sql = $this->getSqlConfig( $path );
1043
		$results = $this->getSearchResults( $conn, str_replace( $find, $replace, $sql ) );
1044
1045
		$row = $results->fetch();
1046
		$results->finish();
1047
1048
		if( $row === null ) {
1049
			throw new \Aimeos\MShop\Locale\Exception( 'No total results value found' );
1050
		}
1051
1052
		return $row['count'];
1053
	}
1054
}
1055