Fix error in Request.php where wrong namespace was used for Exceptions

Remove sample APi
This commit is contained in:
PJ Dietz 2013-01-27 18:07:07 -05:00
parent 871f76f008
commit a44c98efb3
13 changed files with 7 additions and 652 deletions

9
.gitignore vendored
View File

@ -1,9 +1,12 @@
# Composer
vendor/
# Doxygen
docs/html
# Generated documentation
docs/
# OSX
.DS_Store
.AppleDouble
# PhpStorm
workspace.xml

View File

@ -1,8 +0,0 @@
RewriteEngine on
RewriteBase /wellrested/samples/apisample/
# Send all requests to non-regular files and directories to router.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^.+$ index.php [L,QSA]

View File

@ -1,50 +0,0 @@
<?php
namespace ApiSample;
use pjdietz\WellRESTed\Router;
use pjdietz\WellRESTed\Route;
// TODO Revise with autoload required.
/**
* Loads and instantiates handlers based on URI.
*/
class ApiSampleRouter extends Router
{
public function __construct()
{
parent::__construct();
$this->addTemplate(
'/articles/',
'ArticleCollectionHandler'
);
$this->addTemplate(
'/articles/{id}',
'ArticleItemHandler',
array('id' => Route::RE_NUM)
);
$this->addTemplate(
'/articles/{slug}',
'ArticleItemHandler',
array('slug' => Route::RE_SLUG)
);
}
public function addTemplate($template, $handlerClassName, $variables = null)
{
// Customize as needed based on your server.
$template = '/wellrested/samples/apisample' . $template;
$handlerClassName = '\apisample\handlers\\' . $handlerClassName;
$this->addRoute(
Route::newFromUriTemplate(
$template,
$handlerClassName,
$variables
)
);
}
}

View File

@ -1,110 +0,0 @@
<?php
namespace ApiSample;
/**
* Simple class for reading and writing articles to a text file.
*/
class ArticlesController
{
public $data;
protected $path;
public function __construct()
{
$this->path = dirname(__FILE__) . '/data/articles.json';
$this->load();
}
public function load()
{
if (file_exists($this->path)) {
$data = file_get_contents($this->path);
$this->data = json_decode($data, true);
}
}
public function save()
{
if (is_writable($this->path)) {
$data = json_encode($this->data);
return file_put_contents($this->path, $data);
}
return false;
}
public function getArticleById($id)
{
foreach ($this->data as $article) {
if ($article['articleId'] == $id) {
return $article;
}
}
return false;
}
public function getArticleBySlug($slug)
{
foreach ($this->data as $article) {
if ($article['slug'] == $slug) {
return $article;
}
}
return false;
}
public function addArticle($newArticle)
{
$validatedArticle = array(
'articleId' => $this->getNewId(),
'slug' => $newArticle['slug'],
'title' => $newArticle['title'],
'excerpt' => $newArticle['excerpt']
);
$this->data[] = $validatedArticle;
return $validatedArticle;
}
public function updateArticle($newArticle)
{
foreach ($this->data as &$oldArticle) {
if ($oldArticle['articleId'] == $newArticle['articleId']) {
$oldArticle['slug'] = $newArticle['slug'];
$oldArticle['title'] = $newArticle['title'];
$oldArticle['excerpt'] = $newArticle['excerpt'];
return $newArticle;
}
}
return false;
}
public function removeArticle($id)
{
foreach ($this->data as $index => $article) {
if ($article['articleId'] == $id) {
unset($this->data[$index]);
return true;
}
}
return false;
}
protected function getNewId()
{
$maxId = 0;
foreach ($this->data as $article) {
$maxId = max($maxId, $article['articleId']);
}
return $maxId + 1;
}
}

View File

@ -1,11 +0,0 @@
[{
"articleId": 1,
"slug": "good-movie",
"title": "Reports Of Movie Being Good Reach Area Man",
"excerpt": "Local resident Daniel Paxson has reportedly heard dozens of accounts from numerous friendly sources in the past two weeks confirming that the new James Bond film is pretty good. According to persons with knowledge of the situation, an unnamed friend of Paxsons coworker Wendy Mathers watched the movie on opening weekend and found it to be “decent enough.”"
}, {
"articleId": 2,
"slug": "species-protection",
"title": "Endangered Wildlife To Be Given New Identities In Species Protection Program",
"excerpt": "In an effort to protect at-risk animals from those who might wish to do them harm, the U.S. Fish and Wildlife Service announced Friday it had launched a program that provides endangered species with new names and habitats to ensure their anonymity."
}]

View File

@ -1,104 +0,0 @@
<?php
namespace ApiSample\Handlers;
use \pjdietz\WellRESTed\Handler;
/**
* Handler class for a list of articles.
*/
class ArticleCollectionHandler extends Handler
{
/**
* Respond to a GET request.
*/
protected function get()
{
// Display the list of articles.
$articles = new \apisample\ArticlesController();
if (isset($articles->data)) {
$this->response->statusCode = 200;
$this->response->setHeader('Content-type', 'application/json');
$this->response->body = json_encode($articles->data);
} else {
$this->response->statusCode = 500;
$this->response->setHeader('Content-type', 'text/plain');
$this->response->body = 'Unable to read the articles.';
}
}
/**
* Respond to a POST request.
*/
protected function post()
{
// Read the request body, and ensure it is in the proper format.
$article = json_decode($this->request->body, true);
// Ensure the JSON is well-formed.
if (!$article) {
$this->response->statusCode = 400;
$this->response->setHeader('Content-type', 'text/plain');
$this->response->body = 'Unable to parse JSON from request body.';
return;
}
// Ensure requied fields are present.
if (!isset($article['slug']) || $article['slug'] === '') {
$this->response->statusCode = 400;
$this->response->setHeader('Content-type', 'text/plain');
$this->response->body = 'Request body missing slug.';
return;
}
if (!isset($article['title'])) {
$this->response->statusCode = 400;
$this->response->setHeader('Content-type', 'text/plain');
$this->response->body = 'Request body missing title.';
return;
}
if (!isset($article['excerpt'])) {
$this->response->statusCode = 400;
$this->response->setHeader('Content-type', 'text/plain');
$this->response->body = 'Request body missing excerpt.';
return;
}
// Ensure slug is not a duplicate.
$articles = new \apisample\ArticlesController();
if ($articles->getArticleBySlug($article['slug']) !== false) {
$this->response->statusCode = 409;
$this->response->setHeader('Content-type', 'text/plain');
$this->response->body = 'Unable to store article. Slug "' . $article['slug'] . '" is already in use.';
return;
}
// All looks good! Add this to the articles and save!
$article = $articles->addArticle($article);
if ($articles->save() === false) {
$this->response->statusCode = 500;
$this->response->setHeader('Content-type', 'text/plain');
$this->response->body = 'Unable to write to file. Make sure permissions are set properly.';
return;
}
// Ok!
$this->response->statusCode = 201;
$this->response->setHeader('Content-type', 'application/json');
$this->response->body = json_encode($article);
return;
}
}

View File

@ -1,204 +0,0 @@
<?php
namespace ApiSample\Handlers;
use \pjdietz\WellRESTed\Handler;
/**
* Handler class for one specific article.
*
* When instantiated by the Router, this class should receive an id or slug
* argument to identify the article.
*/
class ArticleItemHandler extends Handler
{
/**
* Respond to a GET request.
*/
protected function get()
{
// Read the list of articles.
$articles = new \apisample\ArticlesController();
$article = false;
// Locate the article by ID or slug
if (isset($articles->data)) {
if (isset($this->args['id'])) {
$article = $articles->getArticleById($this->args['id']);
} elseif (isset($this->args['slug'])) {
$article = $articles->getArticleBySlug($this->args['slug']);
}
}
if ($article !== false) {
$this->response->statusCode = 200;
$this->response->setHeader('Content-type', 'application/json');
$this->response->body = json_encode($article);
} else {
$this->response->statusCode = 404;
$this->response->setHeader('Content-type', 'text/plain');
$this->response->body = 'Unable to locate the article.';
}
}
/**
* Respond to a PUT request.
*/
protected function put()
{
// Read the request body, and ensure it is in the proper format.
$article = json_decode($this->request->body, true);
// Ensure the JSON is well-formed.
if (!$article) {
$this->response->statusCode = 400;
$this->response->setHeader('Content-type', 'text/plain');
$this->response->body = 'Unable to parse JSON from request body.';
return;
}
// Ensure required fields are present.
if (!isset($article['slug']) || $article['slug'] === '') {
$this->response->statusCode = 400;
$this->response->setHeader('Content-type', 'text/plain');
$this->response->body = 'Request body missing slug.';
return;
}
if (!isset($article['title'])) {
$this->response->statusCode = 400;
$this->response->setHeader('Content-type', 'text/plain');
$this->response->body = 'Request body missing title.';
return;
}
if (!isset($article['excerpt'])) {
$this->response->statusCode = 400;
$this->response->setHeader('Content-type', 'text/plain');
$this->response->body = 'Request body missing excerpt.';
return;
}
// Read the list of articles.
$articles = new \apisample\ArticlesController();
$oldArticle = false;
// Locate the article by ID or slug
if (isset($articles->data)) {
if (isset($this->args['id'])) {
$oldArticle = $articles->getArticleById($this->args['id']);
} elseif (isset($this->args['slug'])) {
$oldArticle = $articles->getArticleBySlug($this->args['slug']);
}
}
// Fail if the article identified by the URI does not exist.
if ($oldArticle === false) {
$this->response->statusCode = 404;
$this->response->setHeader('Content-type', 'text/plain');
$this->response->body = 'Unable to locate the article.';
return;
}
// If the user located the resource by ID and has passed a slug,
// make sure the new slug is not already in use.
if (isset($this->args['id'])) {
$slugArticle = $articles->getArticleBySlug($article['slug']);
if ($slugArticle && $slugArticle['articleId'] != $article['articleId']) {
$this->response->statusCode = 409;
$this->response->setHeader('Content-type', 'text/plain');
$this->response->body = 'Unable to store article. Slug "' . $article['slug'] . '" is already in use.';
return;
}
}
// Update the article.
// First, ensure the articleId is set.
// It must match the existing article found earlier.
$article['articleId'] = $oldArticle['articleId'];
// Keep the results from the update for the response.
$article = $articles->updateArticle($article);
if ($articles->save() === false) {
$this->response->statusCode = 500;
$this->response->setHeader('Content-type', 'text/plain');
$this->response->body = 'Unable to write to file. Make sure permissions are set properly.';
return;
}
// Ok!
$this->response->statusCode = 200;
$this->response->setHeader('Content-type', 'application/json');
$this->response->body = json_encode($article);
return;
}
/**
* Respond to a DELETE request.
*/
protected function delete()
{
// Read the list of articles.
$articles = new \apisample\ArticlesController();
$article = false;
// Locate the article by ID or slug
if (isset($articles->data)) {
if (isset($this->args['id'])) {
$article = $articles->getArticleById($this->args['id']);
} elseif (isset($this->args['slug'])) {
$article = $articles->getArticleBySlug($this->args['slug']);
}
}
// Ensure the article exists.
if ($article === false) {
$this->response->statusCode = 404;
$this->response->setHeader('Content-type', 'text/plain');
$this->response->body = 'Unable to locate the article.';
return;
}
// Remove the article and save.
$articles->removeArticle($article['articleId']);
if ($articles->save() === false) {
$this->response->statusCode = 500;
$this->response->setHeader('Content-type', 'text/plain');
$this->response->body = 'Unable to write to file. Make sure permissions are set properly.';
return;
}
// Ok!
$this->response->statusCode = 200;
return;
}
}

View File

@ -1,15 +0,0 @@
<?php
require_once('../../vendor/autoload.php');
// Have to add these manually since this isn't part of the normal package.
// Your project won't have to do this.
require_once('ApiSampleRouter.php');
require_once('ArticlesController.php');
require_once('Handlers/ArticleCollectionHandler.php');
require_once('Handlers/ArticleItemHandler.php');
$router = new \ApiSample\ApiSampleRouter();
$response = $router->getResponse();
$response->respond();
exit;

View File

@ -1,55 +0,0 @@
<?php
/*
* Client-side Request and Response
*
* This script will build a request to an external server, issue the request,
* then read the reponse returned by the server.
*
* Please modify samples/client-side-endpoint.php to see results.
*/
// Include the autoload script.
require_once('../vendor/autoload.php');
use \pjdietz\WellRESTed\Request;
use \pjdietz\WellRESTed\Response;
use \pjdietz\WellRESTed\Exceptions\CurlException;
// Make a custom request to talk to the server.
$rqst = new Request();
// Use the client-site-endpoint.php script
$rqst->hostname = $_SERVER['HTTP_HOST'];
$rqst->path = '/wellrested/samples/server-side-response.php';
// Issue the request, and read the response returned by the server.
try {
$resp = $rqst->request();
} catch (CurlException $e) {
// Explain the cURL error and provide an error status code.
$myResponse = new Response();
$myResponse->statusCode = 500;
$myResponse->setHeader('Content-Type', 'text/plain');
$myResponse->body = 'Message: ' .$e->getMessage() ."\n";
$myResponse->body .= 'Code: ' . $e->getCode() . "\n";
$myResponse->respond();
exit;
}
// Create new response to send to output to the browser.
$myResponse = new Response();
$myResponse->statusCode = 200;
$myResponse->setHeader('Content-Type', 'application/json');
$json = array(
'Status Code' => $resp->statusCode,
'Body' => $resp->body,
'Headers' => $resp->headers
);
$myResponse->body = json_encode($json);
$myResponse->respond();
exit;

View File

@ -1,27 +0,0 @@
<?php
/*
* This script will make a request to google and output the response.
*/
// Include the autoload script.
require_once('../vendor/autoload.php');
use \pjdietz\WellRESTed\Request;
// Make a requst to Google in one line:
$rqst = new Request();
$rqst->uri = 'https://www.google.com/search?q=my+search+terms';
// You could also set the members individually, like this:
//$rqst->protocol = 'https';
//$rqst->hostname = 'www.google.com';
//$rqst->path = '/search';
//$rqst->query = array('q' => 'my search terms');
// Make the request and obtain an Response instance.
$resp = $rqst->request();
// Output the response body and exit.
print $resp->body;
exit;

View File

@ -1,46 +0,0 @@
<?php
/*
* Server-side Request and Response
*
* This script will read some data from the request sent to server and respond
* with JSON descrition of the original request.
*/
// Include the autoload script.
require_once('../vendor/autoload.php');
use \pjdietz\WellRESTed\Request;
use \pjdietz\WellRESTed\Response;
// Read the request sent to the server as the singleton instance.
$rqst = Request::getRequest();
// Alternatively, you can create a new Request and call readHttpRequest().
// $rqst = new Request();
// $rqst->readHttpRequest();
// Read some info from the request and store it to an associative array.
$rtn = array(
'Path' => $rqst->path,
'URI' => $rqst->uri,
'Body' => $rqst->body,
'Method' => $rqst->method,
'Headers' => $rqst->headers
);
// Create a new Response instance.
$resp = new Response();
// Set the status code to 200 OK.
$resp->statusCode = 200;
// Set the content type for JSON.
$resp->setHeader('Content-Type', 'application/json');
// Add the associative array, encoded as JSON, as the body.
// (Note, setting the body automatically adds a Content-Length header.)
$resp->body = json_encode($rtn);
// Output the response.
$resp->respond();

View File

@ -1,18 +0,0 @@
<?php
/**
* Create and output a response from the server.
*/
// Include the autoload script.
require_once('../vendor/autoload.php');
use \pjdietz\WellRESTed\Response;
// Create a new Response instance.
$resp = new Response();
$resp->statusCode = 200;
$resp->setHeader('Content-Type', 'text/plain');
$resp->body = 'This is a response.';
$resp->respond();
exit;

View File

@ -307,7 +307,7 @@ class Request extends Message
$error = curl_error($ch);
$errno = curl_errno($ch);
curl_close($ch);
throw new exceptions\CurlException($error, $errno);
throw new Exceptions\CurlException($error, $errno);
}
// Make a reponse to populate and return with data obtained via cURL.