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

File::setupDestination()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 9
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 9
rs 9.6666
cc 3
eloc 6
nc 3
nop 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
}