Completed
Pull Request — master (#1418)
by milkmeowo
04:24 queued 01:28
created

SuiteTicket::setTicket()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 1
dl 0
loc 9
ccs 5
cts 5
cp 1
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
/*
4
 * This file is part of the overtrue/wechat.
5
 *
6
 * (c) overtrue <[email protected]>
7
 *
8
 * This source file is subject to the MIT license that is bundled
9
 * with this source code in the file LICENSE.
10
 */
11
12
namespace EasyWeChat\OpenWork\SuiteAuth;
13
14
use EasyWeChat\Kernel\Exceptions\RuntimeException;
15
use EasyWeChat\Kernel\Traits\InteractsWithCache;
16
use EasyWeChat\OpenWork\Application;
17
18
/**
19
 * SuiteTicket.
20
 *
21
 * @author xiaomin <[email protected]>
22
 */
23
class SuiteTicket
24
{
25
    use InteractsWithCache;
26
27
    /**
28
     * @var Application
29
     */
30
    protected $app;
31
32
    /**
33
     * SuiteTicket constructor.
34
     *
35
     * @param Application $app
36
     */
37 5
    public function __construct(Application $app)
38
    {
39 5
        $this->app = $app;
40 5
    }
41
42
    /**
43
     * @param string $ticket
44
     *
45
     * @return $this
46
     *
47
     * @throws \Psr\SimpleCache\InvalidArgumentException
48
     * @throws \EasyWeChat\Kernel\Exceptions\RuntimeException
49
     */
50 3
    public function setTicket(string $ticket)
51
    {
52 3
        $ok = $this->getCache()->set($this->getCacheKey(), $ticket, 1800);
53
54 3
        if (!$ok) {
55 1
            throw new RuntimeException('Failed to cache suite ticket.');
56
        }
57
58 2
        return $this;
59
    }
60
61
    /**
62
     * @return string
63
     *
64
     * @throws RuntimeException
65
     * @throws \Psr\SimpleCache\InvalidArgumentException
66
     */
67 3
    public function getTicket(): string
68
    {
69 3
        if ($cached = $this->getCache()->get($this->getCacheKey())) {
70 2
            return $cached;
71
        }
72
73 1
        throw new RuntimeException('Credential "suite_ticket" does not exist in cache.');
74
    }
75
76
    /**
77
     * @return string
78
     */
79 5
    protected function getCacheKey(): string
80
    {
81 5
        return 'easywechat.open_work.suite_ticket.'.$this->app['config']['suite_id'];
82
    }
83
}
84