flush
[pharext/pharext.org] / app / Model / Accounts.php
1 <?php
2
3 namespace app\Model;
4
5 use pq\Connection;
6 use pq\Gateway\Table;
7 use pq\Query\Expr;
8
9 class Accounts extends Table
10 {
11 protected $rowset = "app\\Model\\AccountCollection";
12
13 /**
14 * @var \app\Model\Tokens
15 */
16 private $tokens;
17
18 /**
19 * @var \app\Model\Owners
20 */
21 private $owners;
22
23 function __construct(Connection $conn, Tokens $tokens, Owners $owners) {
24 parent::__construct("accounts", $conn);
25 $this->tokens = $tokens;
26 $this->owners = $owners;
27 }
28
29 function getTokens() {
30 return $this->tokens;
31 }
32
33 function getOwners() {
34 return $this->owners;
35 }
36
37 function byOAuth($authority, $token, $user) {
38 if (!($account = $this->byOAuthToken($authority, $token))) {
39 $account = $this->byOAuthOwner($authority, $user);
40 }
41 return $account;
42 }
43
44 function byOAuthToken($authority, $access_token, &$token = null) {
45 $tokens = $this->tokens->find([
46 "token=" => $access_token,
47 "authority=" => $authority,
48 ]);
49
50 if (count($tokens)) {
51 $token = $tokens->current();
52 $accounts = $this->by($token);
53 if (count($accounts)) {
54 return $accounts->current();
55 }
56 }
57 }
58
59 function byOAuthOwner($authority, $login, &$owner = null) {
60 $owners = $this->owners->find([
61 "authority=" => $authority,
62 "login=" => $login,
63 ]);
64
65 if (count($owners)) {
66 $owner = $owners->current();
67 $accounts = $this->by($owner);
68 if (count($accounts)) {
69 return $accounts->current();
70 }
71 }
72 }
73
74 function createOAuthAccount($authority, $token, $user) {
75 $account = $this->create([
76 "account" => new Expr("DEFAULT")
77 ])->current();
78 $this->owners->create([
79 "account" => $account->account,
80 "authority" => $authority,
81 "login" => $user,
82 ]);
83 $this->tokens->create([
84 "account" => $account->account,
85 "authority" => "github",
86 "token" => $token
87 ]);
88 return $account;
89 }
90 }