Completed
Pull Request — master (#248)
by Anton
05:24
created

Crud::setUploadDir()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 4.3731

Importance

Changes 0
Metric Value
cc 4
eloc 7
c 0
b 0
f 0
nc 3
nop 1
dl 0
loc 14
ccs 5
cts 7
cp 0.7143
crap 4.3731
rs 9.2
1
<?php
2
/**
3
 * @copyright Bluz PHP Team
4
 * @link https://github.com/bluzphp/skeleton
5
 */
6
7
/**
8
 * @namespace
9
 */
10
namespace Application\Media;
11
12
use Application\Exception;
13
use Bluz\Proxy\Request;
14
15
/**
16
 * Class Crud of Media
17
 * @package Application\Media
18
 *
19
 * @method Table getTable()
20
 */
21
class Crud extends \Bluz\Crud\Table
22
{
23
    /**
24
     * @var string
25
     */
26
    protected $uploadDir;
27
28
    /**
29
     * createOne
30
     *
31
     * @param array $data
32
     * @throws \Application\Exception
33
     * @return integer
34
     */
35 1
    public function createOne($data)
36
    {
37
        /**
38
         * Process HTTP File
39
         */
40 1
        $file = Request::getFile('file');
41
42 1
        if (!$file or $file->getError() != UPLOAD_ERR_OK) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
43
            if ($file->getError() == UPLOAD_ERR_NO_FILE) {
44
                throw new Exception("Please choose file for upload");
45
            }
46
            throw new Exception("Sorry, I can't receive file");
47
        }
48
49
        /**
50
         * Generate image name
51
         */
52 1
        $pathinfo = pathinfo($file->getClientFilename());
53
54 1
        $fileName = strtolower(isset($data['title'])?$data['title']:$pathinfo['filename']);
55
56
        // Prepare filename
57 1
        $fileName = preg_replace('/[ _;:]+/i', '-', $fileName);
58 1
        $fileName = preg_replace('/[-]+/i', '-', $fileName);
59 1
        $fileName = preg_replace('/[^a-z0-9.-]+/i', '', $fileName);
60
61
        // If name is wrong
62 1
        if (empty($fileName)) {
63
            $fileName = date('Y-m-d-His');
64
        }
65
66
        // If file already exists, increment name
67 1
        $originFileName = $fileName;
68 1
        $counter = 0;
69
70 1
        while (file_exists($this->uploadDir .'/'. $fileName .'.'. $pathinfo['extension'])) {
71
            $counter++;
72
            $fileName = $originFileName .'-'. $counter;
73
        }
74
75 1
        $filePath = $this->uploadDir .'/'. $fileName .'.'. $pathinfo['extension'];
76
77
        // Setup new name and move to user directory
78 1
        $file->moveTo($filePath);
79
80 1
        $publicDir = substr($this->uploadDir, strlen(PATH_PUBLIC) + 1);
81
82 1
        $data['file'] = $publicDir .'/'. $fileName .'.'. $pathinfo['extension'];
83 1
        $data['type'] = $file->getClientMediaType();
84
85 1
        $row = $this->getTable()->create();
86
87 1
        $row->setFromArray($data);
88 1
        return $row->save();
89
    }
90
91
    /**
92
     * setUploadDir
93
     *
94
     * @param $directory
95
     * @throws Exception
96
     * @return self
97
     */
98 3
    public function setUploadDir($directory)
99
    {
100 3
        if (!is_dir($directory) && !@mkdir($directory, 0755, true)) {
101
            throw new Exception("Upload folder is not exists and I can't create it");
102
        }
103
104 3
        if (!is_writable($directory)) {
105
            throw new Exception("Upload folder is not writable");
106
        }
107
108 3
        $this->uploadDir = $directory;
109
110 3
        return $this;
111
    }
112
}
113