Compare commits

...

8 commits

Author SHA1 Message Date
Ben Speakman ec6e3d7263 Merge pull request #4 from WebSpanner/master
Add postId() function to get posts by id
2016-12-02 09:15:58 +00:00
Andrew Feeney a389bcea7a Add postId function to get posts by id 2016-12-02 11:07:30 +11:00
Ben Speakman 387b30fffc Merge pull request #1 from rafaelcneves/patch-2
README adjusts
2016-04-29 15:29:35 +01:00
Rafael César Neves 7f2b217bc0 README adjusts 2016-04-29 11:13:00 -03:00
Ben Speakman 7297886a26 Alias WpApi in facade 2016-04-05 09:13:04 +01:00
Ben Speakman ad9c74f218 Use singleton method for Laravel 5.2 2016-03-16 17:21:59 +00:00
Ben Speakman d2c2c0599c Rename vendor, update guzzle and add test 2016-01-22 13:38:09 +00:00
Ben Speakman 665191e9cd Move entire endpoint url into config. Fixes #3 2015-10-13 11:44:04 +01:00
11 changed files with 371 additions and 199 deletions

View file

@ -1,7 +1,6 @@
language: php language: php
php: php:
- 5.4
- 5.5 - 5.5
- 5.6 - 5.6
- hhvm - hhvm

View file

@ -1,34 +1,37 @@
# laravel-wp-api # laravel-wp-api
[![Build Status](https://travis-ci.org/threesquared/laravel-wp-api.svg?branch=master)](https://travis-ci.org/threesquared/laravel-wp-api) [![Latest Stable Version](https://poser.pugx.org/threesquared/laravel-wp-api/v/stable)](https://packagist.org/packages/threesquared/laravel-wp-api)
Laravel 5 package for the [Wordpress JSON REST API](https://github.com/WP-API/WP-API) Laravel 5 package for the [Wordpress JSON REST API](https://github.com/WP-API/WP-API)
## Install ## Install
Simply add the following line to your `composer.json` and run install/update: Simply add the following line to your `composer.json` and run install/update:
"cyberduck/laravel-wp-api": "~1.0" "threesquared/laravel-wp-api": "~2.0"
## Configuration ## Configuration
Publish the package config files to configure the location of your Wordpress install: You will need to add the service provider and optionally the facade alias to your `config/app.php`:
php artisan vendor:publish
You will also need to add the service provider and optionally the facade alias to your `app/config/app.php`:
```php ```php
'providers' => array( 'providers' => array(
'Cyberduck\LaravelWpApi\LaravelWpApiServiceProvider' Threesquared\LaravelWpApi\LaravelWpApiServiceProvider::class
) )
'aliases' => array( 'aliases' => array(
'WpApi' => 'Cyberduck\LaravelWpApi\Facades\WpApi' 'WpApi' => Threesquared\LaravelWpApi\Facades\WpApi::class
), ),
``` ```
And publish the package config files to configure the location of your Wordpress install:
php artisan vendor:publish
### Usage ### Usage
The package provides a simplified interface to some of the existing api methods documented [here](http://wp-api.org/). The package provides a simplified interface to some of the existing api methods documented [here](http://wp-api.org/).
You can either use the Facade provided or inject the WpApi class. You can either use the Facade provided or inject the `Threesquared\LaravelWpApi\WpApi` class.
#### Posts #### Posts
```php ```php
@ -48,6 +51,11 @@ WpApi::post($slug);
``` ```
```php
WpApi::postId($id);
```
#### Categories #### Categories
```php ```php
WpApi::categories(); WpApi::categories();
@ -62,7 +70,19 @@ WpApi::tags();
#### Category posts #### Category posts
```php ```php
WpApi::category_posts($slug, $page); WpApi::categoryPosts($slug, $page);
```
#### Author posts
```php
WpApi::authorPosts($slug, $page);
```
#### Tag posts
```php
WpApi::tagPosts($slug, $page);
``` ```

View file

@ -1,22 +1,25 @@
{ {
"name": "cyberduck/laravel-wp-api", "name": "threesquared/laravel-wp-api",
"description": "Laravel package for the Wordpress JSON REST API", "description": "Laravel package for the Wordpress JSON REST API",
"keywords": ["laravel", "package", "wordpress", "API", "REST"], "keywords": ["laravel", "package", "wordpress", "API", "REST"],
"license": "MIT", "license": "MIT",
"authors": [ "authors": [
{ {
"name": "Ben Speakman", "name": "Ben Speakman",
"email": "ben@cyber-duck.co.uk" "email": "ben@3sq.re"
} }
], ],
"require": { "require": {
"php": ">=5.4.0", "php": ">=5.5.0",
"illuminate/support": "~5.0|~5.1", "illuminate/support": "~5.2",
"guzzlehttp/guzzle": "~5.0" "guzzlehttp/guzzle": "~6.0"
},
"require-dev": {
"phpunit/phpunit": "4.8.*"
}, },
"autoload": { "autoload": {
"psr-0": { "psr-0": {
"Cyberduck\\LaravelWpApi\\": "src/" "Threesquared\\LaravelWpApi\\": "src/"
} }
}, },
"minimum-stability": "stable" "minimum-stability": "stable"

View file

@ -1,9 +0,0 @@
<?php namespace Cyberduck\LaravelWpApi\Facades;
use Illuminate\Support\Facades\Facade;
class WpApi extends Facade {
protected static function getFacadeAccessor() { return 'wp-api'; }
}

View file

@ -1,59 +0,0 @@
<?php namespace Cyberduck\LaravelWpApi;
use Illuminate\Support\ServiceProvider;
class LaravelWpApiServiceProvider extends ServiceProvider {
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = false;
/**
* Bootstrap the application events.
*
* @return void
*/
public function boot()
{
$this->publishes([
__DIR__.'/../../config/config.php' => config_path('wp-api.php'),
]);
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app->bindShared('wp-api', function ($app) {
$endpoint = $this->app['config']->get('wp-api.endpoint');
$auth = $this->app['config']->get('wp-api.auth');
$client = $this->app->make('GuzzleHttp\Client');
return new WpApi($endpoint, $client, $auth);
});
$this->app->bind('Cyberduck\LaravelWpApi\WpApi', function($app)
{
return $app['wp-api'];
});
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return ['wp-api'];
}
}

View file

@ -1,112 +0,0 @@
<?php namespace Cyberduck\LaravelWpApi;
use GuzzleHttp\Client;
class WpApi
{
protected $client;
public function __construct($endpoint, Client $client, $auth = null)
{
$this->endpoint = $endpoint;
$this->client = $client;
$this->auth = $auth;
}
public function posts($page = null)
{
return $this->_get('posts', ['page' => $page]);
}
public function pages($page = null)
{
return $this->_get('posts', ['type' => 'page', 'page' => $page]);
}
public function post($slug)
{
return $this->_get('posts', ['filter' => ['name' => $slug]]);
}
public function page($slug)
{
return $this->_get('posts', ['type' => 'page', 'filter' => ['name' => $slug]]);
}
public function categories()
{
return $this->_get('taxonomies/category/terms');
}
public function tags()
{
return $this->_get('taxonomies/post_tag/terms');
}
public function category_posts($slug, $page = null)
{
return $this->_get('posts', ['page' => $page, 'filter' => ['category_name' => $slug]]);
}
public function author_posts($name, $page = null)
{
return $this->_get('posts', ['page' => $page, 'filter' => ['author_name' => $name]]);
}
public function tag_posts($tags, $page = null)
{
return $this->_get('posts', ['page' => $page, 'filter' => ['tag' => $tags]]);
}
public function search($query, $page = null)
{
return $this->_get('posts', ['page' => $page, 'filter' => ['s' => $query]]);
}
public function archive($year, $month, $page = null)
{
return $this->_get('posts', ['page' => $page, 'filter' => ['year' => $year, 'monthnum' => $month]]);
}
public function _get($method, array $query = array())
{
try {
$query = ['query' => $query];
if($this->auth) {
$query['auth'] = $this->auth;
}
$response = $this->client->get($this->endpoint . '/wp-json/' . $method, $query);
$return = [
'results' => $response->json(),
'total' => $response->getHeader('X-WP-Total'),
'pages' => $response->getHeader('X-WP-TotalPages')
];
} catch (\GuzzleHttp\Exception\TransferException $e) {
$error['message'] = $e->getMessage();
if ($e->getResponse()) {
$error['code'] = $e->getResponse()->getStatusCode();
}
$return = [
'error' => $error,
'results' => [],
'total' => 0,
'pages' => 0
];
}
return $return;
}
}

View file

@ -0,0 +1,10 @@
<?php namespace Threesquared\LaravelWpApi\Facades;
use Illuminate\Support\Facades\Facade;
use Threesquared\LaravelWpApi\WpApi as WordpressApi;
class WpApi extends Facade {
protected static function getFacadeAccessor() { return WordpressApi::class; }
}

View file

@ -0,0 +1,54 @@
<?php namespace Threesquared\LaravelWpApi;
use Illuminate\Support\ServiceProvider;
class LaravelWpApiServiceProvider extends ServiceProvider
{
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = false;
/**
* Bootstrap the application events.
*
* @return void
*/
public function boot()
{
$this->publishes([
__DIR__.'/../../config/config.php' => config_path('wp-api.php'),
]);
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app->singleton(WpApi::class, function ($app) {
$endpoint = $this->app['config']->get('wp-api.endpoint');
$auth = $this->app['config']->get('wp-api.auth');
$client = $this->app->make('GuzzleHttp\Client');
return new WpApi($endpoint, $client, $auth);
});
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return ['wp-api'];
}
}

View file

@ -0,0 +1,223 @@
<?php namespace Threesquared\LaravelWpApi;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
class WpApi
{
/**
* Guzzle client
* @var Client
*/
protected $client;
/**
* WP-WPI endpoint URL
* @var string
*/
protected $endpoint;
/**
* Auth headers
* @var string
*/
protected $auth;
/**
* Constructor
*
* @param string $endpoint
* @param Client $client
* @param string $auth
*/
public function __construct($endpoint, Client $client, $auth = null)
{
$this->endpoint = $endpoint;
$this->client = $client;
$this->auth = $auth;
}
/**
* Get all posts
*
* @param int $page
* @return array
*/
public function posts($page = null)
{
return $this->get('posts', ['page' => $page]);
}
/**
* Get all pages
*
* @param int $page
* @return array
*/
public function pages($page = null)
{
return $this->get('posts', ['type' => 'page', 'page' => $page]);
}
/**
* Get post by id
*
* @param int $id
* @return array
*/
public function postId($id)
{
return $this->get("posts/$id");
}
/**
* Get post by slug
*
* @param string $slug
* @return array
*/
public function post($slug)
{
return $this->get('posts', ['filter' => ['name' => $slug]]);
}
/**
* Get page by slug
*
* @param string $slug
* @return array
*/
public function page($slug)
{
return $this->get('posts', ['type' => 'page', 'filter' => ['name' => $slug]]);
}
/**
* Get all categories
*
* @return array
*/
public function categories()
{
return $this->get('taxonomies/category/terms');
}
/**
* Get all tags
*
* @return array
*/
public function tags()
{
return $this->get('taxonomies/post_tag/terms');
}
/**
* Get posts from category
*
* @param string $slug
* @param int $page
* @return array
*/
public function categoryPosts($slug, $page = null)
{
return $this->get('posts', ['page' => $page, 'filter' => ['category_name' => $slug]]);
}
/**
* Get posts by author
*
* @param string $name
* @param int $page
* @return array
*/
public function authorPosts($name, $page = null)
{
return $this->get('posts', ['page' => $page, 'filter' => ['author_name' => $name]]);
}
/**
* Get posts tagged with tag
*
* @param string $tags
* @param int $page
* @return array
*/
public function tagPosts($tags, $page = null)
{
return $this->get('posts', ['page' => $page, 'filter' => ['tag' => $tags]]);
}
/**
* Search posts
*
* @param string $query
* @param int $page
* @return array
*/
public function search($query, $page = null)
{
return $this->get('posts', ['page' => $page, 'filter' => ['s' => $query]]);
}
/**
* Get posts by date
*
* @param int $year
* @param int $month
* @param int $page
* @return array
*/
public function archive($year, $month, $page = null)
{
return $this->get('posts', ['page' => $page, 'filter' => ['year' => $year, 'monthnum' => $month]]);
}
/**
* Get data from the API
*
* @param string $method
* @param array $query
* @return array
*/
public function get($method, array $query = array())
{
try {
$query = ['query' => $query];
if ($this->auth) {
$query['auth'] = $this->auth;
}
$response = $this->client->get($this->endpoint . $method, $query);
$return = [
'results' => json_decode((string) $response->getBody(), true),
'total' => $response->getHeaderLine('X-WP-Total'),
'pages' => $response->getHeaderLine('X-WP-TotalPages')
];
} catch (RequestException $e) {
$error['message'] = $e->getMessage();
if ($e->getResponse()) {
$error['code'] = $e->getResponse()->getStatusCode();
}
$return = [
'error' => $error,
'results' => [],
'total' => 0,
'pages' => 0
];
}
return $return;
}
}

View file

@ -2,6 +2,6 @@
return array( return array(
'endpoint' => '<WP_LOCATION>', 'endpoint' => 'http://<WP_LOCATION>/wp-json/',
); );

43
tests/GetTest.php Normal file
View file

@ -0,0 +1,43 @@
<?php
use Threesquared\LaravelWpApi\WpApi;
use GuzzleHttp\Client;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Psr7\Response;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Exception\RequestException;
class GetTest extends PHPUnit_Framework_TestCase {
protected static $wp;
public static function setUpBeforeClass()
{
$mock = new MockHandler([
new Response(200, ['X-WP-Total' => 2, 'X-WP-TotalPages' => 1], json_encode(['posts' => []])),
new RequestException('Error Communicating with Server', new Request('GET', 'test'))
]);
$handler = HandlerStack::create($mock);
$client = new Client(['handler' => $handler]);
self::$wp = new WpApi('http://test.dev/wp-api', $client);
}
public function testCanFetchPosts()
{
$response = self::$wp->posts();
$this->assertEquals($response['results'], ['posts' => []]);
$this->assertEquals($response['total'], 2);
$this->assertEquals($response['pages'], 1);
}
public function testCanHandlerError()
{
$response = self::$wp->posts();
$this->assertEquals($response['error']['message'], 'Error Communicating with Server');
}
}