Base64::fixDestination()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 12
rs 9.2
cc 4
eloc 6
nc 4
nop 2
1
<?php
2
3
namespace Uploader\Adapters;
4
5
use Uploader\Uploader;
6
7
/**
8
 * Adapter to save a file from an url.
9
 */
10
class Base64 implements AdapterInterface
11
{
12
    /**
13
     * {@inheritdoc}
14
     */
15
    public static function check($original)
16
    {
17
        return is_string($original) && (substr($original, 0, 5) === 'data:');
18
    }
19
20
    /**
21
     * {@inheritdoc}
22
     */
23
    public static function fixDestination(Uploader $uploader, $original)
24
    {
25
        if (!$uploader->getFilename()) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $uploader->getFilename() of type null|string is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
26
            $uploader->setFilename(uniqid());
27
        }
28
29
        $fileData = explode(';base64,', $original, 2);
30
31
        if (!$uploader->getExtension() && preg_match('|data:\w+/(\w+)|', $fileData[0], $match)) {
32
            $uploader->setExtension($match[1]);
33
        }
34
    }
35
36
    /**
37
     * {@inheritdoc}
38
     */
39
    public static function save($original, $destination)
40
    {
41
        $fileData = explode(';base64,', $original, 2);
42
43
        if (!@file_put_contents($destination, base64_decode($fileData[1]))) {
44
            throw new \RuntimeException("Unable to copy base64 to '{$destination}'");
45
        }
46
    }
47
}
48