Message::getAttachments()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Fwolf\Tools\TtSync\PluginApi;
4
5
/**
6
 * @copyright   Copyright 2017 Fwolf
7
 * @license     https://opensource.org/licenses/MIT MIT
8
 */
9
class Message implements MessageInterface
10
{
11
    /**
12
     * Keys when exported to json
13
     */
14
    const KEY_ID = 'id';
15
16
    const KEY_CONTENT = 'content';
17
18
    const KEY_UPDATE_TIME = 'updateTime';
19
20
    const KEY_ATTACHMENTS = 'attachments';
21
22
23
    /**
24
     * @var AttachmentInterface[]
25
     */
26
    protected $attachments = [];
27
28
    /**
29
     * @var string
30
     */
31
    protected $content = '';
32
33
    /**
34
     * @var string
35
     */
36
    protected $id = '';
37
38
    /**
39
     * @var string
40
     */
41
    protected $updateTime = '';
42
43
44
    /**
45
     * @inheritdoc
46
     */
47
    public function addAttachment(
48
        AttachmentInterface $attachment
49
    ): MessageInterface {
50
        $this->attachments[] = $attachment;
51
52
        return $this;
53
    }
54
55
56
    /**
57
     * @inheritdoc
58
     */
59
    public function dump(string $dir): MessageInterface
60
    {
61
        $path = $dir . $this->getDumpPath();
62
        $parentDir = dirname($path);
63
        if (!file_exists($parentDir)) {
64
            mkdir($parentDir, 0755, true);
65
        }
66
67
        /** @var AttachmentInterface $attachment */
68
        foreach ($this->getAttachments() as $i => $attachment) {
69
            $attachmentPath =
70
                $this->getAttachmentDumpPath($i + 1, $attachment, $path);
71
            $attachment->save($attachmentPath);
72
        }
73
74
        // Save json after attachment, as attachment may download/move during
75
        // save, cause its filename change.
76
        $jsonStr = $this->toJson(true);
77
        file_put_contents($path, $jsonStr);
78
79
        return $this;
80
    }
81
82
83
    /**
84
     * @inheritDoc
85
     */
86
    public function fromJson(
87
        string $jsonStr,
88
        bool $withAttachments = true
89
    ): MessageInterface {
90
        $jsonAr = json_decode($jsonStr, true);
91
        $this->setId($jsonAr[static::KEY_ID]);
92
        $this->setContent($jsonAr[static::KEY_CONTENT]);
93
        $this->setUpdateTime($jsonAr[static::KEY_UPDATE_TIME]);
94
95
        $this->setAttachments([]);
96
        if ($withAttachments) {
97
            foreach ($jsonAr[static::KEY_ATTACHMENTS] as $attachmentPath) {
98
                $this->addAttachment(new Attachment($attachmentPath));
99
            }
100
        }
101
102
        return $this;
103
    }
104
105
106
    /**
107
     * Get attachment dump path based on json dump path
108
     *
109
     * If json dump file is 'foo.json', then attachments will be same directory
110
     * with name 'foo-1.png', 'foo-2.jpg', the ext name keep same with original
111
     * attachment file.
112
     *
113
     * @param   int                 $seq  Seq of attachment, start from 1.
114
     * @param   AttachmentInterface $attachment
115
     * @param   string              $path Json dump path.
116
     * @return  string
117
     */
118
    protected function getAttachmentDumpPath(
119
        int $seq,
120
        AttachmentInterface $attachment,
121
        string $path
122
    ): string {
123
        $path = substr($path, 0, strlen($path) - 5);
124
125
        $path .= '-' . trim(strval($seq));
126
127
        $attachmentPath = $attachment->getPath();
128
        $pos = strrpos($attachmentPath, '.');
129
        if (false === $pos) {
130
            // Attachment have no ext, return original
131
            return $path;
132
        } else {
133
            return $path . '.' . substr($attachmentPath, $pos + 1);
134
        }
135
    }
136
137
138
    /**
139
     * @inheritdoc
140
     */
141
    public function getAttachments(): array
142
    {
143
        return $this->attachments;
144
    }
145
146
147
    /**
148
     * @inheritdoc
149
     */
150
    public function getContent(): string
151
    {
152
        return $this->content;
153
    }
154
155
156
    /**
157
     * Get dump file path, relative from storage dir
158
     *
159
     * @return  string
160
     */
161
    protected function getDumpPath(): string
162
    {
163
        $year = date('Y', strtotime($this->getUpdateTime()));
164
        $id = $this->getId();
165
166
        $path = "{$year}/{$id}.json";
167
168
        return $path;
169
    }
170
171
172
    /**
173
     * @inheritdoc
174
     */
175
    public function getId(): string
176
    {
177
        return $this->id;
178
    }
179
180
181
    /**
182
     * @inheritDoc
183
     */
184
    public function getUpdateTime(): string
185
    {
186
        return $this->updateTime;
187
    }
188
189
190
    /**
191
     * @inheritDoc
192
     */
193
    public function isEarlierThan(MessageInterface $message): bool
194
    {
195
        $selfUpdateTime = $this->getUpdateTime();
196
        $messageUpdateTime = $message->getUpdateTime();
197
198
        if ($selfUpdateTime == $messageUpdateTime) {
199
            return $this->getId() < $message->getId();
200
        } else {
201
            return strtotime($selfUpdateTime) < strtotime($messageUpdateTime);
202
        }
203
    }
204
205
206
    /**
207
     * @inheritDoc
208
     */
209
    public function load(string $dumpFile): MessageInterface
210
    {
211
        $jsonStr = file_get_contents($dumpFile);
212
213
        $this->fromJson($jsonStr, true);
214
215
        return $this;
216
    }
217
218
219
    /**
220
     * @inheritdoc
221
     */
222
    public function setAttachments(array $attachments): MessageInterface
223
    {
224
        $this->attachments = $attachments;
225
226
        return $this;
227
    }
228
229
230
    /**
231
     * @inheritdoc
232
     */
233
    public function setContent(string $content): MessageInterface
234
    {
235
        $this->content = $content;
236
237
        return $this;
238
    }
239
240
241
    /**
242
     * @inheritdoc
243
     */
244
    public function setId(string $id): MessageInterface
245
    {
246
        $this->id = $id;
247
248
        return $this;
249
    }
250
251
252
    /**
253
     * @inheritDoc
254
     */
255
    public function setUpdateTime(string $updateTime): MessageInterface
256
    {
257
        $this->updateTime = $updateTime;
258
259
        return $this;
260
    }
261
262
263
    /**
264
     * @inheritDoc
265
     */
266
    public function toJson(bool $withAttachments = true): string
267
    {
268
        $jsonAr = [
269
            static::KEY_ID          => $this->getId(),
270
            static::KEY_CONTENT     => $this->getContent(),
271
            static::KEY_UPDATE_TIME => $this->getUpdateTime(),
272
        ];
273
274
        if ($withAttachments) {
275
            $jsonAr[static::KEY_ATTACHMENTS] = [];
276
            /** @var AttachmentInterface $attachment */
277
            foreach ($this->getAttachments() as $attachment) {
278
                $jsonAr[static::KEY_ATTACHMENTS][] = $attachment->getPath();
279
            }
280
        }
281
282
        return json_encode($jsonAr, JSON_UNESCAPED_UNICODE);
283
    }
284
}
285