Completed
Push — 4.0 ( bcbbe3...4201d3 )
by Marco
09:53
created

File::loadFromUploadedFile()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 14
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 14
ccs 0
cts 10
cp 0
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 9
nc 1
nop 1
crap 2
1
<?php namespace Comodojo\Dispatcher\Request;
2
3
use \Exception;
4
5
/**
6
 * @package     Comodojo Dispatcher
7
 * @author      Marco Giovinazzi <[email protected]>
8
 * @author      Marco Castiello <[email protected]>
9
 * @license     GPL-3.0+
10
 *
11
 * LICENSE:
12
 *
13
 * This program is free software: you can redistribute it and/or modify
14
 * it under the terms of the GNU Affero General Public License as
15
 * published by the Free Software Foundation, either version 3 of the
16
 * License, or (at your option) any later version.
17
 *
18
 * This program is distributed in the hope that it will be useful,
19
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21
 * GNU Affero General Public License for more details.
22
 *
23
 * You should have received a copy of the GNU Affero General Public License
24
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
25
 */
26
27
class File {
28
29
    private $slug;
30
31
    private $fname;
32
33
    private $tname;
34
35
    private $upld;
36
37
    private $ctype;
38
39
    private $size = 0;
40
41
    public function __construct($fileControl) {
42
43
        $this->load($fileControl);
44
45
    }
46
47
    public function getTemporaryName() {
48
49
        return $this->tname;
50
51
    }
52
53
    public function getFileName() {
54
55
        return $this->fname;
56
57
    }
58
59
    public function getSlug() {
60
61
        return $this->slug;
62
63
    }
64
65
    public function getContentType() {
66
67
        return $this->ctype;
68
69
    }
70
71
    public function getSize() {
72
73
        return $this->size;
74
75
    }
76
77
    public function getUploadTime() {
78
79
        return $this->upld;
80
81
    }
82
83
    public function getFileData() {
84
85
        $file = $this->getTemporaryName();
86
87
        if (file_exists($file)) return file_get_contents($file);
88
89
        throw new Exception("File does not exists");
90
91
    }
92
93
    public function load($slugOrControl) {
0 ignored issues
show
Coding Style introduced by
load uses the super-global variable $_FILES which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
94
95
        if (isset($_FILES) && isset($_FILES[$slugOrControl])) {
96
97
            $this->loadFromUploadedFile($slugOrControl);
98
99
            return $this;
100
101
        }
102
103
        throw new Exception("The requested file has not been uploaded");
104
105
    }
106
107
    public function save($path, $as_slug = false) {
0 ignored issues
show
Unused Code introduced by
The parameter $path is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
108
109
        if (!empty($this->path) && file_exists($this->path)) {
110
111
            $local_name = "$this->path/" . ($as_slug ? $this->getSlug() : $this->getFileName());
0 ignored issues
show
Bug introduced by
The property path does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
112
113
            if ( file_exists($local_name) ) {
114
115
                $files = glob("$local_name*");
116
117
                $count = count($files);
118
119
                $local_name .= "-$count";
120
121
            }
122
123
            if ( move_uploaded_file($this->getTemporaryName(), $local_name) ) {
124
125
                // return file_exists($local_name);
0 ignored issues
show
Unused Code Comprehensibility introduced by
63% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
126
                return true;
127
128
            }
129
130
            throw new Exception("Unable to save file");
131
132
        }
133
134
        throw new Exception("Repository path not available");
135
136
    }
137
138
    private function loadFromUploadedFile($fileControl) {
0 ignored issues
show
Coding Style introduced by
loadFromUploadedFile uses the super-global variable $_FILES which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
139
140
        $file = $_FILES[$fileControl];
141
142
        $this->tname = $file['tmp_name'];
143
        $this->fname = $file['name'];
144
        $this->ctype = $file['type'];
145
        $this->size = intval($file['size']);
146
        $this->upld = filectime($file['tmp_name']);
147
        $this->slug = self::createSlug($this->fname);
148
149
        return $this;
150
151
    }
152
153
    private static function createSlug($filename) {
154
155
        preg_match_all("/[a-z0-9]+/", iconv("UTF-8", "ASCII//TRANSLIT", strtolower(preg_replace('/\..*?$/', '', $filename))), $matches);
156
157
        return implode('-', $matches[0]);
158
159
    }
160
161
    public static function fromUploadedFiles($repository = '') {
0 ignored issues
show
Coding Style introduced by
fromUploadedFiles uses the super-global variable $_FILES which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
162
163
        $files = array();
164
165
        foreach ($_FILES as $idx => $data) {
166
167
            $files[] = new File($idx, $repository);
0 ignored issues
show
Unused Code introduced by
The call to File::__construct() has too many arguments starting with $repository.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
168
169
        }
170
171
        return $files;
172
173
    }
174
175
}
176