Просмотр файла app/Controllers/SocialController.php

Размер файла: 2.95Kb
  1. <?php
  2.  
  3. declare(strict_types=1);
  4.  
  5. namespace App\Controllers;
  6.  
  7. use App\Classes\Validator;
  8. use App\Models\Social;
  9. use App\Models\User;
  10. use Exception;
  11. use GuzzleHttp\Client;
  12. use GuzzleHttp\Exception\GuzzleException;
  13. use Illuminate\Http\Request;
  14.  
  15. class SocialController extends BaseController
  16. {
  17. /**
  18. * @var User
  19. */
  20. public $user;
  21.  
  22. /**
  23. * Конструктор
  24. */
  25. public function __construct()
  26. {
  27. parent::__construct();
  28.  
  29. if (! $this->user = getUser()) {
  30. abort(403, __('main.not_authorized'));
  31. }
  32. }
  33.  
  34. /**
  35. * Главная страница
  36. *
  37. * @param Request $request
  38. *
  39. * @return string
  40. * @throws GuzzleException
  41. */
  42. public function index(Request $request): string
  43. {
  44. if ($request->isMethod('post')) {
  45. $client = new Client(['timeout' => 30.0]);
  46.  
  47. $response = $client->get('//ulogin.ru/token.php', [
  48. 'query' => [
  49. 'token' => $request->input('token'),
  50. 'host' => $_SERVER['HTTP_HOST'],
  51. ]
  52. ]);
  53.  
  54. if ($response->getStatusCode() === 200) {
  55. $network = json_decode($response->getBody()->getContents());
  56.  
  57. $social = Social::query()
  58. ->where('network', $network->network)
  59. ->where('uid', $network->uid)
  60. ->first();
  61.  
  62. if (! $social) {
  63. Social::query()->create([
  64. 'user_id' => $this->user->id,
  65. 'network' => $network->network,
  66. 'uid' => $network->uid,
  67. 'created_at' => SITETIME,
  68. ]);
  69.  
  70. setFlash('success', __('socials.success_binding'));
  71. } else {
  72. setFlash('danger', __('socials.already_binding'));
  73. }
  74.  
  75. redirect('/socials');
  76. }
  77.  
  78. setFlash('danger', __('socials.failed_binding'));
  79. }
  80.  
  81. $socials = Social::query()
  82. ->where('user_id', $this->user->id)
  83. ->get();
  84.  
  85. return view('socials/index', compact('socials'));
  86. }
  87.  
  88. /**
  89. * Удаление привязки
  90. *
  91. * @param int $id
  92. * @param Request $request
  93. * @param Validator $validator
  94. *
  95. * @throws Exception
  96. */
  97. public function delete(int $id, Request $request, Validator $validator): void
  98. {
  99. $social = Social::query()->where('user_id', $this->user->id)->find($id);
  100.  
  101. $validator->equal($request->input('token'), $_SESSION['token'], __('validator.token'))
  102. ->notEmpty($social, __('socials.not_found_binding'));
  103.  
  104. if ($validator->isValid()) {
  105. $social->delete();
  106.  
  107. setFlash('success', __('socials.success_deleted'));
  108. } else {
  109. setFlash('danger', $validator->getErrors());
  110. }
  111.  
  112. redirect('/socials');
  113. }
  114. }