| Total Complexity | 63 |
| Total Lines | 512 |
| Duplicated Lines | 0 % |
| Changes | 2 | ||
| Bugs | 0 | Features | 0 |
Complex classes like Response often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use Response, and based on these observations, apply Extract Interface, too.
| 1 | <?php |
||
| 27 | class Response{ |
||
| 28 | |||
| 29 | /** |
||
| 30 | * The list of request header to send with response |
||
| 31 | * @var array |
||
| 32 | */ |
||
| 33 | private static $headers = array(); |
||
| 34 | |||
| 35 | /** |
||
| 36 | * The logger instance |
||
| 37 | * @var object |
||
| 38 | */ |
||
| 39 | private static $logger; |
||
| 40 | |||
| 41 | /** |
||
| 42 | * The final page content to display to user |
||
| 43 | * @var string |
||
| 44 | */ |
||
| 45 | private $_pageRender = null; |
||
| 46 | |||
| 47 | /** |
||
| 48 | * The current request URL |
||
| 49 | * @var string |
||
| 50 | */ |
||
| 51 | private $_currentUrl = null; |
||
| 52 | |||
| 53 | /** |
||
| 54 | * The current request URL cache key |
||
| 55 | * @var string |
||
| 56 | */ |
||
| 57 | private $_currentUrlCacheKey = null; |
||
| 58 | |||
| 59 | /** |
||
| 60 | * Whether we can compress the output using Gzip |
||
| 61 | * @var boolean |
||
| 62 | */ |
||
| 63 | private static $_canCompressOutput = false; |
||
| 64 | |||
| 65 | /** |
||
| 66 | * Construct new response instance |
||
| 67 | */ |
||
| 68 | public function __construct(){ |
||
| 85 | } |
||
| 86 | |||
| 87 | |||
| 88 | /** |
||
| 89 | * The signleton of the logger |
||
| 90 | * @return Object the Log instance |
||
| 91 | */ |
||
| 92 | public static function getLogger(){ |
||
| 93 | if(self::$logger == null){ |
||
| 94 | $logger = array(); |
||
| 95 | $logger[0] =& class_loader('Log', 'classes'); |
||
| 96 | $logger[0]->setLogger('Library::Response'); |
||
| 97 | self::$logger = $logger[0]; |
||
| 98 | } |
||
| 99 | return self::$logger; |
||
| 100 | } |
||
| 101 | |||
| 102 | /** |
||
| 103 | * Set the log instance for future use |
||
| 104 | * @param object $logger the log object |
||
| 105 | * @return object the log instance |
||
| 106 | */ |
||
| 107 | public static function setLogger($logger){ |
||
| 108 | self::$logger = $logger; |
||
| 109 | return self::$logger; |
||
| 110 | } |
||
| 111 | |||
| 112 | |||
| 113 | /** |
||
| 114 | * Send the HTTP Response headers |
||
| 115 | * @param integer $httpCode the HTTP status code |
||
| 116 | * @param array $headers the additional headers to add to the existing headers list |
||
| 117 | */ |
||
| 118 | public static function sendHeaders($httpCode = 200, array $headers = array()){ |
||
| 119 | set_http_status_header($httpCode); |
||
| 120 | self::setHeaders($headers); |
||
| 121 | if(! headers_sent()){ |
||
| 122 | foreach(self::getHeaders() as $key => $value){ |
||
| 123 | header($key .': '.$value); |
||
| 124 | } |
||
| 125 | } |
||
| 126 | } |
||
| 127 | |||
| 128 | /** |
||
| 129 | * Get the list of the headers |
||
| 130 | * @return array the headers list |
||
| 131 | */ |
||
| 132 | public static function getHeaders(){ |
||
| 133 | return self::$headers; |
||
| 134 | } |
||
| 135 | |||
| 136 | /** |
||
| 137 | * Get the header value for the given name |
||
| 138 | * @param string $name the header name |
||
| 139 | * @return string|null the header value |
||
| 140 | */ |
||
| 141 | public static function getHeader($name){ |
||
| 142 | if(array_key_exists($name, self::$headers)){ |
||
| 143 | return self::$headers[$name]; |
||
| 144 | } |
||
| 145 | return null; |
||
| 146 | } |
||
| 147 | |||
| 148 | |||
| 149 | /** |
||
| 150 | * Set the header value for the specified name |
||
| 151 | * @param string $name the header name |
||
| 152 | * @param string $value the header value to be set |
||
| 153 | */ |
||
| 154 | public static function setHeader($name, $value){ |
||
| 155 | self::$headers[$name] = $value; |
||
| 156 | } |
||
| 157 | |||
| 158 | /** |
||
| 159 | * Set the headers using array |
||
| 160 | * @param array $headers the list of the headers to set. |
||
| 161 | * Note: this will merge with the existing headers |
||
| 162 | */ |
||
| 163 | public static function setHeaders(array $headers){ |
||
| 165 | } |
||
| 166 | |||
| 167 | /** |
||
| 168 | * Redirect user to the specified page |
||
| 169 | * @param string $path the URL or URI to be redirect to |
||
| 170 | */ |
||
| 171 | public static function redirect($path = ''){ |
||
| 181 | </script>'; |
||
| 182 | } |
||
| 183 | |||
| 184 | /** |
||
| 185 | * Render the view to display later or return the content |
||
| 186 | * @param string $view the view name or path |
||
| 187 | * @param array|object $data the variable data to use in the view |
||
| 188 | * @param boolean $return whether to return the view generated content or display it directly |
||
| 189 | * @return void|string if $return is true will return the view content otherwise |
||
| 190 | * will display the view content. |
||
| 191 | */ |
||
| 192 | public function render($view, $data = null, $return = false){ |
||
| 223 | } |
||
| 224 | |||
| 225 | |||
| 226 | /** |
||
| 227 | * Send the final page output to user |
||
| 228 | */ |
||
| 229 | public function renderFinalPage(){ |
||
| 230 | $logger = self::getLogger(); |
||
| 231 | $obj = & get_instance(); |
||
| 232 | $cachePageStatus = get_config('cache_enable', false) && !empty($obj->view_cache_enable); |
||
| 233 | $dispatcher = $obj->eventdispatcher; |
||
| 234 | $content = $this->_pageRender; |
||
| 235 | if(! $content){ |
||
| 236 | $logger->warning('The final view content is empty.'); |
||
| 237 | return; |
||
| 238 | } |
||
| 239 | //dispatch |
||
| 240 | $event = $dispatcher->dispatch(new EventInfo('FINAL_VIEW_READY', $content, true)); |
||
| 241 | $content = null; |
||
| 242 | if(! empty($event->payload)){ |
||
| 243 | $content = $event->payload; |
||
| 244 | } |
||
| 245 | if(empty($content)){ |
||
| 246 | $logger->warning('The view content is empty after dispatch to event listeners.'); |
||
| 247 | } |
||
| 248 | //remove unsed space in the content |
||
| 249 | $content = preg_replace('~>\s*\n\s*<~', '><', $content); |
||
| 250 | //check whether need save the page into cache. |
||
| 251 | if($cachePageStatus){ |
||
| 252 | $this->savePageContentIntoCache($content); |
||
| 253 | } |
||
| 254 | $content = $this->replaceElapseTimeAndMemoryUsage($content); |
||
| 255 | |||
| 256 | //compress the output if is available |
||
| 257 | $type = null; |
||
| 258 | if (self::$_canCompressOutput){ |
||
| 259 | $type = 'ob_gzhandler'; |
||
| 260 | } |
||
| 261 | ob_start($type); |
||
| 262 | self::sendHeaders(200); |
||
| 263 | echo $content; |
||
| 264 | ob_end_flush(); |
||
| 265 | } |
||
| 266 | |||
| 267 | |||
| 268 | /** |
||
| 269 | * Send the final page output to user if is cached |
||
| 270 | * @param object $cache the cache instance |
||
| 271 | * |
||
| 272 | * @return boolean whether the page content if available or not |
||
| 273 | */ |
||
| 274 | public function renderFinalPageFromCache(&$cache){ |
||
| 275 | $logger = self::getLogger(); |
||
| 276 | //the current page cache key for identification |
||
| 277 | $pageCacheKey = $this->_currentUrlCacheKey; |
||
| 278 | |||
| 279 | $logger->debug('Checking if the page content for the URL [' . $this->_currentUrl . '] is cached ...'); |
||
| 280 | //get the cache information to prepare header to send to browser |
||
| 281 | $cacheInfo = $cache->getInfo($pageCacheKey); |
||
| 282 | if($cacheInfo){ |
||
| 283 | $status = $this->sendCacheNotYetExpireInfoToBrowser($cacheInfo); |
||
| 284 | if($status === false){ |
||
| 285 | return $this->sendCachePageContentToBrowser($cache); |
||
| 286 | } |
||
| 287 | return true; |
||
| 288 | } |
||
| 289 | return false; |
||
| 290 | } |
||
| 291 | |||
| 292 | |||
| 293 | /** |
||
| 294 | * Get the final page to be rendered |
||
| 295 | * @return string |
||
| 296 | */ |
||
| 297 | public function getFinalPageRendered(){ |
||
| 298 | return $this->_pageRender; |
||
| 299 | } |
||
| 300 | |||
| 301 | /** |
||
| 302 | * Send the HTTP 404 error if can not found the |
||
| 303 | * routing information for the current request |
||
| 304 | */ |
||
| 305 | public static function send404(){ |
||
| 306 | /********* for logs **************/ |
||
| 307 | //can't use $obj = & get_instance() here because the global super object will be available until |
||
| 308 | //the main controller is loaded even for Loader::library('xxxx'); |
||
| 309 | $logger = self::getLogger(); |
||
| 310 | $request =& class_loader('Request', 'classes'); |
||
| 311 | $userAgent =& class_loader('Browser'); |
||
| 312 | $browser = $userAgent->getPlatform().', '.$userAgent->getBrowser().' '.$userAgent->getVersion(); |
||
| 313 | |||
| 314 | //here can't use Loader::functions just include the helper manually |
||
| 315 | require_once CORE_FUNCTIONS_PATH . 'function_user_agent.php'; |
||
| 316 | |||
| 317 | $str = '[404 page not found] : '; |
||
| 318 | $str .= ' Unable to find the request page [' . $request->requestUri() . ']. The visitor IP address [' . get_ip() . '], browser [' . $browser . ']'; |
||
| 319 | $logger->error($str); |
||
| 320 | /***********************************/ |
||
| 321 | $path = CORE_VIEWS_PATH . '404.php'; |
||
| 322 | if(file_exists($path)){ |
||
| 323 | //compress the output if is available |
||
| 324 | $type = null; |
||
| 325 | if (self::$_canCompressOutput){ |
||
| 326 | $type = 'ob_gzhandler'; |
||
| 327 | } |
||
| 328 | ob_start($type); |
||
| 329 | require_once $path; |
||
| 330 | $output = ob_get_clean(); |
||
| 331 | self::sendHeaders(404); |
||
| 332 | echo $output; |
||
| 333 | } |
||
| 334 | else{ |
||
| 335 | show_error('The 404 view [' .$path. '] does not exist'); |
||
| 336 | } |
||
| 337 | } |
||
| 338 | |||
| 339 | /** |
||
| 340 | * Display the error to user |
||
| 341 | * @param array $data the error information |
||
| 342 | */ |
||
| 343 | public static function sendError(array $data = array()){ |
||
| 344 | $path = CORE_VIEWS_PATH . 'errors.php'; |
||
| 345 | if(file_exists($path)){ |
||
| 346 | //compress the output if is available |
||
| 347 | $type = null; |
||
| 348 | if (self::$_canCompressOutput){ |
||
| 349 | $type = 'ob_gzhandler'; |
||
| 350 | } |
||
| 351 | ob_start($type); |
||
| 352 | extract($data); |
||
| 353 | require_once $path; |
||
| 354 | $output = ob_get_clean(); |
||
| 355 | self::sendHeaders(503); |
||
| 356 | echo $output; |
||
| 357 | } |
||
| 358 | else{ |
||
| 359 | //can't use show_error() at this time because some dependencies not yet loaded and to prevent loop |
||
| 360 | set_http_status_header(503); |
||
| 361 | echo 'The error view [' . $path . '] does not exist'; |
||
| 362 | } |
||
| 363 | } |
||
| 364 | |||
| 365 | /** |
||
| 366 | * Send the cache not yet expire to browser |
||
| 367 | * @param array $cacheInfo the cache information |
||
| 368 | * @return boolean true if the information is sent otherwise false |
||
| 369 | */ |
||
| 370 | protected function sendCacheNotYetExpireInfoToBrowser($cacheInfo){ |
||
| 371 | if(! empty($cacheInfo)){ |
||
| 372 | $logger = self::getLogger(); |
||
| 373 | $lastModified = $cacheInfo['mtime']; |
||
| 374 | $expire = $cacheInfo['expire']; |
||
| 375 | $maxAge = $expire - $_SERVER['REQUEST_TIME']; |
||
| 376 | self::setHeader('Pragma', 'public'); |
||
| 377 | self::setHeader('Cache-Control', 'max-age=' . $maxAge . ', public'); |
||
| 378 | self::setHeader('Expires', gmdate('D, d M Y H:i:s', $expire).' GMT'); |
||
| 379 | self::setHeader('Last-modified', gmdate('D, d M Y H:i:s', $lastModified).' GMT'); |
||
| 380 | if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && $lastModified <= strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE'])){ |
||
| 381 | $logger->info('The cache page content is not yet expire for the URL [' . $this->_currentUrl . '] send 304 header to browser'); |
||
| 382 | self::sendHeaders(304); |
||
| 383 | return true; |
||
| 384 | } |
||
| 385 | } |
||
| 386 | return false; |
||
| 387 | } |
||
| 388 | |||
| 389 | /** |
||
| 390 | * Set the value of '{elapsed_time}' and '{memory_usage}' |
||
| 391 | * @param string $content the page content |
||
| 392 | * @return string the page content after replace |
||
| 393 | * '{elapsed_time}', '{memory_usage}' |
||
| 394 | */ |
||
| 395 | protected function replaceElapseTimeAndMemoryUsage($content){ |
||
| 396 | //load benchmark class |
||
| 397 | $benchmark = & class_loader('Benchmark'); |
||
| 398 | |||
| 399 | // Parse out the elapsed time and memory usage, |
||
| 400 | // then swap the pseudo-variables with the data |
||
| 401 | $elapsedTime = $benchmark->elapsedTime('APP_EXECUTION_START', 'APP_EXECUTION_END'); |
||
| 402 | $memoryUsage = round($benchmark->memoryUsage('APP_EXECUTION_START', 'APP_EXECUTION_END') / 1024 / 1024, 6) . 'MB'; |
||
| 403 | return str_replace(array('{elapsed_time}', '{memory_usage}'), array($elapsedTime, $memoryUsage), $content); |
||
| 404 | } |
||
| 405 | |||
| 406 | /** |
||
| 407 | * Send the page content from cache to browser |
||
| 408 | * @param object $cache the cache instance |
||
| 409 | * @return boolean the status of the operation |
||
| 410 | */ |
||
| 411 | protected function sendCachePageContentToBrowser(&$cache){ |
||
| 436 | } |
||
| 437 | |||
| 438 | /** |
||
| 439 | * Save the content of page into cache |
||
| 440 | * @param string $content the page content to be saved |
||
| 441 | * @return void |
||
| 442 | */ |
||
| 443 | protected function savePageContentIntoCache($content){ |
||
| 444 | $obj = & get_instance(); |
||
| 445 | $logger = self::getLogger(); |
||
| 446 | |||
| 447 | //current page URL |
||
| 448 | $url = $this->_currentUrl; |
||
| 449 | //Cache view Time to live in second |
||
| 450 | $viewCacheTtl = get_config('cache_ttl'); |
||
| 451 | if (!empty($obj->view_cache_ttl)){ |
||
| 452 | $viewCacheTtl = $obj->view_cache_ttl; |
||
| 453 | } |
||
| 454 | //the cache handler instance |
||
| 455 | $cacheInstance = $obj->cache; |
||
| 456 | //the current page cache key for identification |
||
| 457 | $cacheKey = $this->_currentUrlCacheKey; |
||
| 458 | $logger->debug('Save the page content for URL [' . $url . '] into the cache ...'); |
||
| 459 | $cacheInstance->set($cacheKey, $content, $viewCacheTtl); |
||
| 460 | |||
| 461 | //get the cache information to prepare header to send to browser |
||
| 462 | $cacheInfo = $cacheInstance->getInfo($cacheKey); |
||
| 463 | if($cacheInfo){ |
||
| 464 | $lastModified = $cacheInfo['mtime']; |
||
| 465 | $expire = $cacheInfo['expire']; |
||
| 466 | $maxAge = $expire - time(); |
||
| 467 | self::setHeader('Pragma', 'public'); |
||
| 468 | self::setHeader('Cache-Control', 'max-age=' . $maxAge . ', public'); |
||
| 469 | self::setHeader('Expires', gmdate('D, d M Y H:i:s', $expire).' GMT'); |
||
| 470 | self::setHeader('Last-modified', gmdate('D, d M Y H:i:s', $lastModified).' GMT'); |
||
| 471 | } |
||
| 472 | } |
||
| 473 | |||
| 474 | |||
| 475 | /** |
||
| 476 | * Get the module information for the view to load |
||
| 477 | * @param string $view the view name like moduleName/viewName, viewName |
||
| 478 | * |
||
| 479 | * @return array the module information |
||
| 480 | * array( |
||
| 481 | * 'module'=> 'module_name' |
||
| 482 | * 'view' => 'view_name' |
||
| 483 | * 'viewFile' => 'view_file' |
||
| 484 | * ) |
||
| 485 | */ |
||
| 486 | protected function getModuleInfoForView($view){ |
||
| 507 | ); |
||
| 508 | } |
||
| 509 | |||
| 510 | /** |
||
| 511 | * Render the view page |
||
| 512 | * @see Response::render |
||
| 513 | * @return void|string |
||
| 514 | */ |
||
| 515 | protected function loadView($path, array $data = array(), $return = false){ |
||
| 543 |