Automation/app/Libraries/MyCrawler/MyCrawlerLibrary.php
2024-09-07 15:13:03 +09:00

59 lines
1.8 KiB
PHP

<?php
namespace App\Libraries\MyCrawler;
use Symfony\Component\DomCrawler\Crawler;
use App\Libraries\CommonLibrary;
abstract class MyCrawlerLibrary extends CommonLibrary
{
protected function __construct()
{
parent::__construct();
}
abstract public function getMySocket();
abstract public function getMyStorage();
abstract public function execute(): array;
final protected function getContent(string $url, string $tag): Crawler
{
$response = $this->getMySocket()->getContent($url);
if (!$response) {
throw new \Exception("getCrawler 실패:{$url}");
}
$crawler = new Crawler($response);
return $crawler->filter($tag);
}
final protected function getNodes(Crawler $crawler, array $options, $nodes = []): array
{
$crawler->filter($options["tag"])->each(
function (Crawler $node) use (&$options, &$nodes): void {
log_message("debug", sprintf("getNode-> %s", $options["tag"]));
$nodes[] = $node;
}
);
return $nodes;
}
final protected function download(Crawler $crawler, array $options): array
{
$downloadInfos = [];
$nodes = $this->getNodes($crawler, $options);
foreach ($nodes as $node) {
$original = $node->attr($options["attr"]);
list($fileName, $content) = $this->getMySocket()->download($original);
$this->getMyStorage()->setFileName($fileName);
if (!$this->getMyStorage()->save($content)) {
continue;
}
$downloadInfos[] = [
"orignal" => $node->html(),
"path" => $this->getMyStorage()->getPath(),
"fileName" => $fileName,
];
}
return $downloadInfos;
}
}