2018-06-07 23:46:40 +09:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace App;
|
|
|
|
|
2020-08-10 13:32:47 +09:00
|
|
|
use Carbon\CarbonInterface;
|
|
|
|
use GuzzleHttp\Exception\RequestException;
|
2018-06-07 23:46:40 +09:00
|
|
|
use Illuminate\Database\Eloquent\Model;
|
|
|
|
|
|
|
|
class Metadata extends Model
|
|
|
|
{
|
|
|
|
public $incrementing = false;
|
|
|
|
protected $primaryKey = 'url';
|
|
|
|
protected $keyType = 'string';
|
|
|
|
|
2019-01-15 15:31:15 +09:00
|
|
|
protected $fillable = ['url', 'title', 'description', 'image', 'expires_at'];
|
2019-06-24 22:39:01 +09:00
|
|
|
protected $visible = ['url', 'title', 'description', 'image', 'expires_at', 'tags'];
|
2019-01-16 00:15:41 +09:00
|
|
|
|
2020-08-10 12:25:00 +09:00
|
|
|
protected $dates = ['created_at', 'updated_at', 'expires_at', 'error_at'];
|
2019-04-29 11:40:03 +09:00
|
|
|
|
|
|
|
public function tags()
|
|
|
|
{
|
|
|
|
return $this->belongsToMany(Tag::class)->withTimestamps();
|
|
|
|
}
|
2020-08-10 13:32:47 +09:00
|
|
|
|
|
|
|
public function needRefresh(): bool
|
|
|
|
{
|
|
|
|
return $this->isExpired() || $this->error_at !== null;
|
|
|
|
}
|
|
|
|
|
|
|
|
public function isExpired(): bool
|
|
|
|
{
|
|
|
|
return $this->expires_at !== null && $this->expires_at < now();
|
|
|
|
}
|
|
|
|
|
|
|
|
public function storeException(CarbonInterface $error_at, \Exception $exception): self
|
|
|
|
{
|
|
|
|
$this->prepareFieldsOnError();
|
|
|
|
$this->error_at = $error_at;
|
|
|
|
$this->error_exception_class = get_class($exception);
|
|
|
|
$this->error_body = $exception->getMessage();
|
|
|
|
if ($exception instanceof RequestException) {
|
|
|
|
$this->error_http_code = $exception->getCode();
|
|
|
|
} else {
|
|
|
|
$this->error_http_code = null;
|
|
|
|
}
|
|
|
|
$this->error_count++;
|
|
|
|
|
|
|
|
return $this;
|
|
|
|
}
|
|
|
|
|
|
|
|
public function storeError(CarbonInterface $error_at, string $body, ?int $httpCode = null): self
|
|
|
|
{
|
|
|
|
$this->prepareFieldsOnError();
|
|
|
|
$this->error_at = $error_at;
|
|
|
|
$this->error_exception_class = null;
|
|
|
|
$this->error_body = $body;
|
|
|
|
$this->error_http_code = $httpCode;
|
|
|
|
$this->error_count++;
|
|
|
|
|
|
|
|
return $this;
|
|
|
|
}
|
|
|
|
|
|
|
|
public function clearError(): self
|
|
|
|
{
|
|
|
|
$this->error_at = null;
|
|
|
|
$this->error_exception_class = null;
|
|
|
|
$this->error_body = null;
|
|
|
|
$this->error_http_code = null;
|
|
|
|
$this->error_count = 0;
|
|
|
|
|
|
|
|
return $this;
|
|
|
|
}
|
|
|
|
|
|
|
|
private function prepareFieldsOnError()
|
|
|
|
{
|
|
|
|
$this->title = $this->title ?? '';
|
|
|
|
$this->description = $this->description ?? '';
|
|
|
|
$this->image = $this->image ?? '';
|
|
|
|
}
|
2018-06-07 23:46:40 +09:00
|
|
|
}
|