Passed
Pull Request — develop (#20)
by Stephen
02:56
created

LogoutDiscourseUser::handle()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 26
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 16
c 1
b 0
f 0
nc 3
nop 1
dl 0
loc 26
ccs 0
cts 15
cp 0
crap 12
rs 9.7333
1
<?php
2
3
namespace Spinen\Discourse\Listeners;
4
5
use GuzzleHttp\Client;
6
use Illuminate\Contracts\Queue\ShouldQueue;
7
use Illuminate\Support\Facades\Log;
8
9
/**
10
 * Class LogoutDiscourseUser
11
 *
12
 * When logging out a Laravel user, send a Logout request to Discourse for that user also.
13
 *
14
 * @package Spinen\Discourse\Listeners
15
 */
16
class LogoutDiscourseUser implements ShouldQueue
17
{
18
    /**
19
     * @var Client
20
     */
21
    public $client;
22
23
    /**
24
     * Create the event listener.
25
     *
26
     * @param Client $client
27
     *
28
     * @return void
29
     */
30 1
    public function __construct(Client $client)
31
    {
32 1
        $this->client = $client;
33
    }
34
35
    /**
36
     * Handle the event.
37
     *
38
     * @param mixed $event
39
     *
40
     * @return void
41
     */
42
    public function handle($event)
43
    {
44
        if (!$event->user) {
45
            return;
46
        }
47
48
        $configs = [
49
            'base_uri' => config('services.discourse.url'),
0 ignored issues
show
Bug introduced by
The function config was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

49
            'base_uri' => /** @scrutinizer ignore-call */ config('services.discourse.url'),
Loading history...
50
            'headers'  => [
51
                'Api-Key'      => config('services.discourse.api.key'),
52
                'Api-Username' => config('services.discourse.api.user'),
53
            ],
54
        ];
55
56
        // Get Discourse user to match this one, and send a Logout request to Discourse and get the response
57
        $user = json_decode(
58
            $this->client->get("users/by-external/{$event->user->id}.json", $configs)
59
                         ->getBody()
60
        )->user;
61
62
        $response = $this->client->post("admin/users/{$user->id}/log_out");
63
64
        if ($response->getStatusCode() !== 200) {
65
            Log::notice(
66
                "When logging out user {$event->user->id} Discourse returned status code {$response->getStatusCode()}:",
67
                ['reason' => $response->getReasonPhrase()]
68
            );
69
        }
70
    }
71
}
72