CakePHP
  • Documentation
    • Book
    • API
    • Videos
    • Logos & Trademarks
  • Business Solutions
  • Swag
  • Road Trip
  • Team
  • Community
    • Community
    • Team
    • Issues (Github)
    • YouTube Channel
    • Get Involved
    • Bakery
    • Featured Resources
    • Newsletter
    • Certification
    • My CakePHP
    • CakeFest
    • Facebook
    • Twitter
    • Help & Support
    • Forum
    • Stack Overflow
    • IRC
    • Slack
    • Paid Support
CakePHP

C CakePHP 3.8 Red Velvet API

  • Overview
  • Tree
  • Deprecated
  • Version:
    • 3.8
      • 3.8
      • 3.7
      • 3.6
      • 3.5
      • 3.4
      • 3.3
      • 3.2
      • 3.1
      • 3.0
      • 2.10
      • 2.9
      • 2.8
      • 2.7
      • 2.6
      • 2.5
      • 2.4
      • 2.3
      • 2.2
      • 2.1
      • 2.0
      • 1.3
      • 1.2

Namespaces

  • Cake
    • Auth
      • Storage
    • Cache
      • Engine
    • Collection
      • Iterator
    • Command
    • Console
      • Exception
    • Controller
      • Component
      • Exception
    • Core
      • Configure
        • Engine
      • Exception
      • Retry
    • Database
      • Driver
      • Exception
      • Expression
      • Schema
      • Statement
      • Type
    • Datasource
      • Exception
    • Error
      • Middleware
    • Event
      • Decorator
    • Filesystem
    • Form
    • Http
      • Client
        • Adapter
        • Auth
      • Cookie
      • Exception
      • Middleware
      • Session
    • I18n
      • Formatter
      • Middleware
      • Parser
    • Log
      • Engine
    • Mailer
      • Exception
      • Transport
    • Network
      • Exception
    • ORM
      • Association
      • Behavior
        • Translate
      • Exception
      • Locator
      • Rule
    • Routing
      • Exception
      • Filter
      • Middleware
      • Route
    • Shell
      • Helper
      • Task
    • TestSuite
      • Fixture
      • Stub
    • Utility
      • Exception
    • Validation
    • View
      • Exception
      • Form
      • Helper
      • Widget
  • None

Classes

  • BreadcrumbsHelper
  • FlashHelper
  • FormHelper
  • HtmlHelper
  • NumberHelper
  • PaginatorHelper
  • RssHelper
  • SessionHelper
  • TextHelper
  • TimeHelper
  • UrlHelper

Traits

  • IdGeneratorTrait
  • SecureFieldTokenTrait
  1: <?php
  2: /**
  3:  * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  4:  * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  5:  *
  6:  * Licensed under The MIT License
  7:  * For full copyright and license information, please see the LICENSE.txt
  8:  * Redistributions of files must retain the above copyright notice.
  9:  *
 10:  * @copyright     Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
 11:  * @link          https://cakephp.org CakePHP(tm) Project
 12:  * @since         3.0.0
 13:  * @license       https://opensource.org/licenses/mit-license.php MIT License
 14:  */
 15: namespace Cake\View\Helper;
 16: 
 17: use Cake\Core\Configure;
 18: use Cake\Core\Plugin;
 19: use Cake\Routing\Router;
 20: use Cake\Utility\Inflector;
 21: use Cake\View\Helper;
 22: 
 23: /**
 24:  * UrlHelper class for generating URLs.
 25:  */
 26: class UrlHelper extends Helper
 27: {
 28:     /**
 29:      * Returns a URL based on provided parameters.
 30:      *
 31:      * ### Options:
 32:      *
 33:      * - `escape`: If false, the URL will be returned unescaped, do only use if it is manually
 34:      *    escaped afterwards before being displayed.
 35:      * - `fullBase`: If true, the full base URL will be prepended to the result
 36:      *
 37:      * @param string|array|null $url Either a relative string URL like `/products/view/23` or
 38:      *    an array of URL parameters. Using an array for URLs will allow you to leverage
 39:      *    the reverse routing features of CakePHP.
 40:      * @param array|bool $options Array of options; bool `full` for BC reasons.
 41:      * @return string Full translated URL with base path.
 42:      */
 43:     public function build($url = null, $options = false)
 44:     {
 45:         $defaults = [
 46:             'fullBase' => false,
 47:             'escape' => true,
 48:         ];
 49:         if (!is_array($options)) {
 50:             $options = ['fullBase' => $options];
 51:         }
 52:         $options += $defaults;
 53: 
 54:         /** @var string $url */
 55:         $url = Router::url($url, $options['fullBase']);
 56:         if ($options['escape']) {
 57:             /** @var string $url */
 58:             $url = h($url);
 59:         }
 60: 
 61:         return $url;
 62:     }
 63: 
 64:     /**
 65:      * Generates URL for given image file.
 66:      *
 67:      * Depending on options passed provides full URL with domain name. Also calls
 68:      * `Helper::assetTimestamp()` to add timestamp to local files.
 69:      *
 70:      * @param string|array $path Path string or URL array
 71:      * @param array $options Options array. Possible keys:
 72:      *   `fullBase` Return full URL with domain name
 73:      *   `pathPrefix` Path prefix for relative URLs
 74:      *   `plugin` False value will prevent parsing path as a plugin
 75:      *   `timestamp` Overrides the value of `Asset.timestamp` in Configure.
 76:      *        Set to false to skip timestamp generation.
 77:      *        Set to true to apply timestamps when debug is true. Set to 'force' to always
 78:      *        enable timestamping regardless of debug value.
 79:      * @return string Generated URL
 80:      */
 81:     public function image($path, array $options = [])
 82:     {
 83:         $pathPrefix = Configure::read('App.imageBaseUrl');
 84: 
 85:         return $this->assetUrl($path, $options + compact('pathPrefix'));
 86:     }
 87: 
 88:     /**
 89:      * Generates URL for given CSS file.
 90:      *
 91:      * Depending on options passed provides full URL with domain name. Also calls
 92:      * `Helper::assetTimestamp()` to add timestamp to local files.
 93:      *
 94:      * @param string|array $path Path string or URL array
 95:      * @param array $options Options array. Possible keys:
 96:      *   `fullBase` Return full URL with domain name
 97:      *   `pathPrefix` Path prefix for relative URLs
 98:      *   `ext` Asset extension to append
 99:      *   `plugin` False value will prevent parsing path as a plugin
100:      *   `timestamp` Overrides the value of `Asset.timestamp` in Configure.
101:      *        Set to false to skip timestamp generation.
102:      *        Set to true to apply timestamps when debug is true. Set to 'force' to always
103:      *        enable timestamping regardless of debug value.
104:      * @return string Generated URL
105:      */
106:     public function css($path, array $options = [])
107:     {
108:         $pathPrefix = Configure::read('App.cssBaseUrl');
109:         $ext = '.css';
110: 
111:         return $this->assetUrl($path, $options + compact('pathPrefix', 'ext'));
112:     }
113: 
114:     /**
115:      * Generates URL for given javascript file.
116:      *
117:      * Depending on options passed provides full URL with domain name. Also calls
118:      * `Helper::assetTimestamp()` to add timestamp to local files.
119:      *
120:      * @param string|array $path Path string or URL array
121:      * @param array $options Options array. Possible keys:
122:      *   `fullBase` Return full URL with domain name
123:      *   `pathPrefix` Path prefix for relative URLs
124:      *   `ext` Asset extension to append
125:      *   `plugin` False value will prevent parsing path as a plugin
126:      *   `timestamp` Overrides the value of `Asset.timestamp` in Configure.
127:      *        Set to false to skip timestamp generation.
128:      *        Set to true to apply timestamps when debug is true. Set to 'force' to always
129:      *        enable timestamping regardless of debug value.
130:      * @return string Generated URL
131:      */
132:     public function script($path, array $options = [])
133:     {
134:         $pathPrefix = Configure::read('App.jsBaseUrl');
135:         $ext = '.js';
136: 
137:         return $this->assetUrl($path, $options + compact('pathPrefix', 'ext'));
138:     }
139: 
140:     /**
141:      * Generates URL for given asset file.
142:      *
143:      * Depending on options passed provides full URL with domain name. Also calls
144:      * `Helper::assetTimestamp()` to add timestamp to local files.
145:      *
146:      * ### Options:
147:      *
148:      * - `fullBase` Boolean true or a string (e.g. https://example) to
149:      *    return full URL with protocol and domain name.
150:      * - `pathPrefix` Path prefix for relative URLs
151:      * - `ext` Asset extension to append
152:      * - `plugin` False value will prevent parsing path as a plugin
153:      * - `timestamp` Overrides the value of `Asset.timestamp` in Configure.
154:      *    Set to false to skip timestamp generation.
155:      *    Set to true to apply timestamps when debug is true. Set to 'force' to always
156:      *    enable timestamping regardless of debug value.
157:      *
158:      * @param string|array $path Path string or URL array
159:      * @param array $options Options array.
160:      * @return string Generated URL
161:      */
162:     public function assetUrl($path, array $options = [])
163:     {
164:         if (is_array($path)) {
165:             return $this->build($path, !empty($options['fullBase']));
166:         }
167:         // data URIs only require HTML escaping
168:         if (preg_match('/^data:[a-z]+\/[a-z]+;/', $path)) {
169:             return h($path);
170:         }
171:         if (strpos($path, '://') !== false || preg_match('/^[a-z]+:/i', $path)) {
172:             return ltrim($this->build($path), '/');
173:         }
174:         if (!array_key_exists('plugin', $options) || $options['plugin'] !== false) {
175:             list($plugin, $path) = $this->_View->pluginSplit($path, false);
176:         }
177:         if (!empty($options['pathPrefix']) && $path[0] !== '/') {
178:             $path = $options['pathPrefix'] . $path;
179:         }
180:         if (!empty($options['ext']) &&
181:             strpos($path, '?') === false &&
182:             substr($path, -strlen($options['ext'])) !== $options['ext']
183:         ) {
184:             $path .= $options['ext'];
185:         }
186:         if (preg_match('|^([a-z0-9]+:)?//|', $path)) {
187:             return $this->build($path);
188:         }
189:         if (isset($plugin)) {
190:             $path = Inflector::underscore($plugin) . '/' . $path;
191:         }
192: 
193:         $optionTimestamp = null;
194:         if (array_key_exists('timestamp', $options)) {
195:             $optionTimestamp = $options['timestamp'];
196:         }
197:         $webPath = $this->assetTimestamp($this->webroot($path), $optionTimestamp);
198: 
199:         $path = $this->_encodeUrl($webPath);
200: 
201:         if (!empty($options['fullBase'])) {
202:             $fullBaseUrl = is_string($options['fullBase']) ? $options['fullBase'] : Router::fullBaseUrl();
203:             $path = rtrim($fullBaseUrl, '/') . '/' . ltrim($path, '/');
204:         }
205: 
206:         return $path;
207:     }
208: 
209:     /**
210:      * Encodes a URL for use in HTML attributes.
211:      *
212:      * @param string $url The URL to encode.
213:      * @return string The URL encoded for both URL & HTML contexts.
214:      */
215:     protected function _encodeUrl($url)
216:     {
217:         $path = parse_url($url, PHP_URL_PATH);
218:         $parts = array_map('rawurldecode', explode('/', $path));
219:         $parts = array_map('rawurlencode', $parts);
220:         $encoded = implode('/', $parts);
221: 
222:         /** @var string $url */
223:         $url = h(str_replace($path, $encoded, $url));
224: 
225:         return $url;
226:     }
227: 
228:     /**
229:      * Adds a timestamp to a file based resource based on the value of `Asset.timestamp` in
230:      * Configure. If Asset.timestamp is true and debug is true, or Asset.timestamp === 'force'
231:      * a timestamp will be added.
232:      *
233:      * @param string $path The file path to timestamp, the path must be inside WWW_ROOT
234:      * @param bool|string $timestamp If set will overrule the value of `Asset.timestamp` in Configure.
235:      * @return string Path with a timestamp added, or not.
236:      */
237:     public function assetTimestamp($path, $timestamp = null)
238:     {
239:         if ($timestamp === null) {
240:             $timestamp = Configure::read('Asset.timestamp');
241:         }
242:         $timestampEnabled = $timestamp === 'force' || ($timestamp === true && Configure::read('debug'));
243:         if ($timestampEnabled && strpos($path, '?') === false) {
244:             $filepath = preg_replace(
245:                 '/^' . preg_quote($this->_View->getRequest()->getAttribute('webroot'), '/') . '/',
246:                 '',
247:                 urldecode($path)
248:             );
249:             $webrootPath = WWW_ROOT . str_replace('/', DIRECTORY_SEPARATOR, $filepath);
250:             if (file_exists($webrootPath)) {
251:                 return $path . '?' . filemtime($webrootPath);
252:             }
253:             $segments = explode('/', ltrim($filepath, '/'));
254:             $plugin = Inflector::camelize($segments[0]);
255:             if (Plugin::isLoaded($plugin)) {
256:                 unset($segments[0]);
257:                 $pluginPath = Plugin::path($plugin) . 'webroot' . DIRECTORY_SEPARATOR . implode(DIRECTORY_SEPARATOR, $segments);
258:                 if (file_exists($pluginPath)) {
259:                     return $path . '?' . filemtime($pluginPath);
260:                 }
261:             }
262:         }
263: 
264:         return $path;
265:     }
266: 
267:     /**
268:      * Checks if a file exists when theme is used, if no file is found default location is returned
269:      *
270:      * @param string $file The file to create a webroot path to.
271:      * @return string Web accessible path to file.
272:      */
273:     public function webroot($file)
274:     {
275:         $request = $this->_View->getRequest();
276: 
277:         $asset = explode('?', $file);
278:         $asset[1] = isset($asset[1]) ? '?' . $asset[1] : null;
279:         $webPath = $request->getAttribute('webroot') . $asset[0];
280:         $file = $asset[0];
281: 
282:         if (!empty($this->_View->getTheme())) {
283:             $file = trim($file, '/');
284:             $theme = $this->_inflectThemeName($this->_View->getTheme()) . '/';
285: 
286:             if (DIRECTORY_SEPARATOR === '\\') {
287:                 $file = str_replace('/', '\\', $file);
288:             }
289: 
290:             if (file_exists(Configure::read('App.wwwRoot') . $theme . $file)) {
291:                 $webPath = $request->getAttribute('webroot') . $theme . $asset[0];
292:             } else {
293:                 $themePath = Plugin::path($this->_View->getTheme());
294:                 $path = $themePath . 'webroot/' . $file;
295:                 if (file_exists($path)) {
296:                     $webPath = $request->getAttribute('webroot') . $theme . $asset[0];
297:                 }
298:             }
299:         }
300:         if (strpos($webPath, '//') !== false) {
301:             return str_replace('//', '/', $webPath . $asset[1]);
302:         }
303: 
304:         return $webPath . $asset[1];
305:     }
306: 
307:     /**
308:      * Inflect the theme name to its underscored version.
309:      *
310:      * @param string $name Name of the theme which should be inflected.
311:      * @return string Inflected name of the theme
312:      */
313:     protected function _inflectThemeName($name)
314:     {
315:         return Inflector::underscore($name);
316:     }
317: 
318:     /**
319:      * Event listeners.
320:      *
321:      * @return array
322:      */
323:     public function implementedEvents()
324:     {
325:         return [];
326:     }
327: }
328: 
Follow @CakePHP
#IRC
OpenHub
Rackspace
  • Business Solutions
  • Showcase
  • Documentation
  • Book
  • API
  • Videos
  • Logos & Trademarks
  • Community
  • Team
  • Issues (Github)
  • YouTube Channel
  • Get Involved
  • Bakery
  • Featured Resources
  • Newsletter
  • Certification
  • My CakePHP
  • CakeFest
  • Facebook
  • Twitter
  • Help & Support
  • Forum
  • Stack Overflow
  • IRC
  • Slack
  • Paid Support

Generated using CakePHP API Docs