101 lines
3.3 KiB
PHP
101 lines
3.3 KiB
PHP
<?php
|
|
|
|
namespace App\Traits;
|
|
|
|
use GuzzleHttp\Cookie\CookieJar;
|
|
use GuzzleHttp\Client;
|
|
|
|
trait MyWebTrait
|
|
{
|
|
private $_client = null;
|
|
private $_cookieJar = null;
|
|
private $_host = null;
|
|
|
|
final protected function getHostByMyWeb(): string
|
|
{
|
|
return $this->_host;
|
|
}
|
|
final protected function setHostByMyWeb(string $host): void
|
|
{
|
|
$this->_host = $host;
|
|
}
|
|
|
|
final protected function getClientByMyWeb(): Client
|
|
{
|
|
if ($this->_client === null) {
|
|
$this->_client = new Client(['verify' => false]);
|
|
}
|
|
return $this->_client;
|
|
}
|
|
|
|
final protected function getCookieJarByMyWeb()
|
|
{
|
|
if ($this->_cookieJar === null) {
|
|
$this->_cookieJar = new CookieJar();
|
|
}
|
|
return $this->_cookieJar;
|
|
}
|
|
|
|
//url에 http 나 https가 포함되어 있으면 true
|
|
final protected function isContainsHttpOrHttpsByMyWeb($url): bool
|
|
{
|
|
return strpos($url, 'http://') !== false || strpos($url, 'https://') !== false;
|
|
}
|
|
final protected function getContentByMyWeb(string $url, array $options = []): string
|
|
{
|
|
//url에 http 나 https가 포함되어 있지않으면
|
|
if (!($this->isContainsHttpOrHttpsByMyWeb($url))) {
|
|
$url = $this->gethostByMyWeb() . $url;
|
|
}
|
|
$response = $this->getClientByMyWeb()->get($url, $options);
|
|
if ($response->getStatusCode() != 200) {
|
|
throw new \Exception("error", "{$url} 접속실패: " . $response->getStatusCode());
|
|
}
|
|
return $response->getBody()->getContents();
|
|
}
|
|
|
|
// 로그인 메서드
|
|
final protected function loginByMyWeb($url, $username, $password): void
|
|
{
|
|
$response = $this->getClientByMyWeb()->post($this->gethost() . $url, [
|
|
'form_params' => [
|
|
'username' => $username,
|
|
'password' => $password,
|
|
],
|
|
'cookies' => $this->getCookieJar(),
|
|
]);
|
|
if ($response->getStatusCode() != 200) {
|
|
throw new \Exception("info", "로그인 실패: " . $response->getStatusCode());
|
|
}
|
|
}
|
|
|
|
// 파일 다운로드 메서드
|
|
final protected function downloadByMyWeb(string $url, string $fullPath, bool $debug = false)
|
|
{
|
|
log_message("debug", "donwload:URL-> " . $url);
|
|
$fileNames = explode('/', $url);
|
|
if (!is_array($fileNames) || !count($fileNames)) {
|
|
throw new \Exception("Download URL Error:" . $url);
|
|
}
|
|
if (!is_dir($fullPath)) {
|
|
if (!mkdir($fullPath)) {
|
|
throw new \Exception("Make Directory Error:" . $fullPath);
|
|
}
|
|
}
|
|
$fileName = array_pop($fileNames);
|
|
$savePath = $fullPath . DIRECTORY_SEPARATOR . $fileName;
|
|
log_message("debug", "download:SavePath-> " . $savePath);
|
|
if (!$debug) {
|
|
$response = $this->getContentByMyWeb($url, [
|
|
'cookies' => $this->getCookieJarByMyWeb(),
|
|
// 'sink' => $savePath,
|
|
]);
|
|
if (!$response) {
|
|
throw new \Exception("info", "{$fileName} 파일 다운로드 실패");
|
|
}
|
|
$this->saveByMyStorage($savePath, $response);
|
|
log_message("info", "{$fileName} 파일이 다운로드되었습니다!");
|
|
}
|
|
}
|
|
}
|