Skip to content

Commit

Permalink
2017-02-23 1836
Browse files Browse the repository at this point in the history
  • Loading branch information
allanmcarvalho committed Feb 23, 2017
1 parent cec9586 commit 83a2416
Show file tree
Hide file tree
Showing 6 changed files with 577 additions and 164 deletions.
149 changes: 145 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,11 +1,152 @@
# Upload plugin for CakePHP

## Installation
**Upload plugin for CakePHP 3.x**
=============================
By [Allan Carvalho](https://www.facebook.com/Allan.Mariucci.Carvalho)
---------------------------------------------------------------------

You can install this plugin into your CakePHP application using [composer](http://getcomposer.org).
# **Installation**

### 1. Installing dependency
You can install this plugin into your CakePHP application using [`composer`](http://getcomposer.org).
The recommended way to install composer packages is:
```bacth
composer require allanmcarvalho/upload
```

### 2. Loading plugin

In `App\config\bootstrap.php`
```php
Plugin::load('Upload', ['bootstrap' => true]);
```
composer allanmcarvalho/upload

# **Basic usage**

#### **1** - You should open the table and then add the `behavior` of the plugin **Upload**.


```php
// in App\Model\Table\ExamplesTable.php
class ExamplesTable extends Table
{
...
public function initialize(array $config)
{
parent::initialize($config);

$this->addBehavior('Upload.Upload', [
'file1' => [],
'file2' => []
]);
}
...
```
> **Note:**
> Just adding the `Upload.Upload` **Behavior** does not mean it's ready, in fact, if you just add, nothing will happen. You must define which table columns are going to be responsible for storing the file name as shown above (`file1` and `file2`).
####**2** - Now should open the view from the form and configure the `form` and `input` to be of the file type.

```php
// in App\Template\Controller\add.ctp
...
<?= $this->Form->create($example, ['type' => 'file']) ?>
<?= $this->Form->control('title') ?>
<?= $this->Form->control('file1', ['type' => 'file']) ?>
<?= $this->Form->control('file2', ['type' => 'file']) ?>
<?= $this->Form->button(__('Submit')) ?>
<?= $this->Form->end() ?>
...
```

### Available **Behavior** settings

- **path:**

```php
// in App\Model\Table\ExamplesTable.php

$this->addBehavior('Upload.Upload', [
'file1' => [
'path' => WWW_ROOT . 'img' . DS,
'prefix' => 'example_'
]
]);
```
> **Options**
>
> - **path:** The path where that file will be saved.
>> **Note:**
>> When `path` is not provided, the default is `WWW_ROOT . 'files' . DS . $this->table->getAlias() . DS` or `WWW_ROOT . 'img' . DS . $this->table->getAlias() . DS` when the `image` setting is set.
>
> - **prefix:** A prefix to be added to the image file name. Default: **Does not have**;

----------


- **image:** Set of settings for image uploads;

```php
// in App\Model\Table\ExamplesTable.php

$this->addBehavior('Upload.Upload', [
'file1' => [
'image' => [
'format' => 'jpg',
'quality' => 75,
'watermark' => WWW_ROOT . 'img' . DS . 'watermark.png',
'watermark_position' => 'bottom-right'
'thumbnails' => [ // Optional
[
'width' => 450,
'height' => 400,
],
[
'width' => 225,
'height' => 200,
'watermark' => false;
]
],
],
'prefix' => 'cover_'
]
]);
```
> **Image options:**
>
> - **crop:** (optional) Crop the image. Default: **Does not have**;
- **width:** (required) The crop image width. Default: **Does not have**;
- **height:** (required) The crop image height. Default: **Does not have**;
- **format:** Image format. It can be (jpg, png, gif). Default: `jpg`;
- **quality:** Image quality from 1 to 100. Default: `100`;
- **resize:** (optional) Changes the image size. Default: **Does not have**;
- **width:** (optional) New image width. Default: **If height is set is automatic**;
- **height:** (optional) New image height. Default: **If width is set is automatic**;
- **crop:** (optional) Crop the new image. Default: **Does not have**;
- **width:** (required) New image crop width. Default:**Does not have**;
- **height:** (required) New image height. Default: **Does not have**;
- **thumbnails:** (optional) Setting to set thumbnails to be created. Default: **Does not have**;
- **width:** (required) Thumbnail width. Default: **Does not have**;
- **height:** (required) Thumbnail height. Default: **Does not have**;
- **watermark:** (optional) Sets whether the thumbnail will have the same watermark as the original image (if the original has). Default: `true`;
- **watermark:** (optional) Watermak full file path. Default: **Does not have**;
- **watermark_position:** (optional) Watermak orientation. Default: `bottom-right`. It can be:
- **top-left**
- **top**
- **top-right**
- **left**
- **center**
- **right**
- **bottom-left**
- **bottom**
- **bottom-right**


License


----------


MIT
135 changes: 106 additions & 29 deletions src/File/Writer/DefaultWriter.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,13 @@
use Cake\Filesystem\File;
use Cake\Filesystem\Folder;
use Cake\Utility\Hash;
use Intervention\Image\ImageManager;

/**
* Description of DefaultWriter
*
* @author allancarvalho
*/
class DefaultWriter implements WriterInterface
abstract class DefaultWriter implements WriterInterface
{

/**
Expand Down Expand Up @@ -59,11 +58,17 @@ class DefaultWriter implements WriterInterface
*/
protected $defaultPath = '';

/**
* Destination file path
* @var string
*/
protected $path = null;

/**
* Final file name
* @var string
*/
protected $fileName = null;
protected $filename = null;

/**
* Construct Method
Expand All @@ -78,62 +83,134 @@ public function __construct(Table $table, Entity $entity, $field, $settings)
$this->entity = $entity;
$this->field = $field;
$this->settings = $settings;
$this->fileInfo = $this->entity->get($this->field);
$this->fileInfo = (array) $this->entity->get($this->field);
$this->defaultPath = WWW_ROOT . 'files' . DS . $this->table->getAlias() . DS;
}

public function write()
/**
* Delete a file from path
* @param string $PathAndFilename
* @return boolean
*/
protected function _delete($path, $filename)
{

$file = new File($path . $filename);
if ($file->exists())
{
if (!$file->delete())
{
\Cake\Log\Log::error(__d('upload', 'Unable to delete file "{0}" in entity id "{1}" from table "{2}" and path "{3}"', $filename, $this->entity->get($this->table->getPrimaryKey()), $this->table->getTable(), $path));
return false;
}
} else
{
\Cake\Log\Log::error(__d('upload', 'Unable to delete file "{0}" in entity id "{1}" from table "{2}" and path "{3}" because it does not exist', $filename, $this->entity->get($this->table->getPrimaryKey()), $this->table->getTable(), $path));
return false;
}
return true;
}

public function delete()
/**
* Get a path to save file
* @return string
*/
protected function getPath($subDirectory = null)
{

if ($this->path === null)
{
$path = Hash::get($this->settings, 'path', $this->defaultPath);
$this->path = empty($path) ? $this->defaultPath : (substr($path, -1) === DS ? $path : $path . DS);

if (!is_dir($this->path))
{
$this->createFolderIfItNotExists($this->path);
}
}

if ($subDirectory !== null)
{
$subDirectory = substr($subDirectory, -1) === DS ? $subDirectory : $subDirectory . DS;
$this->createFolderIfItNotExists($this->path . $subDirectory);
return $this->path . $subDirectory;
} else
{
return $this->path;
}
}

/**
* Get a path to save file
* @return string
* Create a folder if it not exist
* @param string $path
*/
protected function getPath()
protected function createFolderIfItNotExists($path)
{
$path = Hash::get($this->settings, 'path', $this->defaultPath);
if (!new Folder($path, true))
{
\Cake\Log\Log::error(__d('upload', 'Unable to create directory: {0}', $path));
}
}

return empty($path) ? $this->defaultPath : (substr($path, -1) === DS ? $path : $path . DS);
/**
* get a image save format from behavior config
* @return type
*/
protected function getConfigFileFormat()
{
if (Hash::get($this->settings, 'image', false))
{
$fileExtension = Hash::get($this->settings, 'image.format', 'jpg');
return substr($fileExtension, 0, 1) === '.' ? $fileExtension : '.' . $fileExtension;
} else
{
$fileExtension = pathinfo(Hash::get($this->fileInfo, 'name', 'err'), PATHINFO_EXTENSION);
return substr($fileExtension, 0, 1) === '.' ? $fileExtension : '.' . $fileExtension;
}
}

/**
* Check if path exist
* @param bool $create Create a path if not exist
* Create a new filename
* @param bool $ifExistCreateNew if true force to create a new filename
* @return string
*/
protected function checkPath($create = true)
{
if (!new Folder($this->getPath(), $create))
protected function createFilename($ifExistCreateNew = false)
{
if ($this->filename === null)
{
$filePrefix = Hash::get($this->settings, 'prefix', '');
$fileUniqidMoreEntropy = Hash::get($this->settings, 'more_entropy', true);
$this->filename = Hash::get($this->settings, 'filename', uniqid($filePrefix, $fileUniqidMoreEntropy)) . $this->getConfigFileFormat();
} elseif ($ifExistCreateNew === true)
{
\Cake\Log\Log::error(__d('upload', 'Unable to create directory: {0}', $this->getPath()));
$filePrefix = Hash::get($this->settings, 'prefix', '');
$fileUniqidMoreEntropy = Hash::get($this->settings, 'more_entropy', true);
$this->filename = Hash::get($this->settings, 'filename', uniqid($filePrefix, $fileUniqidMoreEntropy)) . $this->getConfigFileFormat();
}

return $this->filename;
}

/**
* Return a file name
* @return string
*/
protected function getFileName()
protected function getFilename()
{
if (debug_backtrace()[1]['function'] == 'write')
if ($this->filename === null)
{
if ($this->fileName === null)
if ($this->entity->isNew())
{
$this->createFilename();
} elseif (is_array($this->entity->get($this->field)))
{
$entity = $this->table->get($this->entity->get($this->table->getPrimaryKey()));
$this->filename = $entity->get($this->field);
} else
{
$filePrefix = Hash::get($this->settings, 'prefix', '');
$fileUniqidMoreEntropy = Hash::get($this->settings, 'more_entropy', true);
$this->fileName = Hash::get($this->settings, 'filename', uniqid($filePrefix, $fileUniqidMoreEntropy));
$this->filename = $this->entity->get($this->field);
}
}elseif(debug_backtrace()[1]['function'] == 'delete')
{
$this->fileName = $this->entity->get($this->field);
}
return $this->fileName;

return $this->filename;
}

}
Loading

0 comments on commit 83a2416

Please sign in to comment.