Helper::upload()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 40
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 2
Bugs 1 Features 0
Metric Value
cc 2
eloc 21
c 2
b 1
f 0
nc 2
nop 1
dl 0
loc 40
ccs 0
cts 20
cp 0
crap 6
rs 9.584
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Canvas\Filesystem;
6
7
use Canvas\Models\FileSystem;
8
use Exception;
9
use Phalcon\Di;
10
use Phalcon\Http\Request\File;
0 ignored issues
show
Bug introduced by
The type Phalcon\Http\Request\File was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
11
use Phalcon\Image\Adapter\Gd;
0 ignored issues
show
Bug introduced by
The type Phalcon\Image\Adapter\Gd was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
12
use Phalcon\Text;
0 ignored issues
show
Bug introduced by
The type Phalcon\Text was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
13
14
class Helper
15
{
16
    /**
17
     * Generate a unique name in a specific dir.
18
     *
19
     * @param string $dir the specific dir where the file will be saved
20
     * @param bool $withPath
21
     *
22
     * @return string
23
     */
24
    public static function generateUniqueName(File $file, string $dir, $withPath = false) : string
25
    {
26
        // the provided path has to be a dir
27
        if (!is_dir($dir)) {
28
            throw new Exception("The dir provided: '{$dir}' isn't a valid one.");
29
        }
30
31
        $path = tempnam($dir . '/', '');
32
33
        //this function creates a file (like touch) so, we have to delete it.
34
        unlink($path);
35
        $uniqueName = $path;
36
        if (!$withPath) {
37
            $uniqueName = str_replace($dir, '', $path);
38
        }
39
40
        return $uniqueName . '.' . strtolower($file->getExtension());
41
    }
42
43
    /**
44
     * Create a File instance from a given path.
45
     *
46
     * @param string $path Path of the file to be used
47
     *
48
     * @return File
49
     */
50
    public static function pathToFile(string $path) : File
51
    {
52
        //Simulate the body of a Phalcon\Request\File class
53
        return new File([
54
            'name' => basename($path),
55
            'type' => mime_content_type($path),
56
            'tmp_name' => $path,
57
            'error' => 0,
58
            'size' => filesize($path),
59
        ]);
60
    }
61
62
    /**
63
     * Given a file create it in the filesystem.
64
     *
65
     * @param File $file
66
     *
67
     * @return bool
68
     */
69
    public static function upload(File $file) : FileSystem
70
    {
71
        $di = Di::getDefault();
72
        $config = $di->get('config');
73
74
        //get the filesystem config from app settings (local | s3)
75
        $appSettingFileConfig = $di->get('app')->get('filesystem');
76
        $fileSystemConfig = $config->filesystem->{$appSettingFileConfig};
77
78
        //create local filesystem , for temp files
79
        $di->get('filesystem', ['local'])->createDir($config->filesystem->local->path);
80
81
        //get the tem file
82
        $fileName = self::generateUniqueName($file, $config->filesystem->local->path . '/');
83
        $completeFilePath = $fileSystemConfig->path . DIRECTORY_SEPARATOR . $fileName;
84
        $uploadFileNameWithPath = $appSettingFileConfig === 'local' ? $fileName : $completeFilePath;
85
86
        /**
87
         * upload file base on temp.
88
         *
89
         * @todo change this to determine type of file and recreate it if its a image
90
         */
91
        $di->get('filesystem')->writeStream($uploadFileNameWithPath, fopen($file->getTempName(), 'r'));
92
93
        $fileSystem = new FileSystem();
94
        $fileSystem->name = $file->getName();
95
        $fileSystem->companies_id = $di->get('userData')->currentCompanyId();
96
        $fileSystem->apps_id = $di->get('app')->getId();
97
        $fileSystem->users_id = $di->get('userData')->getId();
98
        $fileSystem->path = Text::reduceSlashes($completeFilePath);
99
        $fileSystem->url = Text::reduceSlashes($fileSystemConfig->cdn . DIRECTORY_SEPARATOR . $uploadFileNameWithPath);
100
        $fileSystem->file_type = $file->getExtension();
101
        $fileSystem->size = $file->getSize();
102
103
        $fileSystem->saveOrFail();
104
105
        //set the unique name we generate
106
        $fileSystem->set('unique_name', $uploadFileNameWithPath);
107
108
        return $fileSystem;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $fileSystem returns the type Canvas\Models\FileSystem which is incompatible with the documented return type boolean.
Loading history...
109
    }
110
111
    /**
112
     * Is this file a image?
113
     *
114
     * @param File $file
115
     *
116
     * @return boolean
117
     */
118
    public static function isImage(File $file) : bool
119
    {
120
        return strpos(mime_content_type($file->getTempName()), 'image/') === 0;
121
    }
122
123
    /**
124
     * Given a image set its dimension.
125
     *
126
     * @param File $file
127
     * @param FileSystem $fileSystem
128
     *
129
     * @return void
130
     */
131
    public static function setImageDimensions(File $file, FileSystem $fileSystem) : void
132
    {
133
        if (Helper::isImage($file)) {
134
            $image = new Gd($file->getTempName());
135
            $fileSystem->set('width', $image->getWidth());
136
            $fileSystem->set('height', $image->getHeight());
137
            $fileSystem->set(
138
                'orientation',
139
                $image->getHeight() > $image->getWidth() ? 'portrait' : 'landscape'
140
            );
141
        }
142
    }
143
}
144