/** * Create a new HTTP text response. * * @param string $contents Text to be transfered as response body. * @param string $type media type of the text payload. * @param string $charset Charset to be used (default to UTF-8).. */ public function __construct(string $contents, string $type = 'text/plain', string $charset = null) { $type = new ContentType($type); if ($type->getMediaType()->isText()) { $type->setParam('charset', $charset ?? 'utf-8'); } parent::__construct(Http::OK, ['Content-Type' => (string) $type]); $this->body = new StringBody($contents); }
/** * Create HTTP file response. * * @param string $file Absolute path of the file to be transfered. * @param string $type Media type of the file (will be guessed from extension if not provided). * @param string $charset Charset to be supplied when media type is text format. */ public function __construct(string $file, string $type = null, string $charset = null) { $type = new ContentType($type ?? Filesystem::guessMimeTypeFromFilename($file)); if ($type->getMediaType()->isText()) { $type->setParam('charset', $charset ?? 'utf-8'); } parent::__construct(Http::OK, ['Content-Type' => (string) $type]); $this->body = new FileBody($file); $this->file = $file; }
public function getAccept() : Accept { return new Accept(...ContentType::parseList($this->getHeaderLine('Accept'))); }
/** * Stable sort implementation that order by relative quality and media type score. * * @param array $types * @return array */ protected function sortByQuality(array $types) : array { $result = []; foreach ($types as $type) { if (!$type instanceof ContentType) { $type = new ContentType($type->getValue(), $type->getParams()); } $priority = \max(0, \min(1, (double) $type->getParam('q', 1))); for ($size = \count($result), $i = 0; $i < $size; $i++) { $insert = $priority > $result[$i][1]; if (!$insert && $priority == $result[$i][1] && $type->getScore() > $result[$i][0]->getScore()) { $insert = true; } if ($insert) { \array_splice($result, $i, 0, [[$type, $priority]]); continue 2; } } $result[] = [$type, $priority]; } return \array_column($result, 0); }
public function getContentType(string $default = 'application/octet-stream') : ContentType { return ContentType::parse($this->hasHeader('Content-Type') ? $this->getHeaderLine('Content-Type') : $default); }