コード例 #1
0
ファイル: Theme.php プロジェクト: karwana/penelope
 public function render($template, $data = null)
 {
     $format = 'html';
     if (!empty($_SERVER['HTTP_ACCEPT'])) {
         $negotiator = new FormatNegotiator();
         $format = $negotiator->getBestFormat($_SERVER['HTTP_ACCEPT'], array('html', 'json'));
     }
     if ('json' === $format) {
         return json_encode($this->data->all());
     }
     $helpers_file = $this->getTemplatePath('helpers.php');
     if (is_file($helpers_file)) {
         $app = $this->app;
         require_once $helpers_file;
     }
     $resources = $this->resources;
     foreach ($resources as $resource_type => $resource_paths) {
         foreach ($resource_paths as $i => $resource_path) {
             // Ignore absolute URLs.
             if (preg_match('/^[a-z]*:?\\/\\//', $resource_path)) {
                 continue;
             }
             $resources[$resource_type][$i] = $this->getResourceUrl($resource_path);
         }
     }
     $header = parent::render('header.php', array('resources' => $resources));
     $footer = parent::render('footer.php');
     return $header . parent::render($template . '.php') . $footer;
 }
コード例 #2
0
 public static function findByAccept($accept)
 {
     $negotiator = new FormatNegotiator();
     $best = $negotiator->getBest($accept, static::allAcceptTypes());
     foreach (static::all() as $name => $mediaType) {
         if (in_array($best->getValue(), $mediaType->accept())) {
             return $mediaType;
         }
     }
     return false;
 }
コード例 #3
0
ファイル: Handler.php プロジェクト: stanlemon/rest-bundle
 /**
  * @param Request $request
  * @param Response $response
  * @param string $resource
  * @param \Closure $callback
  * @return Response
  */
 public function handle(Request $request, Response $response, $resource, $callback)
 {
     $accept = $this->negotiator->getBest($request->headers->get('Accept'));
     $format = $this->negotiator->getFormat($accept->getValue());
     if ($format == 'html') {
         $format = 'json';
     }
     $response->headers->set('Content-Type', $accept->getValue());
     try {
         $manager = $this->managerFactory->create($resource);
         $context = new DeserializationContext();
         $context->enableMaxDepthChecks();
         $object = null;
         $content = $request->getContent();
         if (!empty($content)) {
             $object = $this->serializer->create($request->isMethod('patch') ? 'doctrine' : 'default')->deserialize($request->getContent(), $manager->getClass(), $format, $context);
         }
         $data = $this->envelopeFactory->create($callback($manager, $object))->export();
     } catch (InvalidException $e) {
         $response->setStatusCode(400);
         $data = array("code" => 400, "message" => $e->getMessage(), "errors" => $e->getErrors());
     } catch (NotFoundException $e) {
         $response->setStatusCode(404);
         $data = array("code" => 404, "message" => $e->getMessage());
     } catch (UnsupportedMethodException $e) {
         $response->setStatusCode(405);
         $data = array("code" => 405, "message" => $e->getMessage());
     } catch (HttpException $e) {
         $response->setStatusCode($e->getStatusCode());
         $data = array("code" => $e->getStatusCode(), "message" => $e->getMessage());
     } catch (\Exception $e) {
         $this->logger->critical($e);
         $response->setStatusCode(500);
         $data = array("code" => 500, "message" => $e->getMessage());
     }
     $groups = array('Default', 'lemon_rest', 'lemon_rest_' . $resource, 'lemon_rest_' . $resource . '_' . strtolower($request->getMethod()));
     if (is_object($data)) {
         $groups[] = 'lemon_rest_' . $resource . '_view';
     } else {
         $groups[] = 'lemon_rest_' . $resource . '_list';
     }
     $context = SerializationContext::create()->enableMaxDepthChecks();
     $context->setGroups($groups);
     if ($accept->hasParameter('version')) {
         $context->setVersion($accept->getParameter('version'));
     }
     $output = $this->serializer->create('default')->serialize($data, $format, $context);
     $response->setContent($output);
     return $response;
 }
コード例 #4
0
 /**
  * cf.  https://github.com/willdurand/Negotiation/issues/30,
  *      https://github.com/FriendsOfSymfony/FOSRestBundle/issues/610
  *
  * @dataProvider dataProviderForTakesParametersIntoAccount
  */
 public function testTakesParametersIntoAccount($acceptHeaderString, $expectedFormat)
 {
     $this->negotiator->registerFormat('xml', array('application/vnd.my.app+xml'), true);
     $this->negotiator->registerFormat('json', array('application/vnd.my.app+json'), true);
     $this->negotiator->registerFormat('odata-v4', array('application/json;odata.metadata=full', 'application/json;odata.metadata=none', 'application/json;odata.metadata=minimal'), true);
     $this->negotiator->registerFormat('odata-v4-minimal-streaming', array('application/json;odata.metadata=minimal;odata.streaming=true'), true);
     $this->negotiator->registerFormat('odata-v3-verbose', array('application/json;odata=verbose'), true);
     $this->negotiator->registerFormat('atom-entry', array('application/atom+xml;type=entry'), true);
     $this->assertEquals('json', $this->negotiator->getBestFormat('application/vnd.my.app', array('json', 'xml')));
     $this->assertEquals('json', $this->negotiator->getBestFormat('application/vnd.my.app+json', array('json', 'xml')));
     $this->assertEquals('xml', $this->negotiator->getBestFormat('application/vnd.my.app+xml', array('json', 'xml')));
     $this->assertNotNull($this->negotiator->getBest($acceptHeaderString, array('*/*')));
     $this->assertEquals($expectedFormat, $this->negotiator->getBestFormat($acceptHeaderString, array('*/*')));
 }
コード例 #5
0
 /**
  * Converts the passed data into a Response based on Request parameters.
  *
  * If HTTP_ACCEPT header expects `application/json` then it will wrap the `$result` in `JsonResponse`.
  *
  * Otherwise it will try to render a Twig template with the `$result` data passed to it. The template to render
  * is determined either by Request's `_template` attribute and if none found, then built based on controller name.
  *
  * @param Request $request Request for which to render a response.
  * @param Result  $result  Controller result.
  *
  * @return Response
  *
  * @throws \RuntimeException When could not determine template name.
  */
 public function convertControllerResult(Request $request, Result $result)
 {
     $formatNegotiator = new FormatNegotiator();
     $bestFormat = $formatNegotiator->getBest($request->server->get('HTTP_ACCEPT'), ['application/json', 'text/html']);
     $responseData = $result->getData();
     if ($bestFormat && $bestFormat->getValue() === 'application/json') {
         return new JsonResponse($responseData, $result->getHttpCode());
     }
     // maybe there is a template set explicitly?
     $template = $request->attributes->get('_template');
     // if no template set explicitly then build one based on controller name
     if (!$template) {
         $template = $request->attributes->get('_controller');
         $template = preg_replace('/(\\.|_)?controller(\\.|_)?/i', '', $template);
         $template = str_replace(['.', ':'], '/', $template) . '.html.twig';
     }
     // if still didn't build it then throw exception
     if (!$template || $template === '.html.twig') {
         throw new \RuntimeException('Could not determine what template to render. ' . 'Have you set "_template" or "_controller" attribute in your route definition?');
     }
     $content = $this->templating->render($template, $responseData);
     return new Response($content, $result->getHttpCode());
 }
コード例 #6
0
 /**
  * Uploads User Image
  */
 public function uploadAction()
 {
     $authenticationService = $this->getServiceLocator()->get('zfcuser_auth_service');
     if (!$authenticationService->hasIdentity()) {
         return $this->redirect()->toRoute('zfcuser');
     }
     $user = $this->getUser();
     if (!$user) {
         return $this->notFoundAction();
     }
     $options = $this->getOptions();
     $form = $this->getServiceLocator()->get('HtProfileImage\\ProfileImageForm');
     /** @var \Zend\Http\Request $request */
     $request = $this->getRequest();
     $imageUploaded = false;
     if ($request->isPost()) {
         $negotiator = new FormatNegotiator();
         $format = $negotiator->getBest($request->getHeader('Accept')->getFieldValue(), ['application/json', 'text/html']);
         if ($this->profileImageService->storeImage($user, $request->getFiles()->toArray())) {
             if ($format->getValue() === 'application/json') {
                 return new Model\JsonModel(['uploaded' => true]);
             } elseif ($options->getPostUploadRoute()) {
                 return call_user_func_array([$this->redirect(), 'toRoute'], (array) $options->getPostUploadRoute());
             }
             $imageUploaded = true;
         } else {
             $response = $this->getResponse();
             /** @var \Zend\Http\Response $response */
             $response->setStatusCode(400);
             if ($format->getValue() === 'application/json') {
                 return new Model\JsonModel(['error' => true, 'messages' => $form->getMessages()]);
             }
         }
     }
     return new Model\ViewModel(['form' => $form, 'imageUploaded' => $imageUploaded, 'user' => $user]);
 }
コード例 #7
0
 /**
  * @dataProvider dataProviderForNormalizePriorities
  */
 public function testNormalizePriorities($priorities, $expected)
 {
     $priorities = $this->negotiator->normalizePriorities($priorities);
     $this->assertEquals($expected, $priorities);
 }
コード例 #8
0
ファイル: Request.php プロジェクト: railsphp/framework
 /**
  * Looks for the best format that fits the request.
  * If format is not specified in the request parameters, FormatNegotiator
  * is used to determine the best format.
  * If everything fails, html is assumed.
  *
  * @return string
  */
 public function format()
 {
     if ($this->format === null) {
         if (null !== ($format = $this->parameters->getParam('format'))) {
             $this->format = $format;
         } else {
             $headers = getallheaders();
             if (isset($headers['Accept'])) {
                 $acceptHeader = $headers['Accept'];
                 $negotiator = new FormatNegotiator();
                 $priorities = ['html', 'json', 'xml', 'js', '*.*'];
                 $this->format = $negotiator->getBestFormat($acceptHeader, $priorities) ?: 'html';
             } else {
                 $this->format = 'html';
             }
         }
     }
     return $this->format;
 }
コード例 #9
0
 /**
  * Format using requested formatter (via extension, Accept-header or default)
  *
  * @param Tdt\Core\Datasets\Data $data      The data object on which the response will be based
  * @param string                 $extension The preferred format in which the data should be returned
  *
  * @return \Response
  */
 public static function getResponse($data, $extension = null)
 {
     // Check Accept-header
     $accept_header = \Request::header('Accept');
     // Safety first
     $extension = strtoupper($extension);
     // Formatter class
     $formatter_class = 'Tdt\\Core\\Formatters\\' . $extension . 'Formatter';
     if (empty($extension)) {
         $negotiator = new FormatNegotiator();
         foreach (self::$mime_types_map as $format_name => $mime_types) {
             $negotiator->registerFormat($format_name, $mime_types, true);
         }
         // Create a priority list of formats
         $priorities = array();
         $format_helper = new FormatHelper();
         if (empty($data->preferred_formats)) {
             // Still nothing? Use default formatter
             if (empty($extension) && !$data->is_semantic) {
                 // Default formatter for non semantic data
                 $data->preferred_formats = array('json');
             } elseif (empty($extension) && $data->is_semantic) {
                 // Default formatter for semantic data is turtle
                 $data->preferred_formats = array('ttl');
             }
         }
         if (!in_array('html', $priorities)) {
             array_push($priorities, 'html');
         }
         $priorities = array_merge($data->preferred_formats, $priorities);
         // Add support for our other formatters as well, if they're not already in the priorities
         foreach ($format_helper->getAvailableFormats($data) as $format) {
             if (!in_array($format, $priorities)) {
                 array_push($priorities, $format);
             }
         }
         array_push($priorities, '*/*');
         $format = $negotiator->getBestFormat($accept_header, $priorities);
         $format_object = $negotiator->getBest($accept_header, $priorities);
         if (!$format || $format_object->getQuality() == 0) {
             $format_helper = new FormatHelper();
             $available_formats = implode(', ', array_values($format_helper->getAvailableFormats($data)));
             \App::abort(406, "The requested Content-Type is not supported, or the best quality we found was 0. The supported formats for this resource are: " . $available_formats);
         }
         // Safety first
         $extension = strtoupper($format);
         // Formatter class
         $formatter_class = 'Tdt\\Core\\Formatters\\' . $extension . 'Formatter';
     } elseif (!class_exists($formatter_class)) {
         $format_helper = new FormatHelper();
         $available_formats = implode(', ', array_values($format_helper->getAvailableFormats($data)));
         \App::abort(406, "The requested Content-Type is not supported, or the best quality we found was 0. The supported formats for this resource are: " . $available_formats);
     }
     // Create the response from the designated formatter
     $response = $formatter_class::createResponse($data);
     // Set the paging header
     if (!empty($data->paging)) {
         $response->header('Link', self::getLinkHeader($data->paging));
     }
     // Set the URI template header
     if (!empty($data->optional_parameters) || !empty($data->rest_parameters)) {
         // http://www.mnot.net/blog/2006/10/04/uri_templating
         $link_template = self::fetchUrl($extension);
         if (substr($link_template, -1, 1) == '/') {
             $link_template = substr($link_template, 0, -1);
         }
         // Add the required parameters
         foreach ($data->rest_parameters as $required_parameter) {
             $link_template .= '/{' . $required_parameter . '}';
         }
         // Add the extension if given
         if (!empty($extension)) {
             $link_template .= '.' . strtolower($extension);
         }
         // Add the optional parameters
         if (!empty($data->optional_parameters)) {
             $link_template .= '{?';
             foreach ($data->optional_parameters as $optional_parameter) {
                 $link_template .= $optional_parameter . ', ';
             }
             $link_template = rtrim($link_template, ', ');
             $link_template .= '}';
         }
         $response->header('Link-Template', $link_template);
     }
     // Cache settings
     $cache_minutes = -1;
     if (\Config::get('cache.enabled', true)) {
         $cache_minutes = 1;
         // Cache per resource
         if (!empty($data->source_definition['cache'])) {
             $cache_minutes = $data->source_definition['cache'];
         }
     }
     // Cache headers
     $response->header('Cache-Control', 'public, max-age=' . $cache_minutes * 60 . ', pre-check=' . $cache_minutes * 60 . '');
     $response->header('Pragma', 'public');
     $response->header('Expires', date(DATE_RFC822, strtotime("{$cache_minutes} minute")));
     $response->header('Vary', 'Accept, Accept-encoding');
     // Return formatted response
     return $response;
 }
コード例 #10
0
ファイル: index.php プロジェクト: potherca/parrots
use Potherca\Parrots\Transformers\TextTransformer;
use Potherca\Parrots\Transformers\TransformerInterface;
use Potherca\Parrots\Utilities\ColorConverter;
use Potherca\Parrots\Utilities\TextSplitter;
require '../vendor/autoload.php';
/* Get Config from file */
if (isset($_SERVER['HTTP_HOST'])) {
    $sDomain = $_SERVER['HTTP_HOST'];
} else {
    $sDomain = 'localhost';
}
$sConfigFile = getConfigFileForDomain($sDomain);
$aData = getDataFromConfigFile($sConfigFile);
/* Get Type from HEADER */
if (isset($_SERVER['HTTP_ACCEPT'])) {
    $oNegotiator = new FormatNegotiator();
    $aData[Parrots::PROPERTY_TYPE] = $oNegotiator->getBest($_SERVER['HTTP_ACCEPT'])->getValue();
}
if (isset($_POST['text'], $_POST['trigger_word'])) {
    // Slackbot 1.0 (+https://api.slack.com/robots)
    //text=googlebot: What is the air-speed velocity of an unladen swallow?
    //trigger_word=googlebot:
    $aData[Parrots::PROPERTY_TYPE] = 'application/slack';
    $aData[Parrots::PROPERTY_SUBJECT] = trim(substr($_POST['text'], strlen($_POST['trigger_word'])));
}
/* Get Subject from URL */
if (empty($aData[Parrots::PROPERTY_SUBJECT])) {
    if (isset($_SERVER['PATH_INFO'])) {
        /* Strip leading slash */
        $aData[Parrots::PROPERTY_SUBJECT] = substr($_SERVER['PATH_INFO'], 1);
    }
コード例 #11
0
ファイル: HtmlWrapper.php プロジェクト: byjg/xmlnuke
 /**
  *
  * @return XmlnukeEngine
  */
 public function createXmlnukeEngine()
 {
     $context = Context::getInstance();
     $selectNodes = $context->get("xpath");
     $alternateFilename = str_replace(".", "_", $context->get("fn") != "" ? $context->get("fn") : ($context->getModule() != "" ? $context->getModule() : $context->getXml()));
     $extraParam = array();
     $output = $context->getOutputFormat();
     if ($output == OutputData::Xml) {
         header("Content-Type: text/xml; charset=utf-8");
         header("Content-Disposition: inline; filename=\"{$alternateFilename}.xml\";");
     } elseif ($output == OutputData::Json) {
         $extraParam["json_function"] = $context->get("jsonfn");
         header("Content-Type: application/json; charset=utf-8");
         header("Content-Disposition: inline; filename=\"{$alternateFilename}.json\";");
     } else {
         $contentType = array("xsl" => "", "content-type" => "", "content-disposition" => "", "extension" => "");
         // Check if is Mobile
         if ($this->detectMobile()) {
             $context->setXsl("mobile");
         }
         $contentType = $context->getSuggestedContentType();
         // Get the best content-type for it
         if (!is_array($contentType["content-type"])) {
             $bestContentType = $contentType["content-type"];
         } else {
             $negContentType = new FormatNegotiator();
             $bestContent = $negContentType->getBest($_SERVER['HTTP_ACCEPT'], $contentType["content-type"]);
             if (!is_null($bestContent)) {
                 $bestContentType = $bestContent->getValue();
             } else {
                 $bestContentType = "text/html";
             }
         }
         // Write Headers
         header("Content-Type: {$bestContentType}; charset=utf-8");
         if (isset($contentType["content-disposition"])) {
             header("Content-Disposition: {$contentType["content-disposition"]}; filename=\"{$alternateFilename}.{$contentType["extension"]}\";");
         }
     }
     $engine = new XmlnukeEngine($context, $output, $selectNodes, $extraParam);
     return $engine;
 }