Passed
Push — master ( c34bce...f6db7f )
by Artem
01:28
created

AssessmentService::retrieveUniqueRemotes()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 13
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 10
nc 1
nop 1
dl 0
loc 13
ccs 0
cts 9
cp 0
crap 2
rs 9.9332
c 0
b 0
f 0
1
<?php
2
3
namespace Slides\Connector\Auth\Services\Assessment;
4
5
use Slides\Connector\Auth\Repositories\UserRepository;
6
7
/**
8
 * Class AssessmentService
9
 *
10
 * @package Slides\Connector\Auth\Services\Assessment
11
 */
12
class AssessmentService
13
{
14
    /**
15
     * @var UserRepository
16
     */
17
    protected $users;
18
19
    /**
20
     * AssessmentService constructor.
21
     *
22
     * @param UserRepository $users
23
     */
24
    public function __construct(UserRepository $users)
25
    {
26
        $this->users = $users;
27
    }
28
29
    /**
30
     * Differentiate users with the passed ones.
31
     *
32
     * @param array $keys The remote user keys.
33
     *
34
     * @return array
35
     */
36
    public function differentiateUsers(array $keys): array
37
    {
38
        return [
39
            'uniqueServiceUserKeys' => $this->retrieveUniqueLocals($keys),
40
            'uniqueRemoteKeys' => $this->retrieveUniqueRemotes($keys)
41
        ];
42
    }
43
44
    /**
45
     * Retrieve remote users that not exist locally.
46
     *
47
     * @param array $remoteKeys
48
     *
49
     * @return \Illuminate\Support\Collection
50
     */
51
    protected function retrieveUniqueRemotes(array $remoteKeys)
52
    {
53
        return $this->users->withTemporaryTable('unknownRemotesTable',
54
            function(\Illuminate\Database\Schema\Blueprint $table) {
55
                $table->bigInteger('id');
56
            },
57
            array_map(function($key) {
58
                return ['id' => $key];
59
            }, $remoteKeys),
60
            function(\Illuminate\Database\Eloquent\Builder $query, $table) {
61
                return $query->rightJoin($table, $table . '.id', $this->users->table() . '.remote_id')
62
                    ->whereNull($this->users->table() . '.id')
63
                    ->pluck($table . '.id');
64
            }
65
        );
66
    }
67
68
    /**
69
     * Retrieve local users that not exist remotely.
70
     *
71
     * @param array $remoteKeys
72
     *
73
     * @return \Illuminate\Support\Collection
74
     */
75
    protected function retrieveUniqueLocals(array $remoteKeys)
76
    {
77
        return $this->users->query()
78
            ->whereNotIn('remote_id', $remoteKeys)
79
            ->orWhereNull('remote_id')
80
            ->get();
81
    }
82
}