Skip to content
This repository has been archived by the owner on May 5, 2024. It is now read-only.

Creating a translation class which enables the usage of translated error messages #70

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,34 @@ When the HTML form is submitted, the server-side PHP code can validate and uploa
$errors = $file->getErrors();
}

If you need to use translated messages, you can pass a translation object to the objects, like this:

<?php
$translation = new \Upload\Translation('pt-BR');
$storage = new \Upload\Storage\FileSystem('/path/to/directory', $translation);
$file = new \Upload\File('foo', $storage, $translation);

// Validate file upload
$file->addValidations(array(
// Ensure file is of type "image/png"
new \Upload\Validation\Mimetype('image/png', $translation),

// Ensure file has correct extension
new \Upload\Validation\Extension('png', $translation),

// Ensure file is no larger than 5M (use "B", "K", M", or "G")
new \Upload\Validation\Size('5M', 0, $translation)
));

// Try to upload file
try {
// Success!
$file->upload();
} catch (\Exception $e) {
// Fail!
$errors = $file->getErrors();
}

## How to Install

Install composer in your project:
Expand Down
34 changes: 29 additions & 5 deletions src/Upload/File.php
Original file line number Diff line number Diff line change
Expand Up @@ -126,17 +126,26 @@ class File extends \SplFileInfo
*/
protected $errorCode;

/**
* Translation object
* @var \Upload\Translation
*/
protected $translation;

/**
* 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)
public function __construct($key, \Upload\Storage\Base $storage, \Upload\Translation $translation = null)
{
$this->translation = $translation;

if (!isset($_FILES[$key])) {
throw new \InvalidArgumentException("Cannot find uploaded file identified by key: $key");
$message = $this->getTranslation("Cannot find uploaded file identified by key: %s", array($key));
throw new \InvalidArgumentException($message);
}
$this->storage = $storage;
$this->validations = array();
Expand Down Expand Up @@ -247,12 +256,12 @@ public function validate()
{
// Validate is uploaded OK
if ($this->isOk() === false) {
$this->errors[] = self::$errorCodeMessages[$this->errorCode];
$this->errors[] = $this->getTranslation(self::$errorCodeMessages[$this->errorCode]);
}

// Validate is uploaded file
if ($this->isUploadedFile() === false) {
$this->errors[] = 'The uploaded file was not sent with a POST request';
$this->errors[] = $this->getTranslation('The uploaded file was not sent with a POST request');
}

// User validations
Expand Down Expand Up @@ -299,7 +308,7 @@ public function addError($error)
public function upload($newName = null)
{
if ($this->validate() === false) {
throw new \Upload\Exception\UploadException('File validation failed');
throw new \Upload\Exception\UploadException($this->getTranslation('File validation failed'));
}

// Update the name, leaving out the extension
Expand Down Expand Up @@ -354,4 +363,19 @@ public static function humanReadableToBytes($input)

return $number;
}

/**
* Get the translated message
* @param string $key Message key
* @param array $params List of positional placeholders values
* @return string
*/
protected function getTranslation($key, array $params = array())
{
if ($this->translation === null) {
return vsprintf($key, $params);
}

return $this->translation->getMessage($key, $params);
}
}
22 changes: 22 additions & 0 deletions src/Upload/Language/en.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?php

return array(
'The uploaded file exceeds the upload_max_filesize directive in php.ini' => 'The uploaded file exceeds the upload_max_filesize directive in php.ini',
'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form' => 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form',
'The uploaded file was only partially uploaded' => 'The uploaded file was only partially uploaded',
'No file was uploaded' => 'No file was uploaded',
'Missing a temporary folder' => 'Missing a temporary folder',
'Failed to write file to disk' => 'Failed to write file to disk',
'A PHP extension stopped the file upload' => 'A PHP extension stopped the file upload',
'Cannot find uploaded file identified by key: %s' => 'Cannot find uploaded file identified by key: %s',
'The uploaded file was not sent with a POST request' => 'The uploaded file was not sent with a POST request',
'File validation failed' => 'File validation failed',
'Invalid file extension. Must be one of: %s' => 'Invalid file extension. Must be one of: %s',
'Invalid mimetype' => 'Invalid mimetype',
'Invalid file size' => 'Invalid file size',
'File size is too small' => 'File size is too small',
'File size is too large' => 'File size is too large',
'Directory does not exist' => 'Directory does not exist',
'Directory is not writable' => 'Directory is not writable',
'File already exists' => 'File already exists'
);
22 changes: 22 additions & 0 deletions src/Upload/Language/pt-BR.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?php

return array(
'The uploaded file exceeds the upload_max_filesize directive in php.ini' => 'O tamanho do arquivo enviado excede o tamanho permitido pela diretiva upload_max_filesize do php.ini',
'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form' => 'O tamanho do arquivo enviado excede a diretiva MAX_FILE_SIZE especificada no formulário HTML',
'The uploaded file was only partially uploaded' => 'Arquivo parcialmente enviado',
'No file was uploaded' => 'Nenhum arquivo enviado',
'Missing a temporary folder' => 'Nenhum diretório temporário encontrado',
'Failed to write file to disk' => 'Falha ao gravar o arquivo em disco',
'A PHP extension stopped the file upload' => 'Uma extensão PHP parou o envio do arquivo',
'Cannot find uploaded file identified by key: %s' => 'Não foi possível encontrar o arquivo enviado com a chave: %s',
'The uploaded file was not sent with a POST request' => 'O arquivo não foi enviado utilizando o método POST',
'File validation failed' => 'Validação do arquivo falhou',
'Invalid file extension. Must be one of: %s' => 'Extensão de arquivo inválida. Deve ser uma das: %s',
'Invalid mimetype' => 'Mimetype inválido',
'Invalid file size' => 'Tamanho de arquivo inválido',
'File size is too small' => 'Tamanho do arquivo muito pequeno',
'File size is too large' => 'Tamanho do arquivo muito grande',
'Directory does not exist' => 'Diretório não existe',
'Directory is not writable' => 'Diretório sem permissão de escrita',
'File already exists' => 'Arquivo já existe'
);
21 changes: 21 additions & 0 deletions src/Upload/Storage/Base.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,5 +41,26 @@
*/
abstract class Base
{
/**
* Translation object
* @var \Upload\Translation
*/
protected $translation;

/**
* Get the translated message
* @param string $key Message key
* @param array $params List of positional placeholders values
* @return string
*/
protected function getTranslation($key, array $params = array())
{
if ($this->translation === null) {
return vsprintf($key, $params);
}

return $this->translation->getMessage($key, $params);
}

abstract public function upload(\Upload\File $file, $newName = null);
}
12 changes: 7 additions & 5 deletions src/Upload/Storage/FileSystem.php
Original file line number Diff line number Diff line change
Expand Up @@ -60,13 +60,15 @@ class FileSystem extends \Upload\Storage\Base
* @throws \InvalidArgumentException If directory does not exist
* @throws \InvalidArgumentException If directory is not writable
*/
public function __construct($directory, $overwrite = false)
public function __construct($directory, $overwrite = false, \Upload\Translation $translation = null)
{
$this->translation = $translation;

if (!is_dir($directory)) {
throw new \InvalidArgumentException('Directory does not exist');
throw new \InvalidArgumentException($this->getTranslation('Directory does not exist'));
}
if (!is_writable($directory)) {
throw new \InvalidArgumentException('Directory is not writable');
throw new \InvalidArgumentException($this->getTranslation('Directory is not writable'));
}
$this->directory = rtrim($directory, '/') . DIRECTORY_SEPARATOR;
$this->overwrite = $overwrite;
Expand All @@ -90,8 +92,8 @@ public function upload(\Upload\File $file, $newName = null)

$newFile = $this->directory . $fileName;
if ($this->overwrite === false && file_exists($newFile)) {
$file->addError('File already exists');
throw new \Upload\Exception\UploadException('File already exists');
$file->addError($this->getTranslation('File already exists'));
throw new \Upload\Exception\UploadException($this->getTranslation('File already exists'));
}

return $this->moveUploadedFile($file->getPathname(), $newFile);
Expand Down
90 changes: 90 additions & 0 deletions src/Upload/Translation.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
<?php
/**
* Upload
*
* @author Josh Lockhart <[email protected]>
* @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;

/**
* Translation
*
* This class provides the implementation for translated messages.
*
* @author Ramiro Varandas Jr <[email protected]>
* @package Upload
*/
class Translation
{
/**
* Translation messages
* @var array
*/
protected $messages;

/**
* Constructor
* @param string $language Language prefix (i.e.: en, pt, pt-BR)
* @throws \InvalidArgumentException If translation file does not exist
*/
public function __construct($language)
{
$this->loadTranslationFile($language);
}

/**
* Load a translation file containing the messages used by the library
* @param string $language
* @throws \InvalidArgumentException If translation file does not exist
*/
protected function loadTranslationFile($language)
{
$filename = __DIR__ . "/Language/${language}.php";

if (file_exists($filename) === false) {
throw new \InvalidArgumentException("Cannot find translation file for language: $language");
}

$this->messages = require $filename;
}

/**
* Get a translation message
* @param string $key Message key
* @param array $params Array containing positional placeholders values
* @return string
*/
public function getMessage($key, $params = array())
{
if (array_key_exists($key, $this->messages) === true) {
return vsprintf($this->messages[$key], $params);
} else {
return $key;
}
}

}
21 changes: 21 additions & 0 deletions src/Upload/Validation/Base.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,12 @@ abstract class Base
*/
protected $message;

/**
* Translation object
* @var \Upload\Translation
*/
protected $translation;

/**
* Set error message
* @param string $message
Expand All @@ -66,6 +72,21 @@ public function getMessage()
return $this->message;
}

/**
* Get the translated message
* @param string $key Message key
* @param array $params List of positional placeholders values
* @return string
*/
protected function getTranslation($key, array $params = array())
{
if ($this->translation === null) {
return vsprintf($key, $params);
}

return $this->translation->getMessage($key, $params);
}

/**
* Validate file
* @param \Upload\File $file
Expand Down
7 changes: 5 additions & 2 deletions src/Upload/Validation/Extension.php
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,10 @@ class Extension extends \Upload\Validation\Base
* @example new \Upload\Validation\Extension(array('png','jpg','gif'))
* @example new \Upload\Validation\Extension('png')
*/
public function __construct($allowedExtensions)
public function __construct($allowedExtensions, \Upload\Translation $translation = null)
{
$this->translation = $translation;

if (is_string($allowedExtensions)) {
$allowedExtensions = array($allowedExtensions);
}
Expand All @@ -86,7 +88,8 @@ public function validate(\Upload\File $file)
$isValid = true;

if (!in_array($fileExtension, $this->allowedExtensions)) {
$this->setMessage(sprintf($this->message, implode(', ', $this->allowedExtensions)));
$extensions = array(implode(', ', $this->allowedExtensions));
$this->setMessage($this->getTranslation($this->message, $extensions));
$isValid = false;
}

Expand Down
5 changes: 4 additions & 1 deletion src/Upload/Validation/Mimetype.php
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,11 @@ class Mimetype extends \Upload\Validation\Base
* Constructor
* @param array $mimetypes Array of valid mimetypes
*/
public function __construct($mimetypes)
public function __construct($mimetypes, \Upload\Translation $translation = null)
{
$this->translation = $translation;
$this->message = $this->getTranslation($this->message);

if (!is_array($mimetypes)) {
$mimetypes = array($mimetypes);
}
Expand Down
9 changes: 6 additions & 3 deletions src/Upload/Validation/Size.php
Original file line number Diff line number Diff line change
Expand Up @@ -66,8 +66,11 @@ class Size extends \Upload\Validation\Base
* @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)
public function __construct($maxSize, $minSize = 0, \Upload\Translation $translation = null)
{
$this->translation = $translation;
$this->message = $this->getTranslation($this->message);

if (is_string($maxSize)) {
$maxSize = \Upload\File::humanReadableToBytes($maxSize);
}
Expand All @@ -90,12 +93,12 @@ public function validate(\Upload\File $file)
$isValid = true;

if ($fileSize < $this->minSize) {
$this->setMessage('File size is too small');
$this->setMessage($this->getTranslation('File size is too small'));
$isValid = false;
}

if ($fileSize > $this->maxSize) {
$this->setMessage('File size is too large');
$this->setMessage($this->getTranslation('File size is too large'));
$isValid = false;
}

Expand Down
Loading