flush
[pharext/pharext.org] / app / Controller / Github / Callback.php
1 <?php
2
3 namespace app\Controller\Github;
4
5 use app\Controller\Github;
6 use app\Github\API;
7 use app\Github\Exception;
8 use app\Model\Accounts;
9 use app\Session;
10 use app\Web;
11
12 class Callback extends Github
13 {
14
15 /**
16 * @var Accounts
17 */
18 private $accounts;
19
20 function __construct(Web $app, API $github, Session $session, Accounts $accounts) {
21 parent::__construct($app, $github, $session);
22 $this->accounts = $accounts;
23 }
24
25 function __invoke(array $args = null) {
26 if ($this->app->getRequest()->getQuery("error")) {
27 $this->app->getView()->addData([
28 "error" => $this->app->getRequest()->getQuery("error_description")
29 ]);
30 } else {
31 try {
32 $this->github->fetchToken(
33 $this->app->getRequest()->getQuery("code"),
34 $this->app->getRequest()->getQuery("state"),
35 function($token) {
36 $this->github->setToken($token->access_token);
37 $this->github->fetchUser($this->createUserCallback($token));
38 })->send();
39 if (isset($this->session->returnto)) {
40 $returnto = $this->session->returnto;
41 unset($this->session->returnto);
42 $this->app->redirect($returnto);
43 } else {
44 $this->app->redirect(
45 $this->app->getBaseUrl()->mod("./github"));
46 }
47 } catch (Exception $exception) {
48 $this->app->getView()->addData(compact("exception"));
49 }
50 }
51 $this->app->display("github/callback");
52 }
53
54 function createUserCallback($token) {
55 return function($user) use($token) {
56 $tx = $this->accounts->getConnection()->startTransaction();
57
58 if (!($account = $this->accounts->byOAuth("github", $token->access_token, $user->login))) {
59 $account = $this->accounts->createOAuthAccount("github", $token->access_token, $user->login);
60 }
61 $account->updateToken("github", $token->access_token, $token);
62 $owner = $account->updateOwner("github", $user->login, $user);
63
64 $tx->commit();
65
66 $this->session->account = $account->account->get();
67 $this->session->github = (object) $owner->export();
68 };
69 }
70 }