Created
October 24, 2016 19:24
-
-
Save felixcarpena/884efe695388461a8c02a0d410eb977a to your computer and use it in GitHub Desktop.
Refactor after include Guzzle
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use GuzzleHttp\Exception\ConnectException; | |
use GuzzleHttp\Psr7\Request; | |
include 'classes/cron_display.php'; | |
final class Runner | |
{ | |
private $cron; | |
/** @var \GuzzleHttp\Client */ | |
private $client; | |
/** | |
* Runner constructor. | |
*/ | |
public function __construct() | |
{ | |
$this->cron = new TAP_Cron; | |
$this->client = new \GuzzleHttp\Client(); | |
} | |
public function run($domains_list) | |
{ | |
$this->cron->init_doctype(); | |
$this->cron->log('title=Domain status'); | |
foreach ($domains_list as $entry) { | |
$status = $this->checkDomain($entry['domain']); | |
$this->reportStatus($status); | |
} | |
} | |
/** | |
* @param string $domain | |
* @param int $intent | |
* | |
* @return string | |
* @throws Exception | |
*/ | |
private function checkDomain($domain, $intent = 0) | |
{ | |
$domain_full = 'http://www.' . $domain; | |
$request = new Request('GET', $domain_full); | |
try { | |
$response = $this->client->send($request, ['timeout' => 2, 'allow_redirects' => false]); | |
} catch (ConnectException $e) { | |
if ($intent < 2) { | |
return $this->checkDomain($domain, ++$intent); | |
} | |
} | |
$this->cron->log('Checking: ' . $domain_full); | |
if (!isset($response)) { | |
$status = 'offline'; | |
} elseif ($response->getStatusCode() >= 200 && $response->getStatusCode() < 300) { | |
$status = 'online'; | |
} elseif ($response->getStatusCode() == 301 || $response->getStatusCode() == 302) { | |
$status = 'redirect'; | |
} else { | |
throw new \Exception("Something went wrong"); | |
} | |
return $status; | |
} | |
/** | |
* @param $status | |
*/ | |
private function reportStatus($status) | |
{ | |
if ($status == 'offline') { | |
$this->cron->log('Status: OFFLINE', 1, false); | |
} else { | |
if ($status == 'online') { | |
$this->cron->log('Status: ONLINE', 1, true); | |
} else { | |
$this->cron->log('Status: Redirection', 1); | |
} | |
} | |
$this->cron->log(''); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment