add composer's vendor directory

This commit is contained in:
Marcel Kapfer (mmk2410) 2016-05-07 12:59:40 +02:00
parent 01a3860d73
commit 60b094d5fa
745 changed files with 56017 additions and 1 deletions

19
vendor/codeguy/upload/LICENSE vendored Normal file
View file

@ -0,0 +1,19 @@
Copyright (c) 2012 Josh Lockhart
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

75
vendor/codeguy/upload/README.md vendored Normal file
View file

@ -0,0 +1,75 @@
# Upload
## Usage
This component simplifies file validation and uploading. Assume a file is uploaded with this HTML form:
<form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="foo" value=""/>
<input type="submit" value="Upload File"/>
</form>
When the HTML form is submitted, the server-side PHP code can validate and upload the file like this:
<?php
$storage = new \Upload\Storage\FileSystem('/path/to/directory');
$file = new \Upload\File('foo', $storage);
// Optionally you can rename the file on upload
$new_filename = uniqid();
$file->setName($new_filename);
// Validate file upload
// MimeType List => http://www.webmaster-toolkit.com/mime-types.shtml
$file->addValidations(array(
// Ensure file is of type "image/png"
new \Upload\Validation\Mimetype('image/png'),
// Ensure file is no larger than 5M (use "B", "K", M", or "G")
new \Upload\Validation\Size('5M')
));
// Access data about the file that has been uploaded
$data = array(
'name' => $file->getNameWithExtension(),
'extension' => $file->getExtension(),
'mime' => $file->getMimetype(),
'size' => $file->getSize(),
'md5' => $file->getMd5(),
'dimensions' => $file->getDimensions()
);
// Try to upload file
try {
// Success!
$file->upload();
} catch (\Exception $e) {
// Fail!
$errors = $file->getErrors();
}
## How to Install
Install composer in your project:
curl -s https://getcomposer.org/installer | php
Create a composer.json file in your project root:
{
"require": {
"codeguy/upload": "*"
}
}
Install via composer:
php composer.phar install
## Author
[Josh Lockhart](https://github.com/codeguy)
## License
MIT Public License

25
vendor/codeguy/upload/composer.json vendored Normal file
View file

@ -0,0 +1,25 @@
{
"name": "codeguy/upload",
"type": "library",
"description": "Handle file uploads with extensible validation and storage strategies",
"keywords": ["upload", "validation", "file"],
"homepage": "http://github.com/codeguy/Upload",
"license": "MIT",
"authors": [
{
"name": "Josh Lockhart",
"email": "info@joshlockhart.com",
"homepage": "https://github.com/codeguy/"
}
],
"require": {
"php": ">=5.3.0",
"ext-fileinfo": "*"
},
"require-dev": {
"phpunit/phpunit": "3.7.*"
},
"autoload": {
"psr-0": { "Upload": "src" }
}
}

21
vendor/codeguy/upload/phpunit.xml vendored Normal file
View file

@ -0,0 +1,21 @@
<phpunit backupGlobals="true"
backupStaticAttributes="false"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false"
syntaxCheck="false"
bootstrap="tests/bootstrap.php">
<testsuites>
<testsuite name="Upload Test Suite">
<directory>./tests/</directory>
</testsuite>
</testsuites>
<filter>
<whitelist>
<directory>./src/Upload/</directory>
</whitelist>
</filter>
</phpunit>

View file

@ -0,0 +1,77 @@
<?php
/**
* Upload
*
* @author Josh Lockhart <info@joshlockhart.com>
* @copyright 2012 Josh Lockhart
* @link http://www.joshlockhart.com
* @version 1.0.0
*
* MIT LICENSE
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Upload;
/**
* Autoloader
*
* This class provides a default PSR-0 autoloader if not using Composer.
*
* @author Josh Lockhart <info@joshlockhart.com>
* @since 1.0.0
* @package Upload
*/
class Autoloader
{
/**
* The project's base directory
* @var string
*/
static protected $base;
/**
* Register autoloader
*/
static public function register()
{
self::$base = dirname(__FILE__) . '/../';
spl_autoload_register(array(new self, 'autoload'));
}
/**
* Autoload classname
* @param string $className The class to load
*/
static public function autoload($className)
{
$className = ltrim($className, '\\');
$fileName = '';
$namespace = '';
if ($lastNsPos = strripos($className, '\\')) {
$namespace = substr($className, 0, $lastNsPos);
$className = substr($className, $lastNsPos + 1);
$fileName = str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;
}
$fileName .= str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';
require self::$base . $fileName;
}
}

View file

@ -0,0 +1,7 @@
<?php
namespace Upload\Exception;
class UploadException extends \RuntimeException
{
}

View file

@ -0,0 +1,381 @@
<?php
/**
* Upload
*
* @author Josh Lockhart <info@joshlockhart.com>
* @copyright 2012 Josh Lockhart
* @link http://www.joshlockhart.com
* @version 1.0.0
*
* MIT LICENSE
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Upload;
/**
* File
*
* This class provides the implementation for an uploaded file. It exposes
* common attributes for the uploaded file (e.g. name, extension, media type)
* and allows you to attach validations to the file that must pass for the
* upload to succeed.
*
* @author Josh Lockhart <info@joshlockhart.com>
* @since 1.0.0
* @package Upload
*/
class File extends \SplFileInfo
{
/********************************************************************************
* Static Properties
*******************************************************************************/
/**
* Upload error code messages
* @var array
*/
protected static $errorCodeMessages = array(
1 => 'The uploaded file exceeds the upload_max_filesize directive in php.ini',
2 => 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form',
3 => 'The uploaded file was only partially uploaded',
4 => 'No file was uploaded',
6 => 'Missing a temporary folder',
7 => 'Failed to write file to disk',
8 => 'A PHP extension stopped the file upload'
);
/**
* Lookup hash to convert file units to bytes
* @var array
*/
protected static $units = array(
'b' => 1,
'k' => 1024,
'm' => 1048576,
'g' => 1073741824
);
/********************************************************************************
* Instance Properties
*******************************************************************************/
/**
* Storage delegate
* @var \Upload\Storage\Base
*/
protected $storage;
/**
* Validations
* @var array[\Upload\Validation\Base]
*/
protected $validations;
/**
* Validation errors
* @var array
*/
protected $errors;
/**
* Original file name provided by client (for internal use only)
* @var string
*/
protected $originalName;
/**
* File name (without extension)
* @var string
*/
protected $name;
/**
* File extension (without leading dot)
* @var string
*/
protected $extension;
/**
* File mimetype (e.g. "image/png")
* @var string
*/
protected $mimetype;
/**
* Upload error code (for internal use only)
* @var int
* @link http://www.php.net/manual/en/features.file-upload.errors.php
*/
protected $errorCode;
/**
* Constructor
* @param string $key The file's key in $_FILES superglobal
* @param \Upload\Storage\Base $storage The method with which to store file
* @throws \Upload\Exception\UploadException If file uploads are disabled in the php.ini file
* @throws \InvalidArgumentException If $_FILES key does not exist
*/
public function __construct($key, \Upload\Storage\Base $storage)
{
if (!isset($_FILES[$key])) {
throw new \InvalidArgumentException("Cannot find uploaded file identified by key: $key");
}
$this->storage = $storage;
$this->validations = array();
$this->errors = array();
$this->originalName = $_FILES[$key]['name'];
$this->errorCode = $_FILES[$key]['error'];
parent::__construct($_FILES[$key]['tmp_name']);
}
/**
* Get name
* @return string
*/
public function getName()
{
if (!isset($this->name)) {
$this->name = pathinfo($this->originalName, PATHINFO_FILENAME);
}
return $this->name;
}
/**
* Set name (without extension)
* @param string $name
* @return \Upload\File Self
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get file name with extension
* @return string
*/
public function getNameWithExtension()
{
return sprintf('%s.%s', $this->getName(), $this->getExtension());
}
/**
* Get file extension (without leading dot)
* @return string
*/
public function getExtension()
{
if (!isset($this->extension)) {
$this->extension = strtolower(pathinfo($this->originalName, PATHINFO_EXTENSION));
}
return $this->extension;
}
/**
* Get mimetype
* @return string
*/
public function getMimetype()
{
if (!isset($this->mimeType)) {
$finfo = new \finfo(FILEINFO_MIME);
$mimetype = $finfo->file($this->getPathname());
$mimetypeParts = preg_split('/\s*[;,]\s*/', $mimetype);
$this->mimetype = strtolower($mimetypeParts[0]);
unset($finfo);
}
return $this->mimetype;
}
/**
* Get md5
* @return string
*/
public function getMd5()
{
return md5_file($this->getPathname());
}
/**
* Get image dimensions
* @return array formatted array of dimensions
*/
public function getDimensions()
{
list($width, $height) = getimagesize($this->getPathname());
return array(
'width' => $width,
'height' => $height
);
}
/********************************************************************************
* Validate
*******************************************************************************/
/**
* Add file validations
* @param \Upload\Validation\Base|array[\Upload\Validation\Base] $validations
*/
public function addValidations($validations)
{
if (!is_array($validations)) {
$validations = array($validations);
}
foreach ($validations as $validation) {
if ($validation instanceof \Upload\Validation\Base) {
$this->validations[] = $validation;
}
}
}
/**
* Get file validations
* @return array[\Upload\Validation\Base]
*/
public function getValidations()
{
return $this->validations;
}
/**
* Validate file
* @return bool True if valid, false if invalid
*/
public function validate()
{
// Validate is uploaded OK
if ($this->isOk() === false) {
$this->errors[] = self::$errorCodeMessages[$this->errorCode];
}
// Validate is uploaded file
if ($this->isUploadedFile() === false) {
$this->errors[] = 'The uploaded file was not sent with a POST request';
}
// User validations
foreach ($this->validations as $validation) {
if ($validation->validate($this) === false) {
$this->errors[] = $validation->getMessage();
}
}
return empty($this->errors);
}
/**
* Get file validation errors
* @return array[String]
*/
public function getErrors()
{
return $this->errors;
}
/**
* Add file validation error
* @param string
* @return \Upload\File Self
*/
public function addError($error)
{
$this->errors[] = $error;
return $this;
}
/********************************************************************************
* Upload
*******************************************************************************/
/**
* Upload file (delegated to storage object)
* @param string $newName Give the file it a new name
* @return bool
* @throws \Upload\Exception\UploadException If file does not validate
*/
public function upload($newName = null)
{
if ($this->validate() === false) {
throw new \Upload\Exception\UploadException('File validation failed');
}
// Update the name, leaving out the extension
if (is_string($newName)) {
$this->name = pathinfo($newName, PATHINFO_FILENAME);
}
return $this->storage->upload($this, $newName);
}
/********************************************************************************
* Helpers
*******************************************************************************/
/**
* Is this file uploaded with a POST request?
*
* This is a separate method so that it can be stubbed in unit tests to avoid
* the hard dependency on the `is_uploaded_file` function.
*
* @return bool
*/
public function isUploadedFile()
{
return is_uploaded_file($this->getPathname());
}
/**
* Is this file OK?
*
* This method inspects the upload error code to see if the upload was
* successful or if it failed for a variety of reasons.
*
* @link http://www.php.net/manual/en/features.file-upload.errors.php
* @return bool
*/
public function isOk()
{
return ($this->errorCode === UPLOAD_ERR_OK);
}
/**
* Convert human readable file size (e.g. "10K" or "3M") into bytes
* @param string $input
* @return int
*/
public static function humanReadableToBytes($input)
{
$number = (int)$input;
$unit = strtolower(substr($input, -1));
if (isset(self::$units[$unit])) {
$number = $number * self::$units[$unit];
}
return $number;
}
}

View file

@ -0,0 +1,45 @@
<?php
/**
* Upload
*
* @author Josh Lockhart <info@joshlockhart.com>
* @copyright 2012 Josh Lockhart
* @link http://www.joshlockhart.com
* @version 1.0.0
*
* MIT LICENSE
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Upload\Storage;
/**
* Upload Storage Base
*
* This class defines the interface that must be implemented by each
* concrete Upload storage subclass.
*
* @author Josh Lockhart <info@joshlockhart.com>
* @since 1.0.0
*/
abstract class Base
{
abstract public function upload(\Upload\File $file, $newName = null);
}

View file

@ -0,0 +1,114 @@
<?php
/**
* Upload
*
* @author Josh Lockhart <info@joshlockhart.com>
* @copyright 2012 Josh Lockhart
* @link http://www.joshlockhart.com
* @version 1.0.0
*
* MIT LICENSE
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Upload\Storage;
/**
* FileSystem Storage
*
* This class uploads files to a designated directory on the filesystem.
*
* @author Josh Lockhart <info@joshlockhart.com>
* @since 1.0.0
* @package Upload
*/
class FileSystem extends \Upload\Storage\Base
{
/**
* Upload directory
* @var string
*/
protected $directory;
/**
* Overwrite existing files?
* @var bool
*/
protected $overwrite;
/**
* Constructor
* @param string $directory Relative or absolute path to upload directory
* @param bool $overwrite Should this overwrite existing files?
* @throws \InvalidArgumentException If directory does not exist
* @throws \InvalidArgumentException If directory is not writable
*/
public function __construct($directory, $overwrite = false)
{
if (!is_dir($directory)) {
throw new \InvalidArgumentException('Directory does not exist');
}
if (!is_writable($directory)) {
throw new \InvalidArgumentException('Directory is not writable');
}
$this->directory = rtrim($directory, '/') . DIRECTORY_SEPARATOR;
$this->overwrite = $overwrite;
}
/**
* Upload
* @param \Upload\File $file The file object to upload
* @param string $newName Give the file it a new name
* @return bool
* @throws \RuntimeException If overwrite is false and file already exists
*/
public function upload(\Upload\File $file, $newName = null)
{
if (is_string($newName)) {
$fileName = strpos($newName, '.') ? $newName : $newName.'.'.$file->getExtension();
} else {
$fileName = $file->getNameWithExtension();
}
$newFile = $this->directory . $fileName;
if ($this->overwrite === false && file_exists($newFile)) {
$file->addError('File already exists');
throw new \Upload\Exception\UploadException('File already exists');
}
return $this->moveUploadedFile($file->getPathname(), $newFile);
}
/**
* Move uploaded file
*
* This method allows us to stub this method in unit tests to avoid
* hard dependency on the `move_uploaded_file` function.
*
* @param string $source The source file
* @param string $destination The destination file
* @return bool
*/
protected function moveUploadedFile($source, $destination)
{
return move_uploaded_file($source, $destination);
}
}

View file

@ -0,0 +1,75 @@
<?php
/**
* Upload
*
* @author Josh Lockhart <info@joshlockhart.com>
* @copyright 2012 Josh Lockhart
* @link http://www.joshlockhart.com
* @version 1.0.0
*
* MIT LICENSE
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Upload\Validation;
/**
* Upload Validation Base
*
* This class provides the common implementation and abstract interface
* for all concrete Upload validation subclasses.
*
* @author Josh Lockhart <info@joshlockhart.com>
* @since 1.0.0
* @package Upload
*/
abstract class Base
{
/**
* The error message for this validation
* @var string
*/
protected $message;
/**
* Set error message
* @param string $message
*/
public function setMessage($message)
{
$this->message = $message;
}
/**
* Get error message
* @return string
*/
public function getMessage()
{
return $this->message;
}
/**
* Validate file
* @param \Upload\File $file
* @return bool True if file is valid, false if file is not valid
*/
abstract public function validate(\Upload\File $file);
}

View file

@ -0,0 +1,95 @@
<?php
/**
* Upload
*
* @author Josh Lockhart <info@joshlockhart.com>
* @copyright 2012 Josh Lockhart
* @link http://www.joshlockhart.com
* @version 1.0.0
*
* MIT LICENSE
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Upload\Validation;
/**
* Validate File Extension
*
* This class validates an uploads file extension. It takes file extension with out dot
* or array of extensions. For example: 'png' or array('jpg', 'png', 'gif').
*
* WARING! Validation only by file extension not very secure.
*
* @author Alex Kucherenko <kucherenko.email@gmail.com>
* @package Upload
*/
class Extension extends \Upload\Validation\Base
{
/**
* Array of cceptable file extensions without leading dots
* @var array
*/
protected $allowedExtensions;
/**
* Error message
* @var string
*/
protected $message = 'Invalid file extension. Must be one of: %s';
/**
* Constructor
*
* @param string|array $allowedExtensions Allowed file extensions
* @example new \Upload\Validation\Extension(array('png','jpg','gif'))
* @example new \Upload\Validation\Extension('png')
*/
public function __construct($allowedExtensions)
{
if (is_string($allowedExtensions)) {
$allowedExtensions = array($allowedExtensions);
}
array_filter($allowedExtensions, function ($val) {
return strtolower($val);
});
$this->allowedExtensions = $allowedExtensions;
}
/**
* Validate
* @param \Upload\File $file
* @return bool
*/
public function validate(\Upload\File $file)
{
$fileExtension = strtolower($file->getExtension());
$isValid = true;
if (!in_array($fileExtension, $this->allowedExtensions)) {
$this->setMessage(sprintf($this->message, implode(', ', $this->allowedExtensions)));
$isValid = false;
}
return $isValid;
}
}

View file

@ -0,0 +1,77 @@
<?php
/**
* Upload
*
* @author Josh Lockhart <info@joshlockhart.com>
* @copyright 2012 Josh Lockhart
* @link http://www.joshlockhart.com
* @version 1.0.0
*
* MIT LICENSE
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Upload\Validation;
/**
* Validate Upload Media Type
*
* This class validates an upload's media type (e.g. "image/png").
*
* @author Josh Lockhart <info@joshlockhart.com>
* @since 1.0.0
* @package Upload
*/
class Mimetype extends \Upload\Validation\Base
{
/**
* Valid media types
* @var array
*/
protected $mimetypes;
/**
* Error message
* @var string
*/
protected $message = 'Invalid mimetype';
/**
* Constructor
* @param array $mimetypes Array of valid mimetypes
*/
public function __construct($mimetypes)
{
if (!is_array($mimetypes)) {
$mimetypes = array($mimetypes);
}
$this->mimetypes = $mimetypes;
}
/**
* Validate
* @param \Upload\File $file
* @return bool
*/
public function validate(\Upload\File $file)
{
return in_array($file->getMimetype(), $this->mimetypes);
}
}

View file

@ -0,0 +1,104 @@
<?php
/**
* Upload
*
* @author Josh Lockhart <info@joshlockhart.com>
* @copyright 2012 Josh Lockhart
* @link http://www.joshlockhart.com
* @version 1.0.0
*
* MIT LICENSE
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Upload\Validation;
/**
* Validate Upload File Size
*
* This class validates an uploads file size using maximum and (optionally)
* minimum file size bounds (inclusive). Specify acceptable file sizes
* as an integer (in bytes) or as a human-readable string (e.g. "5MB").
*
* @author Josh Lockhart <info@joshlockhart.com>
* @since 1.0.0
* @package Upload
*/
class Size extends \Upload\Validation\Base
{
/**
* Minimum acceptable file size (bytes)
* @var int
*/
protected $minSize;
/**
* Maximum acceptable file size (bytes)
* @var int
*/
protected $maxSize;
/**
* Error message
* @var string
*/
protected $message = 'Invalid file size';
/**
* Constructor
* @param int $maxSize Maximum acceptable file size in bytes (inclusive)
* @param int $minSize Minimum acceptable file size in bytes (inclusive)
*/
public function __construct($maxSize, $minSize = 0)
{
if (is_string($maxSize)) {
$maxSize = \Upload\File::humanReadableToBytes($maxSize);
}
$this->maxSize = $maxSize;
if (is_string($minSize)) {
$minSize = \Upload\File::humanReadableToBytes($minSize);
}
$this->minSize = $minSize;
}
/**
* Validate
* @param \Upload\File $file
* @return bool
*/
public function validate(\Upload\File $file)
{
$fileSize = $file->getSize();
$isValid = true;
if ($fileSize < $this->minSize) {
$this->setMessage('File size is too small');
$isValid = false;
}
if ($fileSize > $this->maxSize) {
$this->setMessage('File size is too large');
$isValid = false;
}
return $isValid;
}
}

176
vendor/codeguy/upload/tests/FileTest.php vendored Normal file
View file

@ -0,0 +1,176 @@
<?php
class FileTest extends PHPUnit_Framework_TestCase
{
protected $assetsDirectory;
protected $storage;
/********************************************************************************
* Setup
*******************************************************************************/
public function setUp()
{
$this->assetsDirectory = dirname(__FILE__) . '/assets';
$_FILES['foo'] = array(
'name' => 'foo.txt',
'tmp_name' => $this->assetsDirectory . '/foo.txt',
'error' => UPLOAD_ERR_OK
);
}
public function getNewFile()
{
if (is_null($this->storage)) {
// Prepare storage
$this->storage = $this->getMock(
'\Upload\Storage\FileSystem',
array('upload'),
array($this->assetsDirectory)
);
$this->storage->expects($this->any())
->method('upload')
->will($this->returnValue(true));
}
// Prepare file
$file = $this->getMock(
'\Upload\File',
array('isUploadedFile'),
array('foo', $this->storage)
);
$file->expects($this->any())
->method('isUploadedFile')
->will($this->returnValue(true));
return $file;
}
/********************************************************************************
* Tests
*******************************************************************************/
/**
* @expectedException \InvalidArgumentException
*/
public function testConstructionWithInvalidKey()
{
$file = new \Upload\File('bar', new \Upload\Storage\FileSystem($this->assetsDirectory));
}
public function testGetName()
{
$file = $this->getNewFile();
$this->assertEquals('foo', $file->getName());
}
public function testGetNameWithExtension()
{
$file = $this->getNewFile();
$this->assertEquals('foo.txt', $file->getNameWithExtension());
}
public function testGetNameWithExtensionUsingCustomName()
{
$file = $this->getNewFile();
$file->setName('bar');
$this->assertEquals('bar.txt', $file->getNameWithExtension());
}
public function testGetMimetype()
{
$file = $this->getNewFile();
$this->assertEquals('text/plain', $file->getMimetype());
}
public function testAddValidationErrors()
{
$file = $this->getNewFile();
$file->addError('Error');
$this->assertEquals(1, count($file->getErrors()));
}
public function testIsValidIfNoValidations()
{
$file = $this->getNewFile();
$this->assertEmpty($file->getErrors());
}
public function testWillUploadIfNoValidations()
{
$file = $this->getNewFile();
$this->assertTrue($file->upload());
}
public function testAddValidations()
{
$file = $this->getNewFile();
$file->addValidations(new \Upload\Validation\Mimetype(array(
'text/plain'
)));
$this->assertEquals(1, count($file->getValidations()));
}
public function testWillUploadWithPassingValidations()
{
$file = $this->getNewFile();
$file->addValidations(new \Upload\Validation\Mimetype(array(
'text/plain'
)));
$this->assertTrue($file->upload());
}
/**
* @expectedException \Upload\Exception\UploadException
*/
public function testWillNotUploadWithFailingValidations()
{
$file = $this->getNewFile();
$file->addValidations(new \Upload\Validation\Mimetype(array(
'image/png'
)));
$file->upload();
}
public function testPopulatesErrorsWithFailingValidations()
{
$file = $this->getNewFile();
$file->addValidations(new \Upload\Validation\Mimetype(array(
'image/png'
)));
try {
$file->upload();
} catch(\Upload\Exception\UploadException $e) {
$this->assertEquals(1, count($file->getErrors()));
}
}
public function testValidationFailsIfUploadErrorCode()
{
$_FILES['foo']['error'] = 4;
$file = $this->getNewFile();
$this->assertFalse($file->validate());
}
public function testValidationFailsIfNotUploadedFile()
{
$file = $this->getMock(
'\Upload\File',
array('isUploadedFile'),
array('foo', new \Upload\Storage\FileSystem($this->assetsDirectory))
);
$file->expects($this->any())
->method('isUploadedFile')
->will($this->returnValue(false));
$this->assertFalse($file->validate());
}
public function testParsesHumanFriendlyFileSizes()
{
$this->assertEquals(100, \Upload\File::humanReadableToBytes('100'));
$this->assertEquals(102400, \Upload\File::humanReadableToBytes('100K'));
$this->assertEquals(104857600, \Upload\File::humanReadableToBytes('100M'));
$this->assertEquals(107374182400, \Upload\File::humanReadableToBytes('100G'));
$this->assertEquals(100, \Upload\File::humanReadableToBytes('100F')); // <-- Unrecognized. Assume bytes.
}
}

View file

@ -0,0 +1,79 @@
<?php
class FileSystemTest extends PHPUnit_Framework_TestCase
{
/**
* Setup (each test)
*/
public function setUp()
{
// Path to test assets
$this->assetsDirectory = dirname(__DIR__) . '/assets';
// Reset $_FILES superglobal
$_FILES['foo'] = array(
'name' => 'foo.txt',
'tmp_name' => $this->assetsDirectory . '/foo.txt',
'error' => 0
);
}
public function testInstantiationWithValidDirectory()
{
try {
$storage = $this->getMock(
'\Upload\Storage\FileSystem',
array('upload'),
array($this->assetsDirectory)
);
} catch(\InvalidArgumentException $e) {
$this->fail('Unexpected argument thrown during instantiation with valid directory');
}
}
/**
* @expectedException \InvalidArgumentException
*/
public function testInstantiationWithInvalidDirectory()
{
$storage = $this->getMock(
'\Upload\Storage\FileSystem',
array('upload'),
array('/foo')
);
}
/**
* Test won't overwrite existing file
* @expectedException \RuntimeException
*/
public function testWillNotOverwriteFile()
{
$storage = new \Upload\Storage\FileSystem($this->assetsDirectory, false);
$file = new \Upload\File('foo', $storage);
$file->upload();
}
/**
* Test will overwrite existing file
*/
public function testWillOverwriteFile()
{
$storage = $this->getMock(
'\Upload\Storage\FileSystem',
array('moveUploadedFile'),
array($this->assetsDirectory, true)
);
$storage->expects($this->any())
->method('moveUploadedFile')
->will($this->returnValue(true));
$file = $this->getMock(
'\Upload\File',
array('isUploadedFile'),
array('foo', $storage)
);
$file->expects($this->any())
->method('isUploadedFile')
->will($this->returnValue(true));
$this->assertTrue($file->upload());
}
}

View file

@ -0,0 +1,43 @@
<?php
class ExtensionTest extends PHPUnit_Framework_TestCase
{
/**
* Setup (each test)
*/
public function setUp()
{
// Path to test assets
$this->assetsDirectory = dirname(__DIR__) . '/assets';
// Create stubbed storage instance
$this->storage = $this->getMock(
'\Upload\Storage\FileSystem',
array('upload'),
array($this->assetsDirectory)
);
$this->storage->expects($this->any())
->method('upload')
->will($this->returnValue(true));
// Reset $_FILES superglobal
$_FILES['foo'] = array(
'name' => 'foo.txt',
'tmp_name' => $this->assetsDirectory . '/foo.txt',
'error' => 0
);
}
public function testValidExtension()
{
$file = new \Upload\File('foo', $this->storage);
$validation = new \Upload\Validation\Extension('txt');
$this->assertTrue($validation->validate($file));
}
public function testInvalidExtension()
{
$file = new \Upload\File('foo', $this->storage);
$validation = new \Upload\Validation\Extension('csv');
$this->assertFalse($validation->validate($file));
}
}

View file

@ -0,0 +1,47 @@
<?php
class MimetypeTest extends PHPUnit_Framework_TestCase
{
/**
* Setup (each test)
*/
public function setUp()
{
// Path to test assets
$this->assetsDirectory = dirname(__DIR__) . '/assets';
// Create stubbed storage instance
$this->storage = $this->getMock(
'\Upload\Storage\FileSystem',
array('upload'),
array($this->assetsDirectory)
);
$this->storage->expects($this->any())
->method('upload')
->will($this->returnValue(true));
// Reset $_FILES superglobal
$_FILES['foo'] = array(
'name' => 'foo.txt',
'tmp_name' => $this->assetsDirectory . '/foo.txt',
'error' => 0
);
}
public function testValidMimetype()
{
$file = new \Upload\File('foo', $this->storage);
$validation = new \Upload\Validation\Mimetype(array(
'text/plain'
));
$this->assertTrue($validation->validate($file));
}
public function testInvalidMimetype()
{
$file = new \Upload\File('foo', $this->storage);
$validation = new \Upload\Validation\Mimetype(array(
'image/png'
));
$this->assertFalse($validation->validate($file));
}
}

View file

@ -0,0 +1,57 @@
<?php
class SizeTest extends PHPUnit_Framework_TestCase
{
/**
* Setup (each test)
*/
public function setUp()
{
// Path to test assets
$this->assetsDirectory = dirname(__DIR__) . '/assets';
// Create stubbed storage instance
$this->storage = $this->getMock(
'\Upload\Storage\FileSystem',
array('upload'),
array($this->assetsDirectory)
);
$this->storage->expects($this->any())
->method('upload')
->will($this->returnValue(true));
// Reset $_FILES superglobal
$_FILES['foo'] = array(
'name' => 'foo.txt',
'tmp_name' => $this->assetsDirectory . '/foo.txt',
'error' => 0
);
}
public function testValidFileSize()
{
$file = new \Upload\File('foo', $this->storage);
$validation = new \Upload\Validation\Size(500);
$this->assertTrue($validation->validate($file));
}
public function testValidFileSizeWithHumanReadableArgument()
{
$file = new \Upload\File('foo', $this->storage);
$validation = new \Upload\Validation\Size('500B');
$this->assertTrue($validation->validate($file));
}
public function testInvalidFileSize()
{
$file = new \Upload\File('foo', $this->storage);
$validation = new \Upload\Validation\Size(400);
$this->assertFalse($validation->validate($file));
}
public function testInvalidFileSizeWithHumanReadableArgument()
{
$file = new \Upload\File('foo', $this->storage);
$validation = new \Upload\Validation\Size('400B');
$this->assertFalse($validation->validate($file));
}
}

View file

@ -0,0 +1,6 @@
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

View file

@ -0,0 +1,3 @@
<?php
require dirname(__FILE__) . '/../src/Upload/Autoloader.php';
\Upload\Autoloader::register();