MessageMapper::toArray()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 1
eloc 2
c 1
b 0
f 1
nc 1
nop 0
dl 0
loc 4
rs 10
1
<?php
2
/**
3
 * This file is part of GitterBot package.
4
 *
5
 * @author butschster <[email protected]>
6
 * @date 20.207.2016 17:08
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
namespace Interfaces\Slack;
12
13
use Carbon\Carbon;
14
use Domains\Room\RoomInterface;
15
use Illuminate\Contracts\Support\Arrayable;
16
use Interfaces\Gitter\Support\AttributeMapper;
17
18
class MessageMapper implements Arrayable
19
{
20
    /**
21
     * @var array
22
     */
23
    protected $attributes;
24
25
    /**
26
     * MessageMapper constructor.
27
     *
28
     * @param RoomInterface $room
29
     * @param array         $attributes
30
     */
31
    public function __construct(RoomInterface $room, $attributes)
32
    {
33
        $fields = ['gitter_id', 'text', 'html', 'edited', 'user', 'unread',
34
            'read_by', 'urls', 'mentions', 'issues', 'meta', 'created_at', 'updated_at', 'room_id'];
35
36
        $this->attributes = (new AttributeMapper($attributes))
37
            ->rename('channel', 'room_id')
38
            ->value('user', function ($user) use($room) {
39
                return $room->client()->getUserById($user);
40
            })
41
            ->value('ts', function ($date) {
42
                return Carbon::createFromTimestamp($date)->setTimezone('Europe/Moscow');
43
            }, 'created_at')
44
            ->value('mentions', function ($ids) use($room) {
45
                $users = [];
46
                if (is_array($ids)) {
47
                    foreach ($ids as $userId) {
48
                        $users[] = $room->client()->getUserById($userId);
49
                    }
50
                }
51
52
                return $users;
53
            })
54
            ->only($fields)
55
            ->toArray();
56
57
        if (!array_key_exists('room_id', $this->attributes)) {
58
            $this->attributes['room_id'] = $room->id();
59
        }
60
61
        $this->attributes['gitter_id'] = md5($room->id());
62
    }
63
64
    /**
65
     * Get the instance as an array.
66
     *
67
     * @return array
68
     */
69
    public function toArray()
70
    {
71
        return $this->attributes;
72
    }
73
}