Compare commits
3 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 42969feac6 | |||
| b7fce352c9 | |||
| 99d4587b3b |
2
.gitignore
vendored
2
.gitignore
vendored
@@ -2,3 +2,5 @@ build
|
||||
composer.lock
|
||||
docs
|
||||
vendor
|
||||
.php-cs-fixer.cache
|
||||
.phpcs-cache
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
{
|
||||
"name": "1sept/oauth2-vkontakte",
|
||||
"version": "2.1.2",
|
||||
"description": "VK provider for league/oauth2-client",
|
||||
"keywords": [
|
||||
"league",
|
||||
@@ -13,7 +14,7 @@
|
||||
}
|
||||
],
|
||||
"require": {
|
||||
"php" : ">=8.1",
|
||||
"php" : ">=8.3",
|
||||
"league/oauth2-client": "^2.0"
|
||||
},
|
||||
"require-dev": {
|
||||
|
||||
20
phpcs.xml.dist
Normal file
20
phpcs.xml.dist
Normal file
@@ -0,0 +1,20 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
|
||||
<ruleset xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:noNamespaceSchemaLocation="vendor/squizlabs/php_codesniffer/phpcs.xsd">
|
||||
|
||||
<arg name="basepath" value="."/>
|
||||
<arg name="cache" value=".phpcs-cache"/>
|
||||
<arg name="colors"/>
|
||||
<arg name="extensions" value="php"/>
|
||||
|
||||
<rule ref="PSR12">
|
||||
<exclude name="Generic.Files.LineLength"/>
|
||||
<exclude name="PSR1.Methods.CamelCapsMethodName.NotCamelCaps"/>
|
||||
</rule>
|
||||
|
||||
<file>src/</file>
|
||||
|
||||
</ruleset>
|
||||
|
||||
<!-- composer require "squizlabs/php_codesniffer=*" dev -->
|
||||
14
phpstan.dist.neon
Normal file
14
phpstan.dist.neon
Normal file
@@ -0,0 +1,14 @@
|
||||
parameters:
|
||||
level: 5
|
||||
paths:
|
||||
- bin/
|
||||
- config/
|
||||
- public/
|
||||
- src/
|
||||
|
||||
errorFormat: table
|
||||
editorUrl: 'vscode://file/%%file%%:%%line%%'
|
||||
editorUrlTitle: '%%relFile%%:%%line%%'
|
||||
|
||||
ignoreErrors:
|
||||
- '#Construct empty\(\) is not allowed. Use more strict comparison.#'
|
||||
@@ -1,5 +1,7 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Sept\OAuth2\Client\Provider;
|
||||
|
||||
use League\OAuth2\Client\Provider\AbstractProvider;
|
||||
@@ -9,10 +11,10 @@ use Psr\Http\Message\ResponseInterface;
|
||||
|
||||
class VkProvider extends AbstractProvider
|
||||
{
|
||||
protected $baseOAuthUri = 'https://oauth.vk.com';
|
||||
protected $baseUri = 'https://api.vk.com/method';
|
||||
protected $version = '5.236';
|
||||
protected $language = null;
|
||||
protected string $baseOAuthUri = 'https://oauth.vk.com';
|
||||
protected string $baseUri = 'https://api.vk.com/method';
|
||||
protected float $version = 5.199;
|
||||
protected ?string $language = null;
|
||||
|
||||
/**
|
||||
* @see https://vk.com/dev/permissions
|
||||
@@ -21,25 +23,25 @@ class VkProvider extends AbstractProvider
|
||||
'email',
|
||||
// 'friends',
|
||||
// 'offline',
|
||||
//'photos',
|
||||
//'wall',
|
||||
//'ads',
|
||||
//'audio',
|
||||
//'docs',
|
||||
//'groups',
|
||||
//'market',
|
||||
//'messages',
|
||||
//'nohttps',
|
||||
//'notes',
|
||||
//'notifications',
|
||||
//'notify',
|
||||
//'pages',
|
||||
//'stats',
|
||||
//'status',
|
||||
//'video',
|
||||
// 'photos',
|
||||
// 'wall',
|
||||
// 'ads',
|
||||
// 'audio',
|
||||
// 'docs',
|
||||
// 'groups',
|
||||
// 'market',
|
||||
// 'messages',
|
||||
// 'nohttps',
|
||||
// 'notes',
|
||||
// 'notifications',
|
||||
// 'notify',
|
||||
// 'pages',
|
||||
// 'stats',
|
||||
// 'status',
|
||||
// 'video',
|
||||
];
|
||||
|
||||
/**
|
||||
* @type array
|
||||
* @see https://new.vk.com/dev/fields
|
||||
*/
|
||||
public array $userFields = [
|
||||
@@ -60,63 +62,62 @@ class VkProvider extends AbstractProvider
|
||||
'photo_max_orig',
|
||||
'screen_name',
|
||||
'sex',
|
||||
//'about',
|
||||
//'activities',
|
||||
//'blacklisted',
|
||||
//'blacklisted_by_me',
|
||||
//'books',
|
||||
//'can_post',
|
||||
//'can_see_all_posts',
|
||||
//'can_see_audio',
|
||||
//'can_send_friend_request',
|
||||
//'can_write_private_message',
|
||||
//'career',
|
||||
//'common_count',
|
||||
//'connections',
|
||||
//'contacts',
|
||||
//'crop_photo',
|
||||
//'counters',
|
||||
//'deactivated',
|
||||
//'education',
|
||||
//'exports',
|
||||
//'followers_count',
|
||||
//'games',
|
||||
//'has_mobile',
|
||||
//'hidden',
|
||||
//'interests',
|
||||
//'is_favorite',
|
||||
//'is_hidden_from_feed',
|
||||
//'last_seen',
|
||||
//'military',
|
||||
//'movies',
|
||||
//'occupation',
|
||||
//'online',
|
||||
//'personal',
|
||||
//'photo_100',
|
||||
//'photo_200',
|
||||
//'photo_200_orig',
|
||||
//'photo_400_orig',
|
||||
//'photo_50',
|
||||
//'photo_id',
|
||||
//'quotes',
|
||||
//'relation',
|
||||
//'relatives',
|
||||
//'schools',
|
||||
//'site',
|
||||
//'status',
|
||||
//'timezone',
|
||||
//'tv',
|
||||
//'universities',
|
||||
//'verified',
|
||||
//'wall_comments',
|
||||
'deactivated',
|
||||
'is_closed',
|
||||
// 'about',
|
||||
// 'activities',
|
||||
// 'blacklisted',
|
||||
// 'blacklisted_by_me',
|
||||
// 'books',
|
||||
// 'can_post',
|
||||
// 'can_see_all_posts',
|
||||
// 'can_see_audio',
|
||||
// 'can_send_friend_request',
|
||||
// 'can_write_private_message',
|
||||
// 'career',
|
||||
// 'common_count',
|
||||
// 'connections',
|
||||
// 'contacts',
|
||||
// 'crop_photo',
|
||||
// 'counters',
|
||||
// 'deactivated',
|
||||
// 'education',
|
||||
// 'exports',
|
||||
// 'followers_count',
|
||||
// 'games',
|
||||
// 'has_mobile',
|
||||
// 'hidden',
|
||||
// 'interests',
|
||||
// 'is_favorite',
|
||||
// 'is_hidden_from_feed',
|
||||
// 'last_seen',
|
||||
// 'military',
|
||||
// 'movies',
|
||||
// 'occupation',
|
||||
// 'online',
|
||||
// 'personal',
|
||||
// 'photo_100',
|
||||
// 'photo_200',
|
||||
// 'photo_200_orig',
|
||||
// 'photo_400_orig',
|
||||
// 'photo_50',
|
||||
// 'photo_id',
|
||||
// 'quotes',
|
||||
// 'relation',
|
||||
// 'relatives',
|
||||
// 'schools',
|
||||
// 'site',
|
||||
// 'status',
|
||||
// 'timezone',
|
||||
// 'tv',
|
||||
// 'universities',
|
||||
// 'verified',
|
||||
// 'wall_comments',
|
||||
];
|
||||
|
||||
/**
|
||||
* @param string $language
|
||||
*/
|
||||
public function setLanguage(string $language): self
|
||||
{
|
||||
$this->language = (string)$language;
|
||||
$this->language = $language;
|
||||
|
||||
return $this;
|
||||
}
|
||||
@@ -137,7 +138,7 @@ class VkProvider extends AbstractProvider
|
||||
'fields' => $this->userFields,
|
||||
'access_token' => $token->getToken(),
|
||||
'v' => $this->version,
|
||||
'lang' => $this->language
|
||||
'lang' => $this->language,
|
||||
];
|
||||
$query = $this->buildQueryString($params);
|
||||
$url = "$this->baseUri/users.get?$query";
|
||||
@@ -159,12 +160,13 @@ class VkProvider extends AbstractProvider
|
||||
// Response info
|
||||
$responseCode = $response->getStatusCode();
|
||||
$responseMessage = $response->getReasonPhrase();
|
||||
|
||||
// Data info
|
||||
$error = !empty($data['error']) ? $data['error'] : null;
|
||||
$errorCode = !empty($error['error_code']) ? $error['error_code'] : $responseCode;
|
||||
$errorDescription = !empty($data['error_description']) ? $data['error_description'] : null;
|
||||
$errorMessage = !empty($error['error_msg']) ? $error['error_msg'] : $errorDescription;
|
||||
$message = $errorMessage ?: $responseMessage;
|
||||
$message = (bool) $errorMessage ? $errorMessage : $responseMessage;
|
||||
|
||||
// Request/meta validation
|
||||
if (399 < $responseCode) {
|
||||
@@ -172,89 +174,93 @@ class VkProvider extends AbstractProvider
|
||||
}
|
||||
|
||||
// Content validation
|
||||
if ('application/json' != $contentType) {
|
||||
if ('application/json' !== $contentType) {
|
||||
throw new IdentityProviderException($message, $responseCode, $data);
|
||||
}
|
||||
if ($error) {
|
||||
throw new IdentityProviderException($errorMessage, $errorCode, $data);
|
||||
}
|
||||
}
|
||||
|
||||
protected function createResourceOwner(array $response, AccessToken $token): VkUser
|
||||
{
|
||||
$response = reset($response['response']);
|
||||
$additional = $token->getValues();
|
||||
|
||||
if (!empty($additional['email'])) {
|
||||
$response['email'] = $additional['email'];
|
||||
}
|
||||
if (!empty($response['uid']) && 4 === floor($this->version)) {
|
||||
|
||||
if (!empty($response['uid']) && 4 === (int) floor($this->version)) {
|
||||
$response['id'] = $response['uid'];
|
||||
}
|
||||
|
||||
if (!empty($additional['user_id'])) {
|
||||
$response['id'] = $additional['user_id'];
|
||||
}
|
||||
|
||||
return new VkUser($response, $response['id']);
|
||||
return new VkUser($response);
|
||||
}
|
||||
|
||||
/**
|
||||
* Возвращает массив объектов пользователей.
|
||||
*
|
||||
* @see https://vk.com/dev/users.get
|
||||
*
|
||||
* @param integer[] $ids
|
||||
* @param AccessToken|null $token Current user if empty
|
||||
* @param array $params
|
||||
*
|
||||
* @return User[]
|
||||
*/
|
||||
public function usersGet(array $ids = [], AccessToken $token = null, array $params = []): array
|
||||
public function usersGet(array $ids = [], ?AccessToken $token = null, array $params = []): array
|
||||
{
|
||||
if (empty($ids) && !$token) {
|
||||
if (empty($ids) && null === $token) {
|
||||
throw new \InvalidArgumentException('Some of parameters usersIds OR access_token are required');
|
||||
}
|
||||
|
||||
$default = [
|
||||
'user_ids' => implode(',', $ids),
|
||||
'fields' => $this->userFields,
|
||||
'access_token' => $token ? $token->getToken() : null,
|
||||
'access_token' => null !== $token ? $token->getToken() : null,
|
||||
'v' => $this->version,
|
||||
'lang' => $this->language
|
||||
'lang' => $this->language,
|
||||
];
|
||||
|
||||
$params = array_merge($default, $params);
|
||||
$query = $this->buildQueryString($params);
|
||||
$url = "$this->baseUri/users.get?$query";
|
||||
|
||||
$response = $this->getResponse($this->createRequest(static::METHOD_GET, $url, $token, []))['response'];
|
||||
$users = !empty($response['items']) ? $response['items'] : $response;
|
||||
$array2user = function ($userData) {
|
||||
|
||||
$array2user = function (mixed $userData) {
|
||||
return new VkUser($userData);
|
||||
};
|
||||
|
||||
return array_map($array2user, $users);
|
||||
}
|
||||
|
||||
/**
|
||||
* Возвращает список идентификаторов (id) друзей пользователя,
|
||||
* если параметр fields не использовался. При использовании
|
||||
* параметра fields возвращает список объектов пользователей,
|
||||
* но не более 5000.
|
||||
*
|
||||
* @see https://vk.com/dev/friends.get
|
||||
*
|
||||
* @param integer $userId
|
||||
* @param AccessToken|null $token
|
||||
* @param array $params
|
||||
*
|
||||
* @return User[]
|
||||
*/
|
||||
public function friendsGet($userId, AccessToken $token = null, array $params = []): array
|
||||
public function friendsGet(int $userId, ?AccessToken $token = null, array $params = []): array
|
||||
{
|
||||
$default = [
|
||||
'user_id' => $userId,
|
||||
'fields' => $this->userFields,
|
||||
'access_token' => $token ? $token->getToken() : null,
|
||||
'access_token' => null !== $token ? $token->getToken() : null,
|
||||
'v' => $this->version,
|
||||
'lang' => $this->language
|
||||
'lang' => $this->language,
|
||||
];
|
||||
|
||||
$params = array_merge($default, $params);
|
||||
$query = $this->buildQueryString($params);
|
||||
$url = "$this->baseUri/friends.get?$query";
|
||||
|
||||
$response = $this->getResponse($this->createRequest(static::METHOD_GET, $url, $token, []))['response'];
|
||||
$friends = !empty($response['items']) ? $response['items'] : $response;
|
||||
$array2friend = function ($friendData) {
|
||||
|
||||
$array2friend = function (mixed $friendData) {
|
||||
if (is_numeric($friendData)) {
|
||||
$friendData = ['id' => $friendData];
|
||||
}
|
||||
|
||||
126
src/VkUser.php
126
src/VkUser.php
@@ -1,5 +1,7 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Sept\OAuth2\Client\Provider;
|
||||
|
||||
use League\OAuth2\Client\Provider\ResourceOwnerInterface;
|
||||
@@ -9,10 +11,7 @@ use League\OAuth2\Client\Provider\ResourceOwnerInterface;
|
||||
*/
|
||||
class VkUser implements ResourceOwnerInterface
|
||||
{
|
||||
/**
|
||||
* @type array
|
||||
*/
|
||||
protected $response;
|
||||
protected array $response;
|
||||
|
||||
/**
|
||||
* User constructor.
|
||||
@@ -22,129 +21,200 @@ class VkUser implements ResourceOwnerInterface
|
||||
$this->response = $response;
|
||||
}
|
||||
|
||||
/**
|
||||
* Вернуть все поля массивом
|
||||
*/
|
||||
public function toArray(): array
|
||||
{
|
||||
return $this->response;
|
||||
}
|
||||
|
||||
/**
|
||||
* Идентификатор пользователя.
|
||||
*/
|
||||
public function getId(): int
|
||||
{
|
||||
return (int)($this->getField('uid') ?: $this->getField('id'));
|
||||
return (int) ((bool) $this->getField('uid') ? $this->getField('uid') : $this->getField('id'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper for getting user data
|
||||
* Helper for getting user data.
|
||||
*/
|
||||
protected function getField(string $key): mixed
|
||||
{
|
||||
return !empty($this->response[$key]) ? $this->response[$key] : null;
|
||||
return \array_key_exists($key, $this->response) ? $this->response[$key] : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Дата рождения. Возвращается в формате D.M.YYYY или D.M (если год рождения скрыт). Если дата рождения скрыта целиком, поле отсутствует в ответе.
|
||||
*
|
||||
* @return string|null DD.MM.YYYY
|
||||
*/
|
||||
public function getBirthday():string
|
||||
public function getBirthday(): ?string
|
||||
{
|
||||
return $this->getField('bdate');
|
||||
}
|
||||
|
||||
/**
|
||||
* Информация о городе, указанном на странице пользователя в разделе «Контакты». Возвращаются следующие поля:
|
||||
* id (integer) — идентификатор города, который можно использовать для получения его названия с помощью метода database.getCitiesById;
|
||||
* title (string) — название города.
|
||||
*
|
||||
* @return array [id =>, title => string]
|
||||
*/
|
||||
public function getCity(): array
|
||||
public function getCity(): ?array
|
||||
{
|
||||
return $this->getField('city');
|
||||
}
|
||||
|
||||
/**
|
||||
* Информация о стране, указанной на странице пользователя в разделе «Контакты». Возвращаются следующие поля:
|
||||
* id (integer) — идентификатор страны, который можно использовать для получения ее названия с помощью метода database.getCountriesById;
|
||||
* title (string) — название страны.
|
||||
*
|
||||
* @return array [id =>, title => string]
|
||||
*/
|
||||
public function getCountry(): array
|
||||
public function getCountry(): ?array
|
||||
{
|
||||
return $this->getField('country');
|
||||
}
|
||||
|
||||
/**
|
||||
* Short address to user page
|
||||
* Короткий адрес страницы. Возвращается строка, содержащая короткий адрес страницы (например, andrew).
|
||||
* Если он не назначен, возвращается "id"+user_id, например, id35828305.
|
||||
*
|
||||
* Short address to user page.
|
||||
*/
|
||||
public function getDomain(): string|null
|
||||
public function getDomain(): ?string
|
||||
{
|
||||
return $this->getField('domain');
|
||||
}
|
||||
|
||||
public function getFirstName(): string|null
|
||||
/**
|
||||
* Имя.
|
||||
*/
|
||||
public function getFirstName(): ?string
|
||||
{
|
||||
return $this->getField('first_name');
|
||||
}
|
||||
|
||||
/**
|
||||
* Friend status.
|
||||
*
|
||||
* @return int 0|1|2|3 => nobody|resquest_sent|incoming_request|friends
|
||||
*/
|
||||
public function getFriendStatus(): int
|
||||
public function getFriendStatus(): ?int
|
||||
{
|
||||
return $this->getField('friend_Status');
|
||||
}
|
||||
|
||||
/**
|
||||
* Has user avatar?
|
||||
* Информация о том, установил ли пользователь фотографию для профиля. Возвращаемые значения: 1 — установил, 0 — не установил.
|
||||
*/
|
||||
public function isHasPhoto(): bool
|
||||
{
|
||||
return (bool)$this->getField('has_photo');
|
||||
return (bool) $this->getField('has_photo');
|
||||
}
|
||||
|
||||
public function getHomeTown(): string|null
|
||||
/**
|
||||
* Название родного города.
|
||||
*/
|
||||
public function getHomeTown(): ?string
|
||||
{
|
||||
return $this->getField('home_town');
|
||||
}
|
||||
|
||||
/**
|
||||
* Detect if current user is freind to this
|
||||
* Detect if current user is freind to this.
|
||||
*/
|
||||
public function isFriend(): bool
|
||||
{
|
||||
return (bool)$this->getField('is_friend');
|
||||
return (bool) $this->getField('is_friend');
|
||||
}
|
||||
|
||||
public function getLastName(): string|null
|
||||
/**
|
||||
* Фамилия.
|
||||
*/
|
||||
public function getLastName(): ?string
|
||||
{
|
||||
return $this->getField('last_name');
|
||||
}
|
||||
|
||||
public function getMaidenName(): string|null
|
||||
/**
|
||||
* Девичья фамилия.
|
||||
*/
|
||||
public function getMaidenName(): ?string
|
||||
{
|
||||
return $this->getField('maiden_name');
|
||||
}
|
||||
|
||||
public function getNickname(): string|null
|
||||
/**
|
||||
* Никнейм (отчество) пользователя.
|
||||
*/
|
||||
public function getNickname(): ?string
|
||||
{
|
||||
return $this->getField('nickname');
|
||||
}
|
||||
|
||||
/**
|
||||
* It's square!
|
||||
* URL квадратной фотографии с максимальной шириной.
|
||||
* Может быть возвращена фотография, имеющая ширину как 200, так и 100 пикселей.
|
||||
* В случае отсутствия у пользователя фотографии возвращается https://vk.com/images/camera_200.png.
|
||||
*/
|
||||
public function getPhotoMax():string
|
||||
public function getPhotoMax(): ?string
|
||||
{
|
||||
return $this->getField('photo_max');
|
||||
}
|
||||
|
||||
public function getPhotoMaxOrig(): string|null
|
||||
/**
|
||||
* URL фотографии максимального размера. Может быть возвращена фотография,
|
||||
* имеющая ширину как 400, так и 200 пикселей.
|
||||
* В случае отсутствия у пользователя фотографии возвращается https://vk.com/images/camera_400.png.
|
||||
*/
|
||||
public function getPhotoMaxOrig(): ?string
|
||||
{
|
||||
return $this->getField('photo_max_orig');
|
||||
}
|
||||
|
||||
public function getScreenName(): string|null
|
||||
/**
|
||||
* Короткое имя страницы.
|
||||
*/
|
||||
public function getScreenName(): ?string
|
||||
{
|
||||
return $this->getField('screen_name');
|
||||
}
|
||||
|
||||
public function getSex(): int
|
||||
/**
|
||||
* Пол. Возможные значения
|
||||
* 1 — женский;
|
||||
* 2 — мужской;
|
||||
* 0 — пол не указан.
|
||||
*/
|
||||
public function getSex(): ?int
|
||||
{
|
||||
return $this->getField('sex');
|
||||
}
|
||||
|
||||
public function getEmail(): string|null
|
||||
public function getEmail(): ?string
|
||||
{
|
||||
return $this->getField('email');
|
||||
}
|
||||
|
||||
/**
|
||||
* Поле возвращается, если страница пользователя удалена или заблокирована, содержит значение deleted или banned. В этом случае опциональные поля не возвращаются.
|
||||
*
|
||||
* @return string null|deleted|banned
|
||||
*/
|
||||
public function getDeactivated(): ?string
|
||||
{
|
||||
return $this->getField('deactivated');
|
||||
}
|
||||
|
||||
/**
|
||||
* Скрыт ли профиль пользователя настройками приватности.
|
||||
*/
|
||||
public function isClosed(): bool
|
||||
{
|
||||
return $this->getField('is_closed');
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user