Failed Conditions
Pull Request — master (#323)
by Maximo
02:55
created

Helper::setImageDimensions()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
cc 3
nc 2
nop 2
dl 0
loc 13
ccs 0
cts 0
cp 0
crap 12
rs 9.8333
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Canvas\Filesystem;
6
7
use Phalcon\Http\Request\File;
8
use Exception;
9
use Canvas\Models\FileSystem;
10
use Phalcon\Di;
11
use Phalcon\Image\Adapter\Gd;
12
13
class Helper
14
{
15
    /**
16
     * Generate a unique name in a specific dir.
17
     *
18
     * @param string $dir the especific dir where the file will be saved
19
     * @param bool $withPath
20
     *
21
     * @return string
22
     */
23
    public static function generateUniqueName(File $file, string $dir, $withPath = false) : string
24
    {
25
        // the provided path has to be a dir
26
        if (!is_dir($dir)) {
27
            throw new Exception("The dir provided: '{$dir}' isn't a valid one.");
28
        }
29
30
        $path = tempnam($dir . '/', '');
31
32
        //this function creates a file (like touch) so, we have to delete it.
33
        unlink($path);
34
        $uniqueName = $path;
35
        if (!$withPath) {
36
            $uniqueName = str_replace($dir, '', $path);
37
        }
38
39
        return $uniqueName . '.' . strtolower($file->getExtension());
40
    }
41
42
    /**
43
     * Create a File instance from a given path.
44
     *
45
     * @param string $path Path of the file to be used
46
     *
47
     * @return File
48
     */
49
    public static function pathToFile(string $path) : File
50
    {
51
        //Simulate the body of a Phalcon\Request\File class
52
        return new File([
53
            'name' => basename($path),
54
            'type' => mime_content_type($path),
55
            'tmp_name' => $path,
56
            'error' => 0,
57
            'size' => filesize($path),
58
        ]);
59
    }
60
61
    /**
62
     * Given a file create it in the filesystem.
63
     *
64
     * @param File $file
65
     * @return bool
0 ignored issues
show
Documentation introduced by
Should the return type not be FileSystem?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
66
     */
67
    public static function upload(File $file): FileSystem
68
    {
69
        $di = Di::getDefault();
70
        $config = $di->get('config');
71
72
        //get the filesystem config from app settings (local | s3)
73
        $appSettingFileConfig = $di->get('app')->get('filesystem');
74
        $fileSystemConfig = $config->filesystem->{$appSettingFileConfig};
75
76
        //create local filesystem , for temp files
77
        $di->get('filesystem', ['local'])->createDir($config->filesystem->local->path);
78
79
        //get the tem file
80
        $filePath = self::generateUniqueName($file, $config->filesystem->local->path);
81
        $compleFilePath = $fileSystemConfig->path . $filePath;
82
        $uploadFileNameWithPath = $appSettingFileConfig == 'local' ? $filePath : $compleFilePath;
83
84
        /**
85
         * upload file base on temp.
86
         * @todo change this to determine type of file and recreate it if its a image
87
         */
88
        $di->get('filesystem')->writeStream($uploadFileNameWithPath, fopen($file->getTempName(), 'r'));
89
90
        $fileSystem = new FileSystem();
91
        $fileSystem->name = $file->getName();
92
        $fileSystem->companies_id = $di->get('userData')->currentCompanyId();
93
        $fileSystem->apps_id = $di->get('app')->getId();
94
        $fileSystem->users_id = $di->get('userData')->getId();
95
        $fileSystem->path = $compleFilePath;
96
        $fileSystem->url = $fileSystemConfig->cdn . DIRECTORY_SEPARATOR . $uploadFileNameWithPath;
97
        $fileSystem->file_type = $file->getExtension();
98
        $fileSystem->size = $file->getSize();
99
100
        $fileSystem->saveOrFail();
101
102
        return $fileSystem;
103
    }
104
105
    /**
106
     * Is this file a image?
107
     *
108
     * @param File $file
109
     * @return boolean
110
     */
111
    public static function isImage(File $file): bool
112
    {
113
        return strpos(mime_content_type($file->getTempName()), 'image/') === 0;
114
    }
115
116
    /**
117
     * Given a image set its dimension.
118
     *
119
     * @param File $file
120
     * @param FileSystem $fileSystem
121
     * @return void
122
     */
123
    public static function setImageDimensions(File $file, FileSystem $fileSystem): void
124
    {
125
        if (Helper::isImage($file)) {
126
            
127
            $image = new Gd($file->getTempName());
128
            $fileSystem->set('width', $image->getWidth());
129
            $fileSystem->set('height', $image->getHeight());
130
            $fileSystem->set(
131
                'orientation',
132
                $image->getHeight() > $image->getWidth() ? 'portrait' : 'landscape'
133
            );
134
        }
135
    }
136
}
137