/
ProductController.php
908 lines (788 loc) · 30.7 KB
/
ProductController.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
<?php
namespace Pixelant\PxaProductManager\Controller;
use Pixelant\PxaProductManager\Domain\Model\Attribute;
use Pixelant\PxaProductManager\Domain\Model\AttributeSet;
use Pixelant\PxaProductManager\Domain\Model\DTO\Demand;
use Pixelant\PxaProductManager\Domain\Model\Order;
use Pixelant\PxaProductManager\Domain\Model\OrderConfiguration;
use Pixelant\PxaProductManager\Domain\Model\OrderFormField;
use Pixelant\PxaProductManager\Domain\Model\Product;
use Pixelant\PxaProductManager\Service\OrderMailService;
use Pixelant\PxaProductManager\Utility\ConfigurationUtility;
use Pixelant\PxaProductManager\Utility\MainUtility;
use Pixelant\PxaProductManager\Utility\ProductUtility;
use Pixelant\PxaProductManager\Validation\ValidatorResolver;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Core\Utility\StringUtility;
use TYPO3\CMS\Extbase\Mvc\Exception\NoSuchArgumentException;
use TYPO3\CMS\Extbase\Persistence\QueryInterface;
use TYPO3\CMS\Extbase\Persistence\QueryResultInterface;
use TYPO3\CMS\Extbase\SignalSlot\Dispatcher;
/***************************************************************
* Copyright notice
*
* (c) 2014
* All rights reserved
*
* This script is part of the TYPO3 project. The TYPO3 project is
* free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* The GNU General Public License can be found at
* http://www.gnu.org/copyleft/gpl.html.
*
* This script is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* This copyright notice MUST APPEAR in all copies of the script!
***************************************************************/
/**
*
*
* @package pxa_product_manager
* @license http://www.gnu.org/licenses/gpl.html GNU General Public License, version 3 or later
*
*/
class ProductController extends AbstractController
{
/**
* Add JS labels for each action
*/
public function initializeAction()
{
$this->getFrontendLabels();
// Set the pagePid using the flexform -> typoscript -> 0 priority
$this->settings['pagePid'] = $this->settings['pagePid'] ?: ConfigurationUtility::getSettingsByPath('pagePid');
}
/**
* action list
*
* @return void
*/
public function listAction()
{
$category = $this->determinateCategory(
MainUtility::getActiveCategoryFromRequest()
);
if ($category) {
/** @var QueryResultInterface $subCategories */
$subCategories = $this->categoryRepository->findByParent(
$category,
$this->getOrderingsForCategories()
);
if ($subCategories->count() === 0 || $this->settings['showCategoriesWithProducts']) {
$this->settings['demandCategories'] = [$category->getUid()];
$demand = $this->createDemandFromSettings($this->settings);
$products = $this->productRepository->findDemanded($demand);
}
$this->view->assignMultiple([
'subCategories' => $subCategories,
'category' => $category
]);
}
// add navigation if enabled in list view
if ($this->settings['showNavigationListView']) {
$this->view->assign('treeData', $this->getNavigationTree());
}
$this->view->assign('products', $products ?? []);
}
/**
* lazy view action
*
* @return void
*/
public function lazyListAction()
{
$this->settings['demandCategories'] = $this->getDemandCategories(
GeneralUtility::intExplode(',', $this->settings['allowedCategories'], true),
GeneralUtility::intExplode(',', $this->settings['excludeCategories'], true)
);
$demand = $this->createDemandFromSettings($this->settings);
if (!empty($this->settings['filters'])) {
$filtersUids = GeneralUtility::intExplode(',', $this->settings['filters'], true);
$filters = $this->sortQueryResultsByUidList(
$this->filterRepository->findByUidList(
$filtersUids
),
$filtersUids
);
if ((int)$this->settings['hideFilterOptionsNoResult'] === 1) {
// @codingStandardsIgnoreStart
list($availableOptions, $availableCategories, $productsNoLimitCount) = $this->getAvailableFilterOptionsAndCountProductFromDemand(
$demand
);
// @codingStandardsIgnoreEnd
}
}
$countResults = $productsNoLimitCount ?? $this->countDemanded($demand);
$limit = (int)$this->settings['limit'];
if ($uid = (int)$this->configurationManager->getContentObject()->data['uid']) {
$storagePid = ProductUtility::getStoragePidForPlugin($uid);
}
$this->view->assignMultiple([
'demandCategories' => implode(',', $this->settings['demandCategories']),
'ajaxUrl' => $this->getLazyLoadingUrl(),
'storagePid' => $storagePid ?? '',
'lazyLoadingStop' => ($limit === 0 || $limit >= $countResults) ? 1 : 0,
'filters' => $filters ?? [],
'availableOptionsList' => implode(',', $availableOptions ?? []),
'availableCategoriesList' => implode(',', $availableCategories ?? []),
]);
}
/**
* action show
*
* @param \Pixelant\PxaProductManager\Domain\Model\Product $product
* @return void
*/
public function showAction(Product $product = null)
{
// No product found handling
if ($product !== null) {
// save as latest visited
MainUtility::addValueToListCookie(
ProductUtility::LATEST_VISITED_COOKIE_NAME,
$product->getUid(),
((int)$this->settings['latestVisitedProductsLimit'] + 1)
);
// check if categories have a custom single view template set
if ($product->getCategories()->count() > 0) {
/**
* @TODO how to define which template to use if multiple categories
*/
foreach ($product->getCategories() as $category) {
if (!empty($category->getSingleViewTemplate())) {
/** @noinspection PhpUndefinedMethodInspection */
$this->view->setTemplate($category->getSingleViewTemplate());
}
}
}
// add navigation if enabled in list view
if ($this->settings['showNavigationListView']
&& !$this->settings['hideNavigationListViewOnDetailMode']
) {
$this->view->assign('treeData', $this->getNavigationTree());
}
// add latest visited
if ($this->settings['showLatestVisitedProducts']) {
$this->view->assign(
'latestVisitedProducts',
$this->getProductsFromCookieList(
ProductUtility::LATEST_VISITED_COOKIE_NAME,
$product->getUid(),
(int)$this->settings['latestVisitedProductsLimit']
)
);
}
// if product have more than one category - build canonical url to main (first) category
if ((int)$this->settings['disableProductCanonicalUrl'] === 0
&& $product->getCategories()->count() > 1
) {
$this->buildProductCanonicalUrl($product);
}
$this->view->assignMultiple([
'product' => $product,
'category' => MainUtility::getActiveCategoryFromRequest()
]);
} else {
$this->handleNoProductFoundError();
}
}
/**
* Wish list cart
*/
public function wishListCartAction()
{
// Nothing to do. Products are counted by JS to make action cacheable
}
/**
* Wish list of products
*
* @param bool $sendOrder
* @throws \TYPO3\CMS\Extbase\Mvc\Exception\StopActionException
* @throws \TYPO3\CMS\Extbase\Mvc\Exception\UnsupportedRequestTypeException
*/
public function wishListAction(bool $sendOrder = false)
{
// Select the checkout system to use
$checkoutToUse = $this->settings['wishList']['checkoutSystem']
?: ConfigurationUtility::getExtManagerConfigurationByPath('checkoutSystem') ?: 'default';
$checkOutSystems = ConfigurationUtility::getCheckoutSystems();
$checkout = $checkOutSystems[$checkoutToUse] ?: $checkOutSystems['default'];
// Add after checkout system selected slot
$signalSlotDispatcher = GeneralUtility::makeInstance(Dispatcher::class);
$signalSlotDispatcher->dispatch(__CLASS__, 'AfterCheckoutSystemSelected', [&$checkout, $this]);
// If order form enabled
if ($this->isOrderFormAllowed()) {
/** @var OrderConfiguration $orderConfiguration */
$orderConfiguration = $this->orderConfigurationRepository->findByUid(
(int)$this->settings['orderFormConfiguration']
);
$this->view->assign('orderConfiguration', $orderConfiguration);
if ($sendOrder && $orderConfiguration !== null) {
try {
$orderProducts = $this->request->getArgument('orderProducts');
$values = $this->request->getArgument('orderFields');
if ($this->validateOrderFields($orderConfiguration, $values)) {
$order = $this->createAndSaveOrder($orderConfiguration, $orderProducts);
$this->sendOrderEmail($order, $orderConfiguration);
$this->redirect('finishOrder');
}
} catch (NoSuchArgumentException $exception) {
// orderProducts and orderFields are required to send email
}
}
}
if ($this->request->hasArgument('orderProducts')) {
$orderState = $this->request->getArgument('orderProducts');
} else {
$orderState = ProductUtility::getOrderState();
}
$this->view->assignMultiple([
'checkout' => $checkout,
'products' => $this->getProductsFromCookieList(ProductUtility::WISH_LIST_COOKIE_NAME),
'orderProducts' => $orderState ?? [],
'sendOrder' => $sendOrder
]);
}
/**
* Finish order text
* Show some successful texts
*/
public function finishOrderAction()
{
ProductUtility::cleanOngoingOrderInfo();
}
/**
* Compare list cart
*/
public function compareListCartAction()
{
// Nothing to do. Products are counted by JS to make action cacheable
}
/**
* Compare list of products
*/
public function comparePreViewAction()
{
$compareList = MainUtility::getTSFE()->fe_user->getKey('ses', ProductUtility::COMPARE_LIST_SESSION_NAME)
?? [];
$this->view->assign(
'products',
$this->getProductByUidsList($compareList)
);
}
/**
* Create compare view for products
*/
public function compareViewAction()
{
$compareList = MainUtility::getTSFE()->fe_user->getKey('ses', ProductUtility::COMPARE_LIST_SESSION_NAME)
?? [];
$products = $this->getProductByUidsList($compareList);
$productAttributeSets = [];
/** @var Product $product */
foreach ($products as $product) {
/** @var AttributeSet $attributesGroupedBySet */
foreach ($product->getAttributesGroupedBySets() as $attributesGroupedBySet) {
if (!array_key_exists($attributesGroupedBySet->getUid(), $productAttributeSets)) {
$productAttributeSets[$attributesGroupedBySet->getUid()] = [
'attributeSet' => $attributesGroupedBySet
];
}
}
}
foreach ($productAttributeSets as &$attributeSet) {
$attributeSet['attributesListDiff'] = $this->generateAttributesDiffDataForProducts(
$products,
$attributeSet['attributeSet']
);
}
$this->view
->assign(
'products',
$this->getProductByUidsList($compareList)
)
->assign(
'diffData',
$productAttributeSets
);
}
/**
* promotion list action
*
* @return void
*/
public function promotionListAction()
{
$this->settings['demandCategories'] = $this->getDemandCategories(
GeneralUtility::intExplode(',', $this->settings['allowedCategories'], true)
);
$demand = $this->createDemandFromSettings($this->settings);
$products = $this->productRepository->findDemanded($demand);
$this->view->assign('products', $products);
}
/**
* No found page
*/
public function notFoundAction()
{
}
/**
* action grouped list
*
* @return void
*/
public function groupedListAction()
{
$groupedList = [];
$excludeCategories = GeneralUtility::intExplode(',', $this->settings['excludeCategories'], true);
$category = $this->determinateCategory(
MainUtility::getActiveCategoryFromRequest()
);
if ($category !== null) {
// if showCategoriesWithProducts, display products in just this category, not recursive
if ($this->settings['showCategoriesWithProducts']) {
$this->settings['demandCategories'] = [$category->getUid()];
$demand = $this->createDemandFromSettings($this->settings);
$products = $this->productRepository->findDemanded($demand);
}
/** @var QueryResultInterface $subCategories */
$subCategories = $this->categoryRepository->findByParent(
$category,
$this->getOrderingsForCategories()
);
if ($subCategories->count() > 0) {
$groupedListIndex = 0;
$duplicateCategories = [];
foreach ($subCategories as $index => $subCategory) {
$subCategoryUid = $subCategory->getUid();
if (in_array($subCategoryUid, $excludeCategories, true)) {
// excluded category, unset
array_push($duplicateCategories, $index);
} else {
$subCategoryCategories = $this->categoryRepository->findByParent(
$subCategory
);
// if category doesn't have any sub categories, fetch products
if ($subCategoryCategories->count() === 0) {
$this->settings['demandCategories'] = [$subCategoryUid];
$demand = $this->createDemandFromSettings($this->settings);
$subCategoryProducts = $this->productRepository->findDemanded($demand);
if ($subCategoryProducts->count() > 0) {
// if category has products it will be displayed differently,
// remove from "browse" categories
array_push($duplicateCategories, $index);
// add to grouped list instead
$groupedList[$groupedListIndex]['category'] = $subCategory;
$groupedList[$groupedListIndex]['products'] = $subCategoryProducts;
$groupedList[$groupedListIndex]['categoryAttributes'] = 0;
if ($subCategoryProducts->count() > 0) {
$groupedList[$groupedListIndex]['categoryAttributes'] =
$subCategoryProducts->current()->getAttributes()->count();
}
$groupedListIndex++;
}
}
}
}
// remove dublicate categories (added to groupedList)
if (!empty($duplicateCategories)) {
foreach ($duplicateCategories as $index) {
unset($subCategories[$index]);
}
}
}
$this->view->assignMultiple([
'category' => $category,
'products' => $products ?? [],
'subCategories' => $subCategories,
]);
}
$this->view->assign('groupedList', $groupedList ?? []);
}
/**
* List of custom products
*
* @return void
*/
public function customProductsListAction()
{
$mode = $this->settings['customProductsList']['mode'];
$products = [];
// Products mode
if ($mode === 'products') {
$productsList = GeneralUtility::trimExplode(
',',
$this->settings['customProductsList']['productsToShow'],
true
);
$products = $this->getProductByUidsList($productsList);
}
// Category mode
if ($mode === 'category') {
$categories = GeneralUtility::trimExplode(
',',
$this->settings['customProductsList']['productsCategories'],
true
);
// Get products
$products = $this->productRepository->findProductsByCategories(
$categories,
false,
['tstamp' => QueryInterface::ORDER_DESCENDING],
'or',
(int)$this->settings['limit']
);
}
$this->view->assign('products', $products);
}
/**
* Check if order form is allowed
*
* @return bool
*/
protected function isOrderFormAllowed(): bool
{
$requireLogin = (int)$this->settings['orderFormRequireLogin'] === 1;
return !$requireLogin || MainUtility::isFrontendLogin();
}
/**
* Send emails with order
*
* @param Order $order
* @param OrderConfiguration $orderConfiguration
* @return void
*/
protected function sendOrderEmail(Order $order, OrderConfiguration $orderConfiguration)
{
$adminTemplate = $this->settings['wishList']['orderForm']['adminEmailTemplatePath'] ?? '';
$userTemplate = $this->settings['wishList']['orderForm']['userEmailTemplatePath'] ?? '';
/** @var OrderMailService $orderMailService */
$orderMailService = GeneralUtility::makeInstance(OrderMailService::class);
$orderMailService
->setSenderName($this->settings['email']['senderName'])
->setSenderEmail($this->settings['email']['senderEmail']);
// Send email to admins
if (!empty($orderConfiguration->getAdminEmails())) {
$orderMailService
->generateMailBody($adminTemplate, $order)
->setSubject($this->translate('fe.adminEmail.orderForm.subject'))
->setReceivers($orderConfiguration->getAdminEmailsArray())
->send();
}
// Send email to user if enabled
if ($orderConfiguration->isEnabledEmailToUser()) {
/** @var OrderFormField $formField */
foreach ($orderConfiguration->getFormFields() as $formField) {
if ($formField->isUserEmailField()) {
$email = $formField->getValue();
}
}
if (!empty($email)) {
$orderMailService
->generateMailBody($userTemplate, $order)
->setSubject($this->translate('fe.userEmail.orderForm.subject'))
->setReceivers([$email])
->send();
}
}
}
/**
* Save order
*
* @param OrderConfiguration $orderConfiguration
* @param array $orderProducts
* @return Order
*/
protected function createAndSaveOrder(OrderConfiguration $orderConfiguration, array $orderProducts): Order
{
$processedOrderProducts = [];
foreach ($orderProducts as $productUid => $productQuantity) {
$productUid = (int)$productUid;
$productQuantity = (int)$productQuantity;
if ($productUid && $productQuantity) {
$processedOrderProducts[$productUid] = $productQuantity;
}
}
unset($orderProducts);
$orderFields = [];
/** @var OrderFormField $formField */
foreach ($orderConfiguration->getFormFields() as $formField) {
$orderFields[$formField->getUid()] = [
'value' => $formField->getValueAsText(),
'type' => $formField->getType()
];
}
$products = $this->productRepository->findProductsByUids(array_keys($processedOrderProducts));
$order = $this->objectManager->get(Order::class);
$order->setOrderFields($orderFields);
$order->setProductsQuantity($processedOrderProducts);
/** @var Product $product */
foreach ($products as $product) {
$order->addProduct($product);
}
if ($orderConfiguration->getFrontendUser() !== null) {
$order->setFeUser($orderConfiguration->getFrontendUser());
}
$this->orderRepository->add($order);
return $order;
}
/**
* Return false if fields fail validation. Also will add error messages to fields configuration
*
* @param OrderConfiguration $orderConfiguration
* @param array $values
* @return bool
*/
protected function validateOrderFields(OrderConfiguration $orderConfiguration, array $values): bool
{
$isValid = true;
$validationResolver = GeneralUtility::makeInstance(ValidatorResolver::class);
/** @var OrderFormField $field */
foreach ($orderConfiguration->getFormFields() as $field) {
if ($field->isStatic()) {
continue;
}
$value = trim($values[$field->getUid()] ?? '');
$field->setValue($value);
foreach ($field->getValidationRulesArray() as $validationRule) {
$validator = $validationResolver->createValidator($validationRule);
if (!$validator->validate($value)) {
$isValid = false;
$field->addError($validator->getErrorMessage());
}
}
}
return $isValid;
}
/**
* Generate difference data for all products and attribute sets
*
* @param array $products
* @param AttributeSet $attributeSet
* @return array
*/
protected function generateAttributesDiffDataForProducts(array $products, AttributeSet $attributeSet)
{
$diffData = [];
/** @var Attribute $attribute */
foreach ($attributeSet->getAttributes() as $attribute) {
if (!$attribute->isShowInCompare()
|| GeneralUtility::inList(
$this->settings['ignoreAttributeTypesInCompareView'],
$attribute->getType()
)
) {
continue;
}
$diffData[$attribute->getUid()] = $this->getDiffValuesForProductsSingleAttribute(
$products,
$attribute
);
}
return $diffData;
}
/**
* Get difference between products attribute
*
* @param array $products
* @param Attribute $attribute
* @return array
*/
protected function getDiffValuesForProductsSingleAttribute(array $products, Attribute $attribute)
{
$diffData = [
'label' => $attribute->getLabel() ?: $attribute->getName()
];
$attributesList = [];
$tempValues = [];
/** @var Product $product */
foreach ($products as $product) {
$singleAttribute = '';
/** @var Attribute $pAttribute */
foreach ($product->getAttributes() as $pAttribute) {
if ($pAttribute->getUid() === $attribute->getUid()) {
$singleAttribute = $pAttribute;
}
}
$attributesList[] = $singleAttribute;
if (is_object($singleAttribute)) {
switch ($singleAttribute->getType()) {
case Attribute::ATTRIBUTE_TYPE_DROPDOWN:
case Attribute::ATTRIBUTE_TYPE_MULTISELECT:
$tempValues[] = implode(',', $singleAttribute->getValue());
break;
case Attribute::ATTRIBUTE_TYPE_DATETIME:
if (is_object($singleAttribute->getValue())) {
/** @var \DateTime $date */
$date = $singleAttribute->getValue();
$tempValues[] = $date->format('%d-%m-%Y');
} else {
$tempValues[] = '';
}
break;
default:
$tempValues[] = $singleAttribute->getValue();
}
} else {
$tempValues[] = '';
}
}
$diffData['attributesList'] = $attributesList;
$diffData['isDifferent'] = (count(array_unique($tempValues)) !== 1);
return $diffData;
}
/**
* Create demand object
*
* @param array $settings
* @return Demand
*/
protected function createDemandFromSettings(array $settings)
{
/** @var Demand $demand */
$demand = GeneralUtility::makeInstance(Demand::class);
if (!empty($settings['demandCategories'])) {
$demand->setCategories($settings['demandCategories']);
}
if (!empty($settings['allowedCategoriesMode'])) {
$demand->setCategoryConjunction($settings['allowedCategoriesMode']);
}
if ($limit = (int)$settings['limit']) {
$demand->setLimit($limit);
}
if ($offSet = (int)$settings['offSet']) {
$demand->setOffSet($offSet);
}
if (is_array($settings['filters'])) {
$demand->setFilters($settings['filters']);
}
if (!empty($settings['includeDiscontinued'])) {
$demand->setIncludeDiscontinued((bool)$settings['includeDiscontinued']);
}
// set orderings
if ($settings['orderProductBy']) {
$demand->setOrderBy($settings['orderProductBy']);
}
if ($settings['orderProductDirection']) {
$demand->setOrderDirection($settings['orderProductDirection']);
}
if ($settings['orderByAllowed']) {
$demand->setOrderByAllowed($settings['orderByAllowed']);
}
return $demand;
}
/**
* Count results for demand
*
* @param Demand $demand
* @return int
*/
protected function countDemanded(Demand $demand)
{
// Count all products
// reset limit
$demand = clone ($demand);
$demand->setOffSet(0);
$demand->setLimit(0);
return $this->productRepository->countByDemand($demand);
}
/**
* Url for Ajax lazy loading
*
* @return string
*/
protected function getLazyLoadingUrl()
{
$uri = $this->controllerContext->getUriBuilder();
$uri->reset()
->setTargetPageUid(MainUtility::getTSFE()->id)
->setTargetPageType($this->settings['lazyLoading']['pageType'])
->setCreateAbsoluteUri(true);
return $uri->buildFrontendUri();
}
/**
* Add canonical url for product single view
* Make sure any other plugin adding it
*
* @param Product $product
*/
protected function buildProductCanonicalUrl(Product $product)
{
$arguments = MainUtility::buildLinksArguments($product, $product->getFirstCategory());
$uriBuilder = $this->controllerContext->getUriBuilder();
$uriBuilder
->reset()
->setTargetPageUid($this->settings['pageUid'] ?: MainUtility::getTSFE()->id)
->setArguments($arguments)
->setCreateAbsoluteUri(true);
$url = $uriBuilder->buildFrontendUri();
// add only absolute links
if (!empty($url) && StringUtility::beginsWith($url, 'http')) {
/** @noinspection PhpUndefinedMethodInspection */
$this->response->addAdditionalHeaderData(
'<link rel="canonical" href="' . $url . '">'
);
}
}
/**
* Get list of products by cookie list
*
* @param string $cookieName
* @param int $excludeProduct
* @param int $limit
* @return array
*/
protected function getProductsFromCookieList($cookieName, int $excludeProduct = 0, int $limit = 0)
{
$productUids = array_key_exists($cookieName, $_COOKIE)
? GeneralUtility::intExplode(',', $_COOKIE[$cookieName], true)
: [];
$products = $this->getProductByUidsList($productUids, $excludeProduct);
if ($limit && count($products) > $limit) {
$products = array_slice($products, 0, $limit);
}
return $products;
}
/**
* Get product by uids list in same order
*
* @param array $productsUids
* @param int $excludeProduct
* @return array
*/
protected function getProductByUidsList(array $productsUids, int $excludeProduct = 0)
{
// remove product from list
if ($excludeProduct && in_array($excludeProduct, $productsUids)) {
$keys = array_keys($productsUids, $excludeProduct);
foreach ($keys as $key) {
unset($productsUids[$key]);
}
}
$products = $this->productRepository->findProductsByUids($productsUids);
if (is_object($products)) {
$products = $this->sortQueryResultsByUidList($products, $productsUids);
}
return $products;
}
/**
* Error handling if no product entry is found
*
* @return void
*/
protected function handleNoProductFoundError()
{
// If configured, show custom message instead of standard 404
if ((int)$this->settings['enableMessageInsteadOfPage404'] !== 0) {
$this->forward('notFound');
} else {
MainUtility::getTSFE()->pageNotFoundAndExit('No product entry found.');
}
}
}