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

LogoutDiscourseUser   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 52
Duplicated Lines 0 %

Test Coverage

Coverage 11.76%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 4
eloc 19
c 2
b 0
f 0
dl 0
loc 52
ccs 2
cts 17
cp 0.1176
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A handle() 0 26 3
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