Completed
Push — master ( 0d2339...0b8e82 )
by Elf
04:03
created

UuidDriver::decode()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 9
ccs 4
cts 4
cp 1
rs 9.6666
cc 2
eloc 5
nc 2
nop 1
crap 2
1
<?php
2
3
namespace ElfSundae\Laravel\Hashid;
4
5
use Exception;
6
use Ramsey\Uuid\Uuid;
7
use Illuminate\Support\Arr;
8
use InvalidArgumentException;
9
10
class UuidDriver implements DriverInterface
11
{
12
    /**
13
     * The hashid manager instance.
14
     *
15
     * @var \ElfSundae\Laravel\Hashid\HashidManager
16
     */
17
    protected $manager;
18
19
    /**
20
     * The hashid connection name.
21
     *
22
     * @var string
23
     */
24
    protected $connection;
25
26
    /**
27
     * Create a new UUID driver instance.
28
     *
29
     * @param  \ElfSundae\Laravel\Hashid\HashidManager  $manager
30
     * @param  array  $config
31
     *
32
     * @throws \InvalidArgumentException
33
     */
34 4
    public function __construct(HashidManager $manager, array $config)
35
    {
36 4
        $this->manager = $manager;
37
38 4
        $this->connection = Arr::get($config, 'connection', function () {
39 1
            throw new InvalidArgumentException('A connection name must be specified.');
40 4
        });
41 3
    }
42
43
    /**
44
     * Encode the data.
45
     *
46
     * @param  string|\Ramsey\Uuid\Uuid  $data
47
     * @return string
48
     */
49 1
    public function encode($data)
50
    {
51 1
        $uuid = $data instanceof Uuid ? $data : Uuid::fromString($data);
52
53 1
        return $this->getConnection()->encode($uuid->getBytes());
54
    }
55
56
    /**
57
     * Decode the data.
58
     *
59
     * @param  string  $data
60
     * @return \Ramsey\Uuid\Uuid
61
     */
62 2
    public function decode($data)
63
    {
64
        try {
65 2
            return Uuid::fromBytes($this->getConnection()->decode($data));
66 1
        } catch (Exception $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
67
        }
68
69 1
        return Uuid::fromString(Uuid::NIL);
70
    }
71
72
    /**
73
     * Get the hashid connection instance.
74
     *
75
     * @return mixed
76
     */
77 2
    protected function getConnection()
78
    {
79 2
        return $this->manager->connection($this->connection);
80
    }
81
}
82