Completed
Push — master ( 15515b...fd48c6 )
by Mike
02:14
created

File   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 75
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 11
c 2
b 0
f 0
lcom 1
cbo 1
dl 0
loc 75
rs 10

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 8 2
A setupDestination() 0 9 3
A extractFileName() 0 8 3
A getFileName() 0 3 1
A writeFile() 0 5 1
A file() 0 3 1
1
<?php
2
3
namespace SugarAPI\SDK\Response;
4
5
use SugarAPI\SDK\Response\Abstracts\AbstractResponse;
6
7
class File extends AbstractResponse {
8
9
    /**
10
     * The name of the File from Response
11
     * @var string
12
     */
13
    protected $fileName;
14
15
    /**
16
     * File Path for response
17
     * @var string
18
     */
19
    protected $destinationPath;
20
21
    public function __construct($curlResponse, $curlRequest,$destination = null) {
22
        parent::__construct($curlResponse, $curlRequest);
23
        $this->extractFileName();
24
        if (!empty($destination)) {
25
            $this->setupDestination($destination);
26
            $this->writeFile();
27
        }
28
    }
29
30
    /**
31
     * Configure the Destination path to store the File response
32
     * @param null $destination
33
     */
34
    protected function setupDestination($destination = null){
35
        if (empty($destination)){
36
            $destination = sys_get_temp_dir().'/SugarAPI';
37
            if (!file_exists($destination)){
38
                mkdir($destination,0777);
39
            }
40
        }
41
        $this->destinationPath = $destination;
42
    }
43
44
    /**
45
     * Extract the filename from the Headers, and store it in filename property
46
     */
47
    protected function extractFileName(){
48
        foreach (explode("\r\n",$this->headers) as $header)
49
        {
50
            if (strpos($header,'filename')!==FALSE){
51
                $this->fileName = substr($header,(strpos($header,"\"")+1),-1);
52
            }
53
        }
54
    }
55
56
    /**
57
     * Return the filename found in response
58
     * @return mixed
59
     */
60
    public function getFileName(){
61
        return $this->fileName;
62
    }
63
64
    /**
65
     * Write the downloaded file
66
     */
67
    protected function writeFile(){
68
        $fileHandle = fopen($this->file(),'w+');
69
        fwrite($fileHandle,$this->body);
70
        fclose($fileHandle);
71
    }
72
73
    /**
74
     * Return the full File path, where Response was stored
75
     * @return string
76
     */
77
    public function file(){
78
        return rtrim($this->destinationPath,DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR.$this->fileName;
79
    }
80
81
}