Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Possibility to use wordpress public API #17

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 6 additions & 5 deletions composer.json
Original file line number Diff line number Diff line change
@@ -1,10 +1,6 @@
{
"name": "vnn/wordpress-rest-api-client",
"autoload": {
"psr-4": {
"Vnn\\WpApiClient\\": "src/"
}
},
"license": "MIT",
"require": {
"php": ">= 5.6, <= 8.0",
"psr/http-message": "^1.0"
Expand All @@ -18,5 +14,10 @@
},
"suggest": {
"guzzlehttp/guzzle": "^6.2"
},
"autoload": {
"psr-4": {
"Vnn\\WpApiClient\\": "src/"
}
}
}
45 changes: 41 additions & 4 deletions specs/Endpoint/abstract-wp-endpoint.spec.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
$endpoint = new FakeEndpoint($client->reveal());

$data = $endpoint->get(55);
expect($data)->to->equal(['foo' => 'bar']);
expect($data['foo'])->to->equal('bar');
});

it('should make a GET request without any ID', function () {
Expand All @@ -31,7 +31,7 @@
$endpoint = new FakeEndpoint($client->reveal());

$data = $endpoint->get();
expect($data)->to->equal(['foo' => 'bar']);
expect($data['foo'])->to->equal('bar');
});

it('should make a GET request with parameters', function () {
Expand All @@ -45,9 +45,46 @@
$endpoint = new FakeEndpoint($client->reveal());

$data = $endpoint->get(null, ['bar'=>'baz']);
expect($data)->to->equal(['foo' => 'bar']);
expect($data['foo'])->to->equal('bar');
});

it('should expose WP-Total headers', function () {
$client = $this->getProphet()->prophesize(WpClient::class);

$request = new Request('GET', '/foo/55');

$headers = [
'Content-Type' => 'application/json',
'X-WP-Total' => 1,
'X-WP-TotalPages' => 2,
];

$response = new \GuzzleHttp\Psr7\Response(200, $headers, '{"foo": "bar"}');

$client->send($request)->willReturn($response)->shouldBeCalled();

$endpoint = new FakeEndpoint($client->reveal());

$data = $endpoint->get(55);

expect($data->total)->to->equal(1);
expect($data->totalPages)->to->equal(2);
});

it('should include original request', function () {
$client = $this->getProphet()->prophesize(WpClient::class);

$request = new Request('GET', '/foo/55');
$response = new \GuzzleHttp\Psr7\Response(200, ['Content-Type' => 'application/json'], '{"foo": "bar"}');

$client->send($request)->willReturn($response)->shouldBeCalled();

$endpoint = new FakeEndpoint($client->reveal());

$data = $endpoint->get(55);

expect($data->request->getUri()->getPath())->to->equal('/foo/55');
});
});

describe('save()', function () {
Expand All @@ -59,7 +96,7 @@
$endpoint = new FakeEndpoint($client->reveal());

$data = $endpoint->save(['foo' => 'bar']);
expect($data)->to->equal(['foo' => 'bar']);
expect($data['foo'])->to->equal('bar');
});
});

Expand Down
31 changes: 18 additions & 13 deletions src/Endpoint/AbstractWpEndpoint.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,19 @@ abstract class AbstractWpEndpoint
*/
private $client;

/**
* @var bool
*/
private $public;

/**
* Users constructor.
* @param WpClient $client
*/
public function __construct(WpClient $client)
{
$this->client = $client;
$this->public = $client->isPublic();
}

abstract protected function getEndpoint();
Expand All @@ -40,15 +46,7 @@ public function get($id = null, array $params = null)
$uri .= (is_null($id)?'': '/' . $id);
$uri .= (is_null($params)?'': '?' . http_build_query($params));

$request = new Request('GET', $uri);
$response = $this->client->send($request);

if ($response->hasHeader('Content-Type')
&& substr($response->getHeader('Content-Type')[0], 0, 16) === 'application/json') {
return json_decode($response->getBody()->getContents(), true);
}

throw new RuntimeException('Unexpected response');
return $this->sendRequest(new Request('GET', $uri));
}

/**
Expand All @@ -64,12 +62,19 @@ public function save(array $data)
unset($data['id']);
}

$request = new Request('POST', $url, ['Content-Type' => 'application/json'], json_encode($data));
return $this->sendRequest(new Request('POST', $url, ['Content-Type' => 'application/json'], json_encode($data)));
}

/**
* @param \GuzzleHttp\Psr7\Request $request
* @return array
*/
public function sendRequest(Request $request) {
$response = $this->client->send($request);
$results = new ResultSet($request, $response);

if ($response->hasHeader('Content-Type')
&& substr($response->getHeader('Content-Type')[0], 0, 16) === 'application/json') {
return json_decode($response->getBody()->getContents(), true);
if (count($results)) {
return $results;
}

throw new RuntimeException('Unexpected response');
Expand Down
2 changes: 1 addition & 1 deletion src/Endpoint/Categories.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,6 @@ class Categories extends AbstractWpEndpoint
*/
protected function getEndpoint()
{
return '/wp-json/wp/v2/categories';
return '/categories';
}
}
2 changes: 1 addition & 1 deletion src/Endpoint/Comments.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,6 @@ class Comments extends AbstractWpEndpoint
*/
protected function getEndpoint()
{
return '/wp-json/wp/v2/comments';
return '/comments';
}
}
2 changes: 1 addition & 1 deletion src/Endpoint/Media.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,6 @@ class Media extends AbstractWpEndpoint
*/
protected function getEndpoint()
{
return '/wp-json/wp/v2/media';
return '/media';
}
}
2 changes: 1 addition & 1 deletion src/Endpoint/Pages.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,6 @@ class Pages extends AbstractWpEndpoint
*/
protected function getEndpoint()
{
return '/wp-json/wp/v2/pages';
return '/pages';
}
}
2 changes: 1 addition & 1 deletion src/Endpoint/PostStatuses.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,6 @@ class PostStatuses extends AbstractWpEndpoint
*/
protected function getEndpoint()
{
return '/wp-json/wp/v2/statuses';
return '/statuses';
}
}
2 changes: 1 addition & 1 deletion src/Endpoint/PostTypes.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,6 @@ class PostTypes extends AbstractWpEndpoint
*/
protected function getEndpoint()
{
return '/wp-json/wp/v2/types';
return '/types';
}
}
2 changes: 1 addition & 1 deletion src/Endpoint/Posts.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,6 @@ class Posts extends AbstractWpEndpoint
*/
protected function getEndpoint()
{
return '/wp-json/wp/v2/posts';
return '/posts';
}
}
62 changes: 62 additions & 0 deletions src/Endpoint/ResultSet.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
<?php

namespace Vnn\WpApiClient\Endpoint;

use ArrayObject;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\RequestInterface;

/**
* Class ResultSet
* @package Vnn\WpApiClient\Endpoint
*/
class ResultSet extends ArrayObject
{
/**
* @var int
*/
public $total = 0;

/**
* @var int
*/
public $totalPages = 0;

/**
* @var \Psr\Http\Message\RequestInterface
*/
public $request;

/**
* @param RequestInterface $request
* @param ResponseInterface &$response
* @return ResultSet
*/
public function __construct(RequestInterface $request, ResponseInterface &$response)
{
$this->request = $request;

if ($this->validateResponse($response)) {
parent::__construct(json_decode($response->getBody()->getContents(), true));
$this->setHeaders($response);
}
}

private function setHeaders(ResponseInterface &$response)
{
if ($response->hasHeader('X-WP-Total')) {
$this->total = (int) $response->getHeader('X-WP-Total')[0];
}

if ($response->hasHeader('X-WP-TotalPages')) {
$this->totalPages = (int) $response->getHeader('X-WP-TotalPages')[0];
}
}

private function validateResponse(ResponseInterface &$response)
{
return (
$response->hasHeader('Content-Type') &&
substr($response->getHeader('Content-Type')[0], 0, 16) === 'application/json');
}
}
2 changes: 1 addition & 1 deletion src/Endpoint/Tags.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,6 @@ class Tags extends AbstractWpEndpoint
*/
protected function getEndpoint()
{
return '/wp-json/wp/v2/tags';
return '/tags';
}
}
2 changes: 1 addition & 1 deletion src/Endpoint/Users.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,6 @@ class Users extends AbstractWpEndpoint
*/
protected function getEndpoint()
{
return '/wp-json/wp/v2/users';
return '/users';
}
}
38 changes: 33 additions & 5 deletions src/WpClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,15 +45,22 @@ class WpClient
*/
private $endPoints = [];

/**
* @var bool
*/
private $public;

/**
* WpClient constructor.
* @param ClientInterface $httpClient
* @param string $wordpressUrl
* @param bool $public
*/
public function __construct(ClientInterface $httpClient, $wordpressUrl = '')
public function __construct(ClientInterface $httpClient, $wordpressUrl = '', $public = FALSE)
{
$this->httpClient = $httpClient;
$this->wordpressUrl = $wordpressUrl;
$this->public = $public;
}

/**
Expand All @@ -72,6 +79,22 @@ public function setCredentials(AuthInterface $auth)
$this->credentials = $auth;
}

/**
* @param bool
*/
public function setPublic($public = TRUE)
{
$this->public = $public;
}

/**
* @return bool
*/
public function isPublic()
{
return (bool) $this->public;
}

/**
* @param $endpoint
* @param array $args
Expand Down Expand Up @@ -100,10 +123,15 @@ public function send(RequestInterface $request)
if ($this->credentials) {
$request = $this->credentials->addCredentials($request);
}

$request = $request->withUri(
$this->httpClient->makeUri($this->wordpressUrl . $request->getUri())
);
if ($this->isPublic()) {
$raw_uri = $this->httpClient->makeUri($this->wordpressUrl);
$public_uri = 'https://public-api.wordpress.com/wp/v2/sites/' . $raw_uri->getHost();
$uri = $this->httpClient->makeUri($public_uri . $request->getUri());
}
else {
$uri = $this->httpClient->makeUri( $this->wordpressUrl . '/wp-json/wp/v2' . $request->getUri());
}
$request = $request->withUri($uri);

return $this->httpClient->send($request);
}
Expand Down