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

  • AssetMiddleware
  • RoutingMiddleware
  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.3.0
 13:  * @license       https://opensource.org/licenses/mit-license.php MIT License
 14:  */
 15: namespace Cake\Routing\Middleware;
 16: 
 17: use Cake\Core\Plugin;
 18: use Cake\Filesystem\File;
 19: use Cake\Utility\Inflector;
 20: use Psr\Http\Message\ResponseInterface;
 21: use Psr\Http\Message\ServerRequestInterface;
 22: use Zend\Diactoros\Response;
 23: use Zend\Diactoros\Stream;
 24: 
 25: /**
 26:  * Handles serving plugin assets in development mode.
 27:  *
 28:  * This should not be used in production environments as it
 29:  * has sub-optimal performance when compared to serving files
 30:  * with a real webserver.
 31:  */
 32: class AssetMiddleware
 33: {
 34:     /**
 35:      * The amount of time to cache the asset.
 36:      *
 37:      * @var string
 38:      */
 39:     protected $cacheTime = '+1 day';
 40: 
 41:     /**
 42:      * A extension to content type mapping for plain text types.
 43:      *
 44:      * Because finfo doesn't give useful information for plain text types,
 45:      * we have to handle that here.
 46:      *
 47:      * @var array
 48:      */
 49:     protected $typeMap = [
 50:         'css' => 'text/css',
 51:         'json' => 'application/json',
 52:         'js' => 'application/javascript',
 53:         'ico' => 'image/x-icon',
 54:         'eot' => 'application/vnd.ms-fontobject',
 55:         'svg' => 'image/svg+xml',
 56:         'html' => 'text/html',
 57:         'rss' => 'application/rss+xml',
 58:         'xml' => 'application/xml',
 59:     ];
 60: 
 61:     /**
 62:      * Constructor.
 63:      *
 64:      * @param array $options The options to use
 65:      */
 66:     public function __construct(array $options = [])
 67:     {
 68:         if (!empty($options['cacheTime'])) {
 69:             $this->cacheTime = $options['cacheTime'];
 70:         }
 71:         if (!empty($options['types'])) {
 72:             $this->typeMap = array_merge($this->typeMap, $options['types']);
 73:         }
 74:     }
 75: 
 76:     /**
 77:      * Serve assets if the path matches one.
 78:      *
 79:      * @param \Psr\Http\Message\ServerRequestInterface $request The request.
 80:      * @param \Psr\Http\Message\ResponseInterface $response The response.
 81:      * @param callable $next Callback to invoke the next middleware.
 82:      * @return \Psr\Http\Message\ResponseInterface A response
 83:      */
 84:     public function __invoke($request, $response, $next)
 85:     {
 86:         $url = $request->getUri()->getPath();
 87:         if (strpos($url, '..') !== false || strpos($url, '.') === false) {
 88:             return $next($request, $response);
 89:         }
 90: 
 91:         if (strpos($url, '/.') !== false) {
 92:             return $next($request, $response);
 93:         }
 94: 
 95:         $assetFile = $this->_getAssetFile($url);
 96:         if ($assetFile === null || !file_exists($assetFile)) {
 97:             return $next($request, $response);
 98:         }
 99: 
100:         $file = new File($assetFile);
101:         $modifiedTime = $file->lastChange();
102:         if ($this->isNotModified($request, $file)) {
103:             $headers = $response->getHeaders();
104:             $headers['Last-Modified'] = date(DATE_RFC850, $modifiedTime);
105: 
106:             return new Response('php://memory', 304, $headers);
107:         }
108: 
109:         return $this->deliverAsset($request, $response, $file);
110:     }
111: 
112:     /**
113:      * Check the not modified header.
114:      *
115:      * @param \Psr\Http\Message\ServerRequestInterface $request The request to check.
116:      * @param \Cake\Filesystem\File $file The file object to compare.
117:      * @return bool
118:      */
119:     protected function isNotModified($request, $file)
120:     {
121:         $modifiedSince = $request->getHeaderLine('If-Modified-Since');
122:         if (!$modifiedSince) {
123:             return false;
124:         }
125: 
126:         return strtotime($modifiedSince) === $file->lastChange();
127:     }
128: 
129:     /**
130:      * Builds asset file path based off url
131:      *
132:      * @param string $url Asset URL
133:      * @return string|null Absolute path for asset file, null on failure
134:      */
135:     protected function _getAssetFile($url)
136:     {
137:         $parts = explode('/', ltrim($url, '/'));
138:         $pluginPart = [];
139:         for ($i = 0; $i < 2; $i++) {
140:             if (!isset($parts[$i])) {
141:                 break;
142:             }
143:             $pluginPart[] = Inflector::camelize($parts[$i]);
144:             $plugin = implode('/', $pluginPart);
145:             if ($plugin && Plugin::isLoaded($plugin)) {
146:                 $parts = array_slice($parts, $i + 1);
147:                 $fileFragment = implode(DIRECTORY_SEPARATOR, $parts);
148:                 $pluginWebroot = Plugin::path($plugin) . 'webroot' . DIRECTORY_SEPARATOR;
149: 
150:                 return $pluginWebroot . $fileFragment;
151:             }
152:         }
153: 
154:         return null;
155:     }
156: 
157:     /**
158:      * Sends an asset file to the client
159:      *
160:      * @param \Psr\Http\Message\ServerRequestInterface $request The request object to use.
161:      * @param \Psr\Http\Message\ResponseInterface $response The response object to use.
162:      * @param \Cake\Filesystem\File $file The file wrapper for the file.
163:      * @return \Psr\Http\Message\ResponseInterface The response with the file & headers.
164:      */
165:     protected function deliverAsset(ServerRequestInterface $request, ResponseInterface $response, $file)
166:     {
167:         $contentType = $this->getType($file);
168:         $modified = $file->lastChange();
169:         $expire = strtotime($this->cacheTime);
170:         $maxAge = $expire - time();
171: 
172:         $stream = new Stream(fopen($file->path, 'rb'));
173: 
174:         return $response->withBody($stream)
175:             ->withHeader('Content-Type', $contentType)
176:             ->withHeader('Cache-Control', 'public,max-age=' . $maxAge)
177:             ->withHeader('Date', gmdate('D, j M Y G:i:s \G\M\T', time()))
178:             ->withHeader('Last-Modified', gmdate('D, j M Y G:i:s \G\M\T', $modified))
179:             ->withHeader('Expires', gmdate('D, j M Y G:i:s \G\M\T', $expire));
180:     }
181: 
182:     /**
183:      * Return the type from a File object
184:      *
185:      * @param File $file The file from which you get the type
186:      * @return string
187:      */
188:     protected function getType($file)
189:     {
190:         $extension = $file->ext();
191:         if (isset($this->typeMap[$extension])) {
192:             return $this->typeMap[$extension];
193:         }
194: 
195:         return $file->mime() ?: 'application/octet-stream';
196:     }
197: }
198: 
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