PimImport::workwithpictures()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 22
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 16
c 1
b 0
f 0
nc 2
nop 3
dl 0
loc 22
rs 9.7333
1
<?php
2
3
namespace App\Backend\Import;
4
5
use App\Backend\Import\AlphaPimHelper as alpha_pim_helper;
6
use App\Entity\Article;
7
use App\Entity\Attribute;
8
use App\Entity\Category;
9
use App\Entity\Object2category;
10
use App\Repository\ArticleRepository;
11
use App\Repository\AttributeRepository;
12
use App\Repository\CategoryRepository;
13
use SimpleXMLElement;
14
15
declare(ticks=1);
16
17
18
class PimImport
19
{
20
21
    const XML_IMPORT_PATH_DEFAULT = 'XML_IMPORT_PATH_DEFAULT';
22
    const XML_IMPORT_STRUKTUR_FILE_DEFAULT = 'XML_IMPORT_STRUKTUR_FILE_DEFAULT';
23
    const XML_IMPORT_TEILE_FILE_DEFAULT = 'XML_IMPORT_TEILE_FILE_DEFAULT';
24
    const XML_STRUKTUR_PATTERN = '*Strukturexport*.xml';
25
    const XML_TEILE_PATTERN = '*Produktexport*.xml';
26
    const CSV_PREISE_PATTERN = '*preise*.csv';
27
    const STRUKTUR_MERKMALSDEFINITION_SELECTOR = 'Merkmalsdefinition';
28
    const STRUKTUR_WARENGRUPPEN_SELECTOR = 'Warengruppe';
29
    const STRUKTUR_UNTERWARENGRUPPEN_SELECTOR = 'Warenuntergruppen/Warenuntergruppe';
30
31
    /**
32
     * @var oxLegacyDb
0 ignored issues
show
Bug introduced by
The type App\Backend\Import\oxLegacyDb 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...
33
     */
34
    protected $_oDb = null;
35
    protected $remove_images = false;
36
    protected $onWorkedProducts = [];
37
    protected $_aArticleMerkmaleMapping = [
38
        'Mengeneinheit' => [
39
            'field' => 'asy_packaging',
40
            'type' => 'int',
41
        ],
42
        'Mindestbestellmenge' => [
43
            'field' => 'asy_min_order',
44
            'type' => 'int',
45
        ],
46
        'Verkaufseinheit' => [
47
            'field' => 'unitname',
48
            'only_as_oxfield' => false,
49
        ],
50
        'Kurzbeschreibung' => 'shortdesc',
51
        'Langbeschreibung' => 'longdesc',
52
        'Produkt_Artikelname' => 'title',
53
        'Montageoption' => 'asy_installation',
54
        'Energie-Label-Wert' => 'ifellabel',
55
    ];
56
57
    protected $_aAllShops = [];
58
    protected $_blInitialized = false;
59
    protected $_sCsvPreise = null;
60
    protected $_sXmlImportPath = null;
61
    protected $_sXmlImportStrukturFile = null;
62
    protected $_sXmlImportTeileFile = null;
63
    protected $_aImportedAttributeKeys = [];
64
    protected $_aImportedAttributes = [];
65
    protected $_aImportedCategories = [];
66
    protected $_aVariantMerkmale = [];
67
    protected $_aImportedArticles = [];
68
    protected $_iCntArticles = 0;
69
    protected $mainCatSort = 0;
70
    protected $articleProductInStructur = [];
71
    protected $timer;
72
73
    /**
74
     * @var AlphaLogger
0 ignored issues
show
Bug introduced by
The type App\Backend\Import\AlphaLogger 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...
75
     */
76
    protected $_oLog = null;
77
    protected $_aLanguages = [];
78
79
    /**
80
     * @var oxLang
0 ignored issues
show
Bug introduced by
The type App\Backend\Import\oxLang 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...
81
     */
82
    protected $_oLang = null;
83
84
    /**
85
     * @var oxUtilsObject
0 ignored issues
show
Bug introduced by
The type App\Backend\Import\oxUtilsObject 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...
86
     */
87
    protected $_oUtils = null;
88
89
    /** @var  string import type */
90
    protected $type;
91
    /**
92
     * @var \App\Repository\AttributeRepository
93
     */
94
    private $attributeRepository;
95
    /**
96
     * @var \Doctrine\ORM\EntityManagerInterface
97
     */
98
    private $objectManager;
99
    /**
100
     * @var \App\Repository\ArticleRepository
101
     */
102
    private $articleRepository;
103
    /**
104
     * @var \App\Repository\CategoryRepository
105
     */
106
    private $categoryRepository;
107
108
    public function __construct(
109
        \Doctrine\DBAL\Connection $connection,
110
        AttributeRepository $attributeRepository,
111
        \Doctrine\ORM\EntityManagerInterface $objectManager,
112
        ArticleRepository $articleRepository,
113
        CategoryRepository $categoryRepository
114
115
    )
116
    {
117
        $this->type = 'all';
118
        $this->_oDb = $connection;
0 ignored issues
show
Documentation Bug introduced by
It seems like $connection of type Doctrine\DBAL\Connection is incompatible with the declared type App\Backend\Import\oxLegacyDb of property $_oDb.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
119
        $this->_aLanguages = [
120
            (object)[
121
                'abbr' => 'de',
122
                'id' => '1',
123
            ],
124
            (object)[
125
                'abbr' => 'uk',
126
                'id' => '2',
127
            ],
128
        ];
129
        $this->attributeRepository = $attributeRepository;
130
        $this->objectManager = $objectManager;
131
        $this->articleRepository = $articleRepository;
132
        $this->categoryRepository = $categoryRepository;
133
    }
134
135
136
    /**
137
     *
138
     * to run the importer
139
     *
140
     * @param int $sXmlImportPath
141
     * @param int $sXmlImportStrukturFile
142
     * @param int $sXmlImportTeileFile
143
     *
144
     * @todo we can change between delta and full import
145
     *
146
     */
147
    public function run($sXmlImportPath = self::XML_IMPORT_PATH_DEFAULT, $sXmlImportStrukturFile = self::XML_IMPORT_STRUKTUR_FILE_DEFAULT, $sXmlImportTeileFile = self::XML_IMPORT_TEILE_FILE_DEFAULT, $sCsvPreise = self::CSV_PREISE_PATTERN)
148
    {
149
150
151
        $this->timer = microtime(true);
152
        if (!in_array($this->type, ['p', 'b'])) {
153
            $this->_initializeFiles($sXmlImportPath, $sXmlImportStrukturFile, $sXmlImportTeileFile, $sCsvPreise);
154
            $oStrukturXML = null;
155
            $oProductXML = null;
156
            $strukturExists = false;
157
            $produktExists = false;
158
            if (!in_array($this->type, ['g', 'cleanup']) || $sXmlImportPath != self::XML_IMPORT_PATH_DEFAULT) {
159
                $sStrukturCompletePath = $this->_sXmlImportPath . DIRECTORY_SEPARATOR . $this->_sXmlImportStrukturFile;
160
161
                if (file_exists($sStrukturCompletePath) && is_file($sStrukturCompletePath)) {
162
                    $oStrukturXML = simplexml_load_file($sStrukturCompletePath);
163
                    $strukturExists = true;
164
                }
165
            }
166
            if (in_array($this->type, ['a', 'e', 'g', 'all'])) {
167
                $sProductCompletePath = $this->_sXmlImportPath . DIRECTORY_SEPARATOR . $this->_sXmlImportTeileFile;
168
169
                if (file_exists($sProductCompletePath) && is_file($sProductCompletePath)) {
170
                    $oProductXML = simplexml_load_file($sProductCompletePath);
171
                    $produktExists = true;
172
                }
173
            }
174
175
            if (in_array($this->type, ['a', 'all', 'c']) && !$strukturExists && !$produktExists) {
176
                $this->_oLog->error('Keine Struktur und kein Produktexport vorhanden.');
177
                return;
178
            }
179
        }
180
181
        $artNumbs = [
0 ignored issues
show
Unused Code introduced by
The assignment to $artNumbs is dead and can be removed.
Loading history...
182
            '55259627', '55263585', '55286718', '55263609', '55263625', '55134251', '55294565', '55267788', '55272298', '55258031', '55134250', '55258029', '55134260', '55259624', '55294561', '55258026', '55267880', '55236315', '55270516', '55294134', '55263597', '55284694', '55290582', '55272294', '55286722', '55220268', '55291562', '55258547', '55268503', '55268209', '55258028', '55257354', '55224273', '55227280', '55287286', '55208445', '55272633', '55267882', '55270526', '286790', '294570', '258023', '263613', '290582', '267640', '268504', '236316', '270531', '272300', '236311', '278994', '267633', '272330', '275515', '263599', '272333', '258482', '263631', '294568', '294134', '263589', '236313', '227278', '286722', '263624', '272334', '263590', '270526', '279005', '284695', '294566', '294135', '263617', '263610', '279758', '294562', '236274', '270522', '294572', '134428', '263591', '208446', '291562', '278963', '275520', '258568', '267630', '263603', '236318', '274448', '268981', '292136', '286791', '272295', '294138', '294141', '134260', '278962', '275663', '294567', '272339', '263626', '270518', '258536', '263609', '286724', '267632', '284698', '258015', '284696', '272753', '239122', '267637', '272633', '272634', '134426', '263596', '278993', '267641', '286799', '272337', '259627', '267788', '275518', '224273', '272336', '290590', '272297', '287289', '287290', '279007', '258532', '263619', '278995', '272322', '259628', '267880', '294137', '278997', '258026', '272340', '258028', '287286', '286725', '294564', '263627', '294569', '259629', '291565', '134255', '263606', '263600', '239119', '258014', '134256', '263608', '275521', '294565', '263629', '278992', '267635', '236322', '286798', '147049', '268501', '286720', '208447', '236302', '272327', '294140', '294561', '272323', '263611', '258025', '294563', '147048', '263597', '270520', '275522', '272335', '275661', '236305', '257356', '278964', '277552', '284697', '272301', '134251', '263601', '258027', '263595', '268208', '134246', '294139', '258018', '279000', '286718', '258030', '257354', '279002', '268502', '134250', '258021', '263607', '275516', '278990', '275662', '267634', '263586', '267638', '219760', '275513', '286748', '272341', '263604', '263623', '278999', '291564', '263598', '263628', '275658', '274439', '286750', '270528', '270523', '284699', '278998', '279183', '259625', '290583', '278988', '239116', '236272', '290591', '236304', '263594', '236303', '258024', '220270', '270530', '275659', '291563', '272331', '263630', '275514', '275523', '279006', '272294', '263587', '277551', '286792', '258537', '263592', '286796', '258029', '272324', '279003', '286787', '258559', '267789', '263625', '267881', '263593', '263585', '294136', '258547', '275519', '270521', '258031', '279004', '287291', '263615', '286795', '286721', '272299', '286719', '272328', '263616', '258017', '274449', '263602', '279001', '275660', '263605', '134258', '259626', '208448', '134253', '263614', '278991', '220268', '268503', '258020', '259630', '274438', '263621', '272332', '284694', '267631', '268211', '239123', '134248', '263620', '268212', '286793', '286789', '267636', '258022', '272329', '272298', '263612', '286749', '268209', '239117', '287288', '274440', '272296', '258539', '258540', '134245', '275664', '287287', '258538', '272325', '263632', '267639', '278989', '239131', '257355', '278996', '272338', '208445', '258535', '239132', '263588', '258019', '258571', '267882', '272326', '286723', '278965', '275517', '236315', '263618', '286751', '263622', '258016', '274450', '236325', '224275', '259624', '286797', '279757', '210853', '270529', '286794',
183
        ];
184
185
186
        if (($this->type == 'a' || $this->type == 'all') && $produktExists && $strukturExists) { // Produkte und Attribute
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $strukturExists does not seem to be defined for all execution paths leading up to this point.
Loading history...
Comprehensibility Best Practice introduced by
The variable $produktExists does not seem to be defined for all execution paths leading up to this point.
Loading history...
187
            echo 'Beginne Artikel Import ' . '(' . sprintf('%.3f', ((microtime(true) - $this->timer) / 60)) . ')' . PHP_EOL;
188
            echo "Start attributes\n";
189
            $this->_workWithAttributes($oStrukturXML);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $oStrukturXML does not seem to be defined for all execution paths leading up to this point.
Loading history...
190
            echo "Start articles\n";
191
            $this->_workWithArticles($oProductXML);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $oProductXML does not seem to be defined for all execution paths leading up to this point.
Loading history...
192
            if ($this->type == 'a') {
193
                $this->clearImageCache();
0 ignored issues
show
Bug introduced by
The method clearImageCache() does not exist on App\Backend\Import\PimImport. ( Ignorable by Annotation )

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

193
                $this->/** @scrutinizer ignore-call */ 
194
                       clearImageCache();

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

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

Loading history...
194
            }
195
            echo 'Ende Artikel Import' . '(' . sprintf('%.3f', ((microtime(true) - $this->timer) / 60)) . ')' . PHP_EOL;
196
        }
197
        if (($this->type == 'c' || $this->type == 'all' || $this->type == 'oc') && $strukturExists) { // Kategorien und Attributslogik
198
            echo 'Beginne Kategorie Struktur Import' . '(' . sprintf('%.3f', ((microtime(true) - $this->timer) / 60)) . ')' . PHP_EOL;
199
            $this->_workWithCategories($oStrukturXML);
200
            echo 'Ende Kategorie Struktur Import' . '(' . sprintf('%.3f', ((microtime(true) - $this->timer) / 60)) . ')' . PHP_EOL;
201
        }
202
203
//        if (in_array($this->type, ['g', 'a', 'all'])) {  // Crossseller & Zubehör
204
//            echo 'Beginne Crossseller Zubehör Import' . '(' . sprintf('%.3f', ((microtime(true) - $this->timer) / 60)) . ')' . PHP_EOL;
205
//            $this->_workWithAdditionalArticles($oProductXML);
206
//            echo 'Ende Crossseller Zubehör Import' . '(' . sprintf('%.3f', ((microtime(true) - $this->timer) / 60)) . ')' . PHP_EOL;
207
//        }
208
209
        //$this->_cleanup($oStrukturXML);
210
211
        echo "\n\nsuccess" . '(' . sprintf('%.3f', ((microtime(true) - $this->timer) / 60)) . ')' . PHP_EOL;
212
    }
213
214
    protected function _cleanup($oStrukturXML = null)
215
    {
216
        echo 'Beginne Cleanup' . PHP_EOL;
217
218
        /*if ($this->type == 'cleanup_products') {
219
            $this->cleanupProducts();
220
        }*/
221
222
        if (!is_null($oStrukturXML)) {
223
            $this->cleanupArticleStructure($oStrukturXML);
224
        }
225
226
        if (!in_array($this->type, ['p', 'b', 'nl'])) {
227
            $this->prepareLongDescs();
228
        }
229
        echo 'Ende Cleanup' . PHP_EOL;
230
    }
231
232
    /**
233
     *
234
     * to iterate over all articles in product xml export of pim
235
     *
236
     * @param SimpleXMLElement $oXMLElement
237
     */
238
    protected function _workWithArticles(SimpleXMLElement $oXMLElement)
239
    {
240
        /** @var SimpleXMLElement $oProductsXML */
241
        if ($oProductsXML = $oXMLElement->xpath('//Root/Produkt')) {
242
            //work on products -> products are the father articles in oxid
243
            foreach ($oProductsXML as $oProductXML) {
244
                /** @var SimpleXMLElement $oProductXML */
245
                $this->_workOnArticle($oProductXML);
246
            }
247
        }
248
249
        if ($oArticlesXML = $oXMLElement->xpath('//Root/Artikel')) {
250
            //work on articles -> articles are the variants
251
            // or better the buyable unit in oxid
252
            // not all products have variants
253
            foreach ($oArticlesXML as $oArticleXML) {
254
                /** @var SimpleXMLElement $oArticleXML */
255
                $this->_workOnArticle($oArticleXML);
256
            }
257
        }
258
    }
259
260
    /**
261
     * Crossseller und Zubehör werden erst nach dem Import zugeordnet,
262
     * um sicherzustellen das diese Artikel dann auch existieren
263
     *
264
     * @param SimpleXMLElement $oXMLElement
265
     */
266
267
    protected function _workWithAdditionalArticles(SimpleXMLElement $oXMLElement)
268
    {
269
        /** @var SimpleXMLElement $oProductsXML */
270
        if ($oProductsXML = $oXMLElement->xpath('//Root/Produkt')) {
271
            //work on products -> products are the father articles in oxid
272
            foreach ($oProductsXML as $oProductXML) {
273
                /** @var SimpleXMLElement $oProductXML */
274
                $this->_workOnAdditionalArticles($oProductXML);
275
            }
276
        }
277
        if ($oArticlesXML = $oXMLElement->xpath('//Root/Artikel')) {
278
            foreach ($oArticlesXML as $oArticleXML) {
279
                /** @var SimpleXMLElement $oArticleXML */
280
                $this->_workOnAdditionalArticles($oArticleXML, true);
0 ignored issues
show
Bug introduced by
true of type true is incompatible with the type App\Backend\Import\type expected by parameter $setParent of App\Backend\Import\PimIm...kOnAdditionalArticles(). ( Ignorable by Annotation )

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

280
                $this->_workOnAdditionalArticles($oArticleXML, /** @scrutinizer ignore-type */ true);
Loading history...
281
            }
282
        }
283
    }
284
285
    /**
286
     * Zieht die Crosseller aus der XML und prüft,
287
     * ob diese evtl. vom Vaterartikel gezogen werden müssen
288
     *
289
     * @param SimpleXMLElement $oArticleXML
290
     * @param type $setParent
0 ignored issues
show
Bug introduced by
The type App\Backend\Import\type 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...
291
     *
292
     * @return type
293
     */
294
    protected function _workOnAdditionalArticles(SimpleXMLElement $oArticleXML, $setParent = false)
295
    {
296
        $this->_iCntArticles++;
297
        $sArticleNumber = alpha_pim_helper::xmlAttribute($oArticleXML, 'key');
298
299
        /** @var oxArticle $oArticle */
300
        $oArticle = oxNew('oxarticle');
0 ignored issues
show
Bug introduced by
The function oxNew was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

300
        $oArticle = /** @scrutinizer ignore-call */ oxNew('oxarticle');
Loading history...
301
        $oArticle->setEnableMultilang(false);
302
        $oArticle->loadByArtnum($sArticleNumber);
303
        if (!$oArticle->getId())
304
            return;
305
        $oArticle->clearZubehorAndCrosseller();
306
        $aCrosseller = $oArticleXML->xpath('Crossselling/Crossseller');
307
        if (!empty($aCrosseller)) {
308
            $this->addAddidionalArticle($aCrosseller, $oArticle);
0 ignored issues
show
Bug introduced by
$aCrosseller of type SimpleXMLElement[] is incompatible with the type App\Backend\Import\type expected by parameter $aCrosseller of App\Backend\Import\PimIm...:addAddidionalArticle(). ( Ignorable by Annotation )

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

308
            $this->addAddidionalArticle(/** @scrutinizer ignore-type */ $aCrosseller, $oArticle);
Loading history...
309
        } elseif ($setParent !== false) {
310
            $this->addAddidionalArticleFromParent($oArticle);
311
        }
312
        $aZubehor = $oArticleXML->xpath('Zubehoer/Crossseller');
313
        if (!empty($aZubehor)) {
314
            $this->addAddidionalArticle($aZubehor, $oArticle, 'zubehoer');
0 ignored issues
show
Bug introduced by
'zubehoer' of type string is incompatible with the type App\Backend\Import\type expected by parameter $type of App\Backend\Import\PimIm...:addAddidionalArticle(). ( Ignorable by Annotation )

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

314
            $this->addAddidionalArticle($aZubehor, $oArticle, /** @scrutinizer ignore-type */ 'zubehoer');
Loading history...
315
        } elseif ($setParent !== false) {
316
            $this->addAddidionalArticleFromParent($oArticle, 'zubehoer');
0 ignored issues
show
Bug introduced by
'zubehoer' of type string is incompatible with the type App\Backend\Import\type expected by parameter $type of App\Backend\Import\PimIm...onalArticleFromParent(). ( Ignorable by Annotation )

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

316
            $this->addAddidionalArticleFromParent($oArticle, /** @scrutinizer ignore-type */ 'zubehoer');
Loading history...
317
        }
318
    }
319
320
    /**
321
     * Crossseller durchlaufen und zuordnen
322
     *
323
     * @param type $aCrosseller
324
     * @param type $oArticle
325
     * @param type $type
326
     */
327
    protected function addAddidionalArticle($aCrosseller, $oArticle, $type = 'crossseller')
328
    {
329
        foreach ($aCrosseller as $oCrossellerXML) {
330
            $crossellerArticle = oxNew('oxArticle');
0 ignored issues
show
Bug introduced by
The function oxNew was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

330
            $crossellerArticle = /** @scrutinizer ignore-call */ oxNew('oxArticle');
Loading history...
331
            $crossellerArticle->loadByArtnum(alpha_pim_helper::xmlAttribute($oCrossellerXML, 'key'));
332
            if ($crossellerArticle->getId()) {
333
                if ($type === 'crossseller') {
334
                    $oArticle->addCrosseller($crossellerArticle->getId());
335
                } else {
336
                    $oArticle->addZubehor($crossellerArticle->getId());
337
                }
338
            }
339
        }
340
    }
341
342
    /**
343
     * Artikel ohne Crossseller? Dann die vom Vaterartikel nehmen
344
     *
345
     * @param type $oArticle
346
     * @param type $type
347
     *
348
     * @return type
349
     *
350
     */
351
    protected function addAddidionalArticleFromParent($oArticle, $type = 'crossseller')
352
    {
353
        $oParent = oxNew('oxarticle');
0 ignored issues
show
Bug introduced by
The function oxNew was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

353
        $oParent = /** @scrutinizer ignore-call */ oxNew('oxarticle');
Loading history...
354
        $oParent->load($oArticle->oxarticles__oxparentid->value);
355
        if (!$oParent->getId())
356
            return;
357
        $table = $type === 'crossseller' ? 'oxobject2article' : 'oxaccessoire2article';
358
        $sQ = "INSERT INTO {$table} (OXID, OXOBJECTID, OXARTICLENID, OXSORT) "
359
            . "SELECT UUID_SHORT(), OXOBJECTID, ?, OXSORT FROM {$table} WHERE OXARTICLENID = ?";
360
        oxDb::getDb()->Execute($sQ, [$oArticle->getId(), $oParent->getId()]);
0 ignored issues
show
Bug introduced by
The type App\Backend\Import\oxDb 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...
361
    }
362
363
    /**
364
     *
365
     * to work on attributes in structure xml of pim
366
     *
367
     * @param SimpleXMLElement $oMerkmalXML
368
     */
369
    protected function _workOnAttribute(SimpleXMLElement $oMerkmalXML)
370
    {
371
        $sTitle = alpha_pim_helper::xmlAttribute($oMerkmalXML, 'Name');
372
        $sCmiUUID = alpha_pim_helper::xmlAttribute($oMerkmalXML, 'key');
373
374
375
        $oAttribute = $this->attributeRepository->findOneBy(['cmiuuid' => $sCmiUUID]);
376
        if (!$oAttribute instanceof Attribute) {
377
            $oAttribute = new Attribute();
378
            $oAttribute->setTitle($sTitle);
379
        }
380
381
        /**
382
         * @todo mapping pim to oxid table
383
         */
384
        /** <Einheit>mm</Einheit> */
385
        $sUnit = '';
386
        if ($aEinheit = $this->_getSimpleMerkmal($oMerkmalXML, 'Einheit')) {
387
            $sUnit = (string)$aEinheit[0];
388
        }
389
390
        /** <OXID-Merkmal_an_FACT-Finder>ja</OXID-Merkmal_an_FACT-Finder> */
391
        $blExportToFF = false;
392
        if ($aMerkmalToFF = $this->_getSimpleMerkmal($oMerkmalXML, 'OXID-Merkmal_an_FACT-Finder')) {
393
            $blExportToFF = ((string)$aMerkmalToFF[0] == 'ja');
394
        };
395
396
        /** <OXID-Merkmalsname_an_FACT-Finder_xx>Abteilbreite~~mm</OXID-Merkmalsname_an_FACT-Finder_xx> */
397
        $sFFExportTitle = '';
398
        if ($aMerkmalToFFName = $this->_getSimpleMerkmal($oMerkmalXML, 'OXID-Merkmalsname_an_FACT-Finder_xx')) {
399
            $sFFExportTitle = (string)$aMerkmalToFFName[0];
400
        }
401
402
        /** <OXID-Merkmal_im_Warenkorb_anzeigen>nein</OXID-Merkmal_im_Warenkorb_anzeigen> */
403
        $blDisplayInBasket = false;
404
        if ($aMerkmalInBasket = $this->_getSimpleMerkmal($oMerkmalXML, 'OXID-Merkmal_im_Warenkorb_anzeigen')) {
405
            $blDisplayInBasket = ((integer)$aMerkmalInBasket[0] != 'nein');
406
        };
407
408
        /** <OXID-Merkmalssortierung>10013</OXID-Merkmalssortierung> */
409
        $iPos = 99999;
410
        if ($aSort = $this->_getSimpleMerkmal($oMerkmalXML, 'OXID-Merkmalssortierung')) {
411
            $iPos = (integer)$aSort[0];
412
        };
413
414
        /** <Variantenmerkmal>1</Variantenmerkmal> * */
415
        $iVariantenMerkmal = 0;
416
        if ($aVariantenMerkmal = $this->_getSimpleMerkmal($oMerkmalXML, 'Variantenmerkmal')) {
417
            $iVariantenMerkmal = (integer)$aVariantenMerkmal[0];
418
            if ($iVariantenMerkmal > 0) {
419
                $this->_aVariantMerkmale[$iVariantenMerkmal] = $sTitle;
420
            }
421
        };
422
423
        $oAttribute->setTitle($sTitle);
424
        $oAttribute->setSwffexporttoff($blExportToFF);
0 ignored issues
show
Bug introduced by
$blExportToFF of type boolean is incompatible with the type null|string expected by parameter $swffexporttoff of App\Entity\Attribute::setSwffexporttoff(). ( Ignorable by Annotation )

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

424
        $oAttribute->setSwffexporttoff(/** @scrutinizer ignore-type */ $blExportToFF);
Loading history...
425
        $oAttribute->setSwffexporttitle($sFFExportTitle);
426
        $oAttribute->setPos($iPos);
427
        $oAttribute->setDisplayinbasket($blDisplayInBasket);
428
        $oAttribute->setPos($iPos);
429
        $oAttribute->setCmiuuid($sCmiUUID);
430
        $oAttribute->setUnit($sUnit);
431
        $oAttribute->setVariantAttributeSort($iVariantenMerkmal);
432
433
        $this->objectManager->persist($oAttribute);
434
        $this->objectManager->flush();
435
436
        $this->_aImportedAttributes[] = $oAttribute->getId();
437
        $this->_aImportedAttributeKeys[] = $sCmiUUID;
438
    }
439
440
    /**
441
     *
442
     * initializing xml files or file (file only for delta import in this version)
443
     *
444
     * @param $sXmlImportPath
445
     * @param $sXmlImportStrukturFile
446
     * @param $sXmlImportTeileFile
447
     */
448
    public
449
    function _initializeFiles($sXmlImportPath, $sXmlImportStrukturFile, $sXmlImportTeileFile, $sCsvPreise)
450
    {
451
        if ($sXmlImportPath == self::XML_IMPORT_PATH_DEFAULT) {
452
            $this->_sXmlImportPath = __DIR__ . '/files';
453
        } else {
454
            $this->_sXmlImportPath = $sXmlImportPath;
455
        }
456
457
        if ($sXmlImportStrukturFile == self::XML_IMPORT_STRUKTUR_FILE_DEFAULT) {
458
            if ($aFiles = glob($this->_sXmlImportPath . DIRECTORY_SEPARATOR . self::XML_STRUKTUR_PATTERN)) {
459
                //enable the oldest file
460
                $this->_sXmlImportStrukturFile = basename($aFiles[0]);
461
            }
462
        }
463
        if ($sXmlImportTeileFile == self::XML_IMPORT_TEILE_FILE_DEFAULT) {
464
            if ($aFiles = glob($this->_sXmlImportPath . DIRECTORY_SEPARATOR . self::XML_TEILE_PATTERN)) {
465
                //enable the oldest file
466
                $this->_sXmlImportTeileFile = basename($aFiles[0]);
467
            }
468
        }
469
        if ($csvFiles = glob($this->_sXmlImportPath . DIRECTORY_SEPARATOR . $sCsvPreise)) {
470
            $this->_sCsvPreise = basename($csvFiles[0]);
471
        }
472
    }
473
474
    /**
475
     *
476
     * helper methode to get a simple node of xml
477
     *
478
     * @param SimpleXMLElement $oXml
479
     * @param $sName string
480
     */
481
    protected function _getSimpleMerkmal(SimpleXMLElement $oXML, $sName, $blOnlyFirst = true)
482
    {
483
        $sXpathQuery = '(descendant::' . $sName . ')';
484
        if ($blOnlyFirst) {
485
            $sXpathQuery .= '[1]';
486
        }
487
        return alpha_pim_helper::xmlNodeByQuery($oXML, $sXpathQuery);
488
    }
489
490
    /**
491
     *
492
     * helper methode to get a merkmal node with name $sName
493
     *
494
     * @param $oXML SimpleXMLElement
495
     * @param $sName string
496
     */
497
    protected function _getMerkmal($oXML, $sName)
498
    {
499
        return $this->_getSimpleMerkmal($oXML, 'Merkmale[1]/Merkmal[@Name=\'' . $sName . '\']');
500
    }
501
502
    /**
503
     *
504
     * work and save category
505
     *
506
     * @param $oCategoryXML SimpleXMLElement
507
     * @param $mxParent string|oxCategory
508
     */
509
    protected function _workOnCategory($oCategoryXML, $mxParent = 'oxrootid', $mainCat = null)
510
    {
511
        echo "Working on Category " . alpha_pim_helper::xmlAttribute($oCategoryXML, 'Name') . "\n";
512
        /** @var Category $oParentCategory */
513
        if (is_string($mxParent) && $mxParent == 'oxrootid') {
514
            $sParentId = $mxParent;
515
        } elseif (is_string($mxParent) && $mxParent != 'oxrootid') {
516
            $oParentCategory = oxNew('oxcategory');
0 ignored issues
show
Bug introduced by
The function oxNew was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

516
            $oParentCategory = /** @scrutinizer ignore-call */ oxNew('oxcategory');
Loading history...
517
            $oParentCategory->load($mxParent);
518
            $sParentId = $mxParent;
519
        } elseif ($mxParent instanceof oxCategory) {
0 ignored issues
show
Bug introduced by
The type App\Backend\Import\oxCategory 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...
520
            $sParentId = $mxParent->getId();
521
        }
522
523
        $sTitle = alpha_pim_helper::xmlAttribute($oCategoryXML, 'Name');
524
        $sCmiUUID = alpha_pim_helper::xmlAttribute($oCategoryXML, 'uuid');
525
526
        $oCategory = $this->categoryRepository->findOneBy(['cmiuuid' => $sCmiUUID]);
527
        if (!$oCategory instanceof Category) {
528
            $oCategory = new Category();
529
            $oCategory->setTitle($sTitle);
530
            if (isset($sParentId)) {
531
                $oCategory->setParentid($sParentId);
532
            }
533
        }
534
535
        if (!$oCategory->getId()) {
536
            $oCategory->setCmiuuid($sCmiUUID);
537
        }
538
539
        $sTemplate = alpha_pim_helper::xmlAttribute($oCategoryXML, 'Warengruppen_Template');
540
541
        $iCattype = 0;
542
        if ($aCattype = $this->_getMerkmal($oCategoryXML, 'Warengruppentyp')) {
543
            $iCattype = (int)$aCattype[0]->Wert;
544
        }
545
546
        $iSort = $mainCat ? ++$this->mainCatSort : 0;
547
        if ($sSort = alpha_pim_helper::xmlAttribute($oCategoryXML, 'Order_Nr')) {
548
            $iSort = (integer)$sSort;
549
        }
550
551
        if ($aCrosssellingTitle = $this->_getMerkmal($oCategoryXML, 'Cross-selling-title')) {
552
            $crosssellingtitle = alpha_pim_helper::clearFromPIMTags((string)$aCrosssellingTitle[0]->Wert_xx);
553
            $crosssellingtitle_1 = alpha_pim_helper::clearFromPIMTags((string)$aCrosssellingTitle[0]->Wert_xx);
554
            $crosssellingtitle_2 = alpha_pim_helper::clearFromPIMTags((string)$aCrosssellingTitle[0]->Wert_nl);
555
        }
556
557
        $aData = [
558
            'parentid' => $sParentId ?? null,
559
            'sort' => $iSort ?? null,
560
            'active' => true,
561
            'hidden' => false,
562
            'title' => $sTitle ?? null,
563
            'template' => $sTemplate ?? null,
564
            'asy_cattype' => $iCattype ?? null,
565
            'cmiuuid' => $sCmiUUID ?? null,
566
            'crosssellingtitle' => $crosssellingtitle ?? null,
567
            'crosssellingtitle_1' => $crosssellingtitle_1 ?? null,
568
            'crosssellingtitle_2' => $crosssellingtitle_2 ?? null,
569
        ];
570
571
        $sichtbar = strtolower(alpha_pim_helper::xmlAttribute($oCategoryXML, 'sichtbar'));
572
        if (!empty($sichtbar) && $sichtbar == 'nein') {
573
            $aData['hidden'] = true;
574
        }
575
576
        $setangebot = 0;
577
        if ($aSetangebot = $this->_getMerkmal($oCategoryXML, 'Warengruppentyp SET-Artikel')) {
578
            $setangebot = (int)$aSetangebot[0]->Wert;
579
        }
580
        $aData['asy_setcategory'] = (bool)$setangebot;
581
582
        /**
583
         * multilingual fields
584
         * Merkmal[@Name=
585
         */
586
        if ($oNameMerkmal = $this->_getMerkmal($oCategoryXML, 'Produkt/Artikelname')) {
587
            $oNameMerkmal = $oNameMerkmal[0];
588
            foreach ($this->_aLanguages as $oxLang) {
589
                if ($oxLang->abbr == 'de') {
590
                    $sTranslatedValue = alpha_pim_helper::clearFromPIMTags((string)$oNameMerkmal->Wert_xx, null);
591
                    $sField = "title";
592
                } else {
593
                    $sWertPropertyName = sprintf('Wert_%s', $oxLang->abbr);
594
                    if (isset($oNameMerkmal->{$sWertPropertyName})) {
595
                        $sTranslatedValue = alpha_pim_helper::clearFromPIMTags((string)$oNameMerkmal->{$sWertPropertyName}, null);
596
                        $sField = sprintf("title_%d", $oxLang->id);
597
                    } else {
598
                        //go forward we are strict here! ;-)
599
                        continue;
600
                    }
601
                }
602
                $aData[$sField] = $sTranslatedValue;
603
            }
604
        }
605
606
        if ($aShortDescription = $this->_getMerkmal($oCategoryXML, 'Kurzbeschreibung')) {
607
            $aShortDescription = $aShortDescription[0];
608
            foreach ($this->_aLanguages as $oxLang) {
609
                if ($oxLang->abbr == 'de') {
610
                    $sTranslatedValue = alpha_pim_helper::clearFromPIMTags((string)$aShortDescription->Wert_xx, null);
611
                    $sField = "shortdesc";
612
                } else {
613
                    $sWertPropertyName = sprintf('Wert_%s', $oxLang->abbr);
614
                    if (isset($aShortDescription->{$sWertPropertyName})) {
615
                        $sTranslatedValue = alpha_pim_helper::clearFromPIMTags((string)$aShortDescription->{$sWertPropertyName}, null);
616
                        $sField = sprintf("shortdesc_%d", $oxLang->id);
617
                    } else {
618
                        //go forward we are strict here! ;-)
619
                        continue;
620
                    }
621
                }
622
                $aData[$sField] = $sTranslatedValue;
623
            }
624
        }
625
626
        if ($aLongDescription = $this->_getMerkmal($oCategoryXML, 'Langbeschreibung')) {
627
            $aLongDescription = $aLongDescription[0];
628
            foreach ($this->_aLanguages as $oxLang) {
629
                if ($oxLang->abbr == 'de') {
630
                    $sTranslatedValue = alpha_pim_helper::clearFromPIMTags((string)$aLongDescription->Wert_xx);
631
                    $sField = "longdesc";
632
                } else {
633
                    $sWertPropertyName = sprintf('Wert_%s', $oxLang->abbr);
634
                    if (isset($aLongDescription->{$sWertPropertyName})) {
635
                        $sTranslatedValue = alpha_pim_helper::clearFromPIMTags((string)$aLongDescription->{$sWertPropertyName});
636
                        $sField = sprintf("longdesc_%d", $oxLang->id);
637
                    } else {
638
                        //go forward we are strict here! ;-)
639
                        continue;
640
                    }
641
                }
642
                $aData[$sField] = $sTranslatedValue;
643
            }
644
        }
645
646
        $oCategory->setParentid($aData["parentid"] ?? null);
647
        $oCategory->setSort($aData["sort"] ?? null);
648
        $oCategory->setActive($aData["active"] ?? null);
649
        $oCategory->setHidden($aData["hidden"] ?? null);
650
        $oCategory->setTitle($aData["title"] ?? null);
651
        $oCategory->setTemplate($aData["template"] ?? null);
652
        $oCategory->setAsyCattype($aData["asy_cattype"] ?? null);
653
        $oCategory->setCmiuuid($aData["cmiuuid"] ?? null);
654
        $oCategory->setCrosssellingtitle($aData["crosssellingtitle"] ?? null);
655
        $oCategory->setCrosssellingtitle1($aData["crosssellingtitle_1"] ?? null);
656
        $oCategory->setCrosssellingtitle2($aData["crosssellingtitle_2"] ?? null);
657
        $oCategory->setAsySetcategory($aData["asy_setcategory"] ?? null);
658
        $oCategory->setShortdesc($aData["shortdesc"] ?? null);
659
        $oCategory->setLongdesc($aData["longdesc"] ?? null);
660
661
        $this->objectManager->persist($oCategory);
662
        $this->objectManager->flush();
663
664
        $this->_aImportedCategories[] = $oCategory->getId();
665
666
        //produkte -> varianten nur verarbeiten, wenn nicht einfach die kategorien definiert werden sollen
667
        if ($this->type != 'oc') {
668
            $this->_workOnCategoryArticles($oCategoryXML, $oCategory);
669
        }
670
671
        if ($oChildCategories = $oCategoryXML->xpath('Warenuntergruppen/Warenuntergruppe')) {
672
            //child categories avalaible
673
            foreach ($oChildCategories as $oSubCategoryXML) {
674
                /** @var SimpleXMLElement $oSubCategoryXML */
675
                $this->_workOnCategory($oSubCategoryXML, $oCategory);
676
            }
677
        }
678
679
680
    }
681
682
    protected function _prepareVariantSelect($oVariantXML, $oFatherXML, $variantVars)
683
    {
684
        $sArtnum = alpha_pim_helper::xmlAttribute($oVariantXML, 'key');
685
        $oVariantArticle = $this->articleRepository->findOneByArtnum($sArtnum);
686
        if ($oVariantArticle instanceof Article && $oVariantAttributesList = $oVariantArticle->getAttribute() and count($oVariantAttributesList)) {
687
            foreach ($oVariantAttributesList as $oAttribute) {
688
                $attributevalue = $oAttribute->getValue();
689
                $attributetitle = $oAttribute->getAttr()->getTitle();
690
                if (isset($variantVars[$attributetitle])) {
691
                    if (!in_array($attributevalue, $variantVars[$attributetitle])) {
692
                        $variantVars[$attributetitle][] = $attributevalue;
693
                    }
694
                }
695
            }
696
        }
697
        return $variantVars;
698
    }
699
700
    protected function _workOnVariant($oVariantXML, $oFatherXML, $variantVars, $variantVars_1, $variantVars_2, $variantVars_3)
701
    {
702
        $sArtnum = alpha_pim_helper::xmlAttribute($oVariantXML, 'key');
703
        $this->articleProductInStructur[] = $sArtnum;
704
705
        /*if(!in_array($sArtnum, [
706
            270917,
707
            270900,
708
            214994,
709
            214981,
710
            214987,
711
            214995,
712
            214982,
713
            214985,
714
            214989,
715
            270909,
716
            270910,
717
            214998,
718
            214980,
719
            270897,
720
            270928,
721
            270870,
722
            270898,
723
            214983,
724
            270880,
725
            214988,
726
            214991,
727
            270920,
728
            270887,
729
            214984,
730
            214992,
731
            270899,
732
            270927,
733
            270908,
734
            214996,
735
            270918,
736
            270890,
737
            270888,
738
            270919,
739
            270889,
740
            214986,
741
            214990,
742
            270907,
743
            214999,
744
            214993,
745
            214997
746
        ])) return;*/
747
        $oVariantArticle = $this->articleRepository->findOneByArtnum($sArtnum);
748
        if ($oVariantArticle instanceof Article) {
749
            if ($oVariantAttributesList = $oVariantArticle->getAttribute() and count($oVariantAttributesList)) {
750
                $variantvalue = [];
751
                foreach ($oVariantAttributesList as $oAttribute) {
752
753
                    $attributetitle = $oAttribute->getAttr()->getTitle();
754
755
                    if (!empty($attributetitle) && array_key_exists($attributetitle, $variantVars)) {
756
                        $attributevalue = $oAttribute->getValue();
757
                        $variantvalue[] = $attributevalue;
758
                    }
759
                }
760
761
                $sVariantSelect = implode(' | ', $variantvalue);
762
            }
763
764
            $this->_oDb->executeUpdate('update article set varselect=? where id=?', [
765
                $sVariantSelect ?? '',
766
                $oVariantArticle->getId(),
767
            ]);
768
        }
769
    }
770
771
    /**
772
     *
773
     * helper methode to set model properties dynamically by array
774
     *
775
     * @param $aData
776
     * @param $sTableName
777
     * @param oxI18n $oObject
778
     */
779
    protected function _setFieldValuesByArray($aData, $sTableName, oxI18n $oObject)
0 ignored issues
show
Bug introduced by
The type App\Backend\Import\oxI18n 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...
780
    {
781
        foreach ($aData as $sFieldName => $mxFieldValue) {
782
            $sPropertyName = $sTableName . '__' . $sFieldName;
783
            $oObject->{$sPropertyName} = new oxField($mxFieldValue);
0 ignored issues
show
Bug introduced by
The type App\Backend\Import\oxField 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...
784
        }
785
    }
786
787
    /**
788
     *
789
     * work on all attributes of structure xml of pim
790
     *
791
     * @param $oStrukturXML
792
     */
793
    protected function _workWithAttributes(SimpleXMLElement $oStrukturXML)
794
    {
795
        if ($oMerkmalsstruktur = $oStrukturXML->xpath('//' . self::STRUKTUR_MERKMALSDEFINITION_SELECTOR)) {
796
            foreach ($oMerkmalsstruktur as $oMerkmalXML) {
797
                /** <OXID-Merkmalssortierung>10013</OXID-Merkmalssortierung> */
798
                if ($aSort = $this->_getSimpleMerkmal($oMerkmalXML, 'OXID-Merkmalssortierung') and (int)$aSort[0] > 0) {
799
                    $this->_workOnAttribute($oMerkmalXML);
800
                };
801
            }
802
        }
803
        $this->_deleteNotUsedAttributes();
804
    }
805
806
    /**
807
     *
808
     * work on all categories of structure xml of pim
809
     *
810
     * @param $oStrukturXML
811
     *
812
     * @throws object
813
     */
814
    protected function _workWithCategories(SimpleXMLElement $oStrukturXML)
815
    {
816
        if ($oMainCategories = $oStrukturXML->xpath('//' . self::STRUKTUR_WARENGRUPPEN_SELECTOR)) {
817
            foreach ($oMainCategories as $oCategoryXML) {
818
                $this->_workOnCategory($oCategoryXML, 'oxrootid', true);
819
            }
820
        } else {
821
            $sError = 'Oh no dude no categories avalaible.';
822
            $this->_oLog->addError($sError);
823
        }
824
        echo "end workon categorie" . PHP_EOL;
825
        echo "start cleanduplicate articles" . PHP_EOL;
826
        echo "end cleanduplicate articles" . PHP_EOL;
827
        echo "start _deletenotuses Categories" . PHP_EOL;
828
        $this->_deleteNotUsedCategories();
829
        echo "end _delete" . PHP_EOL;
830
        echo "start build actegory tree" . PHP_EOL;
831
        echo "end category tree" . PHP_EOL;
832
    }
833
834
    /**
835
     * deletes categories which are not in the struktur xml file
836
     */
837
    protected function _deleteNotUsedCategories()
838
    {
839
        echo "befor if in delete not used Categories";
840
        if (!empty($this->_aImportedCategories)) {
841
            echo "in if in delete not used Categories";
842
            $sIds = "'" . join("','", $this->_aImportedCategories) . "'";
843
            $sCategorySql = 'select * from category where id not in (' . $sIds . ')';
0 ignored issues
show
Unused Code introduced by
The assignment to $sCategorySql is dead and can be removed.
Loading history...
844
            // this new feature!!!!
845
        }
846
        echo "nach if in delete not used Categories";
847
    }
848
849
    /**
850
     * deletes attributes which are not in the struktur xml file
851
     */
852
    protected function _deleteNotUsedAttributes()
853
    {
854
        if (!empty($this->_aImportedAttributes)) {
855
            $sIds = "'" . join("','", $this->_aImportedAttributes) . "'";
0 ignored issues
show
Unused Code introduced by
The assignment to $sIds is dead and can be removed.
Loading history...
856
            // this new feature!!!!
857
        }
858
    }
859
860
861
    /**
862
     *
863
     * work on a single article and save
864
     *
865
     * @param SimpleXMLElement $oArticleXML
866
     */
867
    protected function _workOnArticle(SimpleXMLElement $oArticleXML)
868
    {
869
        echo "Working on Article " . (string)$oArticleXML['Name'] . "\n";
870
        $this->_iCntArticles++;
871
        $aData = [];
872
        $aAttributes = [];
873
        $sArticleNumber = alpha_pim_helper::xmlAttribute($oArticleXML, 'key');
874
        $articleNumberPrefix = substr($sArticleNumber, 0, 2);
875
        $productNumber = (string)$oArticleXML['Produkt'];
876
877
        $oArticle = $this->articleRepository->findOneBy(['artnum' => $sArticleNumber]);
878
879
        if (!$oArticle instanceof Article) {
880
            $oArticle = new Article();
881
            $oArticle->setArtnum($sArticleNumber);
882
        }
883
884
        if ($aXMLMerkmale = $oArticleXML->xpath('Merkmale/Merkmal')) {
885
            [$aData, $aAttributes, $oArticle] = $this->_workOnArticleMerkmale($aData, $aXMLMerkmale, $aAttributes, $oArticle);
886
        }
887
888
        /**
889
         * varianten Langtext
890
         */
891
        /*if ($oArticle->oxarticles__oxparentid->value) {
892
            $oParent = oxNew('oxarticle');
893
            $oParent->load($oArticle->oxarticles__oxparentid->value);
894
            $aData['oxlongdesc'] = $oParent->oxarticles__oxlongdesc->value;
895
            $aData['oxlongdesc_1'] = $oParent->oxarticles__oxlongdesc_1->value;
896
            $aData['oxlongdesc_2'] = $oParent->oxarticles__oxlongdesc_2->value;
897
            $aData['oxlongdesc_3'] = $oParent->oxarticles__oxlongdesc_3->value;
898
        }*/
899
900
        $aData['artnum'] = $sArticleNumber;
901
902
903
        //um produkte zu identifizieren auf den prefix 55 achten
904
        if (!empty($productNumber) and $articleNumberPrefix != 55) {
905
            $oParentArticle = $this->articleRepository->findOneBy(['artnum' => $productNumber]);
906
            if ($oParentArticle instanceof Article) {
907
                $aData['parentid'] = $oParentArticle->getId();
908
            }
909
        } elseif (empty($productNumber) and $articleNumberPrefix != 55) {
910
            if ($oArticle->getId()) {
911
                $aData['parentid'] = null;
912
            }
913
            $aData['oxvarselect'] = null;
914
            $aData['oxvarselect_1'] = null;
915
            $aData['oxvarselect_2'] = null;
916
            $aData['oxvarname'] = null;
917
            $aData['oxvarname_1'] = null;
918
            $aData['oxvarname_2'] = null;
919
        }
920
921
        if ($oArticleXML['Variantenmerkmale']) {
922
            $aData['alphabytes_variantenmerkmale'] = str_replace(', ', ' | ', (string)$oArticleXML['Variantenmerkmale']);
923
        }
924
925
        //$oArticle->assign($aData);
926
        $oArticle->setAsyPackaging($aData["asy_packaging"] ?? null);
927
        $oArticle->setAsyMinOrder($aData["asy_min_order"] ?? null);
928
        $oArticle->setAsyInstallation($aData["asy_installation"] ?? null);
929
        $oArticle->setTitle($aData["title"] ?? null);
930
        $oArticle->setShortdesc($aData["shortdesc"] ?? null);
931
        $oArticle->setLongdesc($aData["longdesc"] ?? null);
932
        $oArticle->setUnitname($aData["unitname"] ?? null);
933
        $oArticle->setAsyDeltextStandard1($aData["asy_deltext_standard_1"] ?? null);
934
        $oArticle->setAsyDeltextStandardSchweiz($aData["asy_deltext_standard_schweiz"] ?? null);
935
        $oArticle->setAsyDeltextStandard2($aData["asy_deltext_standard_2"] ?? null);
936
        $oArticle->setArtnum($aData["artnum"] ?? null);
0 ignored issues
show
Bug introduced by
It seems like $aData['artnum'] ?? null can also be of type null; however, parameter $artnum of App\Entity\Article::setArtnum() 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

936
        $oArticle->setArtnum(/** @scrutinizer ignore-type */ $aData["artnum"] ?? null);
Loading history...
937
        $oArticle->setAlphabytesVariantenmerkmale($aData["alphabytes_variantenmerkmale"] ?? null);
938
        $oArticle->setAsyDeltextStandard($aData["asy_deltext_standard"] ?? null);
939
        $oArticle->setArtnum(str_replace('WT', '', $aData["artnum"]));
940
        $oArticle->setParentid($aData["parentid"] ?? null);
941
942
        $this->objectManager->persist($oArticle);
943
        $this->objectManager->flush();
944
        $this->_aImportedArticles[] = $sArticleNumber;
945
946
        if ($aAttributes) {
947
            $this->_saveArticleAttributesFromArray($aAttributes, $oArticle, $oArticleXML);
948
        }
949
950
    }
951
952
953
    /**
954
     *
955
     * prepare article attributes and article properties (<-- to save in article table!)
956
     *
957
     * @param $aData
958
     * @param $aXMLMerkmale
959
     * @param $aAttributes
960
     * @param $oArticle oxArticle
0 ignored issues
show
Bug introduced by
The type App\Backend\Import\oxArticle 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...
961
     *
962
     * @return mixed
963
     * @internal param SimpleXMLElement $oArticleXML
964
     * @internal param $aArticleMerkmaleMapping
965
     */
966
    protected function _workOnArticleMerkmale($aData, $aXMLMerkmale, $aAttributes, $oArticle)
967
    {
968
        foreach ($aXMLMerkmale as $oMerkmalXML) {
969
            /** @var SimpleXMLElement $oMerkmalXML */
970
            $sKey = alpha_pim_helper::xmlAttribute($oMerkmalXML, 'key');
971
            if (isset($this->_aArticleMerkmaleMapping[$sKey])) {
972
                /**
973
                 * @todo die bilder behandeln wir einzeln!!
974
                 */
975
                if ($sKey != 'Web-Bild' && $sKey != 'Icons') {
976
                    /** a real article value */
977
                    //$aData[$this->_aArticleMerkmaleMapping[$sKey]] = '';
978
                    if (isset($oMerkmalXML->Wert)) {
979
                        if (is_array($this->_aArticleMerkmaleMapping[$sKey])) {
980
                            $value = alpha_pim_helper::clearFromPIMTags((string)$oMerkmalXML->Wert);
981
                            switch ($this->_aArticleMerkmaleMapping[$sKey]['type']) {
982
                                case 'int':
983
                                    $value = (int)str_replace(',', '.', $value);
984
                                    break;
985
                                default:
986
                                    break;
987
                            }
988
                            $field = $this->_aArticleMerkmaleMapping[$sKey]['field'];
989
                            if (isset($this->_aArticleMerkmaleMapping[$sKey]['only_as_oxfield']) && $this->_aArticleMerkmaleMapping[$sKey]['only_as_oxfield'] === false) {
990
                                //das merkmal wird auch als oxid attribute benötigt
991
                                $aAttributes = $this->declareOxidAttribute($aAttributes, $oMerkmalXML, $sKey);
992
                            }
993
                        } else {
994
                            $value = alpha_pim_helper::clearFromPIMTags((string)$oMerkmalXML->Wert);
995
                            $field = $this->_aArticleMerkmaleMapping[$sKey];
996
                        }
997
                        $aData[$field] = $value;
998
                    } elseif (isset($oMerkmalXML->Wert_xx)) {
999
                        //$aData[$this->_aArticleMerkmaleMapping[$sKey]] = alpha_pim_helper::clearFromPIMTags((string)$oMerkmalXML->Wert_xx);
1000
                        /**
1001
                         * @todo multilingual refactoring
1002
                         */
1003
                        // multilingual field!!
1004
                        if (is_array($this->_aArticleMerkmaleMapping[$sKey])) {
1005
                            $field = $this->_aArticleMerkmaleMapping[$sKey]['field'];
1006
                            if (isset($this->_aArticleMerkmaleMapping[$sKey]['only_as_oxfield']) && $this->_aArticleMerkmaleMapping[$sKey]['only_as_oxfield'] === false) {
1007
                                //das merkmal wird auch als oxid attribute benötigt
1008
                                $aAttributes = $this->declareOxidAttribute($aAttributes, $oMerkmalXML, $sKey);
1009
                            }
1010
                        } else {
1011
                            $field = $this->_aArticleMerkmaleMapping[$sKey];
1012
                        }
1013
                        foreach ($this->_aLanguages as $oxLang) {
1014
                            if ($oxLang->abbr == 'de') {
1015
                                if ($sKey == 'Langbeschreibung') {
1016
                                    $sTranslatedValue = alpha_pim_helper::clearFromPIMTags((string)$oMerkmalXML->Wert_xx, '<p><ul><li><strong><br/><br><br /><b>', false);
1017
                                } else {
1018
                                    $sTranslatedValue = alpha_pim_helper::clearFromPIMTags((string)$oMerkmalXML->Wert_xx, null);
1019
                                }
1020
                                $sField = sprintf("%s", $field);
1021
                            } else {
1022
                                $sWertPropertyName = sprintf('Wert_%s', $oxLang->abbr);
1023
                                if (isset($oMerkmalXML->{$sWertPropertyName})) {
1024
                                    if ($sKey == 'Langbeschreibung') {
1025
                                        $sTranslatedValue = alpha_pim_helper::clearFromPIMTags((string)$oMerkmalXML->{$sWertPropertyName}, '<p><ul><li><strong><br/><br><br /><b>', false);
1026
                                    } else {
1027
                                        $sTranslatedValue = alpha_pim_helper::clearFromPIMTags((string)$oMerkmalXML->{$sWertPropertyName}, null);
1028
                                    }
1029
                                } else {
1030
                                    //go forward we are strict here! ;-)
1031
                                    continue;
1032
                                }
1033
                                $sField = sprintf("%s_%d", $field, $oxLang->id);
1034
                            }
1035
                            if (!empty($sTranslatedValue)) {
1036
                                $aData[$sField] = $sTranslatedValue;
1037
                            }
1038
                        }
1039
                    }
1040
                }
1041
            } else {
1042
                $aAttributes = $this->declareOxidAttribute($aAttributes, $oMerkmalXML, $sKey);
1043
            }
1044
        }
1045
        return [$aData, $aAttributes, $oArticle];
1046
    }
1047
1048
    /**
1049
     *
1050
     * save the article attributes
1051
     *
1052
     * @param $aAttributes
1053
     * @param $oArticle
1054
     */
1055
    protected function _saveArticleAttributesFromArray($aAttributes, $oArticle, $articleXML)
1056
    {
1057
        //beim umbenennen des wertes, ändert sich die "uuid", deshlab alle attributwerte für den artikel löschen
1058
        $this->_oDb->executeQuery('delete from object2attribute where object_id=?', [$oArticle->getId()]);
1059
        foreach ($aAttributes as $sAttributeUUID => $mxAttributeValue) {
1060
            $oAttribute = $this->attributeRepository->findOneBy(['cmiuuid' => $sAttributeUUID]);
1061
            if ($oAttribute instanceof Attribute) {
1062
                $aValues = [];
1063
                $sInsertAttributeSQL = 'insert into object2attribute (object_id, attr_id';
1064
                $aValues = array_merge($aValues, [
1065
                    $oArticle->getId(),
1066
                    $oAttribute->getId(),
1067
                ]);
1068
                $sInsertAttributeValuesSQL = '(?, ?';
1069
                $attrData = $this->attributeRepository->findOneBy(['cmiuuid' => $sAttributeUUID]);
0 ignored issues
show
Unused Code introduced by
The assignment to $attrData is dead and can be removed.
Loading history...
1070
                if ($articleXML['Variantenmerkmale']) {
1071
                    $sInsertAttributeSQL .= ', alpha_variantmerkmal';
1072
                    $merkmale = explode(',', (string)$articleXML['Variantenmerkmale']);
1073
                    $merkmale = array_map('trim', $merkmale);
1074
                    if (in_array($oAttribute->getCmiuuid(), $merkmale)) {
1075
                        $aValues = array_merge($aValues, [
1076
                            1,
1077
                        ]);
1078
                        $sInsertAttributeValuesSQL .= ', ?';
1079
                    } else {
1080
                        $sInsertAttributeValuesSQL .= ', ?';
1081
                        $aValues = array_merge($aValues, [
1082
                            0,
1083
                        ]);
1084
                    }
1085
                }
1086
                $aQueryParameter = [$oArticle->getId(), $oAttribute->getId()];
1087
                if (!is_array($mxAttributeValue)) {
1088
                    $aQueryParameter[] = $mxAttributeValue;
1089
                    $sInsertAttributeSQL .= ', value';
1090
                    $aValues = array_merge($aValues, [
1091
                        trim($mxAttributeValue),
1092
                    ]);
1093
                    $sInsertAttributeValuesSQL .= ', ?';
1094
                } else {
1095
                    foreach ($mxAttributeValue as $sAttributeKey => $sAttritbuteValue) {
1096
                        if (strpos($sAttributeKey, '_0')) {
1097
                            $sAttributeKey = strstr($sAttributeKey, '_0', true);
1098
                        }
1099
                        $aValues = array_merge($aValues, [
1100
                            trim($sAttritbuteValue),
1101
                        ]);
1102
                        $sInsertAttributeValuesSQL .= ',?';
1103
                        $sInsertAttributeSQL .= ', ' . $sAttributeKey;
1104
                    }
1105
                }
1106
1107
1108
                $sInsertAttributeSQL .= ') values ' . $sInsertAttributeValuesSQL . ')';
1109
1110
                $this->_oDb->executeQuery($sInsertAttributeSQL, $aValues);
1111
            }
1112
        }
1113
    }
1114
1115
    /**
1116
     * @param SimpleXMLElement $oArtikelXML
1117
     * @param Category $oCategory
1118
     */
1119
    protected function _addArticleToCategory($oArtikelXML, Category $oCategory)
1120
    {
1121
        /** @var SimpleXMLElement $oArtikelXML */
1122
        $sArtnum = alpha_pim_helper::xmlAttribute($oArtikelXML, 'key');
1123
1124
        $oArticle = $this->articleRepository->findOneBy(['artnum' => $sArtnum]);
1125
1126
        if ($oArticle instanceof Article) {
1127
            $sArticleID = $oArticle->getId();
1128
            //save article $oArticle to category $oCategory
1129
            $sSelect = "select 1 from object2category where catnid=? and objectid=?";
1130
            $result = $this->_oDb->executeQuery($sSelect, [$oCategory->getId(), $sArticleID])->fetch();
1131
            if (!$result) {
1132
                $oObject2Cat = new Object2category();
1133
                $oObject2Cat->setCatnid($oCategory->getId());
1134
                $oObject2Cat->setObjectid($sArticleID);
1135
                $this->objectManager->persist($oObject2Cat);
1136
                $this->objectManager->flush();
1137
            }
1138
        }
1139
    }
1140
1141
1142
    /**
1143
     * @param $oArtikelXML
1144
     * @param $oVariants
1145
     *
1146
     * @return array
1147
     */
1148
    protected function saveVariantsOnArticle($oArtikelXML, $oVariants)
1149
    {
1150
        /** @var SimpleXMLElement $oArtikelXML */
1151
        $sParentArtnum = alpha_pim_helper::xmlAttribute($oArtikelXML, 'key');
1152
        $oParentArticle = $this->articleRepository->findOneByArtnum($sParentArtnum);
1153
        if ($oParentArticle instanceof Article) {
1154
            foreach ($oVariants as $oVariantXML) {
1155
                $sVariantArtnum = alpha_pim_helper::xmlAttribute($oVariantXML, 'key');
1156
1157
                $oVariantArticle = $this->articleRepository->findOneByArtnum($sVariantArtnum);
1158
                if ($oVariantArticle instanceof Article) {
1159
                    $oVariantArticle->setParentid($oParentArticle->getId());
1160
                    $this->objectManager->persist($oVariantArticle);
1161
                }
1162
            }
1163
            $this->objectManager->flush();
1164
        }
1165
        return [$oParentArticle, $oVariantXML];
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $oVariantXML does not seem to be defined for all execution paths leading up to this point.
Loading history...
1166
    }
1167
1168
    /**
1169
     * @param $sIcon
1170
     * @param $sKey
1171
     * @param $object
1172
     *
1173
     * @return object
1174
     * @internal param $aFiles
1175
     */
1176
    protected function workwithpictures($sIcon, $sKey, $object)
1177
    {
1178
        $aFiles = [];
1179
        $filePath = $this->_sXmlImportPath . DIRECTORY_SEPARATOR . $sIcon;
1180
        if (file_exists($filePath)) {
1181
1182
            $finfo = finfo_open(FILEINFO_MIME_TYPE);
1183
            $mime = finfo_file($finfo, $filePath);
1184
1185
            $aFiles['myfile']['name'][$sKey] = $sIcon;
1186
            $aFiles['myfile']['type'][$sKey] = $mime;
1187
            $aFiles['myfile']['tmp_name'][$sKey] = $this->_sXmlImportPath . DIRECTORY_SEPARATOR . $sIcon;
1188
            $aFiles['myfile']['error'][$sKey] = 0;
1189
            $aFiles['myfile']['size'][$sKey] = filesize($this->_sXmlImportPath . DIRECTORY_SEPARATOR . $sIcon);
1190
            /** @var oxUtilsFile $files */
1191
            $files = oxRegistry::get('oxUtilsFile');
0 ignored issues
show
Bug introduced by
The type App\Backend\Import\oxRegistry 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...
1192
            $aFiletype = explode("@", $sKey);
1193
            $sObjectKey = $aFiletype[1];
1194
            $object->{$sObjectKey} = new oxField('');
1195
            $object = $files->processFiles($object, $aFiles, true, false);
1196
        }
1197
        return $object;
1198
    }
1199
1200
    protected function _workWithCategoryArticles($oStrukturXML)
1201
    {
1202
        $oCategories = array_merge(
1203
            $oStrukturXML->xpath('//' . self::STRUKTUR_WARENGRUPPEN_SELECTOR),
1204
            $oStrukturXML->xpath('//' . self::STRUKTUR_UNTERWARENGRUPPEN_SELECTOR)
1205
        );
1206
        if (empty($oCategories)) {
1207
            $this->_oLog->addError('Oh no dude no categories avalaible.');
1208
            return;
1209
        }
1210
        foreach ($oCategories as $oCategoryXML) {
1211
            $this->_workOnCategoryArticles($oCategoryXML);
1212
        }
1213
    }
1214
1215
    protected function _workOnCategoryArticles($oCategoryXML, $oCategory = null)
1216
    {
1217
        $aAllArticleNumbers = [];
1218
        $oArtikelListe = $oCategoryXML->xpath('Produktliste/Produkt');
1219
        if (!empty($oArtikelListe)) {
1220
            //set articles to categories
1221
            foreach ($oArtikelListe as $oArtikelXML) {
1222
                $artikelArtnum = (string)$oArtikelXML['key'];
1223
                $this->articleProductInStructur[] = $artikelArtnum;
1224
                $aAllArticleNumbers[] = $artikelArtnum;
1225
1226
                //if($artikelArtnum != 55214999) continue;
1227
1228
                $oParentArticle = $this->articleRepository->findOneByArtnum($artikelArtnum);
1229
1230
                //produkte müssen auch in die kategorien...
1231
                $this->_addArticleToCategory($oArtikelXML, $oCategory);
1232
1233
                if ($oParentArticle instanceof Article) {
1234
                    if (array_key_exists($artikelArtnum, $this->onWorkedProducts)) {
1235
                        $cntVariants = count($oArtikelXML->xpath('Artikelliste/Artikel'));
0 ignored issues
show
Unused Code introduced by
The assignment to $cntVariants is dead and can be removed.
Loading history...
1236
                        continue;
1237
                    }
1238
1239
                    $variantVars = [];
1240
                    $variantVars_1 = [];
1241
                    $variantVars_2 = [];
1242
                    $variantVars_3 = [];
1243
                    /** @var SimpleXMLElement[] $oVariants */
1244
                    if ($oVariants = $oArtikelXML->xpath('Artikelliste/Artikel')) {
1245
                        //at first set articles father
1246
1247
                        $this->saveVariantsOnArticle($oArtikelXML, $oVariants);
1248
                        //at second set new variant selector to parent
1249
                        /** @var Article $oFirstVariantArticle */
1250
                        $aVariantAttributes = [];
1251
                        $attrCheck = [];
1252
                        foreach ($oVariants as $variant) {
1253
                            $oVariantArticle = $this->articleRepository->findOneByArtnum(alpha_pim_helper::xmlAttribute($variant, 'key'));
1254
                            foreach ($oVariantArticle->getAttribute() as $key => $attrValue) {
1255
1256
                                $title = $attrValue->getAttr()->getTitle();
1257
                                if (!in_array($title, $attrCheck)) {
1258
                                    $attrCheck[] = $title;
1259
                                    $aVariantAttributes[$attrValue->getId()] = [
1260
                                        'title' => $title,
1261
                                    ];
1262
                                }
1263
                            }
1264
                        }
1265
1266
                        if (!empty($aVariantAttributes)) {
1267
                            foreach ($aVariantAttributes as $key => $oVariantAttribute) {
1268
                                $variantVars[$oVariantAttribute['title']] = [];
1269
                            }
1270
                            foreach ($oVariants as $oVariantXML) {
1271
                                $variantVars = $this->_prepareVariantSelect($oVariantXML, $oArtikelXML, $variantVars);
1272
                            }
1273
1274
                            $sVariantVarname = implode(' | ', array_keys($variantVars));
1275
                        }
1276
1277
                        if (is_null($oParentArticle)) {
1278
                            continue;
1279
                        }
1280
1281
                        $this->_oDb->executeUpdate('update article set varname=? where id=?', [
1282
                            $sVariantVarname ?? '',
1283
                            $oParentArticle->getId(),
1284
                        ]);
1285
                        foreach ($oVariants as $oVariantXML) {
1286
                            $this->_workOnVariant($oVariantXML, $oArtikelXML, $variantVars, $variantVars_1, $variantVars_2, $variantVars_3);
1287
                        }
1288
                        $this->onWorkedProducts[$artikelArtnum] = count($oVariants);
1289
                    }
1290
                }
1291
            }
1292
        }
1293
1294
        $oArtikelListe = $oCategoryXML->xpath('Artikelliste/Artikel');
1295
        $aArticlenumbers = [];
1296
        if (!empty($oArtikelListe)) {
1297
            //set articles to categories
1298
            foreach ($oArtikelListe as $oArtikelXML) {
1299
                $artikelArtnum = (string)$oArtikelXML['key'];
1300
                $aArticlenumbers[] = $artikelArtnum;
1301
                /** @var oxArticle $oParentArticle */
1302
                $oParentArticle = $this->articleRepository->findOneByArtnum($artikelArtnum);
1303
                //produkte müssen auch in die kategorien...
1304
                $this->_addArticleToCategory($oArtikelXML, $oCategory);
1305
                if ($oParentArticle instanceof Article) {
1306
                    $this->articleProductInStructur[] = $artikelArtnum;
1307
                }
1308
            }
1309
1310
        }
1311
1312
        $aAllArticleNumbers = array_merge($aArticlenumbers, $aAllArticleNumbers);
1313
        if (count($aAllArticleNumbers) > 0) {
1314
            $this->_clearOldCategoryAssignments($aAllArticleNumbers, $oCategory->getId());
1315
        }
1316
    }
1317
1318
    protected function _clearOldCategoryAssignments($articlenumbers, $catid)
1319
    {
1320
        $oDb = $this->_oDb;
1321
        $sQuery = "    
1322
            DELETE 
1323
            FROM 
1324
                object2category
1325
            WHERE
1326
                catnid = '" . $catid . "'
1327
                AND objectid NOT IN (
1328
                    SELECT
1329
                        art.id
1330
                    FROM
1331
                        article art
1332
                    WHERE
1333
                        art.artnum IN ('" . implode("','", $articlenumbers) . "')
1334
                )
1335
        ";
1336
        $oDb->executeQuery($sQuery);
1337
1338
    }
1339
1340
    protected function _workWithArticlesToCategories($oStrukturXML)
1341
    {
1342
        $oMainCategories = $oStrukturXML->xpath('//' . self::STRUKTUR_WARENGRUPPEN_SELECTOR);
1343
        if (!empty($oMainCategories)) {
1344
            foreach ($oMainCategories as $oCategoryXML) {
1345
                $this->_workOnArticlesToCategories($oCategoryXML);
1346
            }
1347
        }
1348
        $oMainCategories = $oStrukturXML->xpath('//' . self::STRUKTUR_UNTERWARENGRUPPEN_SELECTOR);
1349
        if (!empty($oMainCategories)) {
1350
            foreach ($oMainCategories as $oCategoryXML) {
1351
                $this->_workOnArticlesToCategories($oCategoryXML);
1352
            }
1353
        }
1354
    }
1355
1356
    protected function _workOnArticlesToCategories($oCategoryXML)
1357
    {
1358
        /** @var SimpleXMLElement $oCategoryXML */
1359
        $sCmiUUID = alpha_pim_helper::xmlAttribute($oCategoryXML, 'uuid');
1360
        $oCategory = oxNew('oxcategory');
0 ignored issues
show
Bug introduced by
The function oxNew was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

1360
        $oCategory = /** @scrutinizer ignore-call */ oxNew('oxcategory');
Loading history...
1361
        if (!$oCategory->loadByCmiUUID($sCmiUUID)) {
1362
            return false;
1363
        }
1364
        if ($oProduktListe = $oCategoryXML->xpath('Produktliste/Produkt')) {
1365
            foreach ($oProduktListe as $oProduktXML) {
1366
                $this->_addArticleToCategory($oProduktXML, $oCategory);
1367
                if ($oArtikelListe = $oProduktXML->xpath('Artikelliste/Artikel')) {
1368
                    foreach ($oArtikelListe as $oArtikelXML) {
1369
                        $this->_addArticleToCategory($oArtikelXML, $oCategory);
1370
                    }
1371
                }
1372
            }
1373
        }
1374
1375
        if ($oEinzelArtikelListe = $oCategoryXML->xpath('Artikelliste/Artikel')) {
1376
            foreach ($oEinzelArtikelListe as $oEinzelArtikelXML) {
1377
                $this->_addArticleToCategory($oEinzelArtikelXML, $oCategory);
1378
            }
1379
        }
1380
1381
        return true;
1382
    }
1383
1384
1385
    /**
1386
     * Frühstückt die kritischen Punkte nach dem Import ab,
1387
     * bei denen z.B. verknüpfte Artikel während des Imports noch nicht existieren
1388
     */
1389
    protected function prepareLongDescs()
1390
    {
1391
        $this->_oLog->debug('Langbeschreibung für Artikel setzen');
1392
        $select = 'select a.OXID, b.OXPARENTID from oxartextends a, oxarticles b WHERE a.OXID = b.OXID';
1393
        $articles = $this->_oDb->getAll($select);
1394
        foreach ($articles as $article) {
1395
            if (!empty($article['OXPARENTID']))
1396
                $this->setArtikelLangebeschreibungFromParent($article);
1397
        }
1398
    }
1399
1400
    /**
1401
     *  Falls Artikel keine Langebeschreibung haben, wird die vom Vaterartikel genommen.
1402
     *
1403
     * @param type $article
1404
     */
1405
    protected function setArtikelLangebeschreibungFromParent($article)
1406
    {
1407
        $select = 'SELECT OXLONGDESC, OXLONGDESC_1, OXLONGDESC_2, OXLONGDESC_3 FROM oxartextends WHERE OXID LIKE ?';
1408
        $descriptions = $this->_oDb->getRow($select, [$article['OXPARENTID']]);
1409
        $sQ = "UPDATE oxartextends a SET OXLONGDESC = ?, OXLONGDESC_1 = ?, OXLONGDESC_2 = ?, OXLONGDESC_3 = ? WHERE OXID LIKE ? ";
1410
        oxDb::getDb()->Execute($sQ, [$descriptions['OXLONGDESC'], $descriptions['OXLONGDESC'], $descriptions['OXLONGDESC_2'], $descriptions['OXLONGDESC_3'], $article['OXID']]);
1411
    }
1412
1413
    protected function cleanupArticleStructure($oStrukturXML = null)
1414
    {
1415
        if (!is_null($oStrukturXML)) {
1416
            $produkte = $oStrukturXML->xpath('//Produktliste/Produkt');
1417
            $artikel = $oStrukturXML->xpath('//Artikelliste/Artikel');
1418
            $cntProdukte = count($produkte);
1419
            $cntArtikel = count($artikel);
1420
            if ($cntProdukte > 0 && $cntArtikel > 0) {
1421
                $this->_oDb->execute('DROP TABLE alpha_pim_struktur');
1422
                $this->_oDb->execute('CREATE TABLE alpha_pim_struktur ( artikelNr varchar(255) not null , primary key (artikelNr))');
1423
                foreach ($produkte as $produkt) {
1424
                    $this->_oDb->execute('replace into alpha_pim_struktur values(?)', [$produkt['key']]);
1425
                }
1426
                foreach ($artikel as $art) {
1427
                    $this->_oDb->execute('replace into alpha_pim_struktur values(?)', [$art['key']]);
1428
                }
1429
                $this->_oDb->execute('update oxarticles oa set oa.oxactive = 0 where oa.oxartnum not in (select artikelNr from alpha_pim_struktur)');
1430
            }
1431
        }
1432
    }
1433
1434
    protected function _getAllShops()
1435
    {
1436
        $oDb = oxDb::getDb(oxDb::FETCH_MODE_ASSOC);
1437
        $sQuery = "
1438
            SELECT
1439
                oxid as id,
1440
                alpha_country_alias as country
1441
            FROM
1442
              oxshops
1443
            WHERE 
1444
              1
1445
        ";
1446
        return $oDb->getAll($sQuery);
1447
    }
1448
1449
1450
    /**
1451
     * Moves current seo record to seo history table
1452
     *
1453
     * @param string $sId object id
1454
     * @param int $iShopId active shop id
1455
     * @param int $iLang object language
1456
     * @param string $sType object type (if you pass real object - type is not necessary)
1457
     * @param string $sNewId new object id, mostly used for static url updates (optional)
1458
     */
1459
    protected function _copyToHistory($sId, $iShopId, $iLang, $sType = null, $sNewId = null)
1460
    {
1461
        $oDb = oxDb::getDb();
1462
        $sObjectid = $sNewId ? $oDb->quote($sNewId) : 'oxobjectid';
1463
        $sType = $sType ? "oxtype =" . $oDb->quote($sType) . " and" : '';
1464
        $iLang = (int)$iLang;
1465
1466
        // moving
1467
        $sSub = "select $sObjectid, MD5( LOWER( oxseourl ) ), oxshopid, oxlang, now() from oxseo
1468
                 where {$sType} oxobjectid = " . $oDb->quote($sId) . " and oxshopid = " . $oDb->quote($iShopId) . " and
1469
                 oxlang = {$iLang} and oxexpired = '1'";
1470
        $sQ = "replace oxseohistory ( oxobjectid, oxident, oxshopid, oxlang, oxinsert ) {$sSub}";
1471
        $oDb->execute($sQ);
1472
    }
1473
1474
    /**
1475
     * @param $aAttributes
1476
     * @param $oMerkmalXML
1477
     * @param $sKey
1478
     *
1479
     * @return array
1480
     */
1481
    protected function declareOxidAttribute($aAttributes, $oMerkmalXML, $sKey)
1482
    {
1483
//a simple attribute
1484
        if (isset($oMerkmalXML->Wert)) {
1485
            //non multilingual
1486
            if (!empty($oMerkmalXML->Wert)) {
1487
                foreach ($this->_aLanguages as $oxLang) {
1488
                    $sTranslatedValue = alpha_pim_helper::clearFromPIMTags((string)$oMerkmalXML->Wert);
1489
                    if ($oxLang->abbr == 'de') {
1490
                        $sField = "value";
1491
                    } else {
1492
                        $sField = sprintf("value_%d", $oxLang->id);
1493
                    }
1494
                    $aAttributes[$sKey][$sField] = $sTranslatedValue;
1495
                }
1496
1497
            }
1498
1499
        } elseif (isset($oMerkmalXML->Wert_xx)) {
1500
            $aAttributes[$sKey] = [];
1501
            //multilingual values
1502
            foreach ($this->_aLanguages as $oxLang) {
1503
                if ($oxLang->abbr == 'de') {
1504
                    $sTranslatedValue = alpha_pim_helper::clearFromPIMTags((string)$oMerkmalXML->Wert_xx);
1505
                    $sField = "value";
1506
                } else {
1507
                    $sWertPropertyName = sprintf('Wert_%s', $oxLang->abbr);
1508
                    if (isset($oMerkmalXML->{$sWertPropertyName})) {
1509
                        $sTranslatedValue = alpha_pim_helper::clearFromPIMTags((string)$oMerkmalXML->{$sWertPropertyName});
1510
                        $sField = sprintf("value_%d", $oxLang->id);
1511
                    } else {
1512
                        //go forward we are strict here! ;-)
1513
                        continue;
1514
                    }
1515
                }
1516
                $aAttributes[$sKey][$sField] = $sTranslatedValue;
1517
            }
1518
1519
        }
1520
        return $aAttributes;
1521
    }
1522
}
1523