示例#1
0
 /**
  * 
  * @param \League\Fractal\Resource\ResourceInterface $fractal
  */
 protected function writeJson($resource, $status = 200)
 {
     $fractal = new \League\Fractal\Manager();
     $this->app->response->setStatus($status);
     $this->app->response->headers->set('Content-Type', 'application/json');
     $this->app->contentType('application/json;  charset=utf-8');
     $fractalArray = $fractal->createData($resource)->toArray();
     $this->app->response->setBody(json_encode($fractalArray, JSON_UNESCAPED_SLASHES));
 }
示例#2
0
 /**
  * @param IXmlExporter $exporter
  * @param int $status
  * @param string $contentType
  */
 protected function xmlOutput(IXmlExporter $exporter, $status = 200, $contentType = 'application/xml')
 {
     $this->app->expires(0);
     $this->app->contentType($contentType);
     $response = $this->app->response();
     $response->setStatus($status);
     $response->header('Content-Description', 'File Transfer');
     if ($exporter->isFile()) {
         $response->header('Content-Disposition', 'attachment; filename=' . $exporter->getFileName());
     }
     $response->body($exporter->buildXml());
 }
示例#3
0
 /**
  * Constructor
  * 
  * @param \Slim\Slim $app Slim app reference
  */
 public function __construct(\Slim\Slim $app)
 {
     $this->app = $app;
     $this->app->notFound(function () use($app) {
         $data = array('error' => array('message' => 'Invalid route'));
         $app->contentType('application/json');
         $app->halt(400, json_encode($data));
     });
 }
示例#4
0
 public function error(Exception $e)
 {
     if ($e instanceof \BSA2015\Basket\Exception\Exception) {
         $this->_slim->response()->status($e->getCode());
     } else {
         $this->_slim->response()->status(500);
     }
     $this->_slim->contentType('text/html');
     $this->_slim->response()->body($e->getMessage());
 }
示例#5
0
 /**
  * Output a generic error page
  *
  * @param string $status          The HTTP status code (eg 401, 404, 500)
  * @param string $title           Optional brief title of the page, used in HTML head etc
  * @param string $summary         Optional summary message describing the error
  * @param string $extendedTitle   Optional extended title, used at top of main content
  * @param string $extendedDetails Optional extended details, conveying more details
  *
  * @throws \InvalidArgumentException if the status is not a valid HTTP status code
  */
 protected function outputError($status, $title = null, $summary = '', $extendedTitle = '', $extendedDetails = '')
 {
     if (!is_integer($status)) {
         throw new \InvalidArgumentException('The $status parameter must be a valid integer HTTP status code');
     }
     $this->app->response->setStatus($status);
     // slim does not set the response code in this function
     // setting it manually
     if (!headers_sent()) {
         http_response_code($status);
         // PHP 5.4+
     }
     if (is_null($title)) {
         $title = 'Error ' . $status;
     }
     if ($extendedTitle === '') {
         $defaultMsg = \Slim\Http\Response::getMessageForCode($status);
         if ($defaultMsg !== null) {
             $extendedTitle = substr($defaultMsg, 4);
         } else {
             $extendedTitle = $title;
         }
     }
     // Content negotiation for the error message
     // callbackCheckFormats() middleware does the content negotiation.
     // But it was not executed, yet. Call it now to get the mime type.
     $route = $this->app->router()->getCurrentRoute();
     if ($route) {
         $this->mimeBest = $this->callbackCheckFormats($route);
     }
     // if (!$this->store) {
     // $this->store = $route->getParam('store');
     // }
     // display name of store in titlebar
     if (isset($this->storeOptions[$this->store]['shortName'])) {
         $u = $this->app->request()->getRootUri() . '/datasets/' . $this->store;
         $this->app->view()->set('titleSupplementary', '<a href="' . htmlspecialchars($u, ENT_QUOTES) . '" class="navbar-brand supplementary">' . htmlspecialchars($this->storeOptions[$this->store]['shortName']) . '</a>');
     }
     switch ($this->mimeBest) {
         case 'text/plain':
             $error = "status  => {$status}" . PHP_EOL;
             $error .= "title   => {$extendedTitle}" . PHP_EOL;
             if ($summary) {
                 $error .= "summary => {$summary}" . PHP_EOL;
             }
             if ($extendedDetails) {
                 $error .= "details => " . preg_replace('~[\\n]+|[\\s]{2,}~', ' ', $extendedDetails);
             }
             // setBody does not work in this function
             $this->app->response->setBody($error);
             // render a blank template instead
             // $this->app->render('blank.twig', [ 'content' => $error ] );
             break;
         case 'text/csv':
         case 'text/tab-separated-values':
             if ($this->mimeBest === 'text/csv') {
                 $delimiter = ',';
             } else {
                 $delimiter = "\t";
             }
             $error = [array("status", $status), array("title", $extendedTitle)];
             if ($summary) {
                 $error[] = array("summary", $summary);
             }
             if ($extendedDetails) {
                 $error[] = array("details", preg_replace('~[\\n]+|[\\s]{2,}~', ' ', $extendedDetails));
             }
             ob_start();
             $out = fopen('php://output', 'w');
             foreach ($error as $err) {
                 fputcsv($out, $err, $delimiter);
             }
             fclose($out);
             $out = ob_get_contents();
             ob_end_clean();
             // setBody does not work in this function
             $this->app->response->setBody($out);
             // render a blank template instead
             // $this->app->render('blank.twig', [ 'content' => $out ] );
             break;
         case 'application/rdf+xml':
         case 'application/x-turtle':
         case 'text/turtle':
         case 'application/json':
             $json_error = array('status' => $status, 'title' => $extendedTitle);
             if ($summary) {
                 $json_error['summary'] = $summary;
             }
             if ($extendedDetails) {
                 $json_error['details'] = $extendedDetails;
             }
             // setBody does not work in this function
             $this->app->response->setBody(json_encode($json_error, JSON_PRETTY_PRINT));
             // PHP 5.4+
             // render a blank template instead
             // $this->app->render('blank.twig', [ 'content' => json_encode($json_error, JSON_PRETTY_PRINT) ] );
             break;
         case 'text/html':
         case 'application/xhtml+xml':
         default:
             $summary .= '</p>' . PHP_EOL . PHP_EOL . '<p>Please try returning to <a href="' . $this->app->request()->getURL() . $this->app->request()->getRootUri() . '">the homepage</a>.';
             // overwrite the previous content type definition
             $this->app->contentType($this->mimeBest);
             $this->app->render('error/error-html.twig', ['titleHTML' => ' - ' . strip_tags($title), 'titleHeader' => 'Error ' . $status, 'title' => $extendedTitle, 'summary' => $summary, 'details' => $extendedDetails]);
             break;
     }
     // execution stops here
     $this->app->stop();
 }
if ($appMode !== 'dev') {
    //$logHandlers[]= new \Monolog\Handler\LogglyHandler('loggly api key');
}
$logger = new \Flynsarmy\SlimMonolog\Log\MonologWriter(array('handlers' => $logHandlers, 'processors' => array(new \Monolog\Processor\WebProcessor($_SERVER))));
$app = new Slim(array('mode' => $appMode, 'log.writer' => $logger, 'templates.path' => './views'));
// Only invoked if mode is "prod"
$app->configureMode('prod', function () use($app) {
    $app->config(array('log.enable' => true, 'debug' => false));
});
// Only invoked if mode is "dev"
$app->configureMode('dev', function () use($app) {
    $app->config(array('log.enable' => true, 'debug' => true));
});
$config = Config::getInstance();
$config->setMode($appMode === 'dev' ? Config::DEVELOPMENT : Config::STAGING);
$app->contentType('application/json');
//$app->add(new OAuthVerifyMiddleware());
include 'routes/user.php';
/// ------------------------- ///
/// --- Utility Functions --- ///
/// ------------------------- ///
/**
 * Returns a formatted response to the requesting client.
 * @method sendResponse
 * @param  mixed       $results   The results could be either an array or stdClass.  Should be the data being returned to the client.
 * @param  integer       $startTime Time the app started processing the response.  Used for debugging time on the server during development.
 */
function sendResponse($results, $startTime = null)
{
    $app = Slim::getInstance();
    $details = new stdClass();
示例#7
0
 protected function setContentType($type)
 {
     $this->app->contentType($type);
 }
示例#8
0
 /**
  * Serialize the data based on the provided "Accept" header if it exists,
  * otherwise revert to the predefined default content-type
  *
  * @param \Slim\Slim $app
  * @param            $data
  *
  * @return array|mixed
  */
 public static function getSerializedData(Slim $app, $data)
 {
     self::$contentTypes = $app->config("serializers");
     $env = $app->environment();
     $acceptableContentTypes = explode(";", $env["ACCEPT"]);
     $contentType = "";
     if (count($acceptableContentTypes) > 1 || empty($acceptableContentTypes)) {
         $contentType = $app->config("content-type");
     } else {
         $contentType = $acceptableContentTypes[0];
     }
     // don't allow */* as the content-type, rather favour the default content-type
     if ($contentType == "*/*") {
         $contentType = $app->config("content-type");
     }
     $app->contentType($contentType);
     $data = self::serialize($app, $data, $contentType);
     return $data;
 }
示例#9
0
<?php

require '../vendor/autoload.php';
use Negotiation\Negotiator;
use Faker\Factory;
use Slim\Slim;
use Slim\Views\Twig;
$app = new Slim();
$app->config('templates.path', '../views');
$app->view(new Twig());
$app->faker = Factory::create();
$contentNegotiation = function () use($app) {
    $negotiator = new Negotiator();
    $format = $negotiator->getBest($app->request()->headers('Accept'));
    $type = $format->getValue();
    $app->contentType($type);
    $app->template = 'contacts/show.json.twig';
    if ('application/xml' === $type) {
        $app->template = 'contacts/show.xml.twig';
    }
};
$app->post('/contacts', $contentNegotiation, function () use($app) {
    $contactInformation = $app->request()->getBody();
    parse_str($contactInformation, $contact);
    $contact['contact_id'] = $app->faker->randomDigit;
    //Simulate an insert
    $app->status(201);
    echo $app->render($app->template, ['contact' => $contact]);
});
$app->get('/contacts/:id', $contentNegotiation, function ($id) use($app) {
    //This value should be specific to the current resource