ImageTranscoder   A
last analyzed

Complexity

Total Complexity 16

Size/Duplication

Total Lines 210
Duplicated Lines 3.33 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
dl 7
loc 210
rs 10
c 0
b 0
f 0
wmc 16
lcom 1
cbo 3

4 Methods

Rating   Name   Duplication   Size   Complexity  
C transcode_asset() 7 116 8
B craft_convert_cmd() 0 37 5
A craft_convert_custom_cmd() 0 22 1
A _updateOutputExtension() 0 18 2

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
/*
4
 *   This class handles Images transcoding
5
 *   We transcode and generate an output image using ImageMagic (convert)
6
 *
7
 *   Copyright (C) 2016  BFan Sports - Sport Archive Inc.
8
 *
9
 *   This program is free software; you can redistribute it and/or modify
10
 *   it under the terms of the GNU General Public License as published by
11
 *   the Free Software Foundation; either version 2 of the License, or
12
 *   (at your option) any later version.
13
 *
14
 *   This program is distributed in the hope that it will be useful,
15
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
16
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17
 *   GNU General Public License for more details.
18
 *
19
 *   You should have received a copy of the GNU General Public License along
20
 *   with this program; if not, write to the Free Software Foundation, Inc.,
21
 *   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
22
 */
23
24
require_once __DIR__.'/BasicTranscoder.php';
25
26
use SA\CpeSdk;
27
28
class ImageTranscoder extends BasicTranscoder
29
{
30
    /***********************
31
     * TRANSCODE INPUT IMAGE
32
     * Below is the code used to transcode images based on $outputWanted. 
33
     **********************/
34
35
    // $metadata should contain the ffprobe video stream array.
36
37
    // Start Convert for output transcoding
38
    public function transcode_asset(
39
        $tmpPathInput,
40
        $pathToInputFile, 
41
        $pathToOutputFiles,
42
        $metadata = null, 
43
        $outputWanted)
44
    {
45
        if ($metadata) {
46
            // Extract an sanitize metadata
47
            $metadata = $this->_extractFileInfo($metadata);
48
        }
49
50
        $this->cpeLogger->logOut(
51
            "INFO", 
52
            basename(__FILE__), 
53
            "Start Transcoding Asset '$pathToInputFile' ...",
54
            $this->activityLogKey
55
        );
56
57 View Code Duplication
        if ($metadata)
58
            $this->cpeLogger->logOut(
59
                "INFO", 
60
                basename(__FILE__), 
61
                "Input Video metadata: " . print_r($metadata, true),
62
                $this->activityLogKey
63
            );
64
65
        try {
66
            $convertCmd = "";
67
68
            // Update output extension file if it ends with '.*'
69
            // Output will take the same extension as input
70
            $this->_updateOutputExtension(
71
                $pathToInputFile,
72
                $outputWanted);
73
            
74
            // Custom command
75
            if (isset($outputWanted->{'custom_cmd'}) &&
76
                $outputWanted->{'custom_cmd'}) {
77
                $convertCmd = $this->craft_convert_custom_cmd(
78
                    $tmpPathInput,
79
                    $pathToInputFile,
80
                    $pathToOutputFiles,
81
                    $metadata, 
82
                    $outputWanted
83
                );
84
            }
85
            else {
86
                $convertCmd = $this->craft_convert_cmd(
87
                    $tmpPathInput,
88
                    $pathToInputFile,
89
                    $pathToOutputFiles,
90
                    $metadata, 
91
                    $outputWanted
92
                );
93
            }
94
95
            $this->cpeLogger->logOut(
96
                "INFO",
97
                basename(__FILE__),
98
                "CONVERT CMD:\n$convertCmd\n",
99
                $this->activityLogKey
100
            );
101
102
            // Use executer to start Converter command
103
            // Use 'capture_progression' function as callback
104
            // Pass video 'duration' as parameter
105
            // Sleep 1sec between turns and callback every 10 turns
106
            // Output progression logs (true)
107
            $this->executer->execute(
108
                $convertCmd, 
109
                1, 
110
                array(2 => array("pipe", "w")),
111
                array($this->activityObj, "activityHeartbeat"), 
112
                null, 
113
                true, 
114
                10
115
            );
116
117
            // Test if we have an output file !
118
            if (!file_exists($pathToOutputFiles) || 
119
                $this->isDirEmpty($pathToOutputFiles)) {
120
                throw new CpeSdk\CpeException(
121
                    "Output file '$pathToOutputFiles' hasn't been created successfully or is empty !",
122
                    self::TRANSCODE_FAIL
123
                );
124
            }
125
126
            // FFProbe the output file and return its information
127
            // XXX: Remove FFprobe for image convertion. Save time
128
            $outputInfo =
129
                $this->getAssetInfo($pathToOutputFiles."/".$outputWanted->{'output_file_info'}['basename']);
130
        }
131
        catch (\Exception $e) {
132
            $this->cpeLogger->logOut(
133
                "ERROR", 
134
                basename(__FILE__), 
135
                "Execution of command '".$convertCmd."' failed: " . print_r($metadata, true). ". ".$e->getMessage(),
136
                $this->activityLogKey
0 ignored issues
show
Bug introduced by
The property activityLogKey does not seem to exist. Did you mean logKey?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
137
            );
138
            return false;
139
        }
140
141
        // No error. Transcode successful
142
        $this->cpeLogger->logOut(
143
            "INFO", 
144
            basename(__FILE__), 
145
            "Transcoding successfull !",
146
            $this->activityLogKey
147
        );
148
        
149
        return [
150
            "output"     => $outputWanted,
151
            "outputInfo" => $outputInfo
152
        ];
153
    }
154
155
    // Craft command based on JSON input
156
    private function craft_convert_cmd(
157
        $tmpPathInput,
158
        $pathToInputFile,
159
        $pathToOutputFiles,
160
        $metadata, 
161
        $outputWanted)
162
    {
163
        $convertArgs = "$pathToInputFile ";
164
165
        if (isset($outputWanted->{'quality'})) {
166
            $quality = $outputWanted->{'quality'};
167
            $convertArgs .= "-quality $quality ";
168
        }
169
        
170
        if (isset($outputWanted->{'resize'})) {
171
            $resize = $outputWanted->{'resize'};
172
            $convertArgs .= "-resize $resize ";
173
        }
174
175
        if (isset($outputWanted->{'thumbnail'})) {
176
            $thumbnail = $outputWanted->{'thumbnail'};
177
            $convertArgs .= "-thumbnail $thumbnail ";
178
        }
179
        
180
        if (isset($outputWanted->{'crop'})) {
181
            $crop = $outputWanted->{'crop'};
182
            $convertArgs .= "-crop $crop ";
183
        }
184
        
185
        // Append output filename to path
186
        $pathToOutputFiles .=
187
            "/" . $outputWanted->{'output_file_info'}['basename'];
188
        
189
        $convertCmd = "convert $convertArgs $pathToOutputFiles";
190
191
        return ($convertCmd);
192
    }
193
    
194
    // Craft custom command
195
    private function craft_convert_custom_cmd(
196
        $tmpPathInput,
0 ignored issues
show
Unused Code introduced by
The parameter $tmpPathInput 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...
197
        $pathToInputFile,
198
        $pathToOutputFiles,
199
        $metadata, 
0 ignored issues
show
Unused Code introduced by
The parameter $metadata 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...
200
        $outputWanted)
201
    {
202
        $convertCmd = $outputWanted->{'custom_cmd'};
203
204
        // Replace ${input_file} by input file path
205
        $pathToInputFile = escapeshellarg($pathToInputFile);
206
        $convertCmd = preg_replace('/\$\{input_file\}/',
207
            $pathToInputFile, $convertCmd);
208
209
        // Append output filename to path
210
        $pathToOutputFiles .= "/" . $outputWanted->{'output_file_info'}['basename'];
211
        // Replace ${output_file} by output filename and path to local disk
212
        $convertCmd = preg_replace('/\$\{output_file\}/',
213
            $pathToOutputFiles, $convertCmd);
214
        
215
        return ($convertCmd);
216
    }
217
218
    // Check if output file need an update on the extension
219
    private function _updateOutputExtension(
220
        $pathToInputFile,
221
        &$outputWanted)
222
    {
223
        $inputExtension =
224
            pathinfo($pathToInputFile)['extension'];
225
        
226
        // REplace output extension if == * with the input extension
227
        $outputPathInfo =
228
            pathinfo($outputWanted->{'output_file_info'}['basename']);
229
        $outputExtension = $outputPathInfo['extension'];
230
        if ($outputExtension == "*") {
231
            $outputWanted->{'output_file_info'}['basename'] = preg_replace(
232
                '/\*/',
233
                $inputExtension,
234
                $outputWanted->{'output_file_info'}['basename']);
235
        }
236
    }
237
}