Passed
Push — master ( 3052c0...a438df )
by Aimeos
15:16 queued 11:14
created

Types::saveTypes()   A

Complexity

Conditions 6
Paths 28

Size

Total Lines 38
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 19
c 1
b 0
f 0
nc 28
nop 0
dl 0
loc 38
rs 9.0111
1
<?php
2
3
/**
4
 * @license LGPLv3, http://opensource.org/licenses/LGPL-3.0
5
 * @copyright Aimeos (aimeos.org), 2024
6
 * @package Controller
7
 * @subpackage Jobs
8
 */
9
10
11
namespace Aimeos\Controller\Jobs\Common;
12
13
14
/**
15
 * Trait with methods to add new types
16
 *
17
 * @package Controller
18
 * @subpackage Jobs
19
 */
20
21
trait Types
22
{
23
	private array $typeMap = [];
24
25
26
	/**
27
	 * Returns the context item
28
	 *
29
	 * @return \Aimeos\MShop\ContextIface Context object
30
	 */
31
	abstract protected function context() : \Aimeos\MShop\ContextIface;
32
33
34
	/**
35
	 * Registers a used type which is going to be saved if it doesn't exist yet
36
	 *
37
	 * @param string $path Manager path, e.g. "product/lists/type"
38
	 * @param string $domain Domain name the type belongs to, e.g. "attribute"
39
	 * @param string $code Type code
40
	 * @return self Same object for method chaining
41
	 */
42
	protected function addType( string $path, string $domain, string $code ) : self
43
	{
44
		$this->typeMap[$path][$domain][$code] = $code;
45
		return $this;
46
	}
47
48
49
	/**
50
	 * Stores all types for which no type items exist yet
51
	 *
52
	 * @return self Same object for method chaining
53
	 */
54
	protected function saveTypes() : self
55
	{
56
		foreach( $this->typeMap as $path => $list )
57
		{
58
			$manager = \Aimeos\MShop::create( $this->context(), $path );
59
			$prefix = str_replace( '/', '.', $path );
60
61
			foreach( $list as $codes )
62
			{
63
				$manager->begin();
64
65
				try
66
				{
67
					$types = $items = [];
68
					$search = $manager->filter()->add( [$prefix . '.code' => $codes] )->slice( 0, 10000 );
69
70
					foreach( $manager->search( $search ) as $item ) {
71
						$types[] = $item->getCode();
72
					}
73
74
					foreach( array_diff( $codes, $types ) as $code ) {
75
						$items[] = $manager->create()->setCode( $code )->setLabel( $code );
76
					}
77
78
					$manager->save( $items, false );
79
					$manager->commit();
80
				}
81
				catch( \Exception $e )
82
				{
83
					$manager->rollback();
84
85
					$msg = 'Error saving types: ' . $e->getMessage() . PHP_EOL . $e->getTraceAsString();
86
					$this->context()->logger()->error( $msg, 'import' );
87
				}
88
			}
89
		}
90
91
		return $this;
92
	}
93
}
94