Advertisement
Guest User

Untitled

a guest
Jan 19th, 2020
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.24 KB | None | 0 0
  1. <?php
  2.  
  3. namespace App\Services;
  4.  
  5. use App\Models\ParseLogging;
  6. use App\Models\Site;
  7. use Illuminate\Support\Str;
  8. use PHPHtmlParser\Dom;
  9. use PHPHtmlParser\Dom\HtmlNode;
  10.  
  11. class MacParser
  12. {
  13.     private $usdCurrency;
  14.     private $domParser;
  15.  
  16.     public function __construct(Dom $dom)
  17.     {
  18.         $this->domParser   = $dom;
  19.         $this->usdCurrency = $this->getUsd();
  20.     }
  21.  
  22.     /**
  23.      * @throws \PHPHtmlParser\Exceptions\ChildNotFoundException
  24.      * @throws \PHPHtmlParser\Exceptions\CircularException
  25.      * @throws \PHPHtmlParser\Exceptions\CurlException
  26.      * @throws \PHPHtmlParser\Exceptions\NotLoadedException
  27.      * @throws \PHPHtmlParser\Exceptions\StrictException
  28.      */
  29.     public function parse(): void
  30.     {
  31.         $this->log();
  32.  
  33.         Site::all()->map(function (Site $site) {
  34.             $this->domParser = new Dom;
  35.  
  36.             $this->domParser->loadFromUrl($site->parse_url);
  37.  
  38.             /** @var  HtmlNode $price */
  39.             $price = $this->domParser->find($site->parse_dom_path)[0];
  40.  
  41.             $price = $this->getPrice($site, $this->clearPrice($price->text(true)));
  42.  
  43.             $site->states()->create(compact('price'));
  44.         });
  45.     }
  46.  
  47.     private function getPrice(Site $site, string $priceText): int
  48.     {
  49.         $priceText = (int)Str::substr($priceText, 0, $site->isUAHPrice() ? 5 : 4);
  50.  
  51.         return $site->isUAHPrice() ? $priceText : round($priceText * $this->usdCurrency);
  52.     }
  53.  
  54.     private function clearPrice(string $price): string
  55.     {
  56.         return preg_replace('/[^0-9]/', '', $price);
  57.     }
  58.  
  59.     /**
  60.      * @throws \PHPHtmlParser\Exceptions\ChildNotFoundException
  61.      * @throws \PHPHtmlParser\Exceptions\CircularException
  62.      * @throws \PHPHtmlParser\Exceptions\CurlException
  63.      * @throws \PHPHtmlParser\Exceptions\NotLoadedException
  64.      * @throws \PHPHtmlParser\Exceptions\StrictException
  65.      */
  66.     private function getUsd(): float
  67.     {
  68.         $this->domParser->loadFromUrl('https://privatbank.ua/ru');
  69.  
  70.         /** @var  HtmlNode $price */
  71.         $currency = $this->domParser->find('#USD_sell')[0];
  72.  
  73.         return trim($currency->text());
  74.     }
  75.  
  76.     private function log(): void
  77.     {
  78.         ParseLogging::create();
  79.  
  80.         info(__METHOD__);
  81.     }
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement