4 Commits

Author SHA1 Message Date
Krzysztof Płaczek
2e4c79c87a Merge branch 'master' into feature/order-columns
# Conflicts:
#	Dockerfile
#	templates/productList.html.twig
2025-03-17 12:52:07 +01:00
Krzysztof Płaczek
c947e470af Increase php memory limit 2025-02-04 20:41:58 +01:00
Krzysztof Płaczek
8eeba225ed Merge branch 'master' of 192.168.0.129:krzysiej/ryobi-crawler into feature/order-columns 2025-01-28 09:15:49 +01:00
Krzysztof Płaczek
9b6bcd22be Start working on sorting products by different columns. 2025-01-27 12:10:15 +01:00
22 changed files with 492 additions and 627 deletions

2
.gitignore vendored
View File

@@ -1,5 +1,5 @@
/vendor/ /vendor/
.idea .idea
*.sqlite database.sqlite
var/cache/ var/cache/
.env.local .env.local

View File

@@ -1,8 +1,8 @@
FROM php:8.3-cli FROM php:8.3-cli
WORKDIR /usr/src/app WORKDIR /usr/src/app
ENV PHP_MEMORY_LIMIT=1500M ENV PHP_MEMORY_LIMIT=512M
RUN echo "memory_limit=1500M" > /usr/local/etc/php/conf.d/memory-limit.ini RUN echo "memory_limit=512M" > /usr/local/etc/php/conf.d/memory-limit.ini
RUN apt-get update && apt-get install -y \ RUN apt-get update && apt-get install -y \
git \ git \
unzip \ unzip \

View File

@@ -17,17 +17,10 @@
3. Refresh cache on production by removing cache directory: `rm -rf var/cache` 3. Refresh cache on production by removing cache directory: `rm -rf var/cache`
4. Start and build image in one go with command: `docker compose up -d --build --force-recreate` 4. Start and build image in one go with command: `docker compose up -d --build --force-recreate`
## Bonus
### Install composer package
1. Run `bin/composer require vendor/package-name`
## Running Cron ## Running Cron
For now only way of running `app:scrape` command on schedule is to use host crontab. For now only way of running `app:scrape` command on schedule is to use host crontab.
1. Run `crontab -e` command to edit a host crontab job file 1. Run `crontab -e` command to edit host crontab job file
2. Add a new line with e.g. line like this `0 1 * * * cd /var/project/directory/ && docker compose exec php-app php console.php app:scrape` 2. Add a new line with e.g. line like this `0 1 * * * cd /var/project/directory/ && docker compose exec php-app php console.php app:scrape`
3. Save and exit file editor. Cron will execute `app:scrape` once per day. 3. Save and exit file editor. Cron will execute `app:scrape` once per day.

View File

@@ -1,2 +0,0 @@
#!/usr/bin/env bash
bin/cli rm -rf var/cache

View File

@@ -1,3 +0,0 @@
#!/usr/bin/env bash
[ -z "$1" ] && echo "Please specify a Composer command (ex. install)" && exit
bin/cli composer "$@"

View File

@@ -11,9 +11,7 @@
"symfony/twig-bundle": "^7.1", "symfony/twig-bundle": "^7.1",
"symfony/dotenv": "^7.1", "symfony/dotenv": "^7.1",
"twig/intl-extra": "^3.13", "twig/intl-extra": "^3.13",
"twig/extra-bundle": "^3.13", "twig/extra-bundle": "^3.13"
"symfony/cache": "^7.2",
"twig/cache-extra": "^3.21"
}, },
"autoload": { "autoload": {
"psr-4": { "psr-4": {

803
composer.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -2,16 +2,18 @@
include_once 'vendor/autoload.php'; include_once 'vendor/autoload.php';
use Krzysiej\RyobiCrawler\Kernel; use Krzysiej\RyobiCrawler\Command\Migrate;
use Symfony\Bundle\FrameworkBundle\Console\Application; use Krzysiej\RyobiCrawler\Command\ScrapeWebsite;
use Symfony\Component\Console\Application;
if (php_sapi_name() !== 'cli') { if (php_sapi_name() !== 'cli') {
header('Location: browser.php'); header('Location: browser.php');
echo 'Execute this script in cli only'; echo 'Execute this script in cli only';
exit; exit;
} }
$kernel = new Kernel('dev', true);
$application = new Application($kernel); $application = new Application('Ryobi website scraper application', '1.1.1');
$application->setName('Ryobi website scraper application'); $application->add(new ScrapeWebsite());
$application->setVersion('1.2.0'); $application->add(new Migrate());
$application->run(); $application->run();

View File

@@ -1,11 +1,46 @@
<?php <?php
use Krzysiej\RyobiCrawler\Kernel; use Krzysiej\RyobiCrawler\Twig\AppExtension;
use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symfony\Component\Dotenv\Dotenv; use Symfony\Component\Dotenv\Dotenv;
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Kernel as BaseKernel;
use Symfony\Component\Routing\Loader\Configurator\RoutingConfigurator;
require 'vendor/autoload.php'; require 'vendor/autoload.php';
class Kernel extends BaseKernel
{
use MicroKernelTrait;
public function registerBundles(): iterable
{
return [
new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
new Symfony\Bundle\TwigBundle\TwigBundle(),
new Twig\Extra\TwigExtraBundle\TwigExtraBundle(),
];
}
protected function configureContainer(ContainerConfigurator $container): void
{
$container->extension('framework', [
'secret' => 'S0ME_SECRET'
]);
$container->services()
->load('Krzysiej\\RyobiCrawler\\Controller\\', __DIR__.'/src/Controller/*')
->autowire()
->autoconfigure()
;
$container->services()->set(AppExtension::class)->tag('twig.extension');
}
protected function configureRoutes(RoutingConfigurator $routes): void
{
$routes->import(__DIR__.'/src/Controller/', 'attribute');
}
}
(new Dotenv())->bootEnv(__DIR__.'/.env'); (new Dotenv())->bootEnv(__DIR__.'/.env');
$kernel = new Kernel($_SERVER['APP_ENV'], (bool) $_SERVER['APP_DEBUG']); $kernel = new Kernel($_SERVER['APP_ENV'], (bool) $_SERVER['APP_DEBUG']);

View File

@@ -1,84 +0,0 @@
<?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: '')]
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->orderBy('created_at', 'desc'),
'stock' => fn($query) => $query->orderBy('created_at', 'desc'),
])->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);
}
}

View File

@@ -2,8 +2,9 @@
namespace Krzysiej\RyobiCrawler\Controller; namespace Krzysiej\RyobiCrawler\Controller;
use Illuminate\Database\Eloquent\Builder;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Cache\Adapter\FilesystemAdapter; use Symfony\Component\HttpFoundation\Request;
use Twig\Environment; use Twig\Environment;
use Illuminate\Database\Capsule\Manager as Capsule; use Illuminate\Database\Capsule\Manager as Capsule;
@@ -11,11 +12,26 @@ class BaseController extends AbstractController
{ {
protected Environment $twig; protected Environment $twig;
public function __construct(protected FilesystemAdapter $cache) public function __construct()
{ {
$capsule = new Capsule; $capsule = new Capsule;
$capsule->addConnection(['driver' => 'sqlite', 'database' => __DIR__ . '/../../database.sqlite']); $capsule->addConnection(['driver' => 'sqlite', 'database' => __DIR__ . '/../../database.sqlite']);
$capsule->setAsGlobal(); $capsule->setAsGlobal();
$capsule->bootEloquent(); $capsule->bootEloquent();
} }
protected function handleOrderProducts(Builder $builder, Request $request): Builder
{
$builder->orderByDesc('starred')->orderByDesc('created_by');
if ($request->query->get('order')) {
$orderField = $request->query->get('order');
$direction = 'desc';
if (str_starts_with($orderField, '-')) {
$direction = 'asc';
}
$builder->orderBy($request->query->get('order'), $direction);
}
return $builder;
}
} }

View File

@@ -11,10 +11,6 @@ final class CategoryController extends BaseController
#[Route('/category/{category}', name: 'app_category')] #[Route('/category/{category}', name: 'app_category')]
public function __invoke(string $category): Response public function __invoke(string $category): Response
{ {
if($this->cache->getItem('list_category_'.$category)->isHit()) {
return $this->render('productList.html.twig', ['listType' => 'category_'.$category]);
}
$products = Product::with('price') $products = Product::with('price')
->selectRaw('products.*') ->selectRaw('products.*')
->distinct('products.id') ->distinct('products.id')
@@ -23,7 +19,6 @@ final class CategoryController extends BaseController
->orderByDesc('starred') ->orderByDesc('starred')
->orderByDesc('created_by') ->orderByDesc('created_by')
->get(); ->get();
return $this->render('productList.html.twig', ['products' => $products]);
return $this->render('productList.html.twig', ['products' => $products, 'listType' => 'category_'.$category]);
} }
} }

View File

@@ -13,15 +13,12 @@ final class DiscontinuedController extends BaseController
#[Route('/discontinued', name: 'app_discontinued')] #[Route('/discontinued', name: 'app_discontinued')]
public function __invoke(): Response public function __invoke(): Response
{ {
if($this->cache->getItem('list_discontinued')->isHit()) {
return $this->render('productList.html.twig', ['listType' => 'discontinued']);
}
$products = Product::where('updated_at', '<', now()->format('Y-m-d')) $products = Product::where('updated_at', '<', now()->format('Y-m-d'))
->orderByDesc('starred') ->orderByDesc('starred')
->orderByDesc('created_by') ->orderByDesc('created_by')
->with(['currentPrice']) ->with(['currentPrice'])
->get(); ->get();
return $this->render('productList.html.twig', ['products' => $products, 'listType' => 'discontinued']); return $this->render('productList.html.twig', ['products' => $products]);
} }
} }

View File

@@ -3,22 +3,17 @@
namespace Krzysiej\RyobiCrawler\Controller; namespace Krzysiej\RyobiCrawler\Controller;
use Krzysiej\RyobiCrawler\Models\Product; use Krzysiej\RyobiCrawler\Models\Product;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route; use Symfony\Component\Routing\Attribute\Route;
final class IndexController extends BaseController final class IndexController extends BaseController
{ {
#[Route('/', name: 'app_home')] #[Route('/', name: 'app_home')]
public function __invoke(): Response public function __invoke(Request $request): Response
{ {
if($this->cache->getItem('list_all')->isHit()) { $products = Product::with(['currentStock', 'price', 'currentPrice']);
return $this->render('productList.html.twig', ['listType' => 'all']); $products = $this->handleOrderProducts($products, $request)->get();
} return $this->render('productList.html.twig', ['products' => $products]);
$products = Product::with(['currentStock', 'price'])
->orderByDesc('starred')
->orderByDesc('created_by')
->get();
return $this->render('productList.html.twig', ['products' => $products, 'listType' => 'all']);
} }
} }

View File

@@ -14,15 +14,12 @@ final class NewController extends BaseController
#[Route('/new', name: 'app_new')] #[Route('/new', name: 'app_new')]
public function __invoke(): Response public function __invoke(): Response
{ {
if($this->cache->getItem('list_new')->isHit()) {
return $this->render('productList.html.twig', ['listType' => 'new']);
}
$products = Product::where('created_at', '>', now()->modify('-30 days')->format('Y-m-d')) $products = Product::where('created_at', '>', now()->modify('-30 days')->format('Y-m-d'))
->orderByDesc('starred') ->orderByDesc('starred')
->orderByDesc('name')
->orderByDesc('created_by') ->orderByDesc('created_by')
->with(['currentPrice']) ->with(['currentPrice'])
->get(); ->get();
return $this->render('productList.html.twig', ['products' => $products, 'listType' => 'new']); return $this->render('productList.html.twig', ['products' => $products]);
} }
} }

View File

@@ -3,7 +3,6 @@
namespace Krzysiej\RyobiCrawler\Controller; namespace Krzysiej\RyobiCrawler\Controller;
use Krzysiej\RyobiCrawler\Models\Product; use Krzysiej\RyobiCrawler\Models\Product;
use Symfony\Component\Cache\Adapter\FilesystemAdapter;
use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route; use Symfony\Component\Routing\Attribute\Route;
use Twig\Error\LoaderError; use Twig\Error\LoaderError;
@@ -20,10 +19,6 @@ final class ProductController extends BaseController
#[Route('/product/{productId<\d+>}', name: 'app_product')] #[Route('/product/{productId<\d+>}', name: 'app_product')]
public function __invoke(int $productId): Response public function __invoke(int $productId): Response
{ {
if($this->cache->getItem('product'.$productId)->isHit()) {
return $this->render('product.html.twig', ['product' => ['id' => $productId]]);
}
$product = Product::with([ $product = Product::with([
'price' => fn($query) => $query->orderBy('created_at', 'desc'), 'price' => fn($query) => $query->orderBy('created_at', 'desc'),
'stock' => fn($query) => $query->orderBy('created_at', 'desc'), 'stock' => fn($query) => $query->orderBy('created_at', 'desc'),

View File

@@ -12,15 +12,11 @@ final class PromosController extends BaseController
#[Route('/promos', name: 'app_promos')] #[Route('/promos', name: 'app_promos')]
public function __invoke(): Response public function __invoke(): Response
{ {
if($this->cache->getItem('list_promos')->isHit()) {
return $this->render('productList.html.twig', ['listType' => 'promos']);
}
$products = Product::whereHas('currentPrice', fn(Builder $query) => $query->whereColumn('price', '<', 'productStandardPrice')) $products = Product::whereHas('currentPrice', fn(Builder $query) => $query->whereColumn('price', '<', 'productStandardPrice'))
->orderByDesc('starred') ->orderByDesc('starred')
->orderByDesc('created_by') ->orderByDesc('created_by')
->with(['currentPrice']) ->with(['currentPrice'])
->get(); ->get();
return $this->render('productList.html.twig', ['products' => $products, 'listType' => 'promos']); return $this->render('productList.html.twig', ['products' => $products]);
} }
} }

View File

@@ -1,53 +0,0 @@
<?php
namespace Krzysiej\RyobiCrawler;
use Krzysiej\RyobiCrawler\Twig\AppExtension;
use Symfony\Bundle\FrameworkBundle\FrameworkBundle;
use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait;
use Symfony\Bundle\TwigBundle\TwigBundle;
use Symfony\Component\Cache\Adapter\FilesystemAdapter;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\HttpKernel\Kernel as BaseKernel;
use Symfony\Component\Routing\Loader\Configurator\RoutingConfigurator;
use Twig\Extra\Cache\CacheExtension;
use Twig\Extra\Cache\CacheRuntime;
use Twig\Extra\TwigExtraBundle\TwigExtraBundle;
class Kernel extends BaseKernel
{
use MicroKernelTrait;
public function registerBundles(): iterable
{
return [
new FrameworkBundle(),
new TwigBundle(),
new TwigExtraBundle(),
];
}
protected function configureContainer(ContainerConfigurator $container): void
{
$container->extension('framework', [
'secret' => 'S0ME_SECRET'
]);
$services = $container->services()->defaults()->autowire()->autoconfigure();
$services->load('Krzysiej\\RyobiCrawler\\Controller\\', __DIR__ . '/Controller/*');
$services->load('Krzysiej\\RyobiCrawler\\Command\\', __DIR__ . '/Command/*')->tag('console.command');
$services->set('twig.extension.cache', AppExtension::class)->tag('twig.extension');
$services->set(CacheExtension::class)->tag('twig.extension');
$services->set(FilesystemAdapter::class)->args([
'', // namespace
0, // default lifetime
__DIR__ . '/../var/cache/twig_blocks' // custom path
]);
$services->set('twig.runtime.cache', CacheRuntime::class)->args([new Reference(FilesystemAdapter::class)])->tag('twig.runtime');
}
protected function configureRoutes(RoutingConfigurator $routes): void
{
$routes->import(__DIR__ . '/Controller/', 'attribute');
}
}

View File

@@ -19,7 +19,6 @@ class AppExtension extends AbstractExtension
{ {
return [ return [
new TwigFunction('promosCount', [$this, 'promosCount']), new TwigFunction('promosCount', [$this, 'promosCount']),
new TwigFunction('allCount', [$this, 'allCount']),
new TwigFunction('newCount', [$this, 'newCount']), new TwigFunction('newCount', [$this, 'newCount']),
new TwigFunction('discontinuedCount', [$this, 'discontinuedCount']), new TwigFunction('discontinuedCount', [$this, 'discontinuedCount']),
]; ];
@@ -31,14 +30,10 @@ class AppExtension extends AbstractExtension
new TwigFilter('findByCreatedAtDate', [$this, 'findByCreatedAtDate']), new TwigFilter('findByCreatedAtDate', [$this, 'findByCreatedAtDate']),
]; ];
} }
public function allCount(): int
{
return Product::count();
}
public function promosCount(): int public function promosCount(): int
{ {
return Product::whereHas('currentPrice', fn(Builder $query) => $query->whereColumn('price', '<', 'productStandardPrice'))->count(); return Product::whereHas('currentPrice', fn(Builder $query) => $query->whereColumn('price', '<', 'productStandardPrice'))->with(['currentPrice'])->count();
} }
public function newCount(): int public function newCount(): int

View File

@@ -1,7 +1,6 @@
{% extends "template.html.twig" %} {% extends "template.html.twig" %}
{% block content %} {% block content %}
{% cache 'product' ~ product.id %}
<div class="table-responsive"> <div class="table-responsive">
<table class='table table-hover'> <table class='table table-hover'>
<tr> <tr>
@@ -130,6 +129,5 @@
} }
}); });
</script> </script>
{% endcache %}
{% endblock %} {% endblock %}

View File

@@ -1,17 +1,17 @@
{% extends "template.html.twig" %} {% extends "template.html.twig" %}
{% block content %} {% block content %}
{% cache 'list_' ~ listType %}
<div class="table-responsive"> <div class="table-responsive">
{{ app.request.get('order') }}
<table class='table table-hover'> <table class='table table-hover'>
<thead> <thead>
<tr> <tr>
<th></th> <th></th>
<th></th> <th></th>
<th>Name</th> <th><a href="{{ path( app.request.get('_route') , {'order': app.request.get('order') is same as('-name')?'name':'-name'|default('-name')}) }}">Name</a></th>
<th>Categories</th> <th>Categories</th>
<th></th> <th></th>
<th>Price</th> <th><a href="{{ path( app.request.get('_route') , {'order': app.request.get('order') is same as('-price')?'price':'-price'|default('-price')}) }}">Price</a></th>
<th></th> <th></th>
</tr> </tr>
</thead> </thead>
@@ -58,5 +58,4 @@
{% endfor %} {% endfor %}
</table> </table>
</div> </div>
{% endcache %}
{% endblock %} {% endblock %}

View File

@@ -18,10 +18,6 @@
</button> </button>
<div class="collapse navbar-collapse" id="navbarNav"> <div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav me-auto mb-2 mb-lg-0"> <ul class="navbar-nav me-auto mb-2 mb-lg-0">
{% cache "menu_count" %}
<li class="nav-item">
<a class="nav-link {% if app.request.pathinfo == path('app_home') %}active shadow-sm bg-body rounded{% endif %}" aria-current="page" href="{{ path('app_home') }}">All products <span class="badge text-bg-secondary">{{ allCount() }}</span></a>
</li>
<li class="nav-item"> <li class="nav-item">
<a class="nav-link {% if app.request.pathinfo == path('app_promos') %}active shadow-sm bg-body rounded{% endif %}" aria-current="page" href="{{ path('app_promos') }}">Promos <span class="badge text-bg-secondary">{{ promosCount() }}</span></a> <a class="nav-link {% if app.request.pathinfo == path('app_promos') %}active shadow-sm bg-body rounded{% endif %}" aria-current="page" href="{{ path('app_promos') }}">Promos <span class="badge text-bg-secondary">{{ promosCount() }}</span></a>
</li> </li>
@@ -31,7 +27,6 @@
<li class="nav-item"> <li class="nav-item">
<a class="nav-link {% if app.request.pathinfo == path('app_discontinued') %}active shadow-sm bg-body rounded{% endif %}" aria-current="page" href="{{ path('app_discontinued') }}">Discontinued <span class="badge text-bg-secondary">{{ discontinuedCount() }}</span></a> <a class="nav-link {% if app.request.pathinfo == path('app_discontinued') %}active shadow-sm bg-body rounded{% endif %}" aria-current="page" href="{{ path('app_discontinued') }}">Discontinued <span class="badge text-bg-secondary">{{ discontinuedCount() }}</span></a>
</li> </li>
{% endcache %}
</ul> </ul>
<form class="form-floating d-flex col-lg-6 col-sm-8" role="search" action="{{ path('app_search') }}"> <form class="form-floating d-flex col-lg-6 col-sm-8" role="search" action="{{ path('app_search') }}">