10 Commits

4 changed files with 339 additions and 76 deletions

11
.editorconfig Normal file
View File

@@ -0,0 +1,11 @@
# @see http://EditorConfig.org
root = true
[src/**]
charset = utf-8
end_of_line = lf
tab_width = 4
indent_style = space
trim_trailing_whitespace = true
insert_final_newline = true

View File

@@ -13,11 +13,11 @@
"oauth2", "oauth2",
"client", "client",
"authorization", "authorization",
"authorisation", "authorization",
"1sept" "1sept"
], ],
"require": { "require": {
"php": "^7.0", "php": "^7.3 || ^8",
"league/oauth2-client": "^2.0" "league/oauth2-client": "^2.0"
}, },
"require-dev": { "require-dev": {

View File

@@ -1,17 +1,20 @@
<?php <?php
declare(strict_types=1);
namespace Sept\OAuth2\Client\Provider; namespace Sept\OAuth2\Client\Provider;
use League\OAuth2\Client\Provider\AbstractProvider; use League\OAuth2\Client\Provider\Exception\IdentityProviderException;
use League\OAuth2\Client\Provider\GenericProvider;
use League\OAuth2\Client\Provider\ResourceOwnerInterface;
use League\OAuth2\Client\Token\AccessToken; use League\OAuth2\Client\Token\AccessToken;
use League\OAuth2\Client\Tool\BearerAuthorizationTrait; use League\OAuth2\Client\Tool\BearerAuthorizationTrait;
use League\OAuth2\Client\Provider\Exception\IdentityProviderException;
use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ResponseInterface;
/** /**
* Провайдер данных Первого сентября * Провайдер данных Первого сентября
*/ */
class SeptemberFirstProvider extends AbstractProvider class SeptemberFirstProvider extends GenericProvider
{ {
use BearerAuthorizationTrait; use BearerAuthorizationTrait;
@@ -26,62 +29,71 @@ class SeptemberFirstProvider extends AbstractProvider
const API_BASE = 'https://api.1sept.ru'; const API_BASE = 'https://api.1sept.ru';
/** /**
* @var string Версия API * @var string[] Разрешения (scopes) по умолчанию
*/ */
const API_VERSION = '2.0'; const SCOPES_DEFAULT = ['profile'];
/** /**
* @inheritDoc * @var string Разделитель перечня запрашиваемых разрешений
*/ */
public function getBaseAuthorizationUrl(): string const SCOPES_SEPARATOR = ' ';
/**
* @var string Путь авторизации
*/
const AUTHORIZE_PATH = '/oauth/authorize';
/**
* @var string Путь получения токена
*/
const ACCESS_TOKEN_PATH = '/oauth/access_token';
/**
* @var string Путь получения данных пользователя
*/
const USERINFO_PATH = '/2.0/userinfo';
/**
* Undocumented function
*
* @param mixed[] $options
* @param object[] $collaborators
*/
public function __construct(array $options = [], array $collaborators = [])
{ {
return static::AUTH_BASE.'/oauth/authorize'; $defaultOptions = [
'urlAuthorize' => static::AUTH_BASE.static::AUTHORIZE_PATH,
'urlAccessToken' => static::API_BASE.static::ACCESS_TOKEN_PATH,
'urlResourceOwnerDetails' => static::API_BASE.static::USERINFO_PATH,
'scopes' => static::SCOPES_DEFAULT,
'scopeSeparator' => static::SCOPES_SEPARATOR,
];
parent::__construct(array_merge($defaultOptions, $options), $collaborators);
} }
/** /**
* @inheritDoc * Checks a provider response for errors.
*/ *
public function getBaseAccessTokenUrl(array $params): string * @param ResponseInterface $response
{ * @param mixed[]|string $data — Parsed response data
return static::API_BASE.'/oauth/access_token'; * @return void
} *
* @throws IdentityProviderException
/**
* @inheritDoc
*/
public function getResourceOwnerDetailsUrl(AccessToken $token): string
{
return static::API_BASE.'/'.static::API_VERSION.'/userinfo';
}
/**
* @inheritDoc
*/
public function getDefaultScopes(): array
{
return ['profile'];
}
/**
* @inheritDoc
*/
protected function getScopeSeparator(): string
{
return ' ';
}
/**
* @inheritDoc
*/ */
protected function checkResponse(ResponseInterface $response, $data): void protected function checkResponse(ResponseInterface $response, $data): void
{ {
if (!empty($data['error'])) { if (! empty($data['error'])) {
throw new IdentityProviderException($data['error'].': '.$data['message'], null, $response); throw new IdentityProviderException($data['error'].': '.$data['message'], 0, $response);
} }
} }
/** /**
* @inheritDoc * Generates a resource owner object from a successful resource owner details request.
*
* @param mixed[] $response
* @param AccessToken $token
* @return SeptemberFirstUser
*/ */
protected function createResourceOwner(array $response, AccessToken $token): SeptemberFirstUser protected function createResourceOwner(array $response, AccessToken $token): SeptemberFirstUser
{ {

View File

@@ -1,5 +1,7 @@
<?php <?php
declare(strict_types=1);
namespace Sept\OAuth2\Client\Provider; namespace Sept\OAuth2\Client\Provider;
use League\OAuth2\Client\Provider\ResourceOwnerInterface; use League\OAuth2\Client\Provider\ResourceOwnerInterface;
@@ -12,10 +14,13 @@ class SeptemberFirstUser implements ResourceOwnerInterface
const AVATAR_BASE = 'https://avatar.1sept.ru'; const AVATAR_BASE = 'https://avatar.1sept.ru';
/** /**
* @var array Массив с данными о пользователе * @var mixed[] Массив с данными о пользователе
*/ */
protected $data; protected array $data;
/**
* @param mixed[] $response
*/
public function __construct(array $response) public function __construct(array $response)
{ {
$this->data = $response; $this->data = $response;
@@ -24,7 +29,7 @@ class SeptemberFirstUser implements ResourceOwnerInterface
/** /**
* Массив с данными о пользователе * Массив с данными о пользователе
* *
* @return array * @return mixed[]
*/ */
public function toArray(): array public function toArray(): array
{ {
@@ -56,7 +61,7 @@ class SeptemberFirstUser implements ResourceOwnerInterface
/** /**
* Фамилия * Фамилия
* *
* @var string|null * @return string|null
*/ */
public function getLastName(): ?string public function getLastName(): ?string
{ {
@@ -66,7 +71,7 @@ class SeptemberFirstUser implements ResourceOwnerInterface
/** /**
* Имя * Имя
* *
* @var string|null * @return string|null
*/ */
public function getFirstName(): ?string public function getFirstName(): ?string
{ {
@@ -76,7 +81,7 @@ class SeptemberFirstUser implements ResourceOwnerInterface
/** /**
* Отчество * Отчество
* *
* @var string|null * @return string|null
*/ */
public function getMiddleName(): ?string public function getMiddleName(): ?string
{ {
@@ -113,6 +118,16 @@ class SeptemberFirstUser implements ResourceOwnerInterface
return $this->getField('sex'); return $this->getField('sex');
} }
/**
* Регалии
*
* @return string|null
*/
public function getRegalia(): string|null
{
return $this->getField('regalia');
}
/** /**
* Умер * Умер
* *
@@ -140,18 +155,20 @@ class SeptemberFirstUser implements ResourceOwnerInterface
*/ */
public function getBirthday(): ?\DateTime public function getBirthday(): ?\DateTime
{ {
return !empty($this->data['birthday']) ? new \DateTime($this->data['birthday']) : null; return ! empty($this->data['birthday']) ? new \DateTime($this->data['birthday']) : null;
} }
/** /**
* URL аватарки (150x150) * URL аватарки (150x150)
* *
* @param bool $addVersion Использовать версию аватарки для улучшенного кэширования * @param bool $rejectDefaultAvatar
* @return string|null * @return string|null
*
* @example https://avatar.1sept.ru/12121212-3456-7243-2134-432432144221.jpeg?v=12345
*/ */
public function getAvatarUrl(bool $addVersion = true): ?string public function getAvatarUrl(bool $rejectDefaultAvatar = false): ?string
{ {
return $this->getField('avatar') . ($addVersion ? $this->getAvatarVersionQuery() : ''); return ($rejectDefaultAvatar && $this->isDefaultAvatar()) ? null : $this->getField('avatar');
} }
/** /**
@@ -170,7 +187,7 @@ class SeptemberFirstUser implements ResourceOwnerInterface
} }
/** /**
* URL аватарки для экранов разных разрешений (<img srcset="…" width="size" height="size">) * URL аватарки для экранов разных разрешений (для <img srcset="…" width="size" height="size">)
* *
* @param int $size Размер от 1 до 1990 ($size x $size — квадрат) * @param int $size Размер от 1 до 1990 ($size x $size — квадрат)
* @param bool $addVersion Использовать версию аватарки для улучшенного кэширования * @param bool $addVersion Использовать версию аватарки для улучшенного кэширования
@@ -186,8 +203,10 @@ class SeptemberFirstUser implements ResourceOwnerInterface
/** /**
* URL аватарки c максимальным размером * URL аватарки c максимальным размером
* *
* @param bool $useVersion Использовать версию аватарки для улучшенного кэширования * @param bool $addVersion Использовать версию аватарки для улучшенного кэширования
* @return string|null * @return string|null
*
* @example https://avatar.1sept.ru/12121212-3456-7243-2134-432432144221.max.jpeg?v=12345
*/ */
public function getAvatarMaxUrl(bool $addVersion = false): ?string public function getAvatarMaxUrl(bool $addVersion = false): ?string
{ {
@@ -198,7 +217,7 @@ class SeptemberFirstUser implements ResourceOwnerInterface
* Версия аватарки * Версия аватарки
* Изменение версии сигнализирует об обновлении аватарки. * Изменение версии сигнализирует об обновлении аватарки.
* *
* @return int | null * @return int|null
*/ */
public function getAvatarVersion(): ?int public function getAvatarVersion(): ?int
@@ -209,31 +228,33 @@ class SeptemberFirstUser implements ResourceOwnerInterface
/** /**
* Является ли аватарка заглушкой * Является ли аватарка заглушкой
* *
* @return boolean * @return bool|null
*/ */
public function isDefaultAvatar(): bool public function isDefaultAvatar(): ?bool
{ {
return (bool) $this->getField('avatar_default'); return (bool) $this->getField('avatar_default');
} }
/** /**
* Query cтрока c версией аватарки (улучшает кэширование) * Query строка c версией аватарки (улучшает кэширование)
* *
* @return string * @return string
* @example ?v=12345;
*/ */
public function getAvatarVersionQuery(): string public function getAvatarVersionQuery(): string
{ {
$url = ''; $query = '';
if ($version = $this->getField('avatar_version')) { if ($version = $this->getField('avatar_version')) {
$url .= '?v=' . $version; $query .= '?v=' . $version;
} }
return $url; return $query;
} }
/** /**
* URL публичной страницы профиля * URL публичной страницы профиля
* *
* @return string|null * @return string|null
* @example https://vk.com/hello
*/ */
public function getProfileUrl(): ?string public function getProfileUrl(): ?string
{ {
@@ -241,13 +262,32 @@ class SeptemberFirstUser implements ResourceOwnerInterface
} }
/** /**
* Номер телефона * Номера телефонов
*
* @return array<int, array<string, string>>
* @example [
* [
* "canonical" => "+79161234567",
* "number" => "+7 (916) 123-45-67",
* "type" => "mobile"
* ],
* …
* ]
*/
public function getPhones(): ?array
{
return $this->getField('phones');
}
/**
* СНИЛС
* *
* @return string|null * @return string|null
* @example 123-456-789 01
*/ */
public function getPhone(): ?string public function getSnils(): ?string
{ {
return $this->getField('phone'); return $this->getField('passport.snils');
} }
/** /**
@@ -273,14 +313,37 @@ class SeptemberFirstUser implements ResourceOwnerInterface
} }
/** /**
* Почтовый адрес в строку * ID адреса
*
* @return int|null
* @example 12345
*/
public function getAddressID(): ?int
{
$id = $this->getField('address.id');
return $id ? (int) $id : null;
}
/**
* ID страны адреса
* *
* @return string|null * @return string|null
* @example ул. Гагарина, д.5, кв. 21, Нижний Новгород * @example RU
*/ */
public function getAddressInline(): ?string public function getAddressCountryID(): ?string
{ {
return $this->getField('address.inline'); return $this->getField('address.country_id');
}
/**
* ID региона страны адреса
*
* @return string|null
* @example MOW
*/
public function getAddressRegionID(): ?string
{
return $this->getField('address.region_id');
} }
/** /**
@@ -294,13 +357,189 @@ class SeptemberFirstUser implements ResourceOwnerInterface
return $this->getField('address.postal_code'); return $this->getField('address.postal_code');
} }
/**
* Район
*
* @return string|null
* @example Октябрьский район
*/
public function getAddressArea(): ?string
{
return $this->getField('address.area');
}
/**
* Город
*
* @return string|null
* @example Муром
*/
public function getAddressCity(): ?string
{
return $this->getField('address.city');
}
/**
* Улица
*
* @return string|null
* @example ул. Профсоюзная
*/
public function getAddressStreet(): ?string
{
return $this->getField('address.street');
}
/**
* Здание, сооружение, дом, владение, объект незавершенного строительства
*
* @return string|null
* @example д. 5
*/
public function getAddressHouse(): ?string
{
return $this->getField('address.house');
}
/**
* Строение
*
* @return string|null
* @example стр. 5
*/
public function getAddressBuilding(): ?string
{
return $this->getField('address.building');
}
/**
* Помещение в пределах здания, сооружения (Квартира, офис, помещение и т.д.)
*
* @return string|null
* @example кв. 1б | оф. 13 | помещ. 17
*/
public function getAddressFlat(): ?string
{
return $this->getField('address.flat');
}
/**
* До востребования
*
* @return boolean
* @example true
*/
public function isAddressGeneralDelivery(): bool
{
return (bool) $this->getField('address.general_delivery');
}
/**
* Абонентский ящик (А/Я)
*
* @return string|null
* @example а/я 123
*/
public function getAddressPostalBox(): ?string
{
return $this->getField('address.postal_box');
}
/**
* Организация по адресу
*
* @return string|null
* @example Школа №5
*/
public function getAddressOrganization(): ?string
{
return $this->getField('address.organization');
}
/**
* Почтовый адрес в строку (без индекса)
*
* @return string|null
* @example ул. Гагарина, д.5, кв. 21, Нижний Новгород
*/
public function getAddressInline(): ?string
{
return $this->getField('address.inline');
}
/**
* ID страны (анкета)
*
* @return string|null
* @example RU
*/
public function getLocationCountryID(): ?string
{
return $this->getField('location.country_id');
}
/**
* Название страны (анкета)
*
* @return string|null
* @example Россия
*/
public function getLocationCountryName(): ?string
{
return $this->getField('location.country_name');
}
/**
* Название страны по английски (анкета)
*
* @return string|null
* @example Russia
*/
public function getLocationCountryNameEnglish(): ?string
{
return $this->getField('location.country_name_eng');
}
/**
* ID региона страны (анкета)
*
* @return string|null
* @example MOW
*/
public function getLocationRegionID(): ?string
{
return $this->getField('location.region_id');
}
/**
* Название региона страны (анкета)
*
* @return string|null
* @example Москва
*/
public function getLocationRegionName(): ?string
{
return $this->getField('location.region_name');
}
/**
* Название региона страны по английски (анкета)
*
* @return string|null
* @example Moscow
*/
public function getLocationRegionNameEnglish(): ?string
{
return $this->getField('location.region_name_eng');
}
/** /**
* Элемент массива данных о пользователе * Элемент массива данных о пользователе
* *
* @param string $key Ключ поля (например: email или name.first — вложенность оформляется точкой) * @param string $key Ключ поля (например: email или name.first — вложенность оформляется точкой)
* @return mixed|null * @return mixed
*/ */
protected function getField(string $key) protected function getField(string $key): mixed
{ {
return static::getFieldFromArray($key, $this->data); return static::getFieldFromArray($key, $this->data);
} }
@@ -309,9 +548,10 @@ class SeptemberFirstUser implements ResourceOwnerInterface
* Значение массива (многомерного) * Значение массива (многомерного)
* *
* @param string $key Ключ поля (например: `email` или `name.first` — вложенность оформляется точкой) * @param string $key Ключ поля (например: `email` или `name.first` — вложенность оформляется точкой)
* @return mixed|null * @param mixed[] $array
* @return mixed
*/ */
public static function getFieldFromArray(string $key, ?array $array) public static function getFieldFromArray(string $key, ?array $array): mixed
{ {
if (strpos($key, '.')) { // key.subKey.subSubKey if (strpos($key, '.')) { // key.subKey.subSubKey
list ($key, $subKey) = explode('.', $key, 2); list ($key, $subKey) = explode('.', $key, 2);