Merge branch '1.0'

This commit is contained in:
Robbie Averill 2017-11-17 14:59:38 +13:00
commit e5a757d589
4 changed files with 190 additions and 157 deletions

View File

@ -4,22 +4,16 @@ sudo: false
language: php language: php
php:
- 5.3
- 5.4
- 5.5
env:
- DB=MYSQL CORE_RELEASE=3.5
matrix: matrix:
include: include:
- php: 5.4
env: DB=MYSQL CORE_RELEASE=3.3
- php: 5.5
env: DB=MYSQL CORE_RELEASE=3.4
- php: 5.6 - php: 5.6
env: DB=PGSQL CORE_RELEASE=3.5
- php: 7.0
env: DB=MYSQL CORE_RELEASE=3 env: DB=MYSQL CORE_RELEASE=3
- php: 5.6
env: DB=MYSQL CORE_RELEASE=3.1
- php: 5.6
env: DB=PGSQL CORE_RELEASE=3.2
- php: 7.1 - php: 7.1
env: DB=MYSQL CORE_RELEASE=3.6 env: DB=MYSQL CORE_RELEASE=3.6

View File

@ -3,26 +3,26 @@
* Generic RESTful server, which handles webservice access to arbitrary DataObjects. * Generic RESTful server, which handles webservice access to arbitrary DataObjects.
* Relies on serialization/deserialization into different formats provided * Relies on serialization/deserialization into different formats provided
* by the DataFormatter APIs in core. * by the DataFormatter APIs in core.
* *
* @todo Finish RestfulServer_Item and RestfulServer_List implementation and re-enable $url_handlers * @todo Finish RestfulServer_Item and RestfulServer_List implementation and re-enable $url_handlers
* @todo Implement PUT/POST/DELETE for relations * @todo Implement PUT/POST/DELETE for relations
* @todo Access-Control for relations (you might be allowed to view Members and Groups, * @todo Access-Control for relations (you might be allowed to view Members and Groups,
* but not their relation with each other) * but not their relation with each other)
* @todo Make SearchContext specification customizeable for each class * @todo Make SearchContext specification customizeable for each class
* @todo Allow for range-searches (e.g. on Created column) * @todo Allow for range-searches (e.g. on Created column)
* @todo Filter relation listings by $api_access and canView() permissions * @todo Filter relation listings by $api_access and canView() permissions
* @todo Exclude relations when "fields" are specified through URL (they should be explicitly * @todo Exclude relations when "fields" are specified through URL (they should be explicitly
* requested in this case) * requested in this case)
* @todo Custom filters per DataObject subclass, e.g. to disallow showing unpublished pages in * @todo Custom filters per DataObject subclass, e.g. to disallow showing unpublished pages in
* SiteTree/Versioned/Hierarchy * SiteTree/Versioned/Hierarchy
* @todo URL parameter namespacing for search-fields, limit, fields, add_fields * @todo URL parameter namespacing for search-fields, limit, fields, add_fields
* (might all be valid dataobject properties) * (might all be valid dataobject properties)
* e.g. you wouldn't be able to search for a "limit" property on your subclass as * e.g. you wouldn't be able to search for a "limit" property on your subclass as
* its overlayed with the search logic * its overlayed with the search logic
* @todo i18n integration (e.g. Page/1.xml?lang=de_DE) * @todo i18n integration (e.g. Page/1.xml?lang=de_DE)
* @todo Access to extendable methods/relations like SiteTree/1/Versions or SiteTree/1/Version/22 * @todo Access to extendable methods/relations like SiteTree/1/Versions or SiteTree/1/Version/22
* @todo Respect $api_access array notation in search contexts * @todo Respect $api_access array notation in search contexts
* *
* @package framework * @package framework
* @subpackage api * @subpackage api
*/ */
@ -45,24 +45,24 @@ class RestfulServer extends Controller
* @var string * @var string
*/ */
public static $default_extension = "xml"; public static $default_extension = "xml";
/** /**
* If no extension is given, resolve the request to this mimetype. * If no extension is given, resolve the request to this mimetype.
* *
* @var string * @var string
*/ */
protected static $default_mimetype = "text/xml"; protected static $default_mimetype = "text/xml";
/** /**
* @uses authenticate() * @uses authenticate()
* @var Member * @var Member
*/ */
protected $member; protected $member;
public static $allowed_actions = array( public static $allowed_actions = array(
'index' 'index'
); );
/* /*
function handleItem($request) { function handleItem($request) {
return new RestfulServer_Item(DataObject::get_by_id($request->param("ClassName"), $request->param("ID"))); return new RestfulServer_Item(DataObject::get_by_id($request->param("ClassName"), $request->param("ID")));
@ -97,7 +97,7 @@ class RestfulServer extends Controller
$className = $this->urlParams['ClassName']; $className = $this->urlParams['ClassName'];
$id = (isset($this->urlParams['ID'])) ? $this->urlParams['ID'] : null; $id = (isset($this->urlParams['ID'])) ? $this->urlParams['ID'] : null;
$relation = (isset($this->urlParams['Relation'])) ? $this->urlParams['Relation'] : null; $relation = (isset($this->urlParams['Relation'])) ? $this->urlParams['Relation'] : null;
// Check input formats // Check input formats
if (!class_exists($className)) { if (!class_exists($className)) {
return $this->notFound(); return $this->notFound();
@ -111,7 +111,7 @@ class RestfulServer extends Controller
) { ) {
return $this->notFound(); return $this->notFound();
} }
// if api access is disabled, don't proceed // if api access is disabled, don't proceed
$apiAccess = singleton($className)->stat('api_access'); $apiAccess = singleton($className)->stat('api_access');
if (!$apiAccess) { if (!$apiAccess) {
@ -125,11 +125,11 @@ class RestfulServer extends Controller
if ($this->request->isGET() || $this->request->isHEAD()) { if ($this->request->isGET() || $this->request->isHEAD()) {
return $this->getHandler($className, $id, $relation); return $this->getHandler($className, $id, $relation);
} }
if ($this->request->isPOST()) { if ($this->request->isPOST()) {
return $this->postHandler($className, $id, $relation); return $this->postHandler($className, $id, $relation);
} }
if ($this->request->isPUT()) { if ($this->request->isPUT()) {
return $this->putHandler($className, $id, $relation); return $this->putHandler($className, $id, $relation);
} }
@ -141,10 +141,10 @@ class RestfulServer extends Controller
// if no HTTP verb matches, return error // if no HTTP verb matches, return error
return $this->methodNotAllowed(); return $this->methodNotAllowed();
} }
/** /**
* Handler for object read. * Handler for object read.
* *
* The data object will be returned in the following format: * The data object will be returned in the following format:
* *
* <ClassName> * <ClassName>
@ -164,12 +164,12 @@ class RestfulServer extends Controller
* </ClassName> * </ClassName>
* *
* Access is controlled by two variables: * Access is controlled by two variables:
* *
* - static $api_access must be set. This enables the API on a class by class basis * - static $api_access must be set. This enables the API on a class by class basis
* - $obj->canView() must return true. This lets you implement record-level security * - $obj->canView() must return true. This lets you implement record-level security
* *
* @todo Access checking * @todo Access checking
* *
* @param String $className * @param String $className
* @param Int $id * @param Int $id
* @param String $relation * @param String $relation
@ -178,24 +178,24 @@ class RestfulServer extends Controller
protected function getHandler($className, $id, $relationName) protected function getHandler($className, $id, $relationName)
{ {
$sort = ''; $sort = '';
if ($this->request->getVar('sort')) { if ($this->request->getVar('sort')) {
$dir = $this->request->getVar('dir'); $dir = $this->request->getVar('dir');
$sort = array($this->request->getVar('sort') => ($dir ? $dir : 'ASC')); $sort = array($this->request->getVar('sort') => ($dir ? $dir : 'ASC'));
} }
$limit = array( $limit = array(
'start' => $this->request->getVar('start'), 'start' => $this->request->getVar('start'),
'limit' => $this->request->getVar('limit') 'limit' => $this->request->getVar('limit')
); );
$params = $this->request->getVars(); $params = $this->request->getVars();
$responseFormatter = $this->getResponseDataFormatter($className); $responseFormatter = $this->getResponseDataFormatter($className);
if (!$responseFormatter) { if (!$responseFormatter) {
return $this->unsupportedMediaType(); return $this->unsupportedMediaType();
} }
// $obj can be either a DataObject or a SS_List, // $obj can be either a DataObject or a SS_List,
// depending on the request // depending on the request
if ($id) { if ($id) {
@ -204,7 +204,7 @@ class RestfulServer extends Controller
if (!$obj) { if (!$obj) {
return $this->notFound(); return $this->notFound();
} }
if (!$obj->canView()) { if (!$obj->canView($this->getMember())) {
return $this->permissionFailure(); return $this->permissionFailure();
} }
@ -214,7 +214,7 @@ class RestfulServer extends Controller
if (!$obj) { if (!$obj) {
return $this->notFound(); return $this->notFound();
} }
// TODO Avoid creating data formatter again for relation class (see above) // TODO Avoid creating data formatter again for relation class (see above)
$responseFormatter = $this->getResponseDataFormatter($obj->dataClass()); $responseFormatter = $this->getResponseDataFormatter($obj->dataClass());
} }
@ -222,35 +222,37 @@ class RestfulServer extends Controller
// Format: /api/v1/<MyClass> // Format: /api/v1/<MyClass>
$obj = $this->getObjectsQuery($className, $params, $sort, $limit); $obj = $this->getObjectsQuery($className, $params, $sort, $limit);
} }
$this->getResponse()->addHeader('Content-Type', $responseFormatter->getOutputContentType()); $this->getResponse()->addHeader('Content-Type', $responseFormatter->getOutputContentType());
$rawFields = $this->request->getVar('fields'); $rawFields = $this->request->getVar('fields');
$fields = $rawFields ? explode(',', $rawFields) : null; $fields = $rawFields ? explode(',', $rawFields) : null;
if ($obj instanceof SS_List) { if ($obj instanceof SS_List) {
$responseFormatter->setTotalSize($obj->dataQuery()->query()->unlimitedRowCount()); $objs = ArrayList::create($obj->toArray());
$objs = new ArrayList($obj->toArray());
foreach ($objs as $obj) { foreach ($objs as $obj) {
if (!$obj->canView()) { if (!$obj->canView($this->getMember())) {
$objs->remove($obj); $objs->remove($obj);
} }
} }
$responseFormatter->setTotalSize($objs->count());
return $responseFormatter->convertDataObjectSet($objs, $fields); return $responseFormatter->convertDataObjectSet($objs, $fields);
} elseif (!$obj) { }
if (!$obj) {
$responseFormatter->setTotalSize(0); $responseFormatter->setTotalSize(0);
return $responseFormatter->convertDataObjectSet(new ArrayList(), $fields); return $responseFormatter->convertDataObjectSet(new ArrayList(), $fields);
} else {
return $responseFormatter->convertDataObject($obj, $fields);
} }
return $responseFormatter->convertDataObject($obj, $fields);
} }
/** /**
* Uses the default {@link SearchContext} specified through * Uses the default {@link SearchContext} specified through
* {@link DataObject::getDefaultSearchContext()} to augument * {@link DataObject::getDefaultSearchContext()} to augument
* an existing query object (mostly a component query from {@link DataObject}) * an existing query object (mostly a component query from {@link DataObject})
* with search clauses. * with search clauses.
* *
* @todo Allow specifying of different searchcontext getters on model-by-model basis * @todo Allow specifying of different searchcontext getters on model-by-model basis
* *
* @param string $className * @param string $className
@ -267,12 +269,12 @@ class RestfulServer extends Controller
} }
return $searchContext->getQuery($params, $sort, $limit, $existingQuery); return $searchContext->getQuery($params, $sort, $limit, $existingQuery);
} }
/** /**
* Returns a dataformatter instance based on the request * Returns a dataformatter instance based on the request
* extension or mimetype. Falls back to {@link self::$default_extension}. * extension or mimetype. Falls back to {@link self::$default_extension}.
* *
* @param boolean $includeAcceptHeader Determines wether to inspect and prioritize any HTTP Accept headers * @param boolean $includeAcceptHeader Determines wether to inspect and prioritize any HTTP Accept headers
* @param String Classname of a DataObject * @param String Classname of a DataObject
* @return DataFormatter * @return DataFormatter
*/ */
@ -305,7 +307,7 @@ class RestfulServer extends Controller
if (!$formatter) { if (!$formatter) {
return false; return false;
} }
// set custom fields // set custom fields
if ($customAddFields = $this->request->getVar('add_fields')) { if ($customAddFields = $this->request->getVar('add_fields')) {
$formatter->setCustomAddFields(explode(',', $customAddFields)); $formatter->setCustomAddFields(explode(',', $customAddFields));
@ -314,7 +316,7 @@ class RestfulServer extends Controller
$formatter->setCustomFields(explode(',', $customFields)); $formatter->setCustomFields(explode(',', $customFields));
} }
$formatter->setCustomRelations($this->getAllowedRelations($className)); $formatter->setCustomRelations($this->getAllowedRelations($className));
$apiAccess = singleton($className)->stat('api_access'); $apiAccess = singleton($className)->stat('api_access');
if (is_array($apiAccess)) { if (is_array($apiAccess)) {
$formatter->setCustomAddFields( $formatter->setCustomAddFields(
@ -341,10 +343,10 @@ class RestfulServer extends Controller
if (is_numeric($relationDepth)) { if (is_numeric($relationDepth)) {
$formatter->relationDepth = (int)$relationDepth; $formatter->relationDepth = (int)$relationDepth;
} }
return $formatter; return $formatter;
} }
/** /**
* @param String Classname of a DataObject * @param String Classname of a DataObject
* @return DataFormatter * @return DataFormatter
@ -353,7 +355,7 @@ class RestfulServer extends Controller
{ {
return $this->getDataFormatter(false, $className); return $this->getDataFormatter(false, $className);
} }
/** /**
* @param String Classname of a DataObject * @param String Classname of a DataObject
* @return DataFormatter * @return DataFormatter
@ -362,7 +364,7 @@ class RestfulServer extends Controller
{ {
return $this->getDataFormatter(true, $className); return $this->getDataFormatter(true, $className);
} }
/** /**
* Handler for object delete * Handler for object delete
*/ */
@ -372,12 +374,12 @@ class RestfulServer extends Controller
if (!$obj) { if (!$obj) {
return $this->notFound(); return $this->notFound();
} }
if (!$obj->canDelete()) { if (!$obj->canDelete($this->getMember())) {
return $this->permissionFailure(); return $this->permissionFailure();
} }
$obj->delete(); $obj->delete();
$this->getResponse()->setStatusCode(204); // No Content $this->getResponse()->setStatusCode(204); // No Content
return true; return true;
} }
@ -391,22 +393,26 @@ class RestfulServer extends Controller
if (!$obj) { if (!$obj) {
return $this->notFound(); return $this->notFound();
} }
if (!$obj->canEdit()) { if (!$obj->canEdit($this->getMember())) {
return $this->permissionFailure(); return $this->permissionFailure();
} }
$reqFormatter = $this->getRequestDataFormatter($className); $reqFormatter = $this->getRequestDataFormatter($className);
if (!$reqFormatter) { if (!$reqFormatter) {
return $this->unsupportedMediaType(); return $this->unsupportedMediaType();
} }
$responseFormatter = $this->getResponseDataFormatter($className); $responseFormatter = $this->getResponseDataFormatter($className);
if (!$responseFormatter) { if (!$responseFormatter) {
return $this->unsupportedMediaType(); return $this->unsupportedMediaType();
} }
/** @var DataObject|string */
$obj = $this->updateDataObject($obj, $reqFormatter); $obj = $this->updateDataObject($obj, $reqFormatter);
if (is_string($obj)) {
return $obj;
}
$this->getResponse()->setStatusCode(200); // Success $this->getResponse()->setStatusCode(200); // Success
$this->getResponse()->addHeader('Content-Type', $responseFormatter->getOutputContentType()); $this->getResponse()->addHeader('Content-Type', $responseFormatter->getOutputContentType());
@ -420,13 +426,13 @@ class RestfulServer extends Controller
$objHref = Director::absoluteURL(self::$api_base . "$obj->class/$obj->ID" . $type); $objHref = Director::absoluteURL(self::$api_base . "$obj->class/$obj->ID" . $type);
$this->getResponse()->addHeader('Location', $objHref); $this->getResponse()->addHeader('Location', $objHref);
return $responseFormatter->convertDataObject($obj); return $responseFormatter->convertDataObject($obj);
} }
/** /**
* Handler for object append / method call. * Handler for object append / method call.
* *
* @todo Posting to an existing URL (without a relation) * @todo Posting to an existing URL (without a relation)
* current resolves in creatig a new element, * current resolves in creatig a new element,
* rather than a "Conflict" message. * rather than a "Conflict" message.
@ -438,57 +444,61 @@ class RestfulServer extends Controller
$this->response->setStatusCode(409); $this->response->setStatusCode(409);
return 'Conflict'; return 'Conflict';
} }
$obj = DataObject::get_by_id($className, $id); $obj = DataObject::get_by_id($className, $id);
if (!$obj) { if (!$obj) {
return $this->notFound(); return $this->notFound();
} }
if (!$obj->hasMethod($relation)) { if (!$obj->hasMethod($relation)) {
return $this->notFound(); return $this->notFound();
} }
if (!$obj->stat('allowed_actions') || !in_array($relation, $obj->stat('allowed_actions'))) { if (!$obj->stat('allowed_actions') || !in_array($relation, $obj->stat('allowed_actions'))) {
return $this->permissionFailure(); return $this->permissionFailure();
} }
$obj->$relation(); $obj->$relation();
$this->getResponse()->setStatusCode(204); // No Content $this->getResponse()->setStatusCode(204); // No Content
return true; return true;
} else {
if (!singleton($className)->canCreate()) {
return $this->permissionFailure();
}
$obj = new $className();
$reqFormatter = $this->getRequestDataFormatter($className);
if (!$reqFormatter) {
return $this->unsupportedMediaType();
}
$responseFormatter = $this->getResponseDataFormatter($className);
$obj = $this->updateDataObject($obj, $reqFormatter);
$this->getResponse()->setStatusCode(201); // Created
$this->getResponse()->addHeader('Content-Type', $responseFormatter->getOutputContentType());
// Append the default extension for the output format to the Location header
// or else we'll use the default (XML)
$types = $responseFormatter->supportedExtensions();
$type = '';
if (count($types)) {
$type = ".{$types[0]}";
}
$objHref = Director::absoluteURL(self::$api_base . "$obj->class/$obj->ID" . $type);
$this->getResponse()->addHeader('Location', $objHref);
return $responseFormatter->convertDataObject($obj);
} }
if (!singleton($className)->canCreate($this->getMember())) {
return $this->permissionFailure();
}
$obj = new $className();
$reqFormatter = $this->getRequestDataFormatter($className);
if (!$reqFormatter) {
return $this->unsupportedMediaType();
}
$responseFormatter = $this->getResponseDataFormatter($className);
/** @var DataObject|string $obj */
$obj = $this->updateDataObject($obj, $reqFormatter);
if (is_string($obj)) {
return $obj;
}
$this->getResponse()->setStatusCode(201); // Created
$this->getResponse()->addHeader('Content-Type', $responseFormatter->getOutputContentType());
// Append the default extension for the output format to the Location header
// or else we'll use the default (XML)
$types = $responseFormatter->supportedExtensions();
$type = '';
if (count($types)) {
$type = ".{$types[0]}";
}
$objHref = Director::absoluteURL(self::$api_base . "$obj->class/$obj->ID" . $type);
$this->getResponse()->addHeader('Location', $objHref);
return $responseFormatter->convertDataObject($obj);
} }
/** /**
* Converts either the given HTTP Body into an array * Converts either the given HTTP Body into an array
* (based on the DataFormatter instance), or returns * (based on the DataFormatter instance), or returns
@ -498,7 +508,7 @@ class RestfulServer extends Controller
* *
* @param DataObject $obj * @param DataObject $obj
* @param DataFormatter $formatter * @param DataFormatter $formatter
* @return DataObject The passed object * @return DataObject|string The passed object, or "No Content" if incomplete input data is provided
*/ */
protected function updateDataObject($obj, $formatter) protected function updateDataObject($obj, $formatter)
{ {
@ -508,17 +518,17 @@ class RestfulServer extends Controller
$this->getResponse()->setStatusCode(204); // No Content $this->getResponse()->setStatusCode(204); // No Content
return 'No Content'; return 'No Content';
} }
if (!empty($body)) { if (!empty($body)) {
$data = $formatter->convertStringToArray($body); $data = $formatter->convertStringToArray($body);
} else { } else {
// assume application/x-www-form-urlencoded which is automatically parsed by PHP // assume application/x-www-form-urlencoded which is automatically parsed by PHP
$data = $this->request->postVars(); $data = $this->request->postVars();
} }
// @todo Disallow editing of certain keys in database // @todo Disallow editing of certain keys in database
$data = array_diff_key($data, array('ID', 'Created')); $data = array_diff_key($data, array('ID', 'Created'));
$apiAccess = singleton($this->urlParams['ClassName'])->stat('api_access'); $apiAccess = singleton($this->urlParams['ClassName'])->stat('api_access');
if (is_array($apiAccess) && isset($apiAccess['edit'])) { if (is_array($apiAccess) && isset($apiAccess['edit'])) {
$data = array_intersect_key($data, array_combine($apiAccess['edit'], $apiAccess['edit'])); $data = array_intersect_key($data, array_combine($apiAccess['edit'], $apiAccess['edit']));
@ -526,14 +536,14 @@ class RestfulServer extends Controller
$obj->update($data); $obj->update($data);
$obj->write(); $obj->write();
return $obj; return $obj;
} }
/** /**
* Gets a single DataObject by ID, * Gets a single DataObject by ID,
* through a request like /api/v1/<MyClass>/<MyID> * through a request like /api/v1/<MyClass>/<MyID>
* *
* @param string $className * @param string $className
* @param int $id * @param int $id
* @param array $params * @param array $params
@ -543,7 +553,7 @@ class RestfulServer extends Controller
{ {
return DataList::create($className)->byIDs(array($id)); return DataList::create($className)->byIDs(array($id));
} }
/** /**
* @param DataObject $obj * @param DataObject $obj
* @param array $params * @param array $params
@ -555,8 +565,8 @@ class RestfulServer extends Controller
{ {
return $this->getSearchQuery($className, $params, $sort, $limit); return $this->getSearchQuery($className, $params, $sort, $limit);
} }
/** /**
* @param DataObject $obj * @param DataObject $obj
* @param array $params * @param array $params
@ -575,16 +585,16 @@ class RestfulServer extends Controller
} else { } else {
$list = $obj->$relationName(); $list = $obj->$relationName();
} }
$apiAccess = singleton($list->dataClass())->stat('api_access'); $apiAccess = singleton($list->dataClass())->stat('api_access');
if (!$apiAccess) { if (!$apiAccess) {
return false; return false;
} }
return $this->getSearchQuery($list->dataClass(), $params, $sort, $limit, $list); return $this->getSearchQuery($list->dataClass(), $params, $sort, $limit, $list);
} }
} }
protected function permissionFailure() protected function permissionFailure()
{ {
// return a 401 // return a 401
@ -601,21 +611,21 @@ class RestfulServer extends Controller
$this->getResponse()->addHeader('Content-Type', 'text/plain'); $this->getResponse()->addHeader('Content-Type', 'text/plain');
return "That object wasn't found"; return "That object wasn't found";
} }
protected function methodNotAllowed() protected function methodNotAllowed()
{ {
$this->getResponse()->setStatusCode(405); $this->getResponse()->setStatusCode(405);
$this->getResponse()->addHeader('Content-Type', 'text/plain'); $this->getResponse()->addHeader('Content-Type', 'text/plain');
return "Method Not Allowed"; return "Method Not Allowed";
} }
protected function unsupportedMediaType() protected function unsupportedMediaType()
{ {
$this->response->setStatusCode(415); // Unsupported Media Type $this->response->setStatusCode(415); // Unsupported Media Type
$this->getResponse()->addHeader('Content-Type', 'text/plain'); $this->getResponse()->addHeader('Content-Type', 'text/plain');
return "Unsupported Media Type"; return "Unsupported Media Type";
} }
/** /**
* A function to authenticate a user * A function to authenticate a user
* *
@ -626,11 +636,11 @@ class RestfulServer extends Controller
$authClass = self::config()->authenticator; $authClass = self::config()->authenticator;
return $authClass::authenticate(); return $authClass::authenticate();
} }
/** /**
* Return only relations which have $api_access enabled. * Return only relations which have $api_access enabled.
* @todo Respect field level permissions once they are available in core * @todo Respect field level permissions once they are available in core
* *
* @param string $class * @param string $class
* @param Member $member * @param Member $member
* @return array * @return array
@ -649,11 +659,21 @@ class RestfulServer extends Controller
} }
return $allowedRelations; return $allowedRelations;
} }
/**
* Get the current Member, if available
*
* @return Member|null
*/
protected function getMember()
{
return Member::currentUser();
}
} }
/** /**
* Restful server handler for a SS_List * Restful server handler for a SS_List
* *
* @package framework * @package framework
* @subpackage api * @subpackage api
*/ */
@ -667,7 +687,7 @@ class RestfulServer_List
{ {
$this->list = $list; $this->list = $list;
} }
public function handleItem($request) public function handleItem($request)
{ {
return new RestulServer_Item($this->list->getById($request->param('ID'))); return new RestulServer_Item($this->list->getById($request->param('ID')));
@ -676,7 +696,7 @@ class RestfulServer_List
/** /**
* Restful server handler for a single DataObject * Restful server handler for a single DataObject
* *
* @package framework * @package framework
* @subpackage api * @subpackage api
*/ */
@ -690,7 +710,7 @@ class RestfulServer_Item
{ {
$this->item = $item; $this->item = $item;
} }
public function handleRelation($request) public function handleRelation($request)
{ {
$funcName = $request('Relation'); $funcName = $request('Relation');

View File

@ -1,28 +1,29 @@
{ {
"name": "silverstripe/restfulserver", "name": "silverstripe/restfulserver",
"description": "Add a RESTful API to your SilverStripe application", "description": "Add a RESTful API to your SilverStripe application",
"type": "silverstripe-module", "type": "silverstripe-module",
"keywords": ["silverstripe", "rest", "api"], "keywords": [
"authors": [ "silverstripe",
{ "rest",
"name": "Hamish Friedlander", "api"
"email": "hamish@silverstripe.com" ],
}, "authors": [
{ {
"name": "Sam Minnee", "name": "Hamish Friedlander",
"email": "sam@silverstripe.com" "email": "hamish@silverstripe.com"
} },
], {
"require": "name": "Sam Minnee",
{ "email": "sam@silverstripe.com"
"silverstripe/framework": "3.*" }
}, ],
"extra": "require": {
{ "silverstripe/framework": "3.*"
"branch-alias": },
{ "extra": {
"dev-master": "1.0.x-dev" "branch-alias": {
} "dev-master": "1.1.x-dev"
}, }
"license": "BSD-3-Clause" },
"license": "BSD-3-Clause"
} }

View File

@ -188,18 +188,31 @@ class RestfulServerTest extends SapphireTest
$response->getHeader('Location'), $response->getHeader('Location'),
Controller::join_links(Director::absoluteBaseURL(), $url, $responseArr['ID']) Controller::join_links(Director::absoluteBaseURL(), $url, $responseArr['ID'])
); );
unset($_SERVER['PHP_AUTH_USER']); unset($_SERVER['PHP_AUTH_USER']);
unset($_SERVER['PHP_AUTH_PW']); unset($_SERVER['PHP_AUTH_PW']);
} }
public function testPostWithoutBodyReturnsNoContent()
{
$_SERVER['PHP_AUTH_USER'] = 'editor@test.com';
$_SERVER['PHP_AUTH_PW'] = 'editor';
$url = '/api/v1/RestfulServerTest_Comment';
$response = Director::test($url, null, null, 'POST');
$this->assertEquals('No Content', $response->getBody());
unset($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']);
}
public function testPUTwithJSON() public function testPUTwithJSON()
{ {
$comment1 = $this->objFromFixture('RestfulServerTest_Comment', 'comment1'); $comment1 = $this->objFromFixture('RestfulServerTest_Comment', 'comment1');
$_SERVER['PHP_AUTH_USER'] = 'editor@test.com'; $_SERVER['PHP_AUTH_USER'] = 'editor@test.com';
$_SERVER['PHP_AUTH_PW'] = 'editor'; $_SERVER['PHP_AUTH_PW'] = 'editor';
// by mimetype // by mimetype
$url = "/api/v1/RestfulServerTest_Comment/" . $comment1->ID; $url = "/api/v1/RestfulServerTest_Comment/" . $comment1->ID;
$body = '{"Comment":"updated"}'; $body = '{"Comment":"updated"}';
@ -463,6 +476,8 @@ class RestfulServerTest extends SapphireTest
$response = Director::test($url, null, null, 'GET'); $response = Director::test($url, null, null, 'GET');
$this->assertEquals($response->getStatusCode(), 200); $this->assertEquals($response->getStatusCode(), 200);
$this->assertNotContains('Unspeakable', $response->getBody()); $this->assertNotContains('Unspeakable', $response->getBody());
$responseArray = Convert::json2array($response->getBody());
$this->assertSame(0, $responseArray['totalSize']);
// With authentication // With authentication
$_SERVER['PHP_AUTH_USER'] = 'editor@test.com'; $_SERVER['PHP_AUTH_USER'] = 'editor@test.com';
@ -471,6 +486,9 @@ class RestfulServerTest extends SapphireTest
$response = Director::test($url, null, null, 'GET'); $response = Director::test($url, null, null, 'GET');
$this->assertEquals($response->getStatusCode(), 200); $this->assertEquals($response->getStatusCode(), 200);
$this->assertContains('Unspeakable', $response->getBody()); $this->assertContains('Unspeakable', $response->getBody());
// Assumption: default formatter is XML
$responseArray = Convert::xml2array($response->getBody());
$this->assertEquals(1, $responseArray['@attributes']['totalSize']);
unset($_SERVER['PHP_AUTH_USER']); unset($_SERVER['PHP_AUTH_USER']);
unset($_SERVER['PHP_AUTH_PW']); unset($_SERVER['PHP_AUTH_PW']);
} }