diff options
author | minstel <minstel@yandex.ru> | 2017-01-17 22:13:39 +0700 |
---|---|---|
committer | minstel <minstel@yandex.ru> | 2017-01-17 22:13:39 +0700 |
commit | 36cece638bb83b9755eee620d5132893aa969b28 (patch) | |
tree | afa90e7d24ebe2d7eadb87945fd3f07c66afdb15 /src | |
parent | 9701118b9b34e19d5de1fe56755afdd29c0c93a1 (diff) | |
download | controller-36cece638bb83b9755eee620d5132893aa969b28.zip controller-36cece638bb83b9755eee620d5132893aa969b28.tar.gz controller-36cece638bb83b9755eee620d5132893aa969b28.tar.bz2 |
Add content negotiation (fixes #11)
Diffstat (limited to 'src')
-rw-r--r-- | src/Controller/ContentNegotiation.php | 108 |
1 files changed, 108 insertions, 0 deletions
diff --git a/src/Controller/ContentNegotiation.php b/src/Controller/ContentNegotiation.php new file mode 100644 index 0000000..75aa4f1 --- /dev/null +++ b/src/Controller/ContentNegotiation.php @@ -0,0 +1,108 @@ +<?php + +namespace Jasny\Controller; + +/** + * Controller methods to negotiate content + */ +trait ContentNegotiation +{ + /** + * Get request, set for controller + * + * @return ServerRequestInterface + */ + abstract public function getRequest(); + + /** + * Pick best content type + * + * @param array $priorities + * @return string + */ + public function negotiateContentType(array $priorities) + { + return $this->negotiate($priorities); + } + + /** + * Pick best language + * + * @param array $priorities + * @return string + */ + public function negotiateLanguage(array $priorities) + { + return $this->negotiate($priorities, 'language'); + } + + /** + * Pick best encoding + * + * @param array $priorities + * @return string + */ + public function negotiateEncoding(array $priorities) + { + return $this->negotiate($priorities, 'encoding'); + } + + /** + * Pick best charset + * + * @param array $priorities + * @return string + */ + public function negotiateCharset(array $priorities) + { + return $this->negotiate($priorities, 'charset'); + } + + /** + * Generalize negotiation + * + * @param array $priorities + * @param string $type Negotiator type + * @return string + */ + protected function negotiate(array $priorities, $type = '') + { + $header = 'Accept'; + + if ($type) { + $header .= '-' . ucfirst($type); + } + + $header = $this->getRequest()->getHeader($header); + $header = join(', ', $header); + + $negotiator = $this->getNegotiator($type); + $chosen = $negotiator->getBest($header, $priorities); + + return $chosen ? $chosen->getType() : ''; + } + + /** + * Get negotiation library instance + * + * @param string $type Negotiator type + * @return Negotiation\AbstractNegotiator + */ + protected function getNegotiator($type = '') + { + $class = $this->getNegotiatorName($type); + + return new $class(); + } + + /** + * Get negotiator name + * + * @param string $type + * @return string + */ + protected function getNegotiatorName($type = '') + { + return 'Negotiation\\' . ucfirst($type) . 'Negotiator'; + } +} |