Skip to content
Permalink
Browse files

Extract duplicate code into a helper.

  • Loading branch information...
markstory committed Dec 9, 2016
1 parent 539304b commit 4cafa1e36a28d8c88f041e04eb4ece2e0e86376a
Showing with 29 additions and 32 deletions.
  1. +29 −32 src/Network/Response.php
@@ -2100,27 +2100,12 @@ public function cors(Request $request, $allowedDomains = [], $allowedMethods = [
*/
public function file($path, array $options = [])
{
$file = $this->validateFile($path);
$options += [
'name' => null,
'download' => null
];
if (strpos($path, '../') !== false || strpos($path, '..\\') !== false) {
throw new NotFoundException('The requested file contains `..` and will not be read.');
}
if (!is_file($path)) {
$path = APP . $path;
}
$file = new File($path);
if (!$file->exists() || !$file->readable()) {
if (Configure::read('debug')) {
throw new NotFoundException(sprintf('The requested file %s was not found or not readable', $path));
}
throw new NotFoundException(__d('cake', 'The requested file was not found'));
}
$extension = strtolower($file->ext());
$download = $options['download'];
if ((!$extension || $this->type($extension) === false) && $download === null) {
@@ -2163,22 +2148,7 @@ public function file($path, array $options = [])
public function withFile($path, array $options = [])
{
// TODO move validation into a helper method.
if (strpos($path, '../') !== false || strpos($path, '..\\') !== false) {
throw new NotFoundException('The requested file contains `..` and will not be read.');
}
if (!is_file($path)) {
$path = APP . $path;
}
$file = new File($path);
if (!$file->exists() || !$file->readable()) {
if (Configure::read('debug')) {
throw new NotFoundException(sprintf('The requested file %s was not found or not readable', $path));
}
throw new NotFoundException(__d('cake', 'The requested file was not found'));
}
// end refactor.
$file = $this->validateFile($path);
$options += [
'name' => null,
@@ -2227,6 +2197,33 @@ public function withFile($path, array $options = [])
return $new;
}
/**
* Validate a file path is a valid response body.
*
* @param string $path The path to the file.
* @throws \Cake\Network\Exception\NotFoundException
* @return \Cake\Filesystem\File
*/
protected function validateFile($path)
{
if (strpos($path, '../') !== false || strpos($path, '..\\') !== false) {
throw new NotFoundException('The requested file contains `..` and will not be read.');
}
if (!is_file($path)) {
$path = APP . $path;
}
$file = new File($path);
if (!$file->exists() || !$file->readable()) {
if (Configure::read('debug')) {
throw new NotFoundException(sprintf('The requested file %s was not found or not readable', $path));
}
throw new NotFoundException(__d('cake', 'The requested file was not found'));
}
return $file;
}
/**
* Get the current file if one exists.
*

0 comments on commit 4cafa1e

Please sign in to comment.
You can’t perform that action at this time.