85 lines
2.9 KiB
PHP
85 lines
2.9 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace Krzysiej\RyobiCrawler\Command;
|
|
|
|
use Symfony\Component\Console\Helper\ProgressBar;
|
|
use Symfony\Component\HttpFoundation\Request;
|
|
use Illuminate\Database\Capsule\Manager as Capsule;
|
|
use Krzysiej\RyobiCrawler\Models\Product;
|
|
use Symfony\Component\Cache\Adapter\FilesystemAdapter;
|
|
use Symfony\Component\Console\Attribute\AsCommand;
|
|
use Symfony\Component\Console\Command\Command;
|
|
use Symfony\Component\Console\Input\InputInterface;
|
|
use Symfony\Component\Console\Output\OutputInterface;
|
|
use Symfony\Component\HttpFoundation\RequestStack;
|
|
use Twig\Environment;
|
|
|
|
#[AsCommand(name: 'app:cache:warm-twig', description: 'Warmup twig cache')]
|
|
class CacheWarmCommand extends Command
|
|
{
|
|
public function __construct(
|
|
private Environment $twig,
|
|
private RequestStack $requestStack,
|
|
private FilesystemAdapter $cache,
|
|
) {
|
|
parent::__construct();
|
|
}
|
|
|
|
public function execute(InputInterface $input, OutputInterface $output): int
|
|
{
|
|
$this->cache->clear();
|
|
|
|
$capsule = new Capsule;
|
|
$capsule->addConnection([
|
|
'driver' => 'sqlite',
|
|
'database' => __DIR__ . '/../../database.sqlite',
|
|
]);
|
|
$capsule->setAsGlobal();
|
|
$capsule->bootEloquent();
|
|
|
|
$progress = new ProgressBar($output);
|
|
$progress->start();
|
|
$products = Product::with([
|
|
'price' => fn($query) => $query->orderByDesc('created_at'),
|
|
'stock' => fn($query) => $query->orderByDesc('created_at'),
|
|
])->get();
|
|
$progress->setMaxSteps(count($products));
|
|
|
|
$request = Request::create('/cache-warm');
|
|
$this->requestStack->push($request);
|
|
|
|
foreach ($products as $product) {
|
|
$priceList = $product->price()->pluck('price');
|
|
$stockList = $product->stock()->pluck('stock');
|
|
$priceDates = $product->price()->pluck('created_at')->map(fn($date) => $date->format('Y-m-d'))->toArray();
|
|
$stockDates = $product->stock()->pluck('created_at')->map(fn($date) => $date->format('Y-m-d'))->toArray();
|
|
$this->twig->render('product.html.twig', [
|
|
'product' => $product,
|
|
'price_list' => $this->prepareChartData($priceDates, $priceList),
|
|
'stock_list' => $this->prepareChartData($stockDates, $stockList),
|
|
'price_dates' => implode("','", $priceDates),
|
|
]);
|
|
$progress->advance();
|
|
}
|
|
|
|
$progress->finish();
|
|
$output->writeln('');
|
|
$output->writeln('DONE');
|
|
|
|
return Command::SUCCESS;
|
|
}
|
|
|
|
private function prepareChartData($set1, $set2): string
|
|
{
|
|
$data = [];
|
|
foreach ($set1 as $key => $value) {
|
|
$data[] = ['x' => $value, 'y' => $set2[$key]];
|
|
}
|
|
$stringData = json_encode($data);
|
|
|
|
return str_replace(['"x"', '"y"'], ['x', 'y'], $stringData);
|
|
}
|
|
}
|