Priloha::saveToFile()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 15
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 10
c 2
b 0
f 0
dl 0
loc 15
rs 9.9332
cc 4
nc 4
nop 2
1
<?php
2
3
/**
4
 * FlexiPeeHP - Objekt kontaktu.
5
 *
6
 * @author     Vítězslav Dvořák <[email protected]>
7
 * @copyright  (C) 2015-2020 Spoje.Net
8
 */
9
10
namespace FlexiPeeHP;
11
12
/**
13
 * Příloha
14
 *
15
 * @link https://www.flexibee.eu/api/dokumentace/ref/attachments/
16
 * @link https://demo.flexibee.eu/c/demo/priloha/properties
17
 */
18
class Priloha extends RW {
19
20
    /**
21
     * Evidence užitá objektem.
22
     *
23
     * @var string
24
     */
25
    public $evidence = 'priloha';
26
27
    /**
28
     * Evidence s přílohami
29
     *
30
     * @var array
31
     */
32
    public static $relatedEvidence = [
33
        'prodejka' => 'doklFak', 'pohledavka' => 'doklFak', 'zavazek' => 'doklFak',
34
        'faktura-prijata' => 'doklFak', 'faktura-vydana' => 'doklFak',
35
        'interni-doklad' => 'doklInt', 'pokladni-pohyb' => 'doklInt', 'vzajemny-zapocet' => 'doklInt',
36
        'banka' => 'doklInt',
37
        'poptavka-vydana' => 'doklObch', 'poptavka-prijata' => 'doklObch', 'objednavka-prijata' => 'doklObch',
38
        'nabidka-vydana' => 'doklObch',
39
        'objednavka-vydana' => 'doklObch', 'nabidka-prijata' => 'doklObch',
40
        'skladovy-pohyb' => 'doklSklad',
41
        'cenik' => 'cenik',
42
        'adresar' => 'adresar', 'kontakt' => 'kontakt'
43
    ];
44
45
    /**
46
     * Attach file
47
     * Přilož Soubor
48
     *
49
     * @param string $filepath
50
     * @param array  $attachmentData
51
     */
52
    public function attachFile($filepath, $attachmentData = []) {
53
        if (file_exists($filepath)) {
54
            $attachmentData['nazSoub'] = basename($filepath);
55
            $attachmentData['contentType'] = mime_content_type($filepath);
56
            $attachmentData['dataSize'] = filesize($filepath);
57
            $attachmentData['dataHash'] = md5_file($filepath);
58
59
            switch ($attachmentData['contentType']) {
60
                case 'image/png':
61
                case 'image/gif':
62
                case 'image/jpeg':
63
                    break;
64
            }
65
            $attachmentData['content'] = base64_encode(file_get_contents($filepath));
66
        }
67
    }
68
69
    /**
70
     * Obtain url for Attachment Download
71
     *
72
     * @param RO $object Source object
73
     * @return string url
74
     */
75
    public static function getDownloadUrl($object) {
76
        $urlParts = parse_url($object->apiURL);
77
        $pathParts = pathinfo($urlParts['path']);
78
        return $urlParts['scheme'] . '://' . $urlParts['host'] . ( array_key_exists('port', $urlParts) ? ':' . $urlParts['port'] : '') . $pathParts['dirname'] . '/' . $pathParts['filename'] . '/content';
79
    }
80
81
    /**
82
     * Obtain first attachment for given object
83
     *
84
     * @param  RO $object
85
     * @return array
86
     */
87
    public static function getFirstAttachment($object) {
88
        $attachments = self::getAttachmentsList($object);
89
        return count($attachments) ? current($attachments) : null;
90
    }
91
92
    /**
93
     * Gives you attachment body as return value
94
     * 
95
     * @param int   $attachmentID
96
     * @param array $options      Additional Connection Options
97
     * 
98
     * @return string
99
     */
100
    public static function getAttachment($attachmentID, $options = []) {
101
        $result = null;
102
        $downloader = new Priloha($attachmentID, $options);
103
        if ($downloader->lastResponseCode == 200) {
104
105
            $downloader->doCurlRequest(self::getDownloadURL($downloader), 'GET');
106
            if ($downloader->lastResponseCode == 200) {
107
                $result = $downloader->lastCurlResponse;
0 ignored issues
show
Documentation Bug introduced by
It seems like $downloader->lastCurlResponse can also be of type boolean. However, the property $lastCurlResponse is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
108
            }
109
        }
110
        return $result;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $result also could return the type boolean which is incompatible with the documented return type string.
Loading history...
111
    }
112
113
    /**
114
     * Send "download" headers first and then file itself
115
     *
116
     * @param RO $object
117
     * @param int|string $attachmentID
118
     */
119
    public static function download($object, $format = 'pdf',
120
            $attachmentID = null) {
121
        $attachments = self::getAttachmentsList($object);
122
123
        if (isset($attachmentID) && !array_key_exists($attachmentID,
124
                        $attachments)) {
125
            $object->addStatusMessage(sprintf(_('Attagment %s does no exist'),
126
                            $attachmentID), 'warning');
127
        }
128
129
        $attachmentBody = $object->doCurlRequest(self::getDownloadUrl($object),
130
                'GET');
131
        header('Content-Description: File Transfer');
132
        header('Content-Type: application/octet-stream');
133
        header('Content-Transfer-Encoding: binary');
134
        header('Expires: 0');
135
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
136
        header('Pragma: public');
137
        header('Content-Disposition: attachment; filename=' . $object->getEvidence() . '_' . $object . '.' . $format);
138
        header('Content-Length: ' . strlen($attachmentBody));
139
        echo $attachmentBody;
140
    }
141
142
    /**
143
     * Save attachment to file
144
     *
145
     * @param int $attachmentID
146
     * @param string $destination directory or filename with path
147
     * @return int
148
     */
149
    public static function saveToFile($attachmentID, $destination) {
150
        $result = 0;
151
        $downloader = new Priloha($attachmentID);
152
        if ($downloader->lastResponseCode == 200) {
153
154
            $downloader->doCurlRequest(self::getDownloadURL($downloader), 'GET');
155
            if ($downloader->lastResponseCode == 200) {
156
                if (is_dir($destination)) {
157
                    $destination .= '/' . $downloader->getDataValue('nazSoub');
158
                }
159
                $result = file_put_contents($destination,
160
                        $downloader->lastCurlResponse);
161
            }
162
        }
163
        return $result;
164
    }
165
166
    /**
167
     * Add Attachment from File
168
     *
169
     * @param RW $object
170
     * @param string     $filename
171
     *
172
     * @return Priloha attached file object
173
     */
174
    public static function addAttachmentFromFile($object, $filename) {
175
        return self::addAttachment($object, basename($filename),
176
                        file_get_contents($filename), mime_content_type($filename));
177
    }
178
179
    /**
180
     * Add Attachment related to current $object content
181
     *
182
     * @param RW $object
183
     * @param string $filename
184
     * @param string $attachment Body
185
     * @param string $contentType Attachment Content-Type
186
     *
187
     * @return Priloha attached file object
188
     */
189
    public static function addAttachment($object, $filename, $attachment,
190
            $contentType) {
191
        $attached = new Priloha();
192
        $headersBackup = $object->defaultHttpHeaders;
193
        $codeBackup = $object->lastResponseCode;
194
        $responseBackup = $object->lastCurlResponse;
195
        $object->postFields = $attachment;
196
        $object->defaultHttpHeaders['Content-Type'] = $contentType;
197
        $url = $object->getAbraFlexiURL() . '/prilohy/new/' . $filename;
198
        $response = $object->performRequest($url, 'PUT');
199
        $object->defaultHttpHeaders = $headersBackup;
200
        $attached->setMyKey($response[0]['id']);
201
        $attached->lastResponseCode = $object->lastResponseCode;
202
        $attached->lastCurlResponse = $object->lastCurlResponse;
0 ignored issues
show
Documentation Bug introduced by
It seems like $object->lastCurlResponse can also be of type boolean. However, the property $lastCurlResponse is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
203
        $object->lastResponseCode = $codeBackup;
204
        $object->lastCurlResponse = $responseBackup;
205
        return $attached;
206
    }
207
208
    /**
209
     * Obtain Record related attachments list
210
     *
211
     * @param RO $object
212
     * 
213
     * @return array
214
     */
215
    public static function getAttachmentsList($object) {
216
        $fburl = $object->getAbraFlexiURL();
217
        $attachments = [];
218
        $oFormat = $object->format;
219
        $object->setFormat('json');
220
        $atch = $object->getFlexiData($fburl . '/prilohy' . (count($object->defaultUrlParams) ? '?' . http_build_query($object->defaultUrlParams) : ''));
221
        $object->setFormat($oFormat);
222
        if (count($atch) && ($object->lastResponseCode == 200)) {
223
            foreach ($atch as $attachmentID => $attachmentData) {
224
                $attachments[$attachmentID] = $attachmentData;
225
                $attachments[$attachmentID]['url'] = $object->url . '/c/' . $object->company . '/priloha/' . $attachmentData['id'];
226
            }
227
        }
228
        return $attachments;
229
    }
230
231
}
232