Converted to PSR-2

This commit is contained in:
helpfulrobot 2015-11-21 19:21:34 +13:00
parent de3dc96d39
commit 96f868dbf5
5 changed files with 1279 additions and 1165 deletions

View File

@ -8,8 +8,8 @@
* application accessing the RestfulServer to store logins in plain text (or in
* decrytable form)
*/
class BasicRestfulAuthenticator {
class BasicRestfulAuthenticator
{
/**
* The authenticate function
*
@ -17,9 +17,12 @@ class BasicRestfulAuthenticator {
*
* @return Member|false The Member object, or false if no member
*/
public static function authenticate() {
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;
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();
@ -29,11 +32,10 @@ class BasicRestfulAuthenticator {
));
//Log the member in and return the member, if they were found
if($member) {
if ($member) {
$member->LogIn(false);
return $member;
}
return false;
}
}

View File

@ -26,8 +26,9 @@
* @package framework
* @subpackage api
*/
class RestfulServer extends Controller {
static $url_handlers = array(
class RestfulServer extends Controller
{
public static $url_handlers = array(
'$ClassName/$ID/$Relation' => 'handleAction'
#'$ClassName/#ID' => 'handleItem',
#'$ClassName' => 'handleList',
@ -72,12 +73,15 @@ class RestfulServer extends Controller {
}
*/
function init() {
public function init()
{
/* 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.
* TODO: In 3.2 we should make the default Live, then change to Stage in the admin area (with a nicer API)
*/
if (class_exists('SiteTree')) singleton('SiteTree')->extend('modelascontrollerInit', $this);
if (class_exists('SiteTree')) {
singleton('SiteTree')->extend('modelascontrollerInit', $this);
}
parent::init();
}
@ -85,16 +89,23 @@ class RestfulServer extends Controller {
* This handler acts as the switchboard for the controller.
* Since no $Action url-param is set, all requests are sent here.
*/
function index() {
if(!isset($this->urlParams['ClassName'])) return $this->notFound();
public function index()
{
if (!isset($this->urlParams['ClassName'])) {
return $this->notFound();
}
$className = $this->urlParams['ClassName'];
$id = (isset($this->urlParams['ID'])) ? $this->urlParams['ID'] : null;
$relation = (isset($this->urlParams['Relation'])) ? $this->urlParams['Relation'] : null;
// Check input formats
if(!class_exists($className)) return $this->notFound();
if($id && !is_numeric($id)) return $this->notFound();
if(
if (!class_exists($className)) {
return $this->notFound();
}
if ($id && !is_numeric($id)) {
return $this->notFound();
}
if (
$relation
&& !preg_match('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/', $relation)
) {
@ -103,25 +114,27 @@ class RestfulServer extends Controller {
// if api access is disabled, don't proceed
$apiAccess = singleton($className)->stat('api_access');
if(!$apiAccess) return $this->permissionFailure();
if (!$apiAccess) {
return $this->permissionFailure();
}
// authenticate through HTTP BasicAuth
$this->member = $this->authenticate();
// handle different HTTP verbs
if($this->request->isGET() || $this->request->isHEAD()) {
if ($this->request->isGET() || $this->request->isHEAD()) {
return $this->getHandler($className, $id, $relation);
}
if($this->request->isPOST()) {
if ($this->request->isPOST()) {
return $this->postHandler($className, $id, $relation);
}
if($this->request->isPUT()) {
if ($this->request->isPUT()) {
return $this->putHandler($className, $id, $relation);
}
if($this->request->isDELETE()) {
if ($this->request->isDELETE()) {
return $this->deleteHandler($className, $id, $relation);
}
@ -162,10 +175,11 @@ class RestfulServer extends Controller {
* @param String $relation
* @return String The serialized representation of the requested object(s) - usually XML or JSON.
*/
protected function getHandler($className, $id, $relationName) {
protected function getHandler($className, $id, $relationName)
{
$sort = '';
if($this->request->getVar('sort')) {
if ($this->request->getVar('sort')) {
$dir = $this->request->getVar('dir');
$sort = array($this->request->getVar('sort') => ($dir ? $dir : 'ASC'));
}
@ -178,25 +192,32 @@ class RestfulServer extends Controller {
$params = $this->request->getVars();
$responseFormatter = $this->getResponseDataFormatter($className);
if(!$responseFormatter) return $this->unsupportedMediaType();
if (!$responseFormatter) {
return $this->unsupportedMediaType();
}
// $obj can be either a DataObject or a SS_List,
// depending on the request
if($id) {
if ($id) {
// Format: /api/v1/<MyClass>/<ID>
$obj = $this->getObjectQuery($className, $id, $params)->First();
if(!$obj) return $this->notFound();
if(!$obj->canView()) return $this->permissionFailure();
if (!$obj) {
return $this->notFound();
}
if (!$obj->canView()) {
return $this->permissionFailure();
}
// Format: /api/v1/<MyClass>/<ID>/<Relation>
if($relationName) {
if ($relationName) {
$obj = $this->getObjectRelationQuery($obj, $params, $sort, $limit, $relationName);
if(!$obj) return $this->notFound();
if (!$obj) {
return $this->notFound();
}
// TODO Avoid creating data formatter again for relation class (see above)
$responseFormatter = $this->getResponseDataFormatter($obj->dataClass());
}
} else {
// Format: /api/v1/<MyClass>
$obj = $this->getObjectsQuery($className, $params, $sort, $limit);
@ -207,12 +228,16 @@ class RestfulServer extends Controller {
$rawFields = $this->request->getVar('fields');
$fields = $rawFields ? explode(',', $rawFields) : null;
if($obj instanceof SS_List) {
if ($obj instanceof SS_List) {
$responseFormatter->setTotalSize($obj->dataQuery()->query()->unlimitedRowCount());
$objs = new ArrayList($obj->toArray());
foreach($objs as $obj) if(!$obj->canView()) $objs->remove($obj);
foreach ($objs as $obj) {
if (!$obj->canView()) {
$objs->remove($obj);
}
}
return $responseFormatter->convertDataObjectSet($objs, $fields);
} else if(!$obj) {
} elseif (!$obj) {
$responseFormatter->setTotalSize(0);
return $responseFormatter->convertDataObjectSet(new ArrayList(), $fields);
} else {
@ -235,7 +260,7 @@ class RestfulServer extends Controller {
protected function getSearchQuery($className, $params = null, $sort = null,
$limit = null, $existingQuery = null
) {
if(singleton($className)->hasMethod('getRestfulSearchContext')) {
if (singleton($className)->hasMethod('getRestfulSearchContext')) {
$searchContext = singleton($className)->{'getRestfulSearchContext'}();
} else {
$searchContext = singleton($className)->getDefaultSearchContext();
@ -251,63 +276,71 @@ class RestfulServer extends Controller {
* @param String Classname of a DataObject
* @return DataFormatter
*/
protected function getDataFormatter($includeAcceptHeader = false, $className = null) {
protected function getDataFormatter($includeAcceptHeader = false, $className = null)
{
$extension = $this->request->getExtension();
$contentTypeWithEncoding = $this->request->getHeader('Content-Type');
preg_match('/([^;]*)/',$contentTypeWithEncoding, $contentTypeMatches);
preg_match('/([^;]*)/', $contentTypeWithEncoding, $contentTypeMatches);
$contentType = $contentTypeMatches[0];
$accept = $this->request->getHeader('Accept');
$mimetypes = $this->request->getAcceptMimetypes();
if(!$className) $className = $this->urlParams['ClassName'];
if (!$className) {
$className = $this->urlParams['ClassName'];
}
// get formatter
if(!empty($extension)) {
if (!empty($extension)) {
$formatter = DataFormatter::for_extension($extension);
}elseif($includeAcceptHeader && !empty($accept) && $accept != '*/*') {
} elseif ($includeAcceptHeader && !empty($accept) && $accept != '*/*') {
$formatter = DataFormatter::for_mimetypes($mimetypes);
if(!$formatter) $formatter = DataFormatter::for_extension(self::$default_extension);
} elseif(!empty($contentType)) {
if (!$formatter) {
$formatter = DataFormatter::for_extension(self::$default_extension);
}
} elseif (!empty($contentType)) {
$formatter = DataFormatter::for_mimetype($contentType);
} else {
$formatter = DataFormatter::for_extension(self::$default_extension);
}
if(!$formatter) return false;
if (!$formatter) {
return false;
}
// set custom fields
if($customAddFields = $this->request->getVar('add_fields')) {
$formatter->setCustomAddFields(explode(',',$customAddFields));
if ($customAddFields = $this->request->getVar('add_fields')) {
$formatter->setCustomAddFields(explode(',', $customAddFields));
}
if($customFields = $this->request->getVar('fields')) {
$formatter->setCustomFields(explode(',',$customFields));
if ($customFields = $this->request->getVar('fields')) {
$formatter->setCustomFields(explode(',', $customFields));
}
$formatter->setCustomRelations($this->getAllowedRelations($className));
$apiAccess = singleton($className)->stat('api_access');
if(is_array($apiAccess)) {
if (is_array($apiAccess)) {
$formatter->setCustomAddFields(
array_intersect((array)$formatter->getCustomAddFields(), (array)$apiAccess['view'])
);
if($formatter->getCustomFields()) {
if ($formatter->getCustomFields()) {
$formatter->setCustomFields(
array_intersect((array)$formatter->getCustomFields(), (array)$apiAccess['view'])
);
} else {
$formatter->setCustomFields((array)$apiAccess['view']);
}
if($formatter->getCustomRelations()) {
if ($formatter->getCustomRelations()) {
$formatter->setCustomRelations(
array_intersect((array)$formatter->getCustomRelations(), (array)$apiAccess['view'])
);
} else {
$formatter->setCustomRelations((array)$apiAccess['view']);
}
}
// set relation depth
$relationDepth = $this->request->getVar('relationdepth');
if(is_numeric($relationDepth)) $formatter->relationDepth = (int)$relationDepth;
if (is_numeric($relationDepth)) {
$formatter->relationDepth = (int)$relationDepth;
}
return $formatter;
}
@ -316,7 +349,8 @@ class RestfulServer extends Controller {
* @param String Classname of a DataObject
* @return DataFormatter
*/
protected function getRequestDataFormatter($className = null) {
protected function getRequestDataFormatter($className = null)
{
return $this->getDataFormatter(false, $className);
}
@ -324,17 +358,23 @@ class RestfulServer extends Controller {
* @param String Classname of a DataObject
* @return DataFormatter
*/
protected function getResponseDataFormatter($className = null) {
protected function getResponseDataFormatter($className = null)
{
return $this->getDataFormatter(true, $className);
}
/**
* Handler for object delete
*/
protected function deleteHandler($className, $id) {
protected function deleteHandler($className, $id)
{
$obj = DataObject::get_by_id($className, $id);
if(!$obj) return $this->notFound();
if(!$obj->canDelete()) return $this->permissionFailure();
if (!$obj) {
return $this->notFound();
}
if (!$obj->canDelete()) {
return $this->permissionFailure();
}
$obj->delete();
@ -345,16 +385,25 @@ class RestfulServer extends Controller {
/**
* Handler for object write
*/
protected function putHandler($className, $id) {
protected function putHandler($className, $id)
{
$obj = DataObject::get_by_id($className, $id);
if(!$obj) return $this->notFound();
if(!$obj->canEdit()) return $this->permissionFailure();
if (!$obj) {
return $this->notFound();
}
if (!$obj->canEdit()) {
return $this->permissionFailure();
}
$reqFormatter = $this->getRequestDataFormatter($className);
if(!$reqFormatter) return $this->unsupportedMediaType();
if (!$reqFormatter) {
return $this->unsupportedMediaType();
}
$responseFormatter = $this->getResponseDataFormatter($className);
if(!$responseFormatter) return $this->unsupportedMediaType();
if (!$responseFormatter) {
return $this->unsupportedMediaType();
}
$obj = $this->updateDataObject($obj, $reqFormatter);
@ -382,21 +431,24 @@ class RestfulServer extends Controller {
* current resolves in creatig a new element,
* rather than a "Conflict" message.
*/
protected function postHandler($className, $id, $relation) {
if($id) {
if(!$relation) {
protected function postHandler($className, $id, $relation)
{
if ($id) {
if (!$relation) {
$this->response->setStatusCode(409);
return 'Conflict';
}
$obj = DataObject::get_by_id($className, $id);
if(!$obj) return $this->notFound();
if(!$obj->hasMethod($relation)) {
if (!$obj) {
return $this->notFound();
}
if(!$obj->stat('allowed_actions') || !in_array($relation, $obj->stat('allowed_actions'))) {
if (!$obj->hasMethod($relation)) {
return $this->notFound();
}
if (!$obj->stat('allowed_actions') || !in_array($relation, $obj->stat('allowed_actions'))) {
return $this->permissionFailure();
}
@ -405,11 +457,15 @@ class RestfulServer extends Controller {
$this->getResponse()->setStatusCode(204); // No Content
return true;
} else {
if(!singleton($className)->canCreate()) return $this->permissionFailure();
if (!singleton($className)->canCreate()) {
return $this->permissionFailure();
}
$obj = new $className();
$reqFormatter = $this->getRequestDataFormatter($className);
if(!$reqFormatter) return $this->unsupportedMediaType();
if (!$reqFormatter) {
return $this->unsupportedMediaType();
}
$responseFormatter = $this->getResponseDataFormatter($className);
@ -444,15 +500,16 @@ class RestfulServer extends Controller {
* @param DataFormatter $formatter
* @return DataObject The passed object
*/
protected function updateDataObject($obj, $formatter) {
protected function updateDataObject($obj, $formatter)
{
// if neither an http body nor POST data is present, return error
$body = $this->request->getBody();
if(!$body && !$this->request->postVars()) {
if (!$body && !$this->request->postVars()) {
$this->getResponse()->setStatusCode(204); // No Content
return 'No Content';
}
if(!empty($body)) {
if (!empty($body)) {
$data = $formatter->convertStringToArray($body);
} else {
// assume application/x-www-form-urlencoded which is automatically parsed by PHP
@ -460,11 +517,11 @@ class RestfulServer extends Controller {
}
// @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');
if(is_array($apiAccess) && isset($apiAccess['edit'])) {
$data = array_intersect_key($data, array_combine($apiAccess['edit'],$apiAccess['edit']));
if (is_array($apiAccess) && isset($apiAccess['edit'])) {
$data = array_intersect_key($data, array_combine($apiAccess['edit'], $apiAccess['edit']));
}
$obj->update($data);
@ -482,7 +539,8 @@ class RestfulServer extends Controller {
* @param array $params
* @return DataList
*/
protected function getObjectQuery($className, $id, $params) {
protected function getObjectQuery($className, $id, $params)
{
return DataList::create($className)->byIDs(array($id));
}
@ -493,7 +551,8 @@ class RestfulServer extends Controller {
* @param int|array $limit
* @return SQLQuery
*/
protected function getObjectsQuery($className, $params, $sort, $limit) {
protected function getObjectsQuery($className, $params, $sort, $limit)
{
return $this->getSearchQuery($className, $params, $sort, $limit);
}
@ -506,10 +565,11 @@ class RestfulServer extends Controller {
* @param string $relationName
* @return SQLQuery|boolean
*/
protected function getObjectRelationQuery($obj, $params, $sort, $limit, $relationName) {
protected function getObjectRelationQuery($obj, $params, $sort, $limit, $relationName)
{
// The relation method will return a DataList, that getSearchQuery subsequently manipulates
if($obj->hasMethod($relationName)) {
if($relationClass = $obj->has_one($relationName)) {
if ($obj->hasMethod($relationName)) {
if ($relationClass = $obj->has_one($relationName)) {
$joinField = $relationName . 'ID';
$list = DataList::create($relationClass)->byIDs(array($obj->$joinField));
} else {
@ -517,13 +577,16 @@ class RestfulServer extends Controller {
}
$apiAccess = singleton($list->dataClass())->stat('api_access');
if(!$apiAccess) return false;
if (!$apiAccess) {
return false;
}
return $this->getSearchQuery($list->dataClass(), $params, $sort, $limit, $list);
}
}
protected function permissionFailure() {
protected function permissionFailure()
{
// return a 401
$this->getResponse()->setStatusCode(401);
$this->getResponse()->addHeader('WWW-Authenticate', 'Basic realm="API Access"');
@ -531,20 +594,23 @@ class RestfulServer extends Controller {
return "You don't have access to this item through the API.";
}
protected function notFound() {
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() {
protected function methodNotAllowed()
{
$this->getResponse()->setStatusCode(405);
$this->getResponse()->addHeader('Content-Type', 'text/plain');
return "Method Not Allowed";
}
protected function unsupportedMediaType() {
protected function unsupportedMediaType()
{
$this->response->setStatusCode(415); // Unsupported Media Type
$this->getResponse()->addHeader('Content-Type', 'text/plain');
return "Unsupported Media Type";
@ -555,7 +621,8 @@ class RestfulServer extends Controller {
*
* @return Member|false the logged in member
*/
protected function authenticate() {
protected function authenticate()
{
$authClass = self::config()->authenticator;
return $authClass::authenticate();
}
@ -568,18 +635,20 @@ class RestfulServer extends Controller {
* @param Member $member
* @return array
*/
protected function getAllowedRelations($class, $member = null) {
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')) {
if ($relations) {
foreach ($relations as $relName => $relClass) {
if (singleton($relClass)->stat('api_access')) {
$allowedRelations[] = $relName;
}
}
}
return $allowedRelations;
}
}
/**
@ -588,16 +657,19 @@ class RestfulServer extends Controller {
* @package framework
* @subpackage api
*/
class RestfulServer_List {
static $url_handlers = array(
class RestfulServer_List
{
public static $url_handlers = array(
'#ID' => 'handleItem',
);
function __construct($list) {
public function __construct($list)
{
$this->list = $list;
}
function handleItem($request) {
public function handleItem($request)
{
return new RestulServer_Item($this->list->getById($request->param('ID')));
}
}
@ -608,20 +680,26 @@ class RestfulServer_List {
* @package framework
* @subpackage api
*/
class RestfulServer_Item {
static $url_handlers = array(
class RestfulServer_Item
{
public static $url_handlers = array(
'$Relation' => 'handleRelation',
);
function __construct($item) {
public function __construct($item)
{
$this->item = $item;
}
function handleRelation($request) {
public function handleRelation($request)
{
$funcName = $request('Relation');
$relation = $this->item->$funcName();
if($relation instanceof SS_List) return new RestfulServer_List($relation);
else return new RestfulServer_Item($relation);
if ($relation instanceof SS_List) {
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');
// 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,7 +5,7 @@ define('SS_ENVIRONMENT_TYPE', 'dev');
/* Database connection */
$db = getenv('TESTDB');
switch($db) {
switch ($db) {
case "PGSQL";
define('SS_DATABASE_CLASS', 'PostgreSQLDatabase');
define('SS_DATABASE_USERNAME', 'postgres');

View File

@ -6,9 +6,9 @@
* @todo Test DELETE verb
*
*/
class RestfulServerTest extends SapphireTest {
static $fixture_file = 'RestfulServerTest.yml';
class RestfulServerTest extends SapphireTest
{
public static $fixture_file = 'RestfulServerTest.yml';
protected $extraDataObjects = array(
'RestfulServerTest_Comment',
@ -18,7 +18,8 @@ class RestfulServerTest extends SapphireTest {
'RestfulServerTest_AuthorRating',
);
public function testApiAccess() {
public function testApiAccess()
{
$comment1 = $this->objFromFixture('RestfulServerTest_Comment', 'comment1');
$page1 = $this->objFromFixture('RestfulServerTest_Page', 'page1');
@ -39,7 +40,8 @@ class RestfulServerTest extends SapphireTest {
unset($_SERVER['PHP_AUTH_PW']);
}
public function testApiAccessBoolean() {
public function testApiAccessBoolean()
{
$comment1 = $this->objFromFixture('RestfulServerTest_Comment', 'comment1');
$url = "/api/v1/RestfulServerTest_Comment/" . $comment1->ID;
@ -51,7 +53,8 @@ class RestfulServerTest extends SapphireTest {
$this->assertContains('<Author', $response->getBody());
}
public function testAuthenticatedGET() {
public function testAuthenticatedGET()
{
$thing1 = $this->objFromFixture('RestfulServerTest_SecretThing', 'thing1');
$comment1 = $this->objFromFixture('RestfulServerTest_Comment', 'comment1');
@ -71,7 +74,8 @@ class RestfulServerTest extends SapphireTest {
unset($_SERVER['PHP_AUTH_PW']);
}
public function testAuthenticatedPUT() {
public function testAuthenticatedPUT()
{
$comment1 = $this->objFromFixture('RestfulServerTest_Comment', 'comment1');
$url = "/api/v1/RestfulServerTest_Comment/" . $comment1->ID;
@ -89,7 +93,8 @@ class RestfulServerTest extends SapphireTest {
unset($_SERVER['PHP_AUTH_PW']);
}
public function testGETRelationshipsXML() {
public function testGETRelationshipsXML()
{
$author1 = $this->objFromFixture('RestfulServerTest_Author', 'author1');
$rating1 = $this->objFromFixture('RestfulServerTest_AuthorRating', 'rating1');
$rating2 = $this->objFromFixture('RestfulServerTest_AuthorRating', 'rating2');
@ -113,7 +118,8 @@ class RestfulServerTest extends SapphireTest {
$this->assertContains($rating2->ID, $ratingIDs);
}
public function testGETManyManyRelationshipsXML() {
public function testGETManyManyRelationshipsXML()
{
// author4 has related authors author2 and author3
$author2 = $this->objFromFixture('RestfulServerTest_Author', 'author2');
$author3 = $this->objFromFixture('RestfulServerTest_Author', 'author3');
@ -134,7 +140,8 @@ class RestfulServerTest extends SapphireTest {
$this->assertContains($author3->ID, $ratingIDs);
}
public function testPUTWithFormEncoded() {
public function testPUTWithFormEncoded()
{
$comment1 = $this->objFromFixture('RestfulServerTest_Comment', 'comment1');
$_SERVER['PHP_AUTH_USER'] = 'editor@test.com';
@ -157,7 +164,8 @@ class RestfulServerTest extends SapphireTest {
unset($_SERVER['PHP_AUTH_PW']);
}
public function testPOSTWithFormEncoded() {
public function testPOSTWithFormEncoded()
{
$comment1 = $this->objFromFixture('RestfulServerTest_Comment', 'comment1');
$_SERVER['PHP_AUTH_USER'] = 'editor@test.com';
@ -185,7 +193,8 @@ class RestfulServerTest extends SapphireTest {
unset($_SERVER['PHP_AUTH_PW']);
}
public function testPUTwithJSON() {
public function testPUTwithJSON()
{
$comment1 = $this->objFromFixture('RestfulServerTest_Comment', 'comment1');
$_SERVER['PHP_AUTH_USER'] = 'editor@test.com';
@ -217,7 +226,8 @@ class RestfulServerTest extends SapphireTest {
unset($_SERVER['PHP_AUTH_PW']);
}
public function testPUTwithXML() {
public function testPUTwithXML()
{
$comment1 = $this->objFromFixture('RestfulServerTest_Comment', 'comment1');
$_SERVER['PHP_AUTH_USER'] = 'editor@test.com';
@ -249,7 +259,8 @@ class RestfulServerTest extends SapphireTest {
unset($_SERVER['PHP_AUTH_PW']);
}
public function testHTTPAcceptAndContentType() {
public function testHTTPAcceptAndContentType()
{
$comment1 = $this->objFromFixture('RestfulServerTest_Comment', 'comment1');
$url = "/api/v1/RestfulServerTest_Comment/" . $comment1->ID;
@ -262,7 +273,8 @@ class RestfulServerTest extends SapphireTest {
$this->assertEquals($response->getHeader('Content-Type'), 'application/json');
}
public function testNotFound(){
public function testNotFound()
{
$_SERVER['PHP_AUTH_USER'] = 'user@test.com';
$_SERVER['PHP_AUTH_PW'] = 'user';
@ -274,7 +286,8 @@ class RestfulServerTest extends SapphireTest {
unset($_SERVER['PHP_AUTH_PW']);
}
public function testMethodNotAllowed() {
public function testMethodNotAllowed()
{
$comment1 = $this->objFromFixture('RestfulServerTest_Comment', 'comment1');
$url = "/api/v1/RestfulServerTest_Comment/" . $comment1->ID;
@ -282,7 +295,8 @@ class RestfulServerTest extends SapphireTest {
$this->assertEquals($response->getStatusCode(), 405);
}
public function testConflictOnExistingResourceWhenUsingPost() {
public function testConflictOnExistingResourceWhenUsingPost()
{
$rating1 = $this->objFromFixture('RestfulServerTest_AuthorRating', 'rating1');
$url = "/api/v1/RestfulServerTest_AuthorRating/" . $rating1->ID;
@ -290,7 +304,8 @@ class RestfulServerTest extends SapphireTest {
$this->assertEquals($response->getStatusCode(), 409);
}
public function testUnsupportedMediaType() {
public function testUnsupportedMediaType()
{
$_SERVER['PHP_AUTH_USER'] = 'user@test.com';
$_SERVER['PHP_AUTH_PW'] = 'user';
@ -304,8 +319,9 @@ class RestfulServerTest extends SapphireTest {
unset($_SERVER['PHP_AUTH_PW']);
}
public function testXMLValueFormatting() {
$rating1 = $this->objFromFixture('RestfulServerTest_AuthorRating','rating1');
public function testXMLValueFormatting()
{
$rating1 = $this->objFromFixture('RestfulServerTest_AuthorRating', 'rating1');
$url = "/api/v1/RestfulServerTest_AuthorRating/" . $rating1->ID;
$response = Director::test($url, null, null, 'GET');
@ -313,9 +329,10 @@ class RestfulServerTest extends SapphireTest {
$this->assertContains('<Rating>' . $rating1->Rating . '</Rating>', $response->getBody());
}
public function testApiAccessFieldRestrictions() {
$author1 = $this->objFromFixture('RestfulServerTest_Author','author1');
$rating1 = $this->objFromFixture('RestfulServerTest_AuthorRating','rating1');
public function testApiAccessFieldRestrictions()
{
$author1 = $this->objFromFixture('RestfulServerTest_Author', 'author1');
$rating1 = $this->objFromFixture('RestfulServerTest_AuthorRating', 'rating1');
$url = "/api/v1/RestfulServerTest_AuthorRating/" . $rating1->ID;
$response = Director::test($url, null, null, 'GET');
@ -353,8 +370,9 @@ class RestfulServerTest extends SapphireTest {
);
}
public function testApiAccessRelationRestrictionsInline() {
$author1 = $this->objFromFixture('RestfulServerTest_Author','author1');
public function testApiAccessRelationRestrictionsInline()
{
$author1 = $this->objFromFixture('RestfulServerTest_Author', 'author1');
$url = "/api/v1/RestfulServerTest_Author/" . $author1->ID;
$response = Director::test($url, null, null, 'GET');
@ -362,8 +380,9 @@ class RestfulServerTest extends SapphireTest {
$this->assertNotContains('<PublishedPages', $response->getBody(), 'Restricts has-many with api_access=false');
}
public function testApiAccessRelationRestrictionsOnEndpoint() {
$author1 = $this->objFromFixture('RestfulServerTest_Author','author1');
public function testApiAccessRelationRestrictionsOnEndpoint()
{
$author1 = $this->objFromFixture('RestfulServerTest_Author', 'author1');
$url = "/api/v1/RestfulServerTest_Author/" . $author1->ID . "/ProfilePage";
$response = Director::test($url, null, null, 'GET');
@ -378,8 +397,9 @@ class RestfulServerTest extends SapphireTest {
$this->assertEquals(404, $response->getStatusCode(), 'Restricts has-many with api_access=false');
}
public function testApiAccessWithPUT() {
$rating1 = $this->objFromFixture('RestfulServerTest_AuthorRating','rating1');
public function testApiAccessWithPUT()
{
$rating1 = $this->objFromFixture('RestfulServerTest_AuthorRating', 'rating1');
$url = "/api/v1/RestfulServerTest_AuthorRating/" . $rating1->ID;
$data = array(
@ -393,7 +413,8 @@ class RestfulServerTest extends SapphireTest {
$this->assertNotEquals($responseArr['WriteProtectedField'], 'haxx0red');
}
public function testJSONDataFormatter() {
public function testJSONDataFormatter()
{
$formatter = new JSONDataFormatter();
$editor = $this->objFromFixture('Member', 'editor');
$user = $this->objFromFixture('Member', 'user');
@ -415,7 +436,8 @@ class RestfulServerTest extends SapphireTest {
"Correct JSON formatting on a dataobjectset with field filter");
}
public function testApiAccessWithPOST() {
public function testApiAccessWithPOST()
{
$url = "/api/v1/RestfulServerTest_AuthorRating";
$data = array(
'Rating' => '42',
@ -428,7 +450,8 @@ class RestfulServerTest extends SapphireTest {
$this->assertNotEquals($responseArr['WriteProtectedField'], 'haxx0red');
}
public function testCanViewRespectedInList() {
public function testCanViewRespectedInList()
{
// Default content type
$url = "/api/v1/RestfulServerTest_SecretThing/";
$response = Director::test($url, null, null, 'GET');
@ -451,7 +474,6 @@ class RestfulServerTest extends SapphireTest {
unset($_SERVER['PHP_AUTH_USER']);
unset($_SERVER['PHP_AUTH_PW']);
}
}
/**
@ -459,21 +481,22 @@ class RestfulServerTest extends SapphireTest {
* 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;
static $db = array(
public static $db = array(
"Name" => "Varchar(255)",
"Comment" => "Text"
);
static $has_one = array(
public static $has_one = array(
'Page' => 'RestfulServerTest_Page',
'Author' => 'RestfulServerTest_Author',
);
public function providePermissions(){
public function providePermissions()
{
return array(
'EDIT_Comment' => 'Edit Comment Objects',
'CREATE_Comment' => 'Create Comment Objects',
@ -481,90 +504,97 @@ class RestfulServerTest_Comment extends DataObject implements PermissionProvider
);
}
public function canView($member = null) {
public function canView($member = null)
{
return true;
}
public function canEdit($member = null) {
public function canEdit($member = null)
{
return Permission::checkMember($member, 'EDIT_Comment');
}
public function canDelete($member = null) {
public function canDelete($member = null)
{
return Permission::checkMember($member, 'DELETE_Comment');
}
public function canCreate($member = null) {
public function canCreate($member = null)
{
return Permission::checkMember($member, 'CREATE_Comment');
}
}
class RestfulServerTest_SecretThing extends DataObject implements TestOnly,PermissionProvider{
static $api_access = true;
class RestfulServerTest_SecretThing extends DataObject implements TestOnly,PermissionProvider
{
public static $api_access = true;
static $db = array(
public static $db = array(
"Name" => "Varchar(255)",
);
public function canView($member = null) {
public function canView($member = null)
{
return Permission::checkMember($member, 'VIEW_SecretThing');
}
public function providePermissions(){
public function providePermissions()
{
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;
static $db = array(
public static $db = array(
'Title' => 'Text',
'Content' => 'HTMLText',
);
static $has_one = array(
public static $has_one = array(
'Author' => 'RestfulServerTest_Author',
);
static $has_many = array(
public static $has_many = array(
'TestComments' => 'RestfulServerTest_Comment'
);
static $belongs_many_many = array(
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;
static $db = array(
public static $db = array(
'Name' => 'Text',
);
static $many_many = array(
public static $many_many = array(
'RelatedPages' => 'RestfulServerTest_Page',
'RelatedAuthors' => 'RestfulServerTest_Author',
);
static $has_many = array(
public static $has_many = array(
'PublishedPages' => 'RestfulServerTest_Page',
'Ratings' => 'RestfulServerTest_AuthorRating',
);
public function canView($member = null) {
public function canView($member = null)
{
return true;
}
}
class RestfulServerTest_AuthorRating extends DataObject implements TestOnly {
static $api_access = array(
class RestfulServerTest_AuthorRating extends DataObject implements TestOnly
{
public static $api_access = array(
'view' => array(
'Rating',
'WriteProtectedField',
@ -575,27 +605,29 @@ class RestfulServerTest_AuthorRating extends DataObject implements TestOnly {
)
);
static $db = array(
public static $db = array(
'Rating' => 'Int',
'SecretField' => 'Text',
'WriteProtectedField' => 'Text',
);
static $has_one = array(
public static $has_one = array(
'Author' => 'RestfulServerTest_Author',
'SecretRelation' => 'RestfulServerTest_Author',
);
public function canView($member = null) {
public function canView($member = null)
{
return true;
}
public function canEdit($member = null) {
public function canEdit($member = null)
{
return true;
}
public function canCreate($member = null) {
public function canCreate($member = null)
{
return true;
}
}