Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace App\Services;
- use App\Models\ParseLogging;
- use App\Models\Site;
- use Illuminate\Support\Str;
- use PHPHtmlParser\Dom;
- use PHPHtmlParser\Dom\HtmlNode;
- class MacParser
- {
- private $usdCurrency;
- private $domParser;
- public function __construct(Dom $dom)
- {
- $this->domParser = $dom;
- $this->usdCurrency = $this->getUsd();
- }
- /**
- * @throws \PHPHtmlParser\Exceptions\ChildNotFoundException
- * @throws \PHPHtmlParser\Exceptions\CircularException
- * @throws \PHPHtmlParser\Exceptions\CurlException
- * @throws \PHPHtmlParser\Exceptions\NotLoadedException
- * @throws \PHPHtmlParser\Exceptions\StrictException
- */
- public function parse(): void
- {
- $this->log();
- Site::all()->map(function (Site $site) {
- $this->domParser = new Dom;
- $this->domParser->loadFromUrl($site->parse_url);
- /** @var HtmlNode $price */
- $price = $this->domParser->find($site->parse_dom_path)[0];
- $price = $this->getPrice($site, $this->clearPrice($price->text(true)));
- $site->states()->create(compact('price'));
- });
- }
- private function getPrice(Site $site, string $priceText): int
- {
- $priceText = (int)Str::substr($priceText, 0, $site->isUAHPrice() ? 5 : 4);
- return $site->isUAHPrice() ? $priceText : round($priceText * $this->usdCurrency);
- }
- private function clearPrice(string $price): string
- {
- return preg_replace('/[^0-9]/', '', $price);
- }
- /**
- * @throws \PHPHtmlParser\Exceptions\ChildNotFoundException
- * @throws \PHPHtmlParser\Exceptions\CircularException
- * @throws \PHPHtmlParser\Exceptions\CurlException
- * @throws \PHPHtmlParser\Exceptions\NotLoadedException
- * @throws \PHPHtmlParser\Exceptions\StrictException
- */
- private function getUsd(): float
- {
- $this->domParser->loadFromUrl('https://privatbank.ua/ru');
- /** @var HtmlNode $price */
- $currency = $this->domParser->find('#USD_sell')[0];
- return trim($currency->text());
- }
- private function log(): void
- {
- ParseLogging::create();
- info(__METHOD__);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement