-
Notifications
You must be signed in to change notification settings - Fork 121
Expand file tree
/
Copy pathPopulateCartTask.php
More file actions
52 lines (44 loc) · 1.78 KB
/
PopulateCartTask.php
File metadata and controls
52 lines (44 loc) · 1.78 KB
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
<?php
declare(strict_types=1);
namespace SilverShop\Tasks;
use SilverShop\Cart\ShoppingCart;
use SilverShop\Page\Product;
use SilverStripe\Dev\BuildTask;
use SilverStripe\PolyExecution\PolyOutput;
use SilverStripe\Security\Security;
use SilverStripe\Versioned\Versioned;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
/**
* Add 5 random Live products to cart, with random quantities between 1 and 10.
*/
class PopulateCartTask extends BuildTask
{
protected string $title = 'Populate Cart';
protected static string $description = 'Add 5 random Live products or variations to cart, with random quantities between 1 and 10.';
protected function execute(InputInterface $input, PolyOutput $output): int
{
$shoppingCart = ShoppingCart::singleton();
$count = 5;
$allIds = Versioned::get_by_stage(Product::class, Versioned::LIVE)->column('ID');
shuffle($allIds);
$selectedIds = array_slice($allIds, 0, $count);
$products = Product::get()->filter('ID', $selectedIds);
if ($products->exists()) {
foreach ($products as $product) {
$variations = $product->Variations();
if ($variations->exists()) {
$variationIds = $variations->column('ID');
shuffle($variationIds);
$product = $variations->filter('ID', $variationIds[0])->first();
}
$quantity = rand(1, 5);
if ($product->canPurchase(Security::getCurrentUser(), $quantity)) {
$shoppingCart->add($product, $quantity);
}
}
}
$output->writeln('Cart populated with ' . $count . ' random products.');
return Command::SUCCESS;
}
}