Merge pull request #26 from helpfulrobot/convert-to-psr-2

Converted to PSR-2
This commit is contained in:
Daniel Hensby 2015-11-24 14:14:21 +00:00
commit 90de9c2260
5 changed files with 1279 additions and 1165 deletions

View File

@ -8,32 +8,34 @@
* application accessing the RestfulServer to store logins in plain text (or in * application accessing the RestfulServer to store logins in plain text (or in
* decrytable form) * decrytable form)
*/ */
class BasicRestfulAuthenticator { class BasicRestfulAuthenticator
{
/**
* The authenticate function
*
* Takes the basic auth details and attempts to log a user in from the DB
*
* @return Member|false The Member object, or false if no member
*/
public static function authenticate()
{
//if there is no username or password, break
if (!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW'])) {
return false;
}
/** //Attempt to authenticate with the default authenticator for the site
* The authenticate function $authClass = Authenticator::get_default_authenticator();
* $member = $authClass::authenticate(array(
* Takes the basic auth details and attempts to log a user in from the DB 'Email' => $_SERVER['PHP_AUTH_USER'],
* 'Password' => $_SERVER['PHP_AUTH_PW'],
* @return Member|false The Member object, or false if no member ));
*/
public static function authenticate() {
//if there is no username or password, break
if(!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW'])) return false;
//Attempt to authenticate with the default authenticator for the site
$authClass = Authenticator::get_default_authenticator();
$member = $authClass::authenticate(array(
'Email' => $_SERVER['PHP_AUTH_USER'],
'Password' => $_SERVER['PHP_AUTH_PW'],
));
//Log the member in and return the member, if they were found
if($member) {
$member->LogIn(false);
return $member;
}
return false;
}
//Log the member in and return the member, if they were found
if ($member) {
$member->LogIn(false);
return $member;
}
return false;
}
} }

View File

@ -26,560 +26,629 @@
* @package framework * @package framework
* @subpackage api * @subpackage api
*/ */
class RestfulServer extends Controller { class RestfulServer extends Controller
static $url_handlers = array( {
'$ClassName/$ID/$Relation' => 'handleAction' public static $url_handlers = array(
#'$ClassName/#ID' => 'handleItem', '$ClassName/$ID/$Relation' => 'handleAction'
#'$ClassName' => 'handleList', #'$ClassName/#ID' => 'handleItem',
); #'$ClassName' => 'handleList',
);
protected static $api_base = "api/v1/";
protected static $api_base = "api/v1/";
protected static $authenticator = 'BasicRestfulAuthenticator';
protected static $authenticator = 'BasicRestfulAuthenticator';
/**
* If no extension is given in the request, resolve to this extension /**
* (and subsequently the {@link self::$default_mimetype}. * If no extension is given in the request, resolve to this extension
* * (and subsequently the {@link self::$default_mimetype}.
* @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() /**
* @var Member * @uses authenticate()
*/ * @var Member
protected $member; */
protected $member;
public static $allowed_actions = array(
'index' public static $allowed_actions = array(
); 'index'
);
/*
function handleItem($request) { /*
return new RestfulServer_Item(DataObject::get_by_id($request->param("ClassName"), $request->param("ID"))); function handleItem($request) {
} return new RestfulServer_Item(DataObject::get_by_id($request->param("ClassName"), $request->param("ID")));
}
function handleList($request) {
return new RestfulServer_List(DataObject::get($request->param("ClassName"),"")); function handleList($request) {
} return new RestfulServer_List(DataObject::get($request->param("ClassName"),""));
*/ }
*/
function init() {
/* This sets up SiteTree the same as when viewing a page through the frontend. Versioned defaults public function init()
* to Stage, and then when viewing the front-end Versioned::choose_site_stage changes it to Live. {
* TODO: In 3.2 we should make the default Live, then change to Stage in the admin area (with a nicer API) /* This sets up SiteTree the same as when viewing a page through the frontend. Versioned defaults
*/ * to Stage, and then when viewing the front-end Versioned::choose_site_stage changes it to Live.
if (class_exists('SiteTree')) singleton('SiteTree')->extend('modelascontrollerInit', $this); * TODO: In 3.2 we should make the default Live, then change to Stage in the admin area (with a nicer API)
parent::init(); */
} if (class_exists('SiteTree')) {
singleton('SiteTree')->extend('modelascontrollerInit', $this);
/** }
* This handler acts as the switchboard for the controller. parent::init();
* Since no $Action url-param is set, all requests are sent here. }
*/
function index() { /**
if(!isset($this->urlParams['ClassName'])) return $this->notFound(); * This handler acts as the switchboard for the controller.
$className = $this->urlParams['ClassName']; * Since no $Action url-param is set, all requests are sent here.
$id = (isset($this->urlParams['ID'])) ? $this->urlParams['ID'] : null; */
$relation = (isset($this->urlParams['Relation'])) ? $this->urlParams['Relation'] : null; public function index()
{
// Check input formats if (!isset($this->urlParams['ClassName'])) {
if(!class_exists($className)) return $this->notFound(); return $this->notFound();
if($id && !is_numeric($id)) return $this->notFound(); }
if( $className = $this->urlParams['ClassName'];
$relation $id = (isset($this->urlParams['ID'])) ? $this->urlParams['ID'] : null;
&& !preg_match('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/', $relation) $relation = (isset($this->urlParams['Relation'])) ? $this->urlParams['Relation'] : null;
) {
return $this->notFound(); // Check input formats
} if (!class_exists($className)) {
return $this->notFound();
// if api access is disabled, don't proceed }
$apiAccess = singleton($className)->stat('api_access'); if ($id && !is_numeric($id)) {
if(!$apiAccess) return $this->permissionFailure(); return $this->notFound();
}
// authenticate through HTTP BasicAuth if (
$this->member = $this->authenticate(); $relation
&& !preg_match('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/', $relation)
// handle different HTTP verbs ) {
if($this->request->isGET() || $this->request->isHEAD()) { return $this->notFound();
return $this->getHandler($className, $id, $relation); }
}
// if api access is disabled, don't proceed
if($this->request->isPOST()) { $apiAccess = singleton($className)->stat('api_access');
return $this->postHandler($className, $id, $relation); if (!$apiAccess) {
} return $this->permissionFailure();
}
if($this->request->isPUT()) {
return $this->putHandler($className, $id, $relation); // authenticate through HTTP BasicAuth
} $this->member = $this->authenticate();
if($this->request->isDELETE()) { // handle different HTTP verbs
return $this->deleteHandler($className, $id, $relation); if ($this->request->isGET() || $this->request->isHEAD()) {
} return $this->getHandler($className, $id, $relation);
}
// if no HTTP verb matches, return error
return $this->methodNotAllowed(); if ($this->request->isPOST()) {
} return $this->postHandler($className, $id, $relation);
}
/**
* Handler for object read. if ($this->request->isPUT()) {
* return $this->putHandler($className, $id, $relation);
* The data object will be returned in the following format: }
*
* <ClassName> if ($this->request->isDELETE()) {
* <FieldName>Value</FieldName> return $this->deleteHandler($className, $id, $relation);
* ... }
* <HasOneRelName id="ForeignID" href="LinkToForeignRecordInAPI" />
* ... // if no HTTP verb matches, return error
* <HasManyRelName> return $this->methodNotAllowed();
* <ForeignClass id="ForeignID" href="LinkToForeignRecordInAPI" /> }
* <ForeignClass id="ForeignID" href="LinkToForeignRecordInAPI" />
* </HasManyRelName> /**
* ... * Handler for object read.
* <ManyManyRelName> *
* <ForeignClass id="ForeignID" href="LinkToForeignRecordInAPI" /> * The data object will be returned in the following format:
* <ForeignClass id="ForeignID" href="LinkToForeignRecordInAPI" /> *
* </ManyManyRelName> * <ClassName>
* </ClassName> * <FieldName>Value</FieldName>
* * ...
* Access is controlled by two variables: * <HasOneRelName id="ForeignID" href="LinkToForeignRecordInAPI" />
* * ...
* - static $api_access must be set. This enables the API on a class by class basis * <HasManyRelName>
* - $obj->canView() must return true. This lets you implement record-level security * <ForeignClass id="ForeignID" href="LinkToForeignRecordInAPI" />
* * <ForeignClass id="ForeignID" href="LinkToForeignRecordInAPI" />
* @todo Access checking * </HasManyRelName>
* * ...
* @param String $className * <ManyManyRelName>
* @param Int $id * <ForeignClass id="ForeignID" href="LinkToForeignRecordInAPI" />
* @param String $relation * <ForeignClass id="ForeignID" href="LinkToForeignRecordInAPI" />
* @return String The serialized representation of the requested object(s) - usually XML or JSON. * </ManyManyRelName>
*/ * </ClassName>
protected function getHandler($className, $id, $relationName) { *
$sort = ''; * Access is controlled by two variables:
*
if($this->request->getVar('sort')) { * - static $api_access must be set. This enables the API on a class by class basis
$dir = $this->request->getVar('dir'); * - $obj->canView() must return true. This lets you implement record-level security
$sort = array($this->request->getVar('sort') => ($dir ? $dir : 'ASC')); *
} * @todo Access checking
*
$limit = array( * @param String $className
'start' => $this->request->getVar('start'), * @param Int $id
'limit' => $this->request->getVar('limit') * @param String $relation
); * @return String The serialized representation of the requested object(s) - usually XML or JSON.
*/
$params = $this->request->getVars(); protected function getHandler($className, $id, $relationName)
{
$responseFormatter = $this->getResponseDataFormatter($className); $sort = '';
if(!$responseFormatter) return $this->unsupportedMediaType();
if ($this->request->getVar('sort')) {
// $obj can be either a DataObject or a SS_List, $dir = $this->request->getVar('dir');
// depending on the request $sort = array($this->request->getVar('sort') => ($dir ? $dir : 'ASC'));
if($id) { }
// Format: /api/v1/<MyClass>/<ID>
$obj = $this->getObjectQuery($className, $id, $params)->First(); $limit = array(
if(!$obj) return $this->notFound(); 'start' => $this->request->getVar('start'),
if(!$obj->canView()) return $this->permissionFailure(); 'limit' => $this->request->getVar('limit')
);
// Format: /api/v1/<MyClass>/<ID>/<Relation>
if($relationName) { $params = $this->request->getVars();
$obj = $this->getObjectRelationQuery($obj, $params, $sort, $limit, $relationName);
if(!$obj) return $this->notFound(); $responseFormatter = $this->getResponseDataFormatter($className);
if (!$responseFormatter) {
// TODO Avoid creating data formatter again for relation class (see above) return $this->unsupportedMediaType();
$responseFormatter = $this->getResponseDataFormatter($obj->dataClass()); }
}
// $obj can be either a DataObject or a SS_List,
} else { // depending on the request
// Format: /api/v1/<MyClass> if ($id) {
$obj = $this->getObjectsQuery($className, $params, $sort, $limit); // Format: /api/v1/<MyClass>/<ID>
} $obj = $this->getObjectQuery($className, $id, $params)->First();
if (!$obj) {
$this->getResponse()->addHeader('Content-Type', $responseFormatter->getOutputContentType()); return $this->notFound();
}
$rawFields = $this->request->getVar('fields'); if (!$obj->canView()) {
$fields = $rawFields ? explode(',', $rawFields) : null; return $this->permissionFailure();
}
if($obj instanceof SS_List) {
$responseFormatter->setTotalSize($obj->dataQuery()->query()->unlimitedRowCount()); // Format: /api/v1/<MyClass>/<ID>/<Relation>
$objs = new ArrayList($obj->toArray()); if ($relationName) {
foreach($objs as $obj) if(!$obj->canView()) $objs->remove($obj); $obj = $this->getObjectRelationQuery($obj, $params, $sort, $limit, $relationName);
return $responseFormatter->convertDataObjectSet($objs, $fields); if (!$obj) {
} else if(!$obj) { return $this->notFound();
$responseFormatter->setTotalSize(0); }
return $responseFormatter->convertDataObjectSet(new ArrayList(), $fields);
} else { // TODO Avoid creating data formatter again for relation class (see above)
return $responseFormatter->convertDataObject($obj, $fields); $responseFormatter = $this->getResponseDataFormatter($obj->dataClass());
} }
} } else {
// Format: /api/v1/<MyClass>
/** $obj = $this->getObjectsQuery($className, $params, $sort, $limit);
* Uses the default {@link SearchContext} specified through }
* {@link DataObject::getDefaultSearchContext()} to augument
* an existing query object (mostly a component query from {@link DataObject}) $this->getResponse()->addHeader('Content-Type', $responseFormatter->getOutputContentType());
* with search clauses.
* $rawFields = $this->request->getVar('fields');
* @todo Allow specifying of different searchcontext getters on model-by-model basis $fields = $rawFields ? explode(',', $rawFields) : null;
*
* @param string $className if ($obj instanceof SS_List) {
* @param array $params $responseFormatter->setTotalSize($obj->dataQuery()->query()->unlimitedRowCount());
* @return SS_List $objs = new ArrayList($obj->toArray());
*/ foreach ($objs as $obj) {
protected function getSearchQuery($className, $params = null, $sort = null, if (!$obj->canView()) {
$limit = null, $existingQuery = null $objs->remove($obj);
) { }
if(singleton($className)->hasMethod('getRestfulSearchContext')) { }
$searchContext = singleton($className)->{'getRestfulSearchContext'}(); return $responseFormatter->convertDataObjectSet($objs, $fields);
} else { } elseif (!$obj) {
$searchContext = singleton($className)->getDefaultSearchContext(); $responseFormatter->setTotalSize(0);
} return $responseFormatter->convertDataObjectSet(new ArrayList(), $fields);
return $searchContext->getQuery($params, $sort, $limit, $existingQuery); } else {
} return $responseFormatter->convertDataObject($obj, $fields);
}
/** }
* Returns a dataformatter instance based on the request
* extension or mimetype. Falls back to {@link self::$default_extension}. /**
* * Uses the default {@link SearchContext} specified through
* @param boolean $includeAcceptHeader Determines wether to inspect and prioritize any HTTP Accept headers * {@link DataObject::getDefaultSearchContext()} to augument
* @param String Classname of a DataObject * an existing query object (mostly a component query from {@link DataObject})
* @return DataFormatter * with search clauses.
*/ *
protected function getDataFormatter($includeAcceptHeader = false, $className = null) { * @todo Allow specifying of different searchcontext getters on model-by-model basis
$extension = $this->request->getExtension(); *
$contentTypeWithEncoding = $this->request->getHeader('Content-Type'); * @param string $className
preg_match('/([^;]*)/',$contentTypeWithEncoding, $contentTypeMatches); * @param array $params
$contentType = $contentTypeMatches[0]; * @return SS_List
$accept = $this->request->getHeader('Accept'); */
$mimetypes = $this->request->getAcceptMimetypes(); protected function getSearchQuery($className, $params = null, $sort = null,
if(!$className) $className = $this->urlParams['ClassName']; $limit = null, $existingQuery = null
) {
// get formatter if (singleton($className)->hasMethod('getRestfulSearchContext')) {
if(!empty($extension)) { $searchContext = singleton($className)->{'getRestfulSearchContext'}();
$formatter = DataFormatter::for_extension($extension); } else {
}elseif($includeAcceptHeader && !empty($accept) && $accept != '*/*') { $searchContext = singleton($className)->getDefaultSearchContext();
$formatter = DataFormatter::for_mimetypes($mimetypes); }
if(!$formatter) $formatter = DataFormatter::for_extension(self::$default_extension); return $searchContext->getQuery($params, $sort, $limit, $existingQuery);
} elseif(!empty($contentType)) { }
$formatter = DataFormatter::for_mimetype($contentType);
} else { /**
$formatter = DataFormatter::for_extension(self::$default_extension); * Returns a dataformatter instance based on the request
} * extension or mimetype. Falls back to {@link self::$default_extension}.
*
if(!$formatter) return false; * @param boolean $includeAcceptHeader Determines wether to inspect and prioritize any HTTP Accept headers
* @param String Classname of a DataObject
// set custom fields * @return DataFormatter
if($customAddFields = $this->request->getVar('add_fields')) { */
$formatter->setCustomAddFields(explode(',',$customAddFields)); protected function getDataFormatter($includeAcceptHeader = false, $className = null)
} {
if($customFields = $this->request->getVar('fields')) { $extension = $this->request->getExtension();
$formatter->setCustomFields(explode(',',$customFields)); $contentTypeWithEncoding = $this->request->getHeader('Content-Type');
} preg_match('/([^;]*)/', $contentTypeWithEncoding, $contentTypeMatches);
$formatter->setCustomRelations($this->getAllowedRelations($className)); $contentType = $contentTypeMatches[0];
$accept = $this->request->getHeader('Accept');
$apiAccess = singleton($className)->stat('api_access'); $mimetypes = $this->request->getAcceptMimetypes();
if(is_array($apiAccess)) { if (!$className) {
$formatter->setCustomAddFields( $className = $this->urlParams['ClassName'];
array_intersect((array)$formatter->getCustomAddFields(), (array)$apiAccess['view']) }
);
if($formatter->getCustomFields()) { // get formatter
$formatter->setCustomFields( if (!empty($extension)) {
array_intersect((array)$formatter->getCustomFields(), (array)$apiAccess['view']) $formatter = DataFormatter::for_extension($extension);
); } elseif ($includeAcceptHeader && !empty($accept) && $accept != '*/*') {
} else { $formatter = DataFormatter::for_mimetypes($mimetypes);
$formatter->setCustomFields((array)$apiAccess['view']); if (!$formatter) {
} $formatter = DataFormatter::for_extension(self::$default_extension);
if($formatter->getCustomRelations()) { }
$formatter->setCustomRelations( } elseif (!empty($contentType)) {
array_intersect((array)$formatter->getCustomRelations(), (array)$apiAccess['view']) $formatter = DataFormatter::for_mimetype($contentType);
); } else {
} else { $formatter = DataFormatter::for_extension(self::$default_extension);
$formatter->setCustomRelations((array)$apiAccess['view']); }
}
if (!$formatter) {
} return false;
}
// set relation depth
$relationDepth = $this->request->getVar('relationdepth'); // set custom fields
if(is_numeric($relationDepth)) $formatter->relationDepth = (int)$relationDepth; if ($customAddFields = $this->request->getVar('add_fields')) {
$formatter->setCustomAddFields(explode(',', $customAddFields));
return $formatter; }
} if ($customFields = $this->request->getVar('fields')) {
$formatter->setCustomFields(explode(',', $customFields));
/** }
* @param String Classname of a DataObject $formatter->setCustomRelations($this->getAllowedRelations($className));
* @return DataFormatter
*/ $apiAccess = singleton($className)->stat('api_access');
protected function getRequestDataFormatter($className = null) { if (is_array($apiAccess)) {
return $this->getDataFormatter(false, $className); $formatter->setCustomAddFields(
} array_intersect((array)$formatter->getCustomAddFields(), (array)$apiAccess['view'])
);
/** if ($formatter->getCustomFields()) {
* @param String Classname of a DataObject $formatter->setCustomFields(
* @return DataFormatter array_intersect((array)$formatter->getCustomFields(), (array)$apiAccess['view'])
*/ );
protected function getResponseDataFormatter($className = null) { } else {
return $this->getDataFormatter(true, $className); $formatter->setCustomFields((array)$apiAccess['view']);
} }
if ($formatter->getCustomRelations()) {
/** $formatter->setCustomRelations(
* Handler for object delete array_intersect((array)$formatter->getCustomRelations(), (array)$apiAccess['view'])
*/ );
protected function deleteHandler($className, $id) { } else {
$obj = DataObject::get_by_id($className, $id); $formatter->setCustomRelations((array)$apiAccess['view']);
if(!$obj) return $this->notFound(); }
if(!$obj->canDelete()) return $this->permissionFailure(); }
$obj->delete(); // set relation depth
$relationDepth = $this->request->getVar('relationdepth');
$this->getResponse()->setStatusCode(204); // No Content if (is_numeric($relationDepth)) {
return true; $formatter->relationDepth = (int)$relationDepth;
} }
/** return $formatter;
* Handler for object write }
*/
protected function putHandler($className, $id) { /**
$obj = DataObject::get_by_id($className, $id); * @param String Classname of a DataObject
if(!$obj) return $this->notFound(); * @return DataFormatter
if(!$obj->canEdit()) return $this->permissionFailure(); */
protected function getRequestDataFormatter($className = null)
$reqFormatter = $this->getRequestDataFormatter($className); {
if(!$reqFormatter) return $this->unsupportedMediaType(); return $this->getDataFormatter(false, $className);
}
$responseFormatter = $this->getResponseDataFormatter($className);
if(!$responseFormatter) return $this->unsupportedMediaType(); /**
* @param String Classname of a DataObject
$obj = $this->updateDataObject($obj, $reqFormatter); * @return DataFormatter
*/
$this->getResponse()->setStatusCode(200); // Success protected function getResponseDataFormatter($className = null)
$this->getResponse()->addHeader('Content-Type', $responseFormatter->getOutputContentType()); {
return $this->getDataFormatter(true, $className);
// Append the default extension for the output format to the Location header }
// or else we'll use the default (XML)
$types = $responseFormatter->supportedExtensions(); /**
$type = ''; * Handler for object delete
if (count($types)) { */
$type = ".{$types[0]}"; protected function deleteHandler($className, $id)
} {
$obj = DataObject::get_by_id($className, $id);
$objHref = Director::absoluteURL(self::$api_base . "$obj->class/$obj->ID" . $type); if (!$obj) {
$this->getResponse()->addHeader('Location', $objHref); return $this->notFound();
}
return $responseFormatter->convertDataObject($obj); if (!$obj->canDelete()) {
} return $this->permissionFailure();
}
/**
* Handler for object append / method call. $obj->delete();
*
* @todo Posting to an existing URL (without a relation) $this->getResponse()->setStatusCode(204); // No Content
* current resolves in creatig a new element, return true;
* rather than a "Conflict" message. }
*/
protected function postHandler($className, $id, $relation) { /**
if($id) { * Handler for object write
if(!$relation) { */
$this->response->setStatusCode(409); protected function putHandler($className, $id)
return 'Conflict'; {
} $obj = DataObject::get_by_id($className, $id);
if (!$obj) {
$obj = DataObject::get_by_id($className, $id); return $this->notFound();
if(!$obj) return $this->notFound(); }
if (!$obj->canEdit()) {
if(!$obj->hasMethod($relation)) { return $this->permissionFailure();
return $this->notFound(); }
}
$reqFormatter = $this->getRequestDataFormatter($className);
if(!$obj->stat('allowed_actions') || !in_array($relation, $obj->stat('allowed_actions'))) { if (!$reqFormatter) {
return $this->permissionFailure(); return $this->unsupportedMediaType();
} }
$obj->$relation(); $responseFormatter = $this->getResponseDataFormatter($className);
if (!$responseFormatter) {
$this->getResponse()->setStatusCode(204); // No Content return $this->unsupportedMediaType();
return true; }
} else {
if(!singleton($className)->canCreate()) return $this->permissionFailure(); $obj = $this->updateDataObject($obj, $reqFormatter);
$obj = new $className();
$this->getResponse()->setStatusCode(200); // Success
$reqFormatter = $this->getRequestDataFormatter($className); $this->getResponse()->addHeader('Content-Type', $responseFormatter->getOutputContentType());
if(!$reqFormatter) return $this->unsupportedMediaType();
// Append the default extension for the output format to the Location header
$responseFormatter = $this->getResponseDataFormatter($className); // or else we'll use the default (XML)
$types = $responseFormatter->supportedExtensions();
$obj = $this->updateDataObject($obj, $reqFormatter); $type = '';
if (count($types)) {
$this->getResponse()->setStatusCode(201); // Created $type = ".{$types[0]}";
$this->getResponse()->addHeader('Content-Type', $responseFormatter->getOutputContentType()); }
// Append the default extension for the output format to the Location header $objHref = Director::absoluteURL(self::$api_base . "$obj->class/$obj->ID" . $type);
// or else we'll use the default (XML) $this->getResponse()->addHeader('Location', $objHref);
$types = $responseFormatter->supportedExtensions();
$type = ''; return $responseFormatter->convertDataObject($obj);
if (count($types)) { }
$type = ".{$types[0]}";
} /**
* Handler for object append / method call.
$objHref = Director::absoluteURL(self::$api_base . "$obj->class/$obj->ID" . $type); *
$this->getResponse()->addHeader('Location', $objHref); * @todo Posting to an existing URL (without a relation)
* current resolves in creatig a new element,
return $responseFormatter->convertDataObject($obj); * rather than a "Conflict" message.
} */
} protected function postHandler($className, $id, $relation)
{
/** if ($id) {
* Converts either the given HTTP Body into an array if (!$relation) {
* (based on the DataFormatter instance), or returns $this->response->setStatusCode(409);
* the POST variables. return 'Conflict';
* Automatically filters out certain critical fields }
* that shouldn't be set by the client (e.g. ID).
* $obj = DataObject::get_by_id($className, $id);
* @param DataObject $obj if (!$obj) {
* @param DataFormatter $formatter return $this->notFound();
* @return DataObject The passed object }
*/
protected function updateDataObject($obj, $formatter) { if (!$obj->hasMethod($relation)) {
// if neither an http body nor POST data is present, return error return $this->notFound();
$body = $this->request->getBody(); }
if(!$body && !$this->request->postVars()) {
$this->getResponse()->setStatusCode(204); // No Content if (!$obj->stat('allowed_actions') || !in_array($relation, $obj->stat('allowed_actions'))) {
return 'No Content'; return $this->permissionFailure();
} }
if(!empty($body)) { $obj->$relation();
$data = $formatter->convertStringToArray($body);
} else { $this->getResponse()->setStatusCode(204); // No Content
// assume application/x-www-form-urlencoded which is automatically parsed by PHP return true;
$data = $this->request->postVars(); } else {
} if (!singleton($className)->canCreate()) {
return $this->permissionFailure();
// @todo Disallow editing of certain keys in database }
$data = array_diff_key($data, array('ID','Created')); $obj = new $className();
$apiAccess = singleton($this->urlParams['ClassName'])->stat('api_access'); $reqFormatter = $this->getRequestDataFormatter($className);
if(is_array($apiAccess) && isset($apiAccess['edit'])) { if (!$reqFormatter) {
$data = array_intersect_key($data, array_combine($apiAccess['edit'],$apiAccess['edit'])); return $this->unsupportedMediaType();
} }
$obj->update($data); $responseFormatter = $this->getResponseDataFormatter($className);
$obj->write();
$obj = $this->updateDataObject($obj, $reqFormatter);
return $obj;
} $this->getResponse()->setStatusCode(201); // Created
$this->getResponse()->addHeader('Content-Type', $responseFormatter->getOutputContentType());
/**
* Gets a single DataObject by ID, // Append the default extension for the output format to the Location header
* through a request like /api/v1/<MyClass>/<MyID> // or else we'll use the default (XML)
* $types = $responseFormatter->supportedExtensions();
* @param string $className $type = '';
* @param int $id if (count($types)) {
* @param array $params $type = ".{$types[0]}";
* @return DataList }
*/
protected function getObjectQuery($className, $id, $params) { $objHref = Director::absoluteURL(self::$api_base . "$obj->class/$obj->ID" . $type);
return DataList::create($className)->byIDs(array($id)); $this->getResponse()->addHeader('Location', $objHref);
}
return $responseFormatter->convertDataObject($obj);
/** }
* @param DataObject $obj }
* @param array $params
* @param int|array $sort /**
* @param int|array $limit * Converts either the given HTTP Body into an array
* @return SQLQuery * (based on the DataFormatter instance), or returns
*/ * the POST variables.
protected function getObjectsQuery($className, $params, $sort, $limit) { * Automatically filters out certain critical fields
return $this->getSearchQuery($className, $params, $sort, $limit); * that shouldn't be set by the client (e.g. ID).
} *
* @param DataObject $obj
* @param DataFormatter $formatter
/** * @return DataObject The passed object
* @param DataObject $obj */
* @param array $params protected function updateDataObject($obj, $formatter)
* @param int|array $sort {
* @param int|array $limit // if neither an http body nor POST data is present, return error
* @param string $relationName $body = $this->request->getBody();
* @return SQLQuery|boolean if (!$body && !$this->request->postVars()) {
*/ $this->getResponse()->setStatusCode(204); // No Content
protected function getObjectRelationQuery($obj, $params, $sort, $limit, $relationName) { return 'No Content';
// The relation method will return a DataList, that getSearchQuery subsequently manipulates }
if($obj->hasMethod($relationName)) {
if($relationClass = $obj->has_one($relationName)) { if (!empty($body)) {
$joinField = $relationName . 'ID'; $data = $formatter->convertStringToArray($body);
$list = DataList::create($relationClass)->byIDs(array($obj->$joinField)); } else {
} else { // assume application/x-www-form-urlencoded which is automatically parsed by PHP
$list = $obj->$relationName(); $data = $this->request->postVars();
} }
$apiAccess = singleton($list->dataClass())->stat('api_access'); // @todo Disallow editing of certain keys in database
if(!$apiAccess) return false; $data = array_diff_key($data, array('ID', 'Created'));
return $this->getSearchQuery($list->dataClass(), $params, $sort, $limit, $list); $apiAccess = singleton($this->urlParams['ClassName'])->stat('api_access');
} if (is_array($apiAccess) && isset($apiAccess['edit'])) {
} $data = array_intersect_key($data, array_combine($apiAccess['edit'], $apiAccess['edit']));
}
protected function permissionFailure() {
// return a 401 $obj->update($data);
$this->getResponse()->setStatusCode(401); $obj->write();
$this->getResponse()->addHeader('WWW-Authenticate', 'Basic realm="API Access"');
$this->getResponse()->addHeader('Content-Type', 'text/plain'); return $obj;
return "You don't have access to this item through the API."; }
}
/**
protected function notFound() { * Gets a single DataObject by ID,
// return a 404 * through a request like /api/v1/<MyClass>/<MyID>
$this->getResponse()->setStatusCode(404); *
$this->getResponse()->addHeader('Content-Type', 'text/plain'); * @param string $className
return "That object wasn't found"; * @param int $id
} * @param array $params
* @return DataList
protected function methodNotAllowed() { */
$this->getResponse()->setStatusCode(405); protected function getObjectQuery($className, $id, $params)
$this->getResponse()->addHeader('Content-Type', 'text/plain'); {
return "Method Not Allowed"; return DataList::create($className)->byIDs(array($id));
} }
protected function unsupportedMediaType() { /**
$this->response->setStatusCode(415); // Unsupported Media Type * @param DataObject $obj
$this->getResponse()->addHeader('Content-Type', 'text/plain'); * @param array $params
return "Unsupported Media Type"; * @param int|array $sort
} * @param int|array $limit
* @return SQLQuery
/** */
* A function to authenticate a user protected function getObjectsQuery($className, $params, $sort, $limit)
* {
* @return Member|false the logged in member return $this->getSearchQuery($className, $params, $sort, $limit);
*/ }
protected function authenticate() {
$authClass = self::config()->authenticator;
return $authClass::authenticate(); /**
} * @param DataObject $obj
* @param array $params
/** * @param int|array $sort
* Return only relations which have $api_access enabled. * @param int|array $limit
* @todo Respect field level permissions once they are available in core * @param string $relationName
* * @return SQLQuery|boolean
* @param string $class */
* @param Member $member protected function getObjectRelationQuery($obj, $params, $sort, $limit, $relationName)
* @return array {
*/ // The relation method will return a DataList, that getSearchQuery subsequently manipulates
protected function getAllowedRelations($class, $member = null) { if ($obj->hasMethod($relationName)) {
$allowedRelations = array(); if ($relationClass = $obj->has_one($relationName)) {
$obj = singleton($class); $joinField = $relationName . 'ID';
$relations = (array)$obj->has_one() + (array)$obj->has_many() + (array)$obj->many_many(); $list = DataList::create($relationClass)->byIDs(array($obj->$joinField));
if($relations) foreach($relations as $relName => $relClass) { } else {
if(singleton($relClass)->stat('api_access')) { $list = $obj->$relationName();
$allowedRelations[] = $relName; }
}
} $apiAccess = singleton($list->dataClass())->stat('api_access');
return $allowedRelations; if (!$apiAccess) {
} return false;
}
return $this->getSearchQuery($list->dataClass(), $params, $sort, $limit, $list);
}
}
protected function permissionFailure()
{
// return a 401
$this->getResponse()->setStatusCode(401);
$this->getResponse()->addHeader('WWW-Authenticate', 'Basic realm="API Access"');
$this->getResponse()->addHeader('Content-Type', 'text/plain');
return "You don't have access to this item through the API.";
}
protected function notFound()
{
// return a 404
$this->getResponse()->setStatusCode(404);
$this->getResponse()->addHeader('Content-Type', 'text/plain');
return "That object wasn't found";
}
protected function methodNotAllowed()
{
$this->getResponse()->setStatusCode(405);
$this->getResponse()->addHeader('Content-Type', 'text/plain');
return "Method Not Allowed";
}
protected function unsupportedMediaType()
{
$this->response->setStatusCode(415); // Unsupported Media Type
$this->getResponse()->addHeader('Content-Type', 'text/plain');
return "Unsupported Media Type";
}
/**
* A function to authenticate a user
*
* @return Member|false the logged in member
*/
protected function authenticate()
{
$authClass = self::config()->authenticator;
return $authClass::authenticate();
}
/**
* Return only relations which have $api_access enabled.
* @todo Respect field level permissions once they are available in core
*
* @param string $class
* @param Member $member
* @return array
*/
protected function getAllowedRelations($class, $member = null)
{
$allowedRelations = array();
$obj = singleton($class);
$relations = (array)$obj->has_one() + (array)$obj->has_many() + (array)$obj->many_many();
if ($relations) {
foreach ($relations as $relName => $relClass) {
if (singleton($relClass)->stat('api_access')) {
$allowedRelations[] = $relName;
}
}
}
return $allowedRelations;
}
} }
/** /**
@ -588,18 +657,21 @@ class RestfulServer extends Controller {
* @package framework * @package framework
* @subpackage api * @subpackage api
*/ */
class RestfulServer_List { class RestfulServer_List
static $url_handlers = array( {
'#ID' => 'handleItem', public static $url_handlers = array(
); '#ID' => 'handleItem',
);
function __construct($list) { public function __construct($list)
$this->list = $list; {
} $this->list = $list;
}
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')));
}
} }
/** /**
@ -608,20 +680,26 @@ class RestfulServer_List {
* @package framework * @package framework
* @subpackage api * @subpackage api
*/ */
class RestfulServer_Item { class RestfulServer_Item
static $url_handlers = array( {
'$Relation' => 'handleRelation', public static $url_handlers = array(
); '$Relation' => 'handleRelation',
);
function __construct($item) { public function __construct($item)
$this->item = $item; {
} $this->item = $item;
}
function handleRelation($request) { public function handleRelation($request)
$funcName = $request('Relation'); {
$relation = $this->item->$funcName(); $funcName = $request('Relation');
$relation = $this->item->$funcName();
if($relation instanceof SS_List) return new RestfulServer_List($relation); if ($relation instanceof SS_List) {
else return new RestfulServer_Item($relation); return new RestfulServer_List($relation);
} } else {
return new RestfulServer_Item($relation);
}
}
} }

View File

@ -19,4 +19,6 @@ MySQLDatabase::set_connection_charset('utf8');
SSViewer::set_theme('simple'); SSViewer::set_theme('simple');
// Enable nested URLs for this site (e.g. page/sub-page/) // Enable nested URLs for this site (e.g. page/sub-page/)
if(class_exists('SiteTree')) SiteTree::enable_nested_urls(); if (class_exists('SiteTree')) {
SiteTree::enable_nested_urls();
}

View File

@ -5,23 +5,23 @@ define('SS_ENVIRONMENT_TYPE', 'dev');
/* Database connection */ /* Database connection */
$db = getenv('TESTDB'); $db = getenv('TESTDB');
switch($db) { switch ($db) {
case "PGSQL"; case "PGSQL";
define('SS_DATABASE_CLASS', 'PostgreSQLDatabase'); define('SS_DATABASE_CLASS', 'PostgreSQLDatabase');
define('SS_DATABASE_USERNAME', 'postgres'); define('SS_DATABASE_USERNAME', 'postgres');
define('SS_DATABASE_PASSWORD', ''); define('SS_DATABASE_PASSWORD', '');
break; break;
case "MYSQL": case "MYSQL":
define('SS_DATABASE_CLASS', 'MySQLDatabase'); define('SS_DATABASE_CLASS', 'MySQLDatabase');
define('SS_DATABASE_USERNAME', 'root'); define('SS_DATABASE_USERNAME', 'root');
define('SS_DATABASE_PASSWORD', ''); define('SS_DATABASE_PASSWORD', '');
break; break;
default: default:
define('SS_DATABASE_CLASS', 'SQLitePDODatabase'); define('SS_DATABASE_CLASS', 'SQLitePDODatabase');
define('SS_DATABASE_USERNAME', 'root'); define('SS_DATABASE_USERNAME', 'root');
define('SS_DATABASE_PASSWORD', ''); define('SS_DATABASE_PASSWORD', '');
} }
echo SS_DATABASE_CLASS; echo SS_DATABASE_CLASS;

View File

@ -6,452 +6,474 @@
* @todo Test DELETE verb * @todo Test DELETE verb
* *
*/ */
class RestfulServerTest extends SapphireTest { class RestfulServerTest extends SapphireTest
{
static $fixture_file = 'RestfulServerTest.yml'; public static $fixture_file = 'RestfulServerTest.yml';
protected $extraDataObjects = array( protected $extraDataObjects = array(
'RestfulServerTest_Comment', 'RestfulServerTest_Comment',
'RestfulServerTest_SecretThing', 'RestfulServerTest_SecretThing',
'RestfulServerTest_Page', 'RestfulServerTest_Page',
'RestfulServerTest_Author', 'RestfulServerTest_Author',
'RestfulServerTest_AuthorRating', 'RestfulServerTest_AuthorRating',
); );
public function testApiAccess() { public function testApiAccess()
$comment1 = $this->objFromFixture('RestfulServerTest_Comment', 'comment1'); {
$page1 = $this->objFromFixture('RestfulServerTest_Page', 'page1'); $comment1 = $this->objFromFixture('RestfulServerTest_Comment', 'comment1');
$page1 = $this->objFromFixture('RestfulServerTest_Page', 'page1');
// normal GET should succeed with $api_access enabled
$url = "/api/v1/RestfulServerTest_Comment/" . $comment1->ID; // normal GET should succeed with $api_access enabled
$response = Director::test($url, null, null, 'GET'); $url = "/api/v1/RestfulServerTest_Comment/" . $comment1->ID;
$this->assertEquals($response->getStatusCode(), 200); $response = Director::test($url, null, null, 'GET');
$this->assertEquals($response->getStatusCode(), 200);
$_SERVER['PHP_AUTH_USER'] = 'user@test.com';
$_SERVER['PHP_AUTH_PW'] = 'user'; $_SERVER['PHP_AUTH_USER'] = 'user@test.com';
$_SERVER['PHP_AUTH_PW'] = 'user';
// even with logged in user a GET with $api_access disabled should fail
$url = "/api/v1/RestfulServerTest_Page/" . $page1->ID; // even with logged in user a GET with $api_access disabled should fail
$response = Director::test($url, null, null, 'GET'); $url = "/api/v1/RestfulServerTest_Page/" . $page1->ID;
$this->assertEquals($response->getStatusCode(), 401); $response = Director::test($url, null, null, 'GET');
$this->assertEquals($response->getStatusCode(), 401);
unset($_SERVER['PHP_AUTH_USER']);
unset($_SERVER['PHP_AUTH_PW']); unset($_SERVER['PHP_AUTH_USER']);
} unset($_SERVER['PHP_AUTH_PW']);
}
public function testApiAccessBoolean() {
$comment1 = $this->objFromFixture('RestfulServerTest_Comment', 'comment1'); public function testApiAccessBoolean()
{
$url = "/api/v1/RestfulServerTest_Comment/" . $comment1->ID; $comment1 = $this->objFromFixture('RestfulServerTest_Comment', 'comment1');
$response = Director::test($url, null, null, 'GET');
$this->assertContains('<ID>', $response->getBody()); $url = "/api/v1/RestfulServerTest_Comment/" . $comment1->ID;
$this->assertContains('<Name>', $response->getBody()); $response = Director::test($url, null, null, 'GET');
$this->assertContains('<Comment>', $response->getBody()); $this->assertContains('<ID>', $response->getBody());
$this->assertContains('<Page', $response->getBody()); $this->assertContains('<Name>', $response->getBody());
$this->assertContains('<Author', $response->getBody()); $this->assertContains('<Comment>', $response->getBody());
} $this->assertContains('<Page', $response->getBody());
$this->assertContains('<Author', $response->getBody());
public function testAuthenticatedGET() { }
$thing1 = $this->objFromFixture('RestfulServerTest_SecretThing', 'thing1');
$comment1 = $this->objFromFixture('RestfulServerTest_Comment', 'comment1'); public function testAuthenticatedGET()
{
// @todo create additional mock object with authenticated VIEW permissions $thing1 = $this->objFromFixture('RestfulServerTest_SecretThing', 'thing1');
$url = "/api/v1/RestfulServerTest_SecretThing/" . $thing1->ID; $comment1 = $this->objFromFixture('RestfulServerTest_Comment', 'comment1');
$response = Director::test($url, null, null, 'GET');
$this->assertEquals($response->getStatusCode(), 401); // @todo create additional mock object with authenticated VIEW permissions
$url = "/api/v1/RestfulServerTest_SecretThing/" . $thing1->ID;
$_SERVER['PHP_AUTH_USER'] = 'user@test.com'; $response = Director::test($url, null, null, 'GET');
$_SERVER['PHP_AUTH_PW'] = 'user'; $this->assertEquals($response->getStatusCode(), 401);
$url = "/api/v1/RestfulServerTest_Comment/" . $comment1->ID; $_SERVER['PHP_AUTH_USER'] = 'user@test.com';
$response = Director::test($url, null, null, 'GET'); $_SERVER['PHP_AUTH_PW'] = 'user';
$this->assertEquals($response->getStatusCode(), 200);
$url = "/api/v1/RestfulServerTest_Comment/" . $comment1->ID;
unset($_SERVER['PHP_AUTH_USER']); $response = Director::test($url, null, null, 'GET');
unset($_SERVER['PHP_AUTH_PW']); $this->assertEquals($response->getStatusCode(), 200);
}
unset($_SERVER['PHP_AUTH_USER']);
public function testAuthenticatedPUT() { unset($_SERVER['PHP_AUTH_PW']);
$comment1 = $this->objFromFixture('RestfulServerTest_Comment', 'comment1'); }
$url = "/api/v1/RestfulServerTest_Comment/" . $comment1->ID; public function testAuthenticatedPUT()
$data = array('Comment' => 'created'); {
$comment1 = $this->objFromFixture('RestfulServerTest_Comment', 'comment1');
$response = Director::test($url, $data, null, 'PUT');
$this->assertEquals($response->getStatusCode(), 401); // Permission failure $url = "/api/v1/RestfulServerTest_Comment/" . $comment1->ID;
$data = array('Comment' => 'created');
$_SERVER['PHP_AUTH_USER'] = 'editor@test.com';
$_SERVER['PHP_AUTH_PW'] = 'editor'; $response = Director::test($url, $data, null, 'PUT');
$response = Director::test($url, $data, null, 'PUT'); $this->assertEquals($response->getStatusCode(), 401); // Permission failure
$this->assertEquals($response->getStatusCode(), 200); // Success
$_SERVER['PHP_AUTH_USER'] = 'editor@test.com';
unset($_SERVER['PHP_AUTH_USER']); $_SERVER['PHP_AUTH_PW'] = 'editor';
unset($_SERVER['PHP_AUTH_PW']); $response = Director::test($url, $data, null, 'PUT');
} $this->assertEquals($response->getStatusCode(), 200); // Success
public function testGETRelationshipsXML() { unset($_SERVER['PHP_AUTH_USER']);
$author1 = $this->objFromFixture('RestfulServerTest_Author', 'author1'); unset($_SERVER['PHP_AUTH_PW']);
$rating1 = $this->objFromFixture('RestfulServerTest_AuthorRating', 'rating1'); }
$rating2 = $this->objFromFixture('RestfulServerTest_AuthorRating', 'rating2');
public function testGETRelationshipsXML()
// @todo should be set up by fixtures, doesn't work for some reason... {
$author1->Ratings()->add($rating1); $author1 = $this->objFromFixture('RestfulServerTest_Author', 'author1');
$author1->Ratings()->add($rating2); $rating1 = $this->objFromFixture('RestfulServerTest_AuthorRating', 'rating1');
$rating2 = $this->objFromFixture('RestfulServerTest_AuthorRating', 'rating2');
$url = "/api/v1/RestfulServerTest_Author/" . $author1->ID;
$response = Director::test($url, null, null, 'GET'); // @todo should be set up by fixtures, doesn't work for some reason...
$this->assertEquals($response->getStatusCode(), 200); $author1->Ratings()->add($rating1);
$author1->Ratings()->add($rating2);
$responseArr = Convert::xml2array($response->getBody());
$ratingsArr = $responseArr['Ratings']['RestfulServerTest_AuthorRating']; $url = "/api/v1/RestfulServerTest_Author/" . $author1->ID;
$this->assertEquals(count($ratingsArr), 2); $response = Director::test($url, null, null, 'GET');
$ratingIDs = array( $this->assertEquals($response->getStatusCode(), 200);
(int)$ratingsArr[0]['@attributes']['id'],
(int)$ratingsArr[1]['@attributes']['id'] $responseArr = Convert::xml2array($response->getBody());
); $ratingsArr = $responseArr['Ratings']['RestfulServerTest_AuthorRating'];
$this->assertContains($rating1->ID, $ratingIDs); $this->assertEquals(count($ratingsArr), 2);
$this->assertContains($rating2->ID, $ratingIDs); $ratingIDs = array(
} (int)$ratingsArr[0]['@attributes']['id'],
(int)$ratingsArr[1]['@attributes']['id']
public function testGETManyManyRelationshipsXML() { );
// author4 has related authors author2 and author3 $this->assertContains($rating1->ID, $ratingIDs);
$author2 = $this->objFromFixture('RestfulServerTest_Author', 'author2'); $this->assertContains($rating2->ID, $ratingIDs);
$author3 = $this->objFromFixture('RestfulServerTest_Author', 'author3'); }
$author4 = $this->objFromFixture('RestfulServerTest_Author', 'author4');
public function testGETManyManyRelationshipsXML()
$url = "/api/v1/RestfulServerTest_Author/" . $author4->ID . '/RelatedAuthors'; {
$response = Director::test($url, null, null, 'GET'); // author4 has related authors author2 and author3
$this->assertEquals(200, $response->getStatusCode()); $author2 = $this->objFromFixture('RestfulServerTest_Author', 'author2');
$arr = Convert::xml2array($response->getBody()); $author3 = $this->objFromFixture('RestfulServerTest_Author', 'author3');
$authorsArr = $arr['RestfulServerTest_Author']; $author4 = $this->objFromFixture('RestfulServerTest_Author', 'author4');
$this->assertEquals(count($authorsArr), 2); $url = "/api/v1/RestfulServerTest_Author/" . $author4->ID . '/RelatedAuthors';
$ratingIDs = array( $response = Director::test($url, null, null, 'GET');
(int)$authorsArr[0]['ID'], $this->assertEquals(200, $response->getStatusCode());
(int)$authorsArr[1]['ID'] $arr = Convert::xml2array($response->getBody());
); $authorsArr = $arr['RestfulServerTest_Author'];
$this->assertContains($author2->ID, $ratingIDs);
$this->assertContains($author3->ID, $ratingIDs); $this->assertEquals(count($authorsArr), 2);
} $ratingIDs = array(
(int)$authorsArr[0]['ID'],
public function testPUTWithFormEncoded() { (int)$authorsArr[1]['ID']
$comment1 = $this->objFromFixture('RestfulServerTest_Comment', 'comment1'); );
$this->assertContains($author2->ID, $ratingIDs);
$_SERVER['PHP_AUTH_USER'] = 'editor@test.com'; $this->assertContains($author3->ID, $ratingIDs);
$_SERVER['PHP_AUTH_PW'] = 'editor'; }
$url = "/api/v1/RestfulServerTest_Comment/" . $comment1->ID; public function testPUTWithFormEncoded()
$body = 'Name=Updated Comment&Comment=updated'; {
$headers = array( $comment1 = $this->objFromFixture('RestfulServerTest_Comment', 'comment1');
'Content-Type' => 'application/x-www-form-urlencoded'
); $_SERVER['PHP_AUTH_USER'] = 'editor@test.com';
$response = Director::test($url, null, null, 'PUT', $body, $headers); $_SERVER['PHP_AUTH_PW'] = 'editor';
$this->assertEquals($response->getStatusCode(), 200); // Success
// Assumption: XML is default output $url = "/api/v1/RestfulServerTest_Comment/" . $comment1->ID;
$responseArr = Convert::xml2array($response->getBody()); $body = 'Name=Updated Comment&Comment=updated';
$this->assertEquals($responseArr['ID'], $comment1->ID); $headers = array(
$this->assertEquals($responseArr['Comment'], 'updated'); 'Content-Type' => 'application/x-www-form-urlencoded'
$this->assertEquals($responseArr['Name'], 'Updated Comment'); );
$response = Director::test($url, null, null, 'PUT', $body, $headers);
unset($_SERVER['PHP_AUTH_USER']); $this->assertEquals($response->getStatusCode(), 200); // Success
unset($_SERVER['PHP_AUTH_PW']); // Assumption: XML is default output
} $responseArr = Convert::xml2array($response->getBody());
$this->assertEquals($responseArr['ID'], $comment1->ID);
public function testPOSTWithFormEncoded() { $this->assertEquals($responseArr['Comment'], 'updated');
$comment1 = $this->objFromFixture('RestfulServerTest_Comment', 'comment1'); $this->assertEquals($responseArr['Name'], 'Updated Comment');
$_SERVER['PHP_AUTH_USER'] = 'editor@test.com'; unset($_SERVER['PHP_AUTH_USER']);
$_SERVER['PHP_AUTH_PW'] = 'editor'; unset($_SERVER['PHP_AUTH_PW']);
}
$url = "/api/v1/RestfulServerTest_Comment";
$body = 'Name=New Comment&Comment=created'; public function testPOSTWithFormEncoded()
$headers = array( {
'Content-Type' => 'application/x-www-form-urlencoded' $comment1 = $this->objFromFixture('RestfulServerTest_Comment', 'comment1');
);
$response = Director::test($url, null, null, 'POST', $body, $headers); $_SERVER['PHP_AUTH_USER'] = 'editor@test.com';
$this->assertEquals($response->getStatusCode(), 201); // Created $_SERVER['PHP_AUTH_PW'] = 'editor';
// Assumption: XML is default output
$responseArr = Convert::xml2array($response->getBody()); $url = "/api/v1/RestfulServerTest_Comment";
$this->assertTrue($responseArr['ID'] > 0); $body = 'Name=New Comment&Comment=created';
$this->assertNotEquals($responseArr['ID'], $comment1->ID); $headers = array(
$this->assertEquals($responseArr['Comment'], 'created'); 'Content-Type' => 'application/x-www-form-urlencoded'
$this->assertEquals($responseArr['Name'], 'New Comment'); );
$this->assertEquals( $response = Director::test($url, null, null, 'POST', $body, $headers);
$response->getHeader('Location'), $this->assertEquals($response->getStatusCode(), 201); // Created
Controller::join_links(Director::absoluteBaseURL(), $url, $responseArr['ID']) // Assumption: XML is default output
); $responseArr = Convert::xml2array($response->getBody());
$this->assertTrue($responseArr['ID'] > 0);
unset($_SERVER['PHP_AUTH_USER']); $this->assertNotEquals($responseArr['ID'], $comment1->ID);
unset($_SERVER['PHP_AUTH_PW']); $this->assertEquals($responseArr['Comment'], 'created');
} $this->assertEquals($responseArr['Name'], 'New Comment');
$this->assertEquals(
public function testPUTwithJSON() { $response->getHeader('Location'),
$comment1 = $this->objFromFixture('RestfulServerTest_Comment', 'comment1'); Controller::join_links(Director::absoluteBaseURL(), $url, $responseArr['ID'])
);
$_SERVER['PHP_AUTH_USER'] = 'editor@test.com';
$_SERVER['PHP_AUTH_PW'] = 'editor'; unset($_SERVER['PHP_AUTH_USER']);
unset($_SERVER['PHP_AUTH_PW']);
// by mimetype }
$url = "/api/v1/RestfulServerTest_Comment/" . $comment1->ID;
$body = '{"Comment":"updated"}'; public function testPUTwithJSON()
$response = Director::test($url, null, null, 'PUT', $body, array('Content-Type'=>'application/json')); {
$this->assertEquals($response->getStatusCode(), 200); // Updated $comment1 = $this->objFromFixture('RestfulServerTest_Comment', 'comment1');
$obj = Convert::json2obj($response->getBody());
$this->assertEquals($obj->ID, $comment1->ID); $_SERVER['PHP_AUTH_USER'] = 'editor@test.com';
$this->assertEquals($obj->Comment, 'updated'); $_SERVER['PHP_AUTH_PW'] = 'editor';
// by extension // by mimetype
$url = sprintf("/api/v1/RestfulServerTest_Comment/%d.json", $comment1->ID); $url = "/api/v1/RestfulServerTest_Comment/" . $comment1->ID;
$body = '{"Comment":"updated"}'; $body = '{"Comment":"updated"}';
$response = Director::test($url, null, null, 'PUT', $body); $response = Director::test($url, null, null, 'PUT', $body, array('Content-Type'=>'application/json'));
$this->assertEquals($response->getStatusCode(), 200); // Updated $this->assertEquals($response->getStatusCode(), 200); // Updated
$this->assertEquals( $obj = Convert::json2obj($response->getBody());
$response->getHeader('Location'), $this->assertEquals($obj->ID, $comment1->ID);
Controller::join_links(Director::absoluteBaseURL(), $url) $this->assertEquals($obj->Comment, 'updated');
);
$obj = Convert::json2obj($response->getBody()); // by extension
$this->assertEquals($obj->ID, $comment1->ID); $url = sprintf("/api/v1/RestfulServerTest_Comment/%d.json", $comment1->ID);
$this->assertEquals($obj->Comment, 'updated'); $body = '{"Comment":"updated"}';
$response = Director::test($url, null, null, 'PUT', $body);
unset($_SERVER['PHP_AUTH_USER']); $this->assertEquals($response->getStatusCode(), 200); // Updated
unset($_SERVER['PHP_AUTH_PW']); $this->assertEquals(
} $response->getHeader('Location'),
Controller::join_links(Director::absoluteBaseURL(), $url)
public function testPUTwithXML() { );
$comment1 = $this->objFromFixture('RestfulServerTest_Comment', 'comment1'); $obj = Convert::json2obj($response->getBody());
$this->assertEquals($obj->ID, $comment1->ID);
$_SERVER['PHP_AUTH_USER'] = 'editor@test.com'; $this->assertEquals($obj->Comment, 'updated');
$_SERVER['PHP_AUTH_PW'] = 'editor';
unset($_SERVER['PHP_AUTH_USER']);
// by mimetype unset($_SERVER['PHP_AUTH_PW']);
$url = "/api/v1/RestfulServerTest_Comment/" . $comment1->ID; }
$body = '<RestfulServerTest_Comment><Comment>updated</Comment></RestfulServerTest_Comment>';
$response = Director::test($url, null, null, 'PUT', $body, array('Content-Type'=>'text/xml')); public function testPUTwithXML()
$this->assertEquals($response->getStatusCode(), 200); // Updated {
$obj = Convert::xml2array($response->getBody()); $comment1 = $this->objFromFixture('RestfulServerTest_Comment', 'comment1');
$this->assertEquals($obj['ID'], $comment1->ID);
$this->assertEquals($obj['Comment'], 'updated'); $_SERVER['PHP_AUTH_USER'] = 'editor@test.com';
$_SERVER['PHP_AUTH_PW'] = 'editor';
// by extension
$url = sprintf("/api/v1/RestfulServerTest_Comment/%d.xml", $comment1->ID); // by mimetype
$body = '<RestfulServerTest_Comment><Comment>updated</Comment></RestfulServerTest_Comment>'; $url = "/api/v1/RestfulServerTest_Comment/" . $comment1->ID;
$response = Director::test($url, null, null, 'PUT', $body); $body = '<RestfulServerTest_Comment><Comment>updated</Comment></RestfulServerTest_Comment>';
$this->assertEquals($response->getStatusCode(), 200); // Updated $response = Director::test($url, null, null, 'PUT', $body, array('Content-Type'=>'text/xml'));
$this->assertEquals( $this->assertEquals($response->getStatusCode(), 200); // Updated
$response->getHeader('Location'), $obj = Convert::xml2array($response->getBody());
Controller::join_links(Director::absoluteBaseURL(), $url) $this->assertEquals($obj['ID'], $comment1->ID);
); $this->assertEquals($obj['Comment'], 'updated');
$obj = Convert::xml2array($response->getBody());
$this->assertEquals($obj['ID'], $comment1->ID); // by extension
$this->assertEquals($obj['Comment'], 'updated'); $url = sprintf("/api/v1/RestfulServerTest_Comment/%d.xml", $comment1->ID);
$body = '<RestfulServerTest_Comment><Comment>updated</Comment></RestfulServerTest_Comment>';
unset($_SERVER['PHP_AUTH_USER']); $response = Director::test($url, null, null, 'PUT', $body);
unset($_SERVER['PHP_AUTH_PW']); $this->assertEquals($response->getStatusCode(), 200); // Updated
} $this->assertEquals(
$response->getHeader('Location'),
public function testHTTPAcceptAndContentType() { Controller::join_links(Director::absoluteBaseURL(), $url)
$comment1 = $this->objFromFixture('RestfulServerTest_Comment', 'comment1'); );
$obj = Convert::xml2array($response->getBody());
$url = "/api/v1/RestfulServerTest_Comment/" . $comment1->ID; $this->assertEquals($obj['ID'], $comment1->ID);
$this->assertEquals($obj['Comment'], 'updated');
$headers = array('Accept' => 'application/json');
$response = Director::test($url, null, null, 'GET', null, $headers); unset($_SERVER['PHP_AUTH_USER']);
$this->assertEquals($response->getStatusCode(), 200); // Success unset($_SERVER['PHP_AUTH_PW']);
$obj = Convert::json2obj($response->getBody()); }
$this->assertEquals($obj->ID, $comment1->ID);
$this->assertEquals($response->getHeader('Content-Type'), 'application/json'); public function testHTTPAcceptAndContentType()
} {
$comment1 = $this->objFromFixture('RestfulServerTest_Comment', 'comment1');
public function testNotFound(){
$_SERVER['PHP_AUTH_USER'] = 'user@test.com'; $url = "/api/v1/RestfulServerTest_Comment/" . $comment1->ID;
$_SERVER['PHP_AUTH_PW'] = 'user';
$headers = array('Accept' => 'application/json');
$url = "/api/v1/RestfulServerTest_Comment/99"; $response = Director::test($url, null, null, 'GET', null, $headers);
$response = Director::test($url, null, null, 'GET'); $this->assertEquals($response->getStatusCode(), 200); // Success
$this->assertEquals($response->getStatusCode(), 404); $obj = Convert::json2obj($response->getBody());
$this->assertEquals($obj->ID, $comment1->ID);
unset($_SERVER['PHP_AUTH_USER']); $this->assertEquals($response->getHeader('Content-Type'), 'application/json');
unset($_SERVER['PHP_AUTH_PW']); }
}
public function testNotFound()
public function testMethodNotAllowed() { {
$comment1 = $this->objFromFixture('RestfulServerTest_Comment', 'comment1'); $_SERVER['PHP_AUTH_USER'] = 'user@test.com';
$_SERVER['PHP_AUTH_PW'] = 'user';
$url = "/api/v1/RestfulServerTest_Comment/" . $comment1->ID;
$response = Director::test($url, null, null, 'UNKNOWNHTTPMETHOD'); $url = "/api/v1/RestfulServerTest_Comment/99";
$this->assertEquals($response->getStatusCode(), 405); $response = Director::test($url, null, null, 'GET');
} $this->assertEquals($response->getStatusCode(), 404);
public function testConflictOnExistingResourceWhenUsingPost() { unset($_SERVER['PHP_AUTH_USER']);
$rating1 = $this->objFromFixture('RestfulServerTest_AuthorRating', 'rating1'); unset($_SERVER['PHP_AUTH_PW']);
}
$url = "/api/v1/RestfulServerTest_AuthorRating/" . $rating1->ID;
$response = Director::test($url, null, null, 'POST'); public function testMethodNotAllowed()
$this->assertEquals($response->getStatusCode(), 409); {
} $comment1 = $this->objFromFixture('RestfulServerTest_Comment', 'comment1');
public function testUnsupportedMediaType() { $url = "/api/v1/RestfulServerTest_Comment/" . $comment1->ID;
$_SERVER['PHP_AUTH_USER'] = 'user@test.com'; $response = Director::test($url, null, null, 'UNKNOWNHTTPMETHOD');
$_SERVER['PHP_AUTH_PW'] = 'user'; $this->assertEquals($response->getStatusCode(), 405);
}
$url = "/api/v1/RestfulServerTest_Comment";
$data = "Comment||\/||updated"; // weird format public function testConflictOnExistingResourceWhenUsingPost()
$headers = array('Content-Type' => 'text/weirdformat'); {
$response = Director::test($url, null, null, 'POST', $data, $headers); $rating1 = $this->objFromFixture('RestfulServerTest_AuthorRating', 'rating1');
$this->assertEquals($response->getStatusCode(), 415);
$url = "/api/v1/RestfulServerTest_AuthorRating/" . $rating1->ID;
unset($_SERVER['PHP_AUTH_USER']); $response = Director::test($url, null, null, 'POST');
unset($_SERVER['PHP_AUTH_PW']); $this->assertEquals($response->getStatusCode(), 409);
} }
public function testXMLValueFormatting() { public function testUnsupportedMediaType()
$rating1 = $this->objFromFixture('RestfulServerTest_AuthorRating','rating1'); {
$_SERVER['PHP_AUTH_USER'] = 'user@test.com';
$url = "/api/v1/RestfulServerTest_AuthorRating/" . $rating1->ID; $_SERVER['PHP_AUTH_PW'] = 'user';
$response = Director::test($url, null, null, 'GET');
$this->assertContains('<ID>' . $rating1->ID . '</ID>', $response->getBody()); $url = "/api/v1/RestfulServerTest_Comment";
$this->assertContains('<Rating>' . $rating1->Rating . '</Rating>', $response->getBody()); $data = "Comment||\/||updated"; // weird format
} $headers = array('Content-Type' => 'text/weirdformat');
$response = Director::test($url, null, null, 'POST', $data, $headers);
public function testApiAccessFieldRestrictions() { $this->assertEquals($response->getStatusCode(), 415);
$author1 = $this->objFromFixture('RestfulServerTest_Author','author1');
$rating1 = $this->objFromFixture('RestfulServerTest_AuthorRating','rating1'); unset($_SERVER['PHP_AUTH_USER']);
unset($_SERVER['PHP_AUTH_PW']);
$url = "/api/v1/RestfulServerTest_AuthorRating/" . $rating1->ID; }
$response = Director::test($url, null, null, 'GET');
$this->assertContains('<ID>', $response->getBody()); public function testXMLValueFormatting()
$this->assertContains('<Rating>', $response->getBody()); {
$this->assertContains('<Author', $response->getBody()); $rating1 = $this->objFromFixture('RestfulServerTest_AuthorRating', 'rating1');
$this->assertNotContains('<SecretField>', $response->getBody());
$this->assertNotContains('<SecretRelation>', $response->getBody()); $url = "/api/v1/RestfulServerTest_AuthorRating/" . $rating1->ID;
$response = Director::test($url, null, null, 'GET');
$url = "/api/v1/RestfulServerTest_AuthorRating/" . $rating1->ID . '?add_fields=SecretField,SecretRelation'; $this->assertContains('<ID>' . $rating1->ID . '</ID>', $response->getBody());
$response = Director::test($url, null, null, 'GET'); $this->assertContains('<Rating>' . $rating1->Rating . '</Rating>', $response->getBody());
$this->assertNotContains('<SecretField>', $response->getBody(), }
'"add_fields" URL parameter filters out disallowed fields from $api_access'
); public function testApiAccessFieldRestrictions()
$this->assertNotContains('<SecretRelation>', $response->getBody(), {
'"add_fields" URL parameter filters out disallowed relations from $api_access' $author1 = $this->objFromFixture('RestfulServerTest_Author', 'author1');
); $rating1 = $this->objFromFixture('RestfulServerTest_AuthorRating', 'rating1');
$url = "/api/v1/RestfulServerTest_AuthorRating/" . $rating1->ID . '?fields=SecretField,SecretRelation'; $url = "/api/v1/RestfulServerTest_AuthorRating/" . $rating1->ID;
$response = Director::test($url, null, null, 'GET'); $response = Director::test($url, null, null, 'GET');
$this->assertNotContains('<SecretField>', $response->getBody(), $this->assertContains('<ID>', $response->getBody());
'"fields" URL parameter filters out disallowed fields from $api_access' $this->assertContains('<Rating>', $response->getBody());
); $this->assertContains('<Author', $response->getBody());
$this->assertNotContains('<SecretRelation>', $response->getBody(), $this->assertNotContains('<SecretField>', $response->getBody());
'"fields" URL parameter filters out disallowed relations from $api_access' $this->assertNotContains('<SecretRelation>', $response->getBody());
);
$url = "/api/v1/RestfulServerTest_AuthorRating/" . $rating1->ID . '?add_fields=SecretField,SecretRelation';
$url = "/api/v1/RestfulServerTest_Author/" . $author1->ID . '/Ratings'; $response = Director::test($url, null, null, 'GET');
$response = Director::test($url, null, null, 'GET'); $this->assertNotContains('<SecretField>', $response->getBody(),
$this->assertContains('<Rating>', $response->getBody(), '"add_fields" URL parameter filters out disallowed fields from $api_access'
'Relation viewer shows fields allowed through $api_access' );
); $this->assertNotContains('<SecretRelation>', $response->getBody(),
$this->assertNotContains('<SecretField>', $response->getBody(), '"add_fields" URL parameter filters out disallowed relations from $api_access'
'Relation viewer on has-many filters out disallowed fields from $api_access' );
);
} $url = "/api/v1/RestfulServerTest_AuthorRating/" . $rating1->ID . '?fields=SecretField,SecretRelation';
$response = Director::test($url, null, null, 'GET');
public function testApiAccessRelationRestrictionsInline() { $this->assertNotContains('<SecretField>', $response->getBody(),
$author1 = $this->objFromFixture('RestfulServerTest_Author','author1'); '"fields" URL parameter filters out disallowed fields from $api_access'
);
$url = "/api/v1/RestfulServerTest_Author/" . $author1->ID; $this->assertNotContains('<SecretRelation>', $response->getBody(),
$response = Director::test($url, null, null, 'GET'); '"fields" URL parameter filters out disallowed relations from $api_access'
$this->assertNotContains('<RelatedPages', $response->getBody(), 'Restricts many-many with api_access=false'); );
$this->assertNotContains('<PublishedPages', $response->getBody(), 'Restricts has-many with api_access=false');
} $url = "/api/v1/RestfulServerTest_Author/" . $author1->ID . '/Ratings';
$response = Director::test($url, null, null, 'GET');
public function testApiAccessRelationRestrictionsOnEndpoint() { $this->assertContains('<Rating>', $response->getBody(),
$author1 = $this->objFromFixture('RestfulServerTest_Author','author1'); 'Relation viewer shows fields allowed through $api_access'
);
$url = "/api/v1/RestfulServerTest_Author/" . $author1->ID . "/ProfilePage"; $this->assertNotContains('<SecretField>', $response->getBody(),
$response = Director::test($url, null, null, 'GET'); 'Relation viewer on has-many filters out disallowed fields from $api_access'
$this->assertEquals(404, $response->getStatusCode(), 'Restricts has-one with api_access=false'); );
}
$url = "/api/v1/RestfulServerTest_Author/" . $author1->ID . "/RelatedPages";
$response = Director::test($url, null, null, 'GET'); public function testApiAccessRelationRestrictionsInline()
$this->assertEquals(404, $response->getStatusCode(), 'Restricts many-many with api_access=false'); {
$author1 = $this->objFromFixture('RestfulServerTest_Author', 'author1');
$url = "/api/v1/RestfulServerTest_Author/" . $author1->ID . "/PublishedPages";
$response = Director::test($url, null, null, 'GET'); $url = "/api/v1/RestfulServerTest_Author/" . $author1->ID;
$this->assertEquals(404, $response->getStatusCode(), 'Restricts has-many with api_access=false'); $response = Director::test($url, null, null, 'GET');
} $this->assertNotContains('<RelatedPages', $response->getBody(), 'Restricts many-many with api_access=false');
$this->assertNotContains('<PublishedPages', $response->getBody(), 'Restricts has-many with api_access=false');
public function testApiAccessWithPUT() { }
$rating1 = $this->objFromFixture('RestfulServerTest_AuthorRating','rating1');
public function testApiAccessRelationRestrictionsOnEndpoint()
$url = "/api/v1/RestfulServerTest_AuthorRating/" . $rating1->ID; {
$data = array( $author1 = $this->objFromFixture('RestfulServerTest_Author', 'author1');
'Rating' => '42',
'WriteProtectedField' => 'haxx0red' $url = "/api/v1/RestfulServerTest_Author/" . $author1->ID . "/ProfilePage";
); $response = Director::test($url, null, null, 'GET');
$response = Director::test($url, $data, null, 'PUT'); $this->assertEquals(404, $response->getStatusCode(), 'Restricts has-one with api_access=false');
// Assumption: XML is default output
$responseArr = Convert::xml2array($response->getBody()); $url = "/api/v1/RestfulServerTest_Author/" . $author1->ID . "/RelatedPages";
$this->assertEquals($responseArr['Rating'], 42); $response = Director::test($url, null, null, 'GET');
$this->assertNotEquals($responseArr['WriteProtectedField'], 'haxx0red'); $this->assertEquals(404, $response->getStatusCode(), 'Restricts many-many with api_access=false');
}
$url = "/api/v1/RestfulServerTest_Author/" . $author1->ID . "/PublishedPages";
public function testJSONDataFormatter() { $response = Director::test($url, null, null, 'GET');
$formatter = new JSONDataFormatter(); $this->assertEquals(404, $response->getStatusCode(), 'Restricts has-many with api_access=false');
$editor = $this->objFromFixture('Member', 'editor'); }
$user = $this->objFromFixture('Member', 'user');
public function testApiAccessWithPUT()
$this->assertEquals( {
$formatter->convertDataObject($editor, array("FirstName", "Email")), $rating1 = $this->objFromFixture('RestfulServerTest_AuthorRating', 'rating1');
'{"FirstName":"Editor","Email":"editor@test.com"}',
"Correct JSON formatting with field subset"); $url = "/api/v1/RestfulServerTest_AuthorRating/" . $rating1->ID;
$data = array(
$set = DataObject::get( 'Rating' => '42',
"Member", 'WriteProtectedField' => 'haxx0red'
sprintf('"Member"."ID" IN (%s)', implode(',', array($editor->ID, $user->ID))), );
'"Email" ASC' // for sorting for postgres $response = Director::test($url, $data, null, 'PUT');
); // Assumption: XML is default output
$this->assertEquals( $responseArr = Convert::xml2array($response->getBody());
$formatter->convertDataObjectSet($set, array("FirstName", "Email")), $this->assertEquals($responseArr['Rating'], 42);
'{"totalSize":null,"items":[{"FirstName":"Editor","Email":"editor@test.com"},' . $this->assertNotEquals($responseArr['WriteProtectedField'], 'haxx0red');
'{"FirstName":"User","Email":"user@test.com"}]}', }
"Correct JSON formatting on a dataobjectset with field filter");
} public function testJSONDataFormatter()
{
public function testApiAccessWithPOST() { $formatter = new JSONDataFormatter();
$url = "/api/v1/RestfulServerTest_AuthorRating"; $editor = $this->objFromFixture('Member', 'editor');
$data = array( $user = $this->objFromFixture('Member', 'user');
'Rating' => '42',
'WriteProtectedField' => 'haxx0red' $this->assertEquals(
); $formatter->convertDataObject($editor, array("FirstName", "Email")),
$response = Director::test($url, $data, null, 'POST'); '{"FirstName":"Editor","Email":"editor@test.com"}',
// Assumption: XML is default output "Correct JSON formatting with field subset");
$responseArr = Convert::xml2array($response->getBody());
$this->assertEquals($responseArr['Rating'], 42); $set = DataObject::get(
$this->assertNotEquals($responseArr['WriteProtectedField'], 'haxx0red'); "Member",
} sprintf('"Member"."ID" IN (%s)', implode(',', array($editor->ID, $user->ID))),
'"Email" ASC' // for sorting for postgres
public function testCanViewRespectedInList() { );
// Default content type $this->assertEquals(
$url = "/api/v1/RestfulServerTest_SecretThing/"; $formatter->convertDataObjectSet($set, array("FirstName", "Email")),
$response = Director::test($url, null, null, 'GET'); '{"totalSize":null,"items":[{"FirstName":"Editor","Email":"editor@test.com"},' .
$this->assertEquals($response->getStatusCode(), 200); '{"FirstName":"User","Email":"user@test.com"}]}',
$this->assertNotContains('Unspeakable', $response->getBody()); "Correct JSON formatting on a dataobjectset with field filter");
}
// JSON content type
$url = "/api/v1/RestfulServerTest_SecretThing.json"; public function testApiAccessWithPOST()
$response = Director::test($url, null, null, 'GET'); {
$this->assertEquals($response->getStatusCode(), 200); $url = "/api/v1/RestfulServerTest_AuthorRating";
$this->assertNotContains('Unspeakable', $response->getBody()); $data = array(
'Rating' => '42',
// With authentication 'WriteProtectedField' => 'haxx0red'
$_SERVER['PHP_AUTH_USER'] = 'editor@test.com'; );
$_SERVER['PHP_AUTH_PW'] = 'editor'; $response = Director::test($url, $data, null, 'POST');
$url = "/api/v1/RestfulServerTest_SecretThing/"; // Assumption: XML is default output
$response = Director::test($url, null, null, 'GET'); $responseArr = Convert::xml2array($response->getBody());
$this->assertEquals($response->getStatusCode(), 200); $this->assertEquals($responseArr['Rating'], 42);
$this->assertContains('Unspeakable', $response->getBody()); $this->assertNotEquals($responseArr['WriteProtectedField'], 'haxx0red');
unset($_SERVER['PHP_AUTH_USER']); }
unset($_SERVER['PHP_AUTH_PW']);
} public function testCanViewRespectedInList()
{
// Default content type
$url = "/api/v1/RestfulServerTest_SecretThing/";
$response = Director::test($url, null, null, 'GET');
$this->assertEquals($response->getStatusCode(), 200);
$this->assertNotContains('Unspeakable', $response->getBody());
// JSON content type
$url = "/api/v1/RestfulServerTest_SecretThing.json";
$response = Director::test($url, null, null, 'GET');
$this->assertEquals($response->getStatusCode(), 200);
$this->assertNotContains('Unspeakable', $response->getBody());
// With authentication
$_SERVER['PHP_AUTH_USER'] = 'editor@test.com';
$_SERVER['PHP_AUTH_PW'] = 'editor';
$url = "/api/v1/RestfulServerTest_SecretThing/";
$response = Director::test($url, null, null, 'GET');
$this->assertEquals($response->getStatusCode(), 200);
$this->assertContains('Unspeakable', $response->getBody());
unset($_SERVER['PHP_AUTH_USER']);
unset($_SERVER['PHP_AUTH_PW']);
}
} }
/** /**
@ -459,143 +481,153 @@ class RestfulServerTest extends SapphireTest {
* but only "editors" can edit or delete them. * but only "editors" can edit or delete them.
* *
*/ */
class RestfulServerTest_Comment extends DataObject implements PermissionProvider,TestOnly { class RestfulServerTest_Comment extends DataObject implements PermissionProvider,TestOnly
{
public static $api_access = true;
static $api_access = true; public static $db = array(
"Name" => "Varchar(255)",
"Comment" => "Text"
);
static $db = array( public static $has_one = array(
"Name" => "Varchar(255)", 'Page' => 'RestfulServerTest_Page',
"Comment" => "Text" 'Author' => 'RestfulServerTest_Author',
); );
static $has_one = array( public function providePermissions()
'Page' => 'RestfulServerTest_Page', {
'Author' => 'RestfulServerTest_Author', return array(
); 'EDIT_Comment' => 'Edit Comment Objects',
'CREATE_Comment' => 'Create Comment Objects',
'DELETE_Comment' => 'Delete Comment Objects',
);
}
public function providePermissions(){ public function canView($member = null)
return array( {
'EDIT_Comment' => 'Edit Comment Objects', return true;
'CREATE_Comment' => 'Create Comment Objects', }
'DELETE_Comment' => 'Delete Comment Objects',
);
}
public function canView($member = null) { public function canEdit($member = null)
return true; {
} return Permission::checkMember($member, 'EDIT_Comment');
}
public function canEdit($member = null) { public function canDelete($member = null)
return Permission::checkMember($member, 'EDIT_Comment'); {
} return Permission::checkMember($member, 'DELETE_Comment');
}
public function canDelete($member = null) {
return Permission::checkMember($member, 'DELETE_Comment');
}
public function canCreate($member = null) {
return Permission::checkMember($member, 'CREATE_Comment');
}
public function canCreate($member = null)
{
return Permission::checkMember($member, 'CREATE_Comment');
}
} }
class RestfulServerTest_SecretThing extends DataObject implements TestOnly,PermissionProvider{ class RestfulServerTest_SecretThing extends DataObject implements TestOnly,PermissionProvider
static $api_access = true; {
public static $api_access = true;
static $db = array( public static $db = array(
"Name" => "Varchar(255)", "Name" => "Varchar(255)",
); );
public function canView($member = null) { public function canView($member = null)
return Permission::checkMember($member, 'VIEW_SecretThing'); {
} return Permission::checkMember($member, 'VIEW_SecretThing');
}
public function providePermissions(){ public function providePermissions()
return array( {
'VIEW_SecretThing' => 'View Secret Things', return array(
); 'VIEW_SecretThing' => 'View Secret Things',
} );
}
} }
class RestfulServerTest_Page extends DataObject implements TestOnly { class RestfulServerTest_Page extends DataObject implements TestOnly
{
public static $api_access = false;
static $api_access = false; public static $db = array(
'Title' => 'Text',
'Content' => 'HTMLText',
);
static $db = array( public static $has_one = array(
'Title' => 'Text', 'Author' => 'RestfulServerTest_Author',
'Content' => 'HTMLText', );
);
static $has_one = array( public static $has_many = array(
'Author' => 'RestfulServerTest_Author', 'TestComments' => 'RestfulServerTest_Comment'
); );
static $has_many = array(
'TestComments' => 'RestfulServerTest_Comment'
);
static $belongs_many_many = array(
'RelatedAuthors' => 'RestfulServerTest_Author',
);
public static $belongs_many_many = array(
'RelatedAuthors' => 'RestfulServerTest_Author',
);
} }
class RestfulServerTest_Author extends DataObject implements TestOnly { class RestfulServerTest_Author extends DataObject implements TestOnly
{
public static $api_access = true;
static $api_access = true; public static $db = array(
'Name' => 'Text',
);
static $db = array( public static $many_many = array(
'Name' => 'Text', 'RelatedPages' => 'RestfulServerTest_Page',
); 'RelatedAuthors' => 'RestfulServerTest_Author',
);
static $many_many = array( public static $has_many = array(
'RelatedPages' => 'RestfulServerTest_Page', 'PublishedPages' => 'RestfulServerTest_Page',
'RelatedAuthors' => 'RestfulServerTest_Author', 'Ratings' => 'RestfulServerTest_AuthorRating',
); );
static $has_many = array( public function canView($member = null)
'PublishedPages' => 'RestfulServerTest_Page', {
'Ratings' => 'RestfulServerTest_AuthorRating', return true;
); }
public function canView($member = null) {
return true;
}
} }
class RestfulServerTest_AuthorRating extends DataObject implements TestOnly { class RestfulServerTest_AuthorRating extends DataObject implements TestOnly
static $api_access = array( {
'view' => array( public static $api_access = array(
'Rating', 'view' => array(
'WriteProtectedField', 'Rating',
'Author' 'WriteProtectedField',
), 'Author'
'edit' => array( ),
'Rating' 'edit' => array(
) 'Rating'
); )
);
static $db = array( public static $db = array(
'Rating' => 'Int', 'Rating' => 'Int',
'SecretField' => 'Text', 'SecretField' => 'Text',
'WriteProtectedField' => 'Text', 'WriteProtectedField' => 'Text',
); );
static $has_one = array( public static $has_one = array(
'Author' => 'RestfulServerTest_Author', 'Author' => 'RestfulServerTest_Author',
'SecretRelation' => 'RestfulServerTest_Author', 'SecretRelation' => 'RestfulServerTest_Author',
); );
public function canView($member = null) { public function canView($member = null)
return true; {
} return true;
}
public function canEdit($member = null) { public function canEdit($member = null)
return true; {
} return true;
}
public function canCreate($member = null) { public function canCreate($member = null)
return true; {
} return true;
}
} }