Skip to content

Commit

Permalink
Refactor services and change some logs
Browse files Browse the repository at this point in the history
  • Loading branch information
duboiss committed Oct 12, 2021
1 parent f1e384f commit a680deb
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 34 deletions.
7 changes: 4 additions & 3 deletions src/Service/NotifyService.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,13 @@ public function notify(array $product, string $formattedPrice): void
{
$notification = (new Notification('Price alert'))
->importance(Notification::IMPORTANCE_HIGH)
->subject(sprintf('Price alert / %s %s', $product['title'], $formattedPrice))
->subject(sprintf('Price alert / %s - %s', $product['title'], $formattedPrice))
->content(sprintf(
'Price alert for %s product : %s (%s€ desired)',
'Price alert for "%s" product : %s (%s€ desired) at url %s',
$product['title'],
$formattedPrice,
$product['desiredPrice']
$product['desiredPrice'],
$product['url']
))
;

Expand Down
62 changes: 31 additions & 31 deletions src/Service/ProductService.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,13 @@
use Symfony\Component\DomCrawler\Crawler;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Finder\SplFileInfo;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Symfony\Contracts\HttpClient\ResponseInterface;

class ProductService
{
private string $filePath = '';
private ?array $dataProducts = null;

public function __construct(private HttpClientInterface $httpClient, private LoggerInterface $logger, private NotifyService $notifyService, private EventDispatcherInterface $dispatcher)
Expand All @@ -25,13 +25,15 @@ public function __construct(private HttpClientInterface $httpClient, private Log

public function analyse(SplFileInfo $file): void
{
$this->filePath = $file->getRealPath();
$this->dataProducts = $this->getDataProducts();
$filePath = $file->getRealPath();

$this->dataProducts = $this->getDataProducts($filePath);
$crawlerSelector = $this->dataProducts['selector'];
$products = $this->dataProducts['products'];

foreach ($products as $index => $product) {
sleep(5);
foreach ($this->dataProducts['products'] as $index => $product) {
// Avoid being blocked by the rate limiter
sleep(15);

if (!$response = $this->getResponse($product)) {
continue;
}
Expand All @@ -42,59 +44,57 @@ public function analyse(SplFileInfo $file): void
if (!$selector->count()) {
$this->logger->error(
sprintf(
'Selector not found for "%s" product (%s)',
'Selector not found for product "%s" (%s)',
$product['title'],
$file->getFilename()
$product['url']
)
);

continue;
}

$formattedPrice = $selector->text();

$formattedPrice = trim($selector->text());
$this->dispatcher->dispatch(new ProductParsedEvent($product, $formattedPrice));

$price = (int) str_replace(',', '', $selector->text());

$this->checkProductPrice($product, $price, $index, $formattedPrice);
}

$this->updateDataProducts();
$this->updateDataProducts($filePath);
}

private function getDataProducts(): array
private function getDataProducts(string $filePath): array
{
/** @var string $jsonContent */
$jsonContent = file_get_contents($this->filePath);
$jsonContent = file_get_contents($filePath);

try {
return json_decode($jsonContent, true, 512, JSON_THROW_ON_ERROR);
} catch (\JsonException $e) {
throw new RuntimeException("Failure during decoding of {$this->filePath}.json file: {$e}");
throw new RuntimeException("Failure during decoding of {$filePath}.json file: {$e}");
}
}

private function getResponse(array $product): ?ResponseInterface
{
try {
$response = $this->httpClient->request('GET', $product['url']);
} catch (TransportExceptionInterface $e) {
throw new RuntimeException("Failure during the request {$product['url']}: {$e}");
}

if (($statusCode = $response->getStatusCode()) !== 200) {
$this->logger->error(sprintf(
'Unable to check product "%s" (%s) : status code %d.',
$product['title'],
$product['url'],
$statusCode
));
if (($statusCode = $response->getStatusCode()) !== Response::HTTP_OK) {
$this->logger->error(sprintf(
'Unable to check product "%s" (%s) : status code %d.',
$product['title'],
$product['url'],
$statusCode
));

return null;
}
return null;
}

return $response;
return $response;
} catch (TransportExceptionInterface $e) {
throw new RuntimeException("Failure during the request {$product['url']}: {$e}");
}
}

private function checkProductPrice(array $product, int $price, int $index, string $formattedPrice): void
Expand All @@ -112,12 +112,12 @@ private function updateProductAlertedPrice(int $productIndex, int $price): void
$this->dataProducts['products'][$productIndex]['alertedPrice'] = $price;
}

private function updateDataProducts(): void
private function updateDataProducts(string $filePath): void
{
try {
file_put_contents($this->filePath, json_encode($this->dataProducts, JSON_THROW_ON_ERROR | JSON_PRETTY_PRINT));
file_put_contents($filePath, json_encode($this->dataProducts, JSON_THROW_ON_ERROR | JSON_PRETTY_PRINT));
} catch (\JsonException $e) {
throw new RuntimeException("Failure during encoding of {$this->filePath}.json file: {$e}");
throw new RuntimeException("Failure during encoding of {$filePath}.json file: {$e}");
}
}
}

0 comments on commit a680deb

Please sign in to comment.