作者:我是王美慧 | 来源:互联网 | 2023-09-14 11:32
本文由编程笔记#小编为大家整理,主要介绍了php WordPress服务相关的知识,希望对你有一定的参考价值。
namespace OSI\Services;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
/**
* WordPress Service
*/
class WordPress
{
/**
* The current.
*
* @var $current
*/
protected $current;
/**
* The total.
*
* @var $total
*/
protected $total;
/**
* The uri.
*
* @var $uri
*/
protected $uri;
/**
* Create a new GetPost domain.
*
* @return void
*/
public function __construct($domain)
{
$this->domain = $domain;
$this->total = 100;
$this->current = 0;
}
/**
* Create an domain of GetPost
*
* @return OSI\Services\WordPress\GetPost
*/
public static function make($domain)
{
return new self($domain);
}
/**
* Set URI
* @param string $uri
* @return $this
*/
public function setUri(string $uri)
{
$this->uri = $uri;
return $this;
}
/**
* Get URI
* @return string
*/
public function getUri()
{
return $this->uri;
}
/**
* Handle the processing
*
* @return void
*/
public function handle()
{
$client = new Client([
'base_uri' => $this->domain,
]);
$offset = ($this->total - $this->current);
if ($offset <0) {
return false;
}
$request = new Request(&#39;GET&#39;, $this->getUri(), [
&#39;query&#39; => [
&#39;per_page&#39; => 100,
&#39;offset&#39; => $offset,
],
]);
$promise = $client->sendAsync($request)->then(function ($response) {
$this->total = $response->getHeader(&#39;x-wp-total&#39;)[0];
$this->total = ((int) $this->total);
$this->store($this->uri, $response->getBody());
});
$promise->wait();
if ($this->current <$this->total) {
$this->current = $this->current + 100;
$this->handle();
}
}
/**
* Store in WP storage
* @param string $type Type of Resource
* @param json $content
* @return void
*/
private function store($type, $content)
{
$filename = &#39;wp/&#39; . $type . &#39;_&#39; . \Carbon\Carbon::now()->format(&#39;YmdHis&#39;) . &#39;.json&#39;;
file_put_contents(storage_path($filename), $this->json_pretty($content));
}
/**
* Format to JSON Pretty
* @param json $data JSON Encoded
* @return json JSON Pretty Encoded
*/
private function json_pretty($data)
{
$data = json_decode($data);
return json_encode($data, JSON_PRETTY_PRINT);
}
}