Example #1
0
 /**
  * Detect if we should use the JsonRenderer based on model type and/or
  * Accept header
  *
  * @param  ViewEvent $e
  * @return null|JsonRenderer
  */
 public function selectRenderer(ViewEvent $e)
 {
     $model = $e->getModel();
     if ($model instanceof Model\JsonModel) {
         // JsonModel found
         return $this->renderer;
     }
     $request = $e->getRequest();
     if (!$request instanceof HttpRequest) {
         // Not an HTTP request; cannot autodetermine
         return;
     }
     $headers = $request->getHeaders();
     if ($headers->has('accept')) {
         $accept = $headers->get('Accept');
         foreach ($accept->getPrioritized() as $mediaType) {
             if (0 === strpos($mediaType, 'application/json')) {
                 // application/json Accept header found
                 return $this->renderer;
             }
             if (0 === strpos($mediaType, 'application/javascript')) {
                 // application/javascript Accept header found
                 if (false != ($callback = $request->getQuery()->get('callback'))) {
                     $this->renderer->setJsonpCallback($callback);
                 }
                 return $this->renderer;
             }
         }
     }
     // Not matched!
     return;
 }
Example #2
0
 /**
  * Detect if we should use the JsonRenderer based on model type and/or
  * Accept header
  *
  * @param  ViewEvent $e
  * @return null|JsonRenderer
  */
 public function selectRenderer(ViewEvent $e)
 {
     $model = $e->getModel();
     if ($model instanceof Model\JsonModel) {
         // JsonModel found
         return $this->renderer;
     }
     $request = $e->getRequest();
     if (!$request instanceof HttpRequest) {
         // Not an HTTP request; cannot autodetermine
         return;
     }
     $headers = $request->getHeaders();
     if (!$headers->has('accept')) {
         return;
     }
     $accept = $headers->get('Accept');
     if (($match = $accept->match('application/json, application/javascript')) == false) {
         return;
     }
     if ($match->getTypeString() == 'application/json') {
         // application/json Accept header found
         return $this->renderer;
     }
     if ($match->getTypeString() == 'application/javascript') {
         // application/javascript Accept header found
         if (false != ($callback = $request->getQuery()->get('callback'))) {
             $this->renderer->setJsonpCallback($callback);
         }
         return $this->renderer;
     }
 }
Example #3
0
 public function testRendersNonTraversableNonJsonSerializableObjectsAsJsonObjectsWithJsonpCallback()
 {
     $model = new stdClass();
     $model->foo = 'bar';
     $model->bar = 'baz';
     $expected = 'callback(' . json_encode(get_object_vars($model)) . ');';
     $this->renderer->setJsonpCallback('callback');
     $test = $this->renderer->render($model);
     $this->assertEquals($expected, $test);
 }