Author: Fabien Potencier (fabien.potencier@symfony-project.com)
示例#1
0
 protected function respondWithArray(array $array, array $headers = [])
 {
     $mimeTypeRaw = Input::server('HTTP_ACCEPT', '*/*');
     // If its empty or has */* then default to JSON
     if ($mimeTypeRaw === '*/*') {
         $mimeType = 'application/json';
     } else {
         // You'll probably want to do something intelligent with charset if provided
         // This chapter just assumes UTF8 everything everywhere
         $mimeParts = (array) explode(',', $mimeTypeRaw);
         $mimeType = strtolower($mimeParts[0]);
     }
     switch ($mimeType) {
         case 'application/json':
             $contentType = 'application/json';
             $content = json_encode($array);
             break;
         case 'application/x-yaml':
             $contentType = 'application/x-yaml';
             $dumper = new YamlDumper();
             $content = $dumper->dump($array, 2);
             break;
         default:
             $contentType = 'application/json';
             $content = json_encode(['error' => ['code' => static::CODE_INVALID_MIME_TYPE, 'http_code' => 415, 'message' => sprintf('Content of type %s is not supported.', $mimeType)]]);
     }
     $response = Response::make($content, $this->statusCode, $headers);
     $response->header('Content-Type', $contentType);
     return $response;
 }
示例#2
0
 /**
  * Dump YAML from PHP array statically
  *
  * The dump method, when supplied with an array, will do its best
  * to convert the array into friendly YAML.
  *
  * @param array $array PHP array
  *
  * @return string
  */
 public static function dump($array, $inline = 2)
 {
     require_once dirname(__FILE__) . '/Yaml/YamlDumper.php';
     $yaml = new YamlDumper();
     return $yaml->dump($array, $inline);
 }