3 * Zend Framework (http://framework.zend.com/)
5 * @link http://github.com/zendframework/zf2 for the canonical source repository
6 * @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com)
7 * @license http://framework.zend.com/license/new-bsd New BSD License
10 namespace Zend\Filter
;
12 use Zend\Filter\AbstractFilter
;
13 use Zend\Filter\Exception\InvalidArgumentException
;
14 use Zend\Uri\Exception\ExceptionInterface
as UriException
;
15 use Zend\Uri\UriFactory
;
18 class UriNormalize
extends AbstractFilter
21 * The default scheme to use when parsing scheme-less URIs
25 protected $defaultScheme = null;
28 * Enforced scheme for scheme-less URIs. See setEnforcedScheme docs for info
32 protected $enforcedScheme = null;
37 * @param array|\Traversable|null $options
39 public function __construct($options = null)
42 $this->setOptions($options);
47 * Set the default scheme to use when parsing scheme-less URIs
49 * The scheme used when parsing URIs may affect the specific object used to
50 * normalize the URI and thus may affect the resulting normalize URI.
52 * @param string $defaultScheme
55 public function setDefaultScheme($defaultScheme)
57 $this->defaultScheme
= $defaultScheme;
62 * Set a URI scheme to enforce on schemeless URIs
64 * This allows forcing input values such as 'www.example.com/foo' into
65 * 'http://www.example.com/foo'.
67 * This should be used with caution, as a standard-compliant URI parser
68 * would regard 'www.example.com' in the above input URI to be the path and
69 * not host part of the URI. While this option can assist in solving
70 * real-world user mishaps, it may yield unexpected results at times.
72 * @param string $enforcedScheme
75 public function setEnforcedScheme($enforcedScheme)
77 $this->enforcedScheme
= $enforcedScheme;
82 * Filter the URL by normalizing it and applying a default scheme if set
84 * @param string $value
87 public function filter($value)
89 $defaultScheme = $this->defaultScheme ?
: $this->enforcedScheme
;
91 // Reset default scheme if it is not a known scheme
92 if (!UriFactory
::getRegisteredSchemeClass($defaultScheme)) {
93 $defaultScheme = null;
97 $uri = UriFactory
::factory($value, $defaultScheme);
98 if ($this->enforcedScheme
&& (!$uri->getScheme())) {
99 $this->enforceScheme($uri);
102 } catch (UriException
$ex) {
103 // We are unable to parse / enfore scheme with the given config and input
109 if (!$uri->isValid()) {
113 return $uri->toString();
117 * Enforce the defined scheme on the URI
119 * This will also adjust the host and path parts of the URI as expected in
120 * the case of scheme-less network URIs
124 protected function enforceScheme(Uri
$uri)
126 $path = $uri->getPath();
127 if (strpos($path, '/') !== false) {
128 list($host, $path) = explode('/', $path, 2);
135 // We have nothing to do if we have no host
140 $uri->setScheme($this->enforcedScheme
)