Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save nguyenphuocnhatthanh/b93ddcda04ec716e153477fc7306c0a1 to your computer and use it in GitHub Desktop.
Save nguyenphuocnhatthanh/b93ddcda04ec716e153477fc7306c0a1 to your computer and use it in GitHub Desktop.
Social Account Service
<?php
namespace App\Services\Social;
use App\Exceptions\FurusatoException;
use App\Repositories\UserDeviceRepository;
use App\Repositories\UserRepository;
use Carbon\Carbon;
use DB;
use App\Models\User;
use App\Models\SocialAccount;
/**
* Class SocialAccountService
* @package App
*/
class SocialAccountService
{
/**
* @var mixed
*/
private $service;
/**
* @var
*/
private $provider;
/**
* SocialAccountService constructor.
* @param $provider
*/
public function __construct($provider)
{
$this->provider = $provider;
$this->service = $this->getSocialServiceByProvider($provider);
}
/**
* @param $provider
* @return mixed
* @throws FurusatoException
*/
private function getSocialServiceByProvider($provider)
{
switch ($provider) {
case 'facebook':
return app()->make(FacebookService::class);
case 'google':
return $this->service = app()->make(GoogleService::class);
}
throw new FurusatoException('Provider is invalid!');
}
/**
* Return one user
*
* @param array $params
* @return \App\Models\UserDevice
*/
public function firstOrCreate(array $params)
{
$social = $this->service->getData($params['access_token']);
$account = SocialAccount::whereProviderByUserSocial($this->provider, $social['id'])->first();
if ($account) {
return $account->user;
}
DB::transaction(function() use($social, $params, &$user) {
$account = new SocialAccount([
'provider_user_id' => $social['id'],
'provider' => $this->provider
]);
$user = User::whereEmail($social['email'])->first();
if (! $user) {
$user = new User();
$user->email = $social['email'];
$user->nickname = $social['nickname'];
$user->images = $social['images'];
$user->save();
}
$account->user()->associate($user);
$account->save();
});
return $user;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment