From 23c2ea20402fa7329688296b881fabcbdf6fc0e8 Mon Sep 17 00:00:00 2001
From: Schizo
Date: Sat, 22 Oct 2022 22:02:55 +0300
Subject: [PATCH 01/24] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB?=
=?UTF-8?q?=D0=B5=D0=BD=D0=B0=20=D0=BC=D0=BE=D0=B4=D0=B5=D0=BB=D1=8C=20?=
=?UTF-8?q?=D0=BF=D0=BE=D0=BB=D1=8C=D0=B7=D0=BE=D0=B2=D0=B0=D1=82=D0=B5?=
=?UTF-8?q?=D0=BB=D1=8F=20=D0=B2=20=D1=84=D0=B0=D1=81=D0=B0=D0=B4=20=D0=B8?=
=?UTF-8?q?=20=D0=B2=D1=85=D0=BE=D0=B4=D1=8F=D1=89=D0=B5=D0=B5=20=D1=81?=
=?UTF-8?q?=D0=BE=D0=BE=D0=B1=D1=89=D0=B5=D0=BD=D0=B8=D0=B5?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
LICENSE.md | 2 +-
README.md => README_RU.md | 32 +-
composer.json | 15 +-
src/.root/config/vk-sdk.php | 58 +-
.../migrations/create_events_table.php | 30 +
src/.root/lang/en.php | 162 --
src/.root/lang/ru.php | 317 ++--
src/.root/routes/callbacks.php | 29 +-
src/Contracts/CallbackEventsContract.php | 155 +-
src/Contracts/CanFormat.php | 5 +-
.../Api/Accesses/AccessAlbumException.php | 23 -
.../Api/Accesses/AccessAudioException.php | 22 -
.../Api/Accesses/AccessCommentException.php | 22 -
.../Api/Accesses/AccessException.php | 22 -
.../Api/Accesses/AccessGroupException.php | 22 -
.../Api/Accesses/AccessGroupsException.php | 22 -
.../Api/Accesses/AccessMarketException.php | 22 -
.../Api/Accesses/AccessMenuException.php | 22 -
.../Accesses/AccessNoteCommentException.php | 22 -
.../Api/Accesses/AccessNoteException.php | 22 -
.../Api/Accesses/AccessPageException.php | 22 -
.../Api/Accesses/AccessVideoException.php | 22 -
.../Api/Ads/AdsObjectDeletedException.php | 22 -
.../Api/Ads/AdsPartialSuccessException.php | 22 -
.../Api/Ads/AdsPermissionException.php | 22 -
.../Api/Ads/AdsSpecificException.php | 22 -
.../Api/Albums/AlbumFullException.php | 22 -
.../Api/Albums/AlbumsLimitException.php | 23 -
src/Exceptions/Api/ApiError.php | 112 --
src/Exceptions/Api/ApiException.php | 71 +-
src/Exceptions/Api/ApiExceptionMapper.php | 56 +-
src/Exceptions/Api/Apps/AppAuthException.php | 22 -
.../Api/Apps/AppsAlreadyUnlockedException.php | 23 -
...AppsSubscriptionInvalidStatusException.php | 22 -
.../AppsSubscriptionNotFoundException.php | 22 -
.../Api/Auth/AuthDelayException.php | 22 -
src/Exceptions/Api/Auth/AuthException.php | 22 -
.../Api/Auth/AuthFloodException.php | 22 -
.../Api/Auth/AuthHttpsException.php | 22 -
.../Api/Auth/AuthValidationException.php | 22 -
...ttyCardsCardIsConnectedToPostException.php | 22 -
.../PrettyCardsCardNotFoundException.php | 22 -
.../PrettyCardsTooManyCardsException.php | 22 -
.../Api/Common/ActionFailedException.php | 23 -
.../Api/Common/BlockedException.php | 23 -
.../CallbackApiServersLimitException.php | 20 -
.../Api/Common/CaptchaException.php | 22 -
.../Api/Common/CompileException.php | 23 -
.../Api/Common/DisabledException.php | 23 -
.../Api/Common/EnabledInTestException.php | 23 -
src/Exceptions/Api/Common/FloodException.php | 23 -
.../Api/Common/InsufficientFundsException.php | 23 -
.../Api/Common/InvalidAddressException.php | 23 -
src/Exceptions/Api/Common/LimitsException.php | 23 -
.../Common/MobileNotActivatedException.php | 23 -
.../Api/Common/NotFoundException.php | 23 -
.../Api/Common/PermissionException.php | 23 -
.../Api/Common/PhoneAlreadyUsedException.php | 23 -
.../Api/Common/PhotoChangedException.php | 23 -
.../Api/Common/PrivateProfileException.php | 23 -
.../Api/Common/RateLimitException.php | 23 -
.../Api/Common/RequestException.php | 23 -
.../Api/Common/RuntimeException.php | 23 -
.../Api/Common/SaveFileException.php | 23 -
src/Exceptions/Api/Common/ServerException.php | 23 -
.../Api/Common/SignatureException.php | 23 -
.../Api/Common/StatusNoAudioException.php | 23 -
.../Api/Common/TooManyException.php | 23 -
.../Api/Common/TooManyListsException.php | 23 -
.../Api/Common/UnknownException.php | 23 -
src/Exceptions/Api/Common/UploadException.php | 23 -
.../Api/Common/UserDeletedException.php | 23 -
.../Api/Common/WeightedFloodException.php | 23 -
.../CommunitiesCatalogDisabledException.php | 22 -
...CommunitiesCategoriesDisabledException.php | 22 -
.../NeedConfirmationException.php | 23 -
.../NeedTokenConfirmationException.php | 23 -
.../Api/Friends/FriendsAddEnemyException.php | 22 -
.../Friends/FriendsAddInEnemyException.php | 22 -
.../Friends/FriendsAddNotFoundException.php | 22 -
.../Friends/FriendsAddYourselfException.php | 22 -
.../Api/Friends/FriendsListIdException.php | 22 -
.../Api/Friends/FriendsListLimitException.php | 22 -
...pAppIsNotInstalledInCommunityException.php | 22 -
.../Api/Groups/GroupAuthException.php | 22 -
.../Groups/GroupChangeCreatorException.php | 22 -
.../Api/Groups/GroupHostNeed2FaException.php | 22 -
.../Api/Groups/GroupNeed2FaException.php | 22 -
.../Api/Groups/GroupNotInClubException.php | 22 -
.../Groups/GroupTooManyAddressesException.php | 22 -
.../Groups/GroupTooManyOfficersException.php | 22 -
.../Api/HttpStatusCodeException.php | 19 +
.../Market/MarketAlbumNotFoundException.php | 22 -
.../Market/MarketCommentsClosedException.php | 22 -
...emsMustHaveDistinctPropertiesException.php | 22 -
...ingMustContainMoreThanOneItemException.php | 22 -
.../MarketItemAlreadyAddedException.php | 22 -
.../Market/MarketItemHasBadLinksException.php | 22 -
.../Market/MarketItemNotFoundException.php | 22 -
.../MarketPropertyNotFoundException.php | 22 -
.../Market/MarketRestoreTooLateException.php | 22 -
.../Market/MarketTooManyAlbumsException.php | 22 -
.../Market/MarketTooManyItemsException.php | 22 -
.../MarketTooManyItemsInAlbumException.php | 22 -
.../Market/MarketVariantNotFoundException.php | 22 -
.../MessagesCantChangeInviteLinkException.php | 23 -
.../MessagesCantDeleteForAllException.php | 23 -
.../Api/Messages/MessagesCantFwdException.php | 23 -
.../MessagesCantPinOneTimeStoryException.php | 23 -
.../MessagesCantSeeInviteLinkException.php | 23 -
.../MessagesChatBotFeatureException.php | 23 -
.../MessagesChatNotAdminException.php | 23 -
.../MessagesChatNotExistException.php | 23 -
.../MessagesChatUserNoAccessException.php | 23 -
.../MessagesChatUserNotInChatException.php | 23 -
.../MessagesContactNotFoundException.php | 23 -
.../Messages/MessagesDenySendException.php | 23 -
.../Messages/MessagesEditExpiredException.php | 23 -
.../MessagesEditKindDisallowedException.php | 23 -
.../MessagesGroupPeerAccessException.php | 23 -
.../MessagesKeyboardInvalidException.php | 23 -
...agesMessageRequestAlreadySendException.php | 23 -
...agesMessageRequestAlreadySentException.php | 23 -
.../Api/Messages/MessagesPrivacyException.php | 23 -
.../Api/Messages/MessagesTooBigException.php | 23 -
.../MessagesTooLongForwardsException.php | 23 -
.../MessagesTooLongMessageException.php | 23 -
.../MessagesTooManyPostsException.php | 23 -
.../Messages/MessagesTooNewPtsException.php | 23 -
.../Messages/MessagesTooOldPtsException.php | 23 -
.../Messages/MessagesUserBlockedException.php | 23 -
.../Api/Methods/MethodAdsException.php | 22 -
.../Api/Methods/MethodDisabledException.php | 22 -
.../Api/Methods/MethodException.php | 22 -
.../Api/Methods/MethodPermissionException.php | 22 -
.../Api/Parameters/ParamAlbumIdException.php | 22 -
.../Api/Parameters/ParamApiIdException.php | 22 -
.../Parameters/ParamDocAccessException.php | 22 -
.../ParamDocDeleteAccessException.php | 22 -
.../Api/Parameters/ParamDocIdException.php | 22 -
.../Api/Parameters/ParamDocTitleException.php | 22 -
.../Api/Parameters/ParamException.php | 22 -
.../Api/Parameters/ParamGroupIdException.php | 22 -
.../Api/Parameters/ParamHashException.php | 22 -
.../Api/Parameters/ParamNoteIdException.php | 22 -
.../Api/Parameters/ParamPageIdException.php | 22 -
.../Api/Parameters/ParamPhoneException.php | 22 -
.../Api/Parameters/ParamPhotoException.php | 22 -
.../Api/Parameters/ParamPhotosException.php | 22 -
.../Api/Parameters/ParamServerException.php | 22 -
.../Parameters/ParamTimestampException.php | 22 -
.../Api/Parameters/ParamTitleException.php | 22 -
.../Api/Parameters/ParamUserIdException.php | 22 -
.../Api/Polls/PollsAccessException.php | 22 -
.../Polls/PollsAccessWithoutVoteException.php | 22 -
.../Api/Polls/PollsAnswerIdException.php | 22 -
.../Api/Polls/PollsPollIdException.php | 22 -
.../Api/Story/StoryExpiredException.php | 22 -
.../StoryIncorrectReplyPrivacyException.php | 22 -
.../Api/Video/VideoAlreadyAddedException.php | 22 -
.../Video/VideoCommentsClosedException.php | 22 -
src/Exceptions/Api/Votes/VotesException.php | 22 -
.../Api/Votes/VotesPermissionException.php | 22 -
.../Api/Walls/WallAccessAddReplyException.php | 22 -
.../Api/Walls/WallAccessCommentException.php | 22 -
.../Api/Walls/WallAccessPostException.php | 22 -
.../Api/Walls/WallAccessRepliesException.php | 22 -
.../Api/Walls/WallAddPostException.php | 22 -
.../WallAdsPostLimitReachedException.php | 22 -
.../Api/Walls/WallAdsPublishedException.php | 22 -
.../Api/Walls/WallLinksForbiddenException.php | 22 -
.../Walls/WallReplyOwnerFloodException.php | 22 -
.../Walls/WallTooManyRecipientsException.php | 22 -
src/Exceptions/Callback/CallbackException.php | 52 +-
src/Exceptions/SdkException.php | 52 +
src/Facades/Format.php | 9 +-
src/Facades/Group.php | 17 -
src/Facades/SdkConfig.php | 20 +
src/Facades/{Configure.php => VkApi.php} | 8 +-
.../ArrayParametersRequestFormatter.php | 30 +
...ClearEmptiesParametersRequestFormatter.php | 26 +
src/Formatters/JsonExceptionFormatter.php | 3 +-
src/Formatters/JsonLogFormatter.php | 19 +-
src/Foundation/Core/Api/Client.php | 41 +
src/Foundation/Core/Api/Languages.php | 21 +
src/Foundation/Core/Api/OAuth.php | 102 ++
src/Foundation/Core/Api/Request.php | 127 ++
src/Foundation/Core/Callback/BaseEvent.php | 84 ++
.../Core/Callback/EventsHandler.php | 345 +++++
src/Foundation/Core/CallbackEventsHandler.php | 342 -----
src/Foundation/Core/Community.php | 1306 -----------------
src/Foundation/Core/Community/Links.php | 127 --
src/Foundation/Core/GroupInstance.php | 8 -
.../Core/Models/Client/ClientFields.php | 80 +
.../Models/Groups/AddressWorkInfoStatus.php | 16 +
src/Foundation/Core/Models/Groups/Group.php | 176 +++
.../Core/Models/Groups/GroupAccess.php | 14 +
.../Core/Models/Groups/GroupAgeLimits.php | 14 +
.../Core/Models/Groups/GroupAudio.php | 14 +
.../Core/Models/Groups/GroupDocs.php | 20 +
.../Models/Groups/GroupMarketCurrency.php | 28 +
.../Core/Models/Groups/GroupPhotos.php | 20 +
.../Core/Models/Groups/GroupRole.php | 20 +
.../Core/Models/Groups/GroupSubject.php | 176 +++
.../Core/Models/Groups/GroupTopics.php | 20 +
.../Core/Models/Groups/GroupVideo.php | 20 +
.../Core/Models/Groups/GroupWall.php | 24 +
.../Core/Models/Groups/GroupWiki.php | 20 +
.../Messages/Attachments/Audio/Audio.php | 46 +
.../Models/Messages/Attachments/Photo.php | 81 +
.../Core/Models/Messages/Message.php | 198 +++
.../Core/Models/Messages/MessageFields.php | 160 ++
.../Models/Messages/MessageRequestFields.php | 393 +++++
src/Foundation/Core/Models/Owner/Owner.php | 19 +
src/Foundation/Core/Models/Users/User.php | 50 +
.../Core/Models/Users/UserFields.php | 95 ++
.../Core/Models/Users/UserNameCases.php | 18 +
.../Core/Models/Users/UserProfileFields.php | 78 +
.../Core/Models/Users/UserRequestFields.php | 55 +
src/Foundation/Core/PrivateMessage.php | 199 ---
.../Format.php} | 8 +-
.../{Configure.php => SdkConfig.php} | 32 +-
src/Models/Event.php | 21 +
src/Providers/ServiceProvider.php | 17 +-
src/Services/CallbackEventService.php | 24 +-
225 files changed, 3212 insertions(+), 6301 deletions(-)
rename README.md => README_RU.md (62%)
create mode 100644 src/.root/database/migrations/create_events_table.php
delete mode 100644 src/.root/lang/en.php
delete mode 100644 src/Exceptions/Api/Accesses/AccessAlbumException.php
delete mode 100644 src/Exceptions/Api/Accesses/AccessAudioException.php
delete mode 100644 src/Exceptions/Api/Accesses/AccessCommentException.php
delete mode 100644 src/Exceptions/Api/Accesses/AccessException.php
delete mode 100644 src/Exceptions/Api/Accesses/AccessGroupException.php
delete mode 100644 src/Exceptions/Api/Accesses/AccessGroupsException.php
delete mode 100644 src/Exceptions/Api/Accesses/AccessMarketException.php
delete mode 100644 src/Exceptions/Api/Accesses/AccessMenuException.php
delete mode 100644 src/Exceptions/Api/Accesses/AccessNoteCommentException.php
delete mode 100644 src/Exceptions/Api/Accesses/AccessNoteException.php
delete mode 100644 src/Exceptions/Api/Accesses/AccessPageException.php
delete mode 100644 src/Exceptions/Api/Accesses/AccessVideoException.php
delete mode 100644 src/Exceptions/Api/Ads/AdsObjectDeletedException.php
delete mode 100644 src/Exceptions/Api/Ads/AdsPartialSuccessException.php
delete mode 100644 src/Exceptions/Api/Ads/AdsPermissionException.php
delete mode 100644 src/Exceptions/Api/Ads/AdsSpecificException.php
delete mode 100644 src/Exceptions/Api/Albums/AlbumFullException.php
delete mode 100644 src/Exceptions/Api/Albums/AlbumsLimitException.php
delete mode 100644 src/Exceptions/Api/ApiError.php
delete mode 100644 src/Exceptions/Api/Apps/AppAuthException.php
delete mode 100644 src/Exceptions/Api/Apps/AppsAlreadyUnlockedException.php
delete mode 100644 src/Exceptions/Api/Apps/AppsSubscriptionInvalidStatusException.php
delete mode 100644 src/Exceptions/Api/Apps/AppsSubscriptionNotFoundException.php
delete mode 100644 src/Exceptions/Api/Auth/AuthDelayException.php
delete mode 100644 src/Exceptions/Api/Auth/AuthException.php
delete mode 100644 src/Exceptions/Api/Auth/AuthFloodException.php
delete mode 100644 src/Exceptions/Api/Auth/AuthHttpsException.php
delete mode 100644 src/Exceptions/Api/Auth/AuthValidationException.php
delete mode 100644 src/Exceptions/Api/Cards/PrettyCardsCardIsConnectedToPostException.php
delete mode 100644 src/Exceptions/Api/Cards/PrettyCardsCardNotFoundException.php
delete mode 100644 src/Exceptions/Api/Cards/PrettyCardsTooManyCardsException.php
delete mode 100644 src/Exceptions/Api/Common/ActionFailedException.php
delete mode 100644 src/Exceptions/Api/Common/BlockedException.php
delete mode 100644 src/Exceptions/Api/Common/CallbackApiServersLimitException.php
delete mode 100644 src/Exceptions/Api/Common/CaptchaException.php
delete mode 100644 src/Exceptions/Api/Common/CompileException.php
delete mode 100644 src/Exceptions/Api/Common/DisabledException.php
delete mode 100644 src/Exceptions/Api/Common/EnabledInTestException.php
delete mode 100644 src/Exceptions/Api/Common/FloodException.php
delete mode 100644 src/Exceptions/Api/Common/InsufficientFundsException.php
delete mode 100644 src/Exceptions/Api/Common/InvalidAddressException.php
delete mode 100644 src/Exceptions/Api/Common/LimitsException.php
delete mode 100644 src/Exceptions/Api/Common/MobileNotActivatedException.php
delete mode 100644 src/Exceptions/Api/Common/NotFoundException.php
delete mode 100644 src/Exceptions/Api/Common/PermissionException.php
delete mode 100644 src/Exceptions/Api/Common/PhoneAlreadyUsedException.php
delete mode 100644 src/Exceptions/Api/Common/PhotoChangedException.php
delete mode 100644 src/Exceptions/Api/Common/PrivateProfileException.php
delete mode 100644 src/Exceptions/Api/Common/RateLimitException.php
delete mode 100644 src/Exceptions/Api/Common/RequestException.php
delete mode 100644 src/Exceptions/Api/Common/RuntimeException.php
delete mode 100644 src/Exceptions/Api/Common/SaveFileException.php
delete mode 100644 src/Exceptions/Api/Common/ServerException.php
delete mode 100644 src/Exceptions/Api/Common/SignatureException.php
delete mode 100644 src/Exceptions/Api/Common/StatusNoAudioException.php
delete mode 100644 src/Exceptions/Api/Common/TooManyException.php
delete mode 100644 src/Exceptions/Api/Common/TooManyListsException.php
delete mode 100644 src/Exceptions/Api/Common/UnknownException.php
delete mode 100644 src/Exceptions/Api/Common/UploadException.php
delete mode 100644 src/Exceptions/Api/Common/UserDeletedException.php
delete mode 100644 src/Exceptions/Api/Common/WeightedFloodException.php
delete mode 100644 src/Exceptions/Api/Community/CommunitiesCatalogDisabledException.php
delete mode 100644 src/Exceptions/Api/Community/CommunitiesCategoriesDisabledException.php
delete mode 100644 src/Exceptions/Api/Confirmation/NeedConfirmationException.php
delete mode 100644 src/Exceptions/Api/Confirmation/NeedTokenConfirmationException.php
delete mode 100644 src/Exceptions/Api/Friends/FriendsAddEnemyException.php
delete mode 100644 src/Exceptions/Api/Friends/FriendsAddInEnemyException.php
delete mode 100644 src/Exceptions/Api/Friends/FriendsAddNotFoundException.php
delete mode 100644 src/Exceptions/Api/Friends/FriendsAddYourselfException.php
delete mode 100644 src/Exceptions/Api/Friends/FriendsListIdException.php
delete mode 100644 src/Exceptions/Api/Friends/FriendsListLimitException.php
delete mode 100644 src/Exceptions/Api/Groups/GroupAppIsNotInstalledInCommunityException.php
delete mode 100644 src/Exceptions/Api/Groups/GroupAuthException.php
delete mode 100644 src/Exceptions/Api/Groups/GroupChangeCreatorException.php
delete mode 100644 src/Exceptions/Api/Groups/GroupHostNeed2FaException.php
delete mode 100644 src/Exceptions/Api/Groups/GroupNeed2FaException.php
delete mode 100644 src/Exceptions/Api/Groups/GroupNotInClubException.php
delete mode 100644 src/Exceptions/Api/Groups/GroupTooManyAddressesException.php
delete mode 100644 src/Exceptions/Api/Groups/GroupTooManyOfficersException.php
create mode 100644 src/Exceptions/Api/HttpStatusCodeException.php
delete mode 100644 src/Exceptions/Api/Market/MarketAlbumNotFoundException.php
delete mode 100644 src/Exceptions/Api/Market/MarketCommentsClosedException.php
delete mode 100644 src/Exceptions/Api/Market/MarketGroupingItemsMustHaveDistinctPropertiesException.php
delete mode 100644 src/Exceptions/Api/Market/MarketGroupingMustContainMoreThanOneItemException.php
delete mode 100644 src/Exceptions/Api/Market/MarketItemAlreadyAddedException.php
delete mode 100644 src/Exceptions/Api/Market/MarketItemHasBadLinksException.php
delete mode 100644 src/Exceptions/Api/Market/MarketItemNotFoundException.php
delete mode 100644 src/Exceptions/Api/Market/MarketPropertyNotFoundException.php
delete mode 100644 src/Exceptions/Api/Market/MarketRestoreTooLateException.php
delete mode 100644 src/Exceptions/Api/Market/MarketTooManyAlbumsException.php
delete mode 100644 src/Exceptions/Api/Market/MarketTooManyItemsException.php
delete mode 100644 src/Exceptions/Api/Market/MarketTooManyItemsInAlbumException.php
delete mode 100644 src/Exceptions/Api/Market/MarketVariantNotFoundException.php
delete mode 100644 src/Exceptions/Api/Messages/MessagesCantChangeInviteLinkException.php
delete mode 100644 src/Exceptions/Api/Messages/MessagesCantDeleteForAllException.php
delete mode 100644 src/Exceptions/Api/Messages/MessagesCantFwdException.php
delete mode 100644 src/Exceptions/Api/Messages/MessagesCantPinOneTimeStoryException.php
delete mode 100644 src/Exceptions/Api/Messages/MessagesCantSeeInviteLinkException.php
delete mode 100644 src/Exceptions/Api/Messages/MessagesChatBotFeatureException.php
delete mode 100644 src/Exceptions/Api/Messages/MessagesChatNotAdminException.php
delete mode 100644 src/Exceptions/Api/Messages/MessagesChatNotExistException.php
delete mode 100644 src/Exceptions/Api/Messages/MessagesChatUserNoAccessException.php
delete mode 100644 src/Exceptions/Api/Messages/MessagesChatUserNotInChatException.php
delete mode 100644 src/Exceptions/Api/Messages/MessagesContactNotFoundException.php
delete mode 100644 src/Exceptions/Api/Messages/MessagesDenySendException.php
delete mode 100644 src/Exceptions/Api/Messages/MessagesEditExpiredException.php
delete mode 100644 src/Exceptions/Api/Messages/MessagesEditKindDisallowedException.php
delete mode 100644 src/Exceptions/Api/Messages/MessagesGroupPeerAccessException.php
delete mode 100644 src/Exceptions/Api/Messages/MessagesKeyboardInvalidException.php
delete mode 100644 src/Exceptions/Api/Messages/MessagesMessageRequestAlreadySendException.php
delete mode 100644 src/Exceptions/Api/Messages/MessagesMessageRequestAlreadySentException.php
delete mode 100644 src/Exceptions/Api/Messages/MessagesPrivacyException.php
delete mode 100644 src/Exceptions/Api/Messages/MessagesTooBigException.php
delete mode 100644 src/Exceptions/Api/Messages/MessagesTooLongForwardsException.php
delete mode 100644 src/Exceptions/Api/Messages/MessagesTooLongMessageException.php
delete mode 100644 src/Exceptions/Api/Messages/MessagesTooManyPostsException.php
delete mode 100644 src/Exceptions/Api/Messages/MessagesTooNewPtsException.php
delete mode 100644 src/Exceptions/Api/Messages/MessagesTooOldPtsException.php
delete mode 100644 src/Exceptions/Api/Messages/MessagesUserBlockedException.php
delete mode 100644 src/Exceptions/Api/Methods/MethodAdsException.php
delete mode 100644 src/Exceptions/Api/Methods/MethodDisabledException.php
delete mode 100644 src/Exceptions/Api/Methods/MethodException.php
delete mode 100644 src/Exceptions/Api/Methods/MethodPermissionException.php
delete mode 100644 src/Exceptions/Api/Parameters/ParamAlbumIdException.php
delete mode 100644 src/Exceptions/Api/Parameters/ParamApiIdException.php
delete mode 100644 src/Exceptions/Api/Parameters/ParamDocAccessException.php
delete mode 100644 src/Exceptions/Api/Parameters/ParamDocDeleteAccessException.php
delete mode 100644 src/Exceptions/Api/Parameters/ParamDocIdException.php
delete mode 100644 src/Exceptions/Api/Parameters/ParamDocTitleException.php
delete mode 100644 src/Exceptions/Api/Parameters/ParamException.php
delete mode 100644 src/Exceptions/Api/Parameters/ParamGroupIdException.php
delete mode 100644 src/Exceptions/Api/Parameters/ParamHashException.php
delete mode 100644 src/Exceptions/Api/Parameters/ParamNoteIdException.php
delete mode 100644 src/Exceptions/Api/Parameters/ParamPageIdException.php
delete mode 100644 src/Exceptions/Api/Parameters/ParamPhoneException.php
delete mode 100644 src/Exceptions/Api/Parameters/ParamPhotoException.php
delete mode 100644 src/Exceptions/Api/Parameters/ParamPhotosException.php
delete mode 100644 src/Exceptions/Api/Parameters/ParamServerException.php
delete mode 100644 src/Exceptions/Api/Parameters/ParamTimestampException.php
delete mode 100644 src/Exceptions/Api/Parameters/ParamTitleException.php
delete mode 100644 src/Exceptions/Api/Parameters/ParamUserIdException.php
delete mode 100644 src/Exceptions/Api/Polls/PollsAccessException.php
delete mode 100644 src/Exceptions/Api/Polls/PollsAccessWithoutVoteException.php
delete mode 100644 src/Exceptions/Api/Polls/PollsAnswerIdException.php
delete mode 100644 src/Exceptions/Api/Polls/PollsPollIdException.php
delete mode 100644 src/Exceptions/Api/Story/StoryExpiredException.php
delete mode 100644 src/Exceptions/Api/Story/StoryIncorrectReplyPrivacyException.php
delete mode 100644 src/Exceptions/Api/Video/VideoAlreadyAddedException.php
delete mode 100644 src/Exceptions/Api/Video/VideoCommentsClosedException.php
delete mode 100644 src/Exceptions/Api/Votes/VotesException.php
delete mode 100644 src/Exceptions/Api/Votes/VotesPermissionException.php
delete mode 100644 src/Exceptions/Api/Walls/WallAccessAddReplyException.php
delete mode 100644 src/Exceptions/Api/Walls/WallAccessCommentException.php
delete mode 100644 src/Exceptions/Api/Walls/WallAccessPostException.php
delete mode 100644 src/Exceptions/Api/Walls/WallAccessRepliesException.php
delete mode 100644 src/Exceptions/Api/Walls/WallAddPostException.php
delete mode 100644 src/Exceptions/Api/Walls/WallAdsPostLimitReachedException.php
delete mode 100644 src/Exceptions/Api/Walls/WallAdsPublishedException.php
delete mode 100644 src/Exceptions/Api/Walls/WallLinksForbiddenException.php
delete mode 100644 src/Exceptions/Api/Walls/WallReplyOwnerFloodException.php
delete mode 100644 src/Exceptions/Api/Walls/WallTooManyRecipientsException.php
create mode 100644 src/Exceptions/SdkException.php
delete mode 100644 src/Facades/Group.php
create mode 100644 src/Facades/SdkConfig.php
rename src/Facades/{Configure.php => VkApi.php} (56%)
create mode 100644 src/Formatters/ArrayParametersRequestFormatter.php
create mode 100644 src/Formatters/ClearEmptiesParametersRequestFormatter.php
create mode 100644 src/Foundation/Core/Api/Client.php
create mode 100644 src/Foundation/Core/Api/Languages.php
create mode 100644 src/Foundation/Core/Api/OAuth.php
create mode 100644 src/Foundation/Core/Api/Request.php
create mode 100644 src/Foundation/Core/Callback/BaseEvent.php
create mode 100644 src/Foundation/Core/Callback/EventsHandler.php
delete mode 100644 src/Foundation/Core/CallbackEventsHandler.php
delete mode 100644 src/Foundation/Core/Community.php
delete mode 100644 src/Foundation/Core/Community/Links.php
delete mode 100644 src/Foundation/Core/GroupInstance.php
create mode 100644 src/Foundation/Core/Models/Client/ClientFields.php
create mode 100644 src/Foundation/Core/Models/Groups/AddressWorkInfoStatus.php
create mode 100644 src/Foundation/Core/Models/Groups/Group.php
create mode 100644 src/Foundation/Core/Models/Groups/GroupAccess.php
create mode 100644 src/Foundation/Core/Models/Groups/GroupAgeLimits.php
create mode 100644 src/Foundation/Core/Models/Groups/GroupAudio.php
create mode 100644 src/Foundation/Core/Models/Groups/GroupDocs.php
create mode 100644 src/Foundation/Core/Models/Groups/GroupMarketCurrency.php
create mode 100644 src/Foundation/Core/Models/Groups/GroupPhotos.php
create mode 100644 src/Foundation/Core/Models/Groups/GroupRole.php
create mode 100644 src/Foundation/Core/Models/Groups/GroupSubject.php
create mode 100644 src/Foundation/Core/Models/Groups/GroupTopics.php
create mode 100644 src/Foundation/Core/Models/Groups/GroupVideo.php
create mode 100644 src/Foundation/Core/Models/Groups/GroupWall.php
create mode 100644 src/Foundation/Core/Models/Groups/GroupWiki.php
create mode 100644 src/Foundation/Core/Models/Messages/Attachments/Audio/Audio.php
create mode 100644 src/Foundation/Core/Models/Messages/Attachments/Photo.php
create mode 100644 src/Foundation/Core/Models/Messages/Message.php
create mode 100644 src/Foundation/Core/Models/Messages/MessageFields.php
create mode 100644 src/Foundation/Core/Models/Messages/MessageRequestFields.php
create mode 100644 src/Foundation/Core/Models/Owner/Owner.php
create mode 100644 src/Foundation/Core/Models/Users/User.php
create mode 100644 src/Foundation/Core/Models/Users/UserFields.php
create mode 100644 src/Foundation/Core/Models/Users/UserNameCases.php
create mode 100644 src/Foundation/Core/Models/Users/UserProfileFields.php
create mode 100644 src/Foundation/Core/Models/Users/UserRequestFields.php
delete mode 100644 src/Foundation/Core/PrivateMessage.php
rename src/{Formatters/BaseFormatter.php => Foundation/Format.php} (83%)
rename src/Foundation/{Configure.php => SdkConfig.php} (62%)
create mode 100644 src/Models/Event.php
diff --git a/LICENSE.md b/LICENSE.md
index 3ad2180..03ba601 100644
--- a/LICENSE.md
+++ b/LICENSE.md
@@ -1,6 +1,6 @@
# MIT License
-> Copyright (c) 2022 [Schizo](https://vk.com/id244036703), [AnnieNiku](https://vk.com/id116596882)
+> Copyright (c) 2022 [Schizo](https://vk.com/id244036703), translated by [AnnieNiku](https://vk.com/id116596882)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
diff --git a/README.md b/README_RU.md
similarity index 62%
rename from README.md
rename to README_RU.md
index 30df347..8b57491 100644
--- a/README.md
+++ b/README_RU.md
@@ -2,9 +2,7 @@
-# Laravel VK API SDK
-
-
+
@@ -12,39 +10,35 @@
+> #### You can read the [English version](https://github.com/H0pex/laravel-vk-sdk/README_EN)
+
[Laravel](https://github.com/laravel/laravel) библиотека для упрощенного использования API модулей социальной сети ВКонтакте.
Предназначена для быстрого развертывания приложений-ботов, а также использования VK API в одностороннем порядке.
-### Содержание
-* [Приступая к работе](#Приступая к работе)
- * [Установка](#Установка)
- * [Внутренние зависимости](#Внутренние зависимости)
-* [Лицензия](#license)
-
-## Приступая к работе
-
-### Установка
-Установка пакета через [composer](https://getcomposer.org/):
+# Установка
+Осуществить установку можно используя [composer](https://getcomposer.org/):
```
composer require hopex/vk-api-sdk
```
-#### Внутренние зависимости
-Публикация зависимостей:
+Публикация необходимых ресурсов:
```
-php artisan vendor:publish --provider=Hopex\VkSdk\Providers\ServiceProvider --tag=vk-sdk-config --tag=vk-sdk-lang
+php artisan vendor:publish --tag=vk-sdk-config --tag=vk-sdk-lang
```
Провайдер и фасады будут автоматически зарегистрированы, однако вы можете вручную добавить их в `config/app.php`.
```php
'providers' => [
// ...
- Hopex\VkApiSdk\Providers\VkApiSdkServiceProvider::class,
+ Hopex\VkApiSdk\Providers\ServiceProvider::class,
],
'aliases' => Facade::defaultAliases()->merge([
// ...
- 'VkApiSdk' => \Hopex\VkApiSdk\Facade::class,
+ 'VkApi' => \Hopex\VkSdk\Foundation\Core\Api\Client::class,
+ 'Format' => \Hopex\VkSdk\Foundation\Format::class,
+ 'SdkConfig' => \Hopex\VkSdk\Foundation\SdkConfig::class,
])->toArray(),
```
-# Лицензия [MIT](https://github.com/H0pex/vk-api-sdk/LICENSE)
+# Лицензия
+[MIT License](https://github.com/H0pex/vk-api-sdk/LICENSE)
diff --git a/composer.json b/composer.json
index 09ab714..3e476a6 100644
--- a/composer.json
+++ b/composer.json
@@ -1,6 +1,6 @@
{
"name": "hopex/laravel-vk-sdk",
- "description": "Laravel SDK для быстрого развертывания приложений-ботов и простого использования VK API.",
+ "description": "Laravel SDK for fast deployment of bot applications and easy use of VK API.",
"type": "library",
"license": "MIT",
"version": "0.0.2",
@@ -13,10 +13,11 @@
}
],
"require": {
- "php": "^7.4||^8",
+ "php": "^8",
"ext-json": "*"
},
"require-dev": {
+ "barryvdh/laravel-ide-helper": "^2.12"
},
"autoload": {
"psr-4": {
@@ -29,12 +30,18 @@
"Hopex\\VkSdk\\Providers\\ServiceProvider"
],
"aliases": {
- "Group": "Hopex\\VkSdk\\Facades\\Group",
+ "VkApi": "Hopex\\VkSdk\\Facades\\VkApi",
"Format": "Hopex\\VkSdk\\Facades\\Format",
- "Configure": "Hopex\\VkSdk\\Facades\\Configure"
+ "SdkConfig": "Hopex\\VkSdk\\Facades\\SdkConfig"
}
}
},
+ "repositories": [
+ {
+ "type": "git",
+ "url": "https://github.com/H0pex/laravel-vk-sdk"
+ }
+ ],
"config": {
"optimize-autoloader": true
},
diff --git a/src/.root/config/vk-sdk.php b/src/.root/config/vk-sdk.php
index b93a720..c8c8aec 100644
--- a/src/.root/config/vk-sdk.php
+++ b/src/.root/config/vk-sdk.php
@@ -56,7 +56,8 @@
// TODO: исправить документацию для api и groups
'api' => [
- 'endpoint' => 'https://api.vk.com/method/',
+ 'auth' => 'https://oauth.vk.com',
+ 'endpoint' => 'https://api.vk.com/method',
'version' => '5.131',
],
@@ -68,7 +69,15 @@
'code' => '745cc77d276cf36c694e',
'verify' => true,
],
- 'events' => \App\VK\Chat::class
+ 'events' => \App\VK\Chat::class,
+ 'allow_retry_events' => true,
+ ],
+ ],
+
+ 'apps' => [
+ '7967757' => [
+ 'token' => 'b89c4892b89c4892b89c4892aeb8e5dc9fbb89cb89c4892d9c7b14801fb3358d6dcd092',
+ 'secret' => 'OaQA1ddYuF2PLGAGKOjd',
],
],
@@ -102,49 +111,4 @@
],
],
],
-
- /*
- |--------------------------------------------------------------------------
- | Базовые коды ошибок
- |--------------------------------------------------------------------------
- */
-
- 'errors' => [
- '1' => \Hopex\VkSdk\Exceptions\Api\Common\UnknownException::class,
- '2' => \Hopex\VkSdk\Exceptions\Api\Common\DisabledException::class,
- '3' => \Hopex\VkSdk\Exceptions\Api\Methods\MethodException::class,
- '4' => \Hopex\VkSdk\Exceptions\Api\Common\SignatureException::class,
- '5' => \Hopex\VkSdk\Exceptions\Api\Auth\AuthException::class,
- '6' => \Hopex\VkSdk\Exceptions\Api\Common\TooManyException::class,
- '7' => \Hopex\VkSdk\Exceptions\Api\Common\PermissionException::class,
- '8' => \Hopex\VkSdk\Exceptions\Api\Common\RequestException::class,
- '9' => \Hopex\VkSdk\Exceptions\Api\Common\FloodException::class,
- '10' => \Hopex\VkSdk\Exceptions\Api\Common\ServerException::class,
- '11' => \Hopex\VkSdk\Exceptions\Api\Common\EnabledInTestException::class,
- '14' => \Hopex\VkSdk\Exceptions\Api\Common\CaptchaException::class,
- '15' => \Hopex\VkSdk\Exceptions\Api\Accesses\AccessException::class,
- '16' => \Hopex\VkSdk\Exceptions\Api\Auth\AuthHttpsException::class,
- '17' => \Hopex\VkSdk\Exceptions\Api\Auth\AuthValidationException::class,
- '18' => \Hopex\VkSdk\Exceptions\Api\Common\UserDeletedException::class,
- '20' => \Hopex\VkSdk\Exceptions\Api\Methods\MethodPermissionException::class,
- '21' => \Hopex\VkSdk\Exceptions\Api\Methods\MethodAdsException::class,
- '23' => \Hopex\VkSdk\Exceptions\Api\Methods\MethodDisabledException::class,
- '24' => \Hopex\VkSdk\Exceptions\Api\Confirmation\NeedConfirmationException::class,
- '25' => \Hopex\VkSdk\Exceptions\Api\Confirmation\NeedTokenConfirmationException::class,
- '27' => \Hopex\VkSdk\Exceptions\Api\Groups\GroupAuthException::class,
- '28' => \Hopex\VkSdk\Exceptions\Api\Apps\AppAuthException::class,
- '29' => \Hopex\VkSdk\Exceptions\Api\Common\RateLimitException::class,
- '30' => \Hopex\VkSdk\Exceptions\Api\Common\PrivateProfileException::class,
- '100' => \Hopex\VkSdk\Exceptions\Api\Parameters\ParamException::class,
- '101' => \Hopex\VkSdk\Exceptions\Api\Parameters\ParamApiIdException::class,
- '113' => \Hopex\VkSdk\Exceptions\Api\Parameters\ParamUserIdException::class,
- '150' => \Hopex\VkSdk\Exceptions\Api\Parameters\ParamTimestampException::class,
- '200' => \Hopex\VkSdk\Exceptions\Api\Accesses\AccessAlbumException::class,
- '201' => \Hopex\VkSdk\Exceptions\Api\Accesses\AccessAudioException::class,
- '203' => \Hopex\VkSdk\Exceptions\Api\Accesses\AccessGroupException::class,
- '300' => \Hopex\VkSdk\Exceptions\Api\Albums\AlbumFullException::class,
- '500' => \Hopex\VkSdk\Exceptions\Api\Votes\VotesPermissionException::class,
- '600' => \Hopex\VkSdk\Exceptions\Api\Ads\AdsPermissionException::class,
- '603' => \Hopex\VkSdk\Exceptions\Api\Ads\AdsSpecificException::class,
- ]
];
diff --git a/src/.root/database/migrations/create_events_table.php b/src/.root/database/migrations/create_events_table.php
new file mode 100644
index 0000000..d61e76e
--- /dev/null
+++ b/src/.root/database/migrations/create_events_table.php
@@ -0,0 +1,30 @@
+id();
+ $table->unsignedBigInteger('group_id');
+ $table->string('type');
+ $table->string('event_id')->unique();
+ $table->timestamps();
+ });
+ }
+
+ /**
+ * @return void
+ */
+ public function down(): void
+ {
+ Schema::dropIfExists('vk__events');
+ }
+};
diff --git a/src/.root/lang/en.php b/src/.root/lang/en.php
deleted file mode 100644
index f6806bb..0000000
--- a/src/.root/lang/en.php
+++ /dev/null
@@ -1,162 +0,0 @@
- 'Access denied',
- '0002' => 'Access to comment denied',
- '0003' => 'Access to group denied',
- '0004' => 'Access to the groups list is denied due to the user\'s privacy settings',
- '0005' => 'Access to the menu of the user denied',
- '0006' => 'You can\'t comment this note',
- '0007' => 'Access to note denied',
- '0008' => 'Access to page denied',
- '0009' => 'Object deleted',
- '0010' => 'Some part of the request has not been completed',
- '0011' => 'Permission denied. You have no access to operations specified with given object(s)',
- '0012' => 'Some ads error occurred',
- '0013' => 'This album is full',
- '0014' => 'Albums number limit is reached',
- '0015' => 'Application authorization failed',
- '0016' => 'This achievement is already unlocked',
- '0017' => 'Subscription is in invalid status',
- '0018' => 'Subscription not found',
- '0019' => 'Processing.. Try later',
- '0020' => 'User authorization failed',
- '0021' => 'Too many auth attempts, try again later',
- '0022' => 'HTTP authorization failed',
- '0023' => 'Validation required',
- '0024' => 'Card is connected to post',
- '0025' => 'Card not found',
- '0026' => 'Too many cards',
- '0027' => 'Catalog is not available for this user',
- '0028' => 'Catalog categories are not available for this user',
- '0029' => 'Cannot add this user to friends as you put him on blacklist',
- '0030' => 'Cannot add this user to friends as they have put you on their blacklist',
- '0031' => 'Cannot add this user to friends as user not found',
- '0032' => 'Cannot add user himself as friend',
- '0033' => 'Invalid list id',
- '0034' => 'Reached the maximum number of lists',
- '0035' => 'Permission to perform this action is allowed only for standalone and OpenAPI applications',
- '0036' => 'This method was disabled',
- '0037' => 'Unknown method passed',
- '0038' => 'Permission to perform this action is denied for non-standalone applications',
- '0039' => 'Invalid album id',
- '0040' => 'Invalid application API ID',
- '0041' => 'Access to document is denied',
- '0042' => 'Access to document deleting is denied',
- '0043' => 'Invalid document id',
- '0044' => 'Invalid document title',
- '0045' => 'One of the parameters specified was missing or invalid',
- '0046' => 'Invalid group id',
- '0047' => 'Invalid hash',
- '0048' => 'Note not found',
- '0049' => 'Page not found',
- '0050' => 'Invalid phone number',
- '0051' => 'Invalid photo',
- '0052' => 'Invalid photos',
- '0053' => 'Invalid server',
- '0054' => 'Invalid timestamp',
- '0055' => 'Invalid title',
- '0056' => 'Invalid user id',
- '0057' => 'Access to poll denied',
- '0058' => 'Access denied, please vote first',
- '0059' => 'Invalid answer id',
- '0060' => 'Invalid poll id',
- '0061' => 'Story has already expired',
- '0062' => 'Incorrect reply privacy',
- '0063' => 'This video is already added',
- '0064' => 'Comments for this video are closed',
- '0065' => 'Not enough votes',
- '0066' => 'Permission denied. You must enable votes processing in application settings',
- '0067' => 'Access to status replies denied',
- '0068' => 'Access to wall\'s comment denied',
- '0069' => 'Access to wall\'s post denied',
- '0070' => 'Access to post comments denied',
- '0071' => 'Access to adding post denied',
- '0072' => 'Too many ads posts',
- '0073' => 'Advertisement post was recently added',
- '0074' => 'Hyperlinks are forbidden',
- '0075' => 'Too many replies',
- '0076' => 'Too many recipients',
- '0077' => 'Application is not installed in community',
- '0078' => 'Group authorization failed',
- '0079' => 'Cannot edit creator role',
- '0080' => 'User needs to enable 2FA for this action',
- '0081' => 'You need to enable 2FA for this action',
- '0082' => 'User should be in club',
- '0083' => 'Too many addresses in club',
- '0084' => 'Too many officers in club',
- '0085' => 'Album not found',
- '0086' => 'Comments for this market are closed',
- '0087' => 'Item must have distinct properties',
- '0088' => 'Grouping must have two or more items',
- '0089' => 'Item already added to album',
- '0090' => 'Item has bad links in description',
- '0091' => 'Item not found',
- '0092' => 'Property not found',
- '0093' => 'Too late for restore',
- '0094' => 'Too many albums',
- '0095' => 'Too many items',
- '0096' => 'Too many items in album',
- '0097' => 'Variant not found',
- "0098" => "You can\'t change invite link for this chat",
- "0099" => "Can\'t delete this message for everybody",
- "0100" => "Can\'t forward these messages",
- "0101" => "Cannot pin one-time story",
- "0102" => "You can\'t see invite link for this chat",
- "0103" => "This is a chat bot feature, change this status in settings",
- "0104" => "You are not admin of this chat",
- "0105" => "Chat does not exist",
- "0106" => "You don\'t have access to this chat",
- "0107" => "User not found in chat",
- "0108" => "Contact not found",
- "0109" => "Can\'t send messages for users without permission",
- "0110" => "Can't edit this message, because it\'s too old",
- "0111" => "Can\'t edit this kind of message",
- "0112" => "Your community can\'t interact with this peer",
- "0113" => "Keyboard format is invalid",
- "0114" => "Message request already send",
- "0115" => "Message request already sent",
- "0116" => "Can\'t send messages to this user due to their privacy settings",
- "0117" => "Can't sent this message, because it\'s too big",
- "0118" => "Too many forwarded messages",
- "0119" => "Message is too long",
- "0120" => "Too many posts in messages",
- "0121" => "Value of ts or pts is too new",
- "0122" => "Value of ts or pts is too old",
- "0123" => "Can\'t send messages for users from blacklist",
- "0124" => "Captcha needed",
- "0125" => "Unable to process action",
- "0126" => "Content blocked",
- "0127" => "Servers number limit is reached",
- "0128" => "Unable to compile code",
- "0129" => "Application is disabled. Enable your application or use test mode",
- "0130" => "In test mode application should be disabled or user should be authorized",
- "0131" => "Flood control",
- "0132" => "Application has insufficient funds",
- "0133" => "Invalid screen name",
- "0134" => "Out of limits",
- "0135" => "The mobile number of the user is unknown",
- "0136" => "Confirmation required",
- "0137" => "Token confirmation required",
- "0138" => "Not found",
- "0139" => "Permission to perform this action is denied",
- "0140" => "This phone number is used by another user",
- "0141" => "Original photo was changed",
- "0142" => "This profile is private",
- "0143" => "Rate limit reached",
- "0144" => "Invalid request",
- "0145" => "Runtime error occurred during code invocation",
- "0146" => "Couldn\'t save file",
- "0147" => "Internal server error",
- "0148" => "Incorrect signature",
- "0149" => "User disabled track name broadcast",
- "0150" => "Too many requests per second",
- "0151" => "Too many feed lists",
- "0152" => "Unknown error occurred",
- "0153" => "Upload error",
- "0154" => "User was deleted or banned",
- "0155" => "Permission denied. You have requested too many actions this day. Try later.",
- "0156" => "Access denied. The secret code of the event was not authenticated. Check the configuration settings.",
- "0157" => "Unknown community id",
- "0158" => "Unknown callback event",
-];
diff --git a/src/.root/lang/ru.php b/src/.root/lang/ru.php
index d85b3b2..3f015ef 100644
--- a/src/.root/lang/ru.php
+++ b/src/.root/lang/ru.php
@@ -1,162 +1,163 @@
'Доступ запрещен',
- '0002' => 'Доступ к комментариям закрыт',
- '0003' => 'Доступ в группу закрыт',
- '0004' => 'Доступ к списку групп закрыт из-за настроек конфиденциальности пользователя',
- '0005' => 'Доступ к меню пользователя закрыт',
- '0006' => 'Вы не можете комментировать эту запись',
- '0007' => 'Доступ к записи закрыт',
- '0008' => 'Доступ к странице запрещен',
- '0009' => 'Объект удален',
- '0010' => 'Некоторая часть запроса не была выполнена',
- '0011' => 'Отказано в доступе. У вас нет прав на выполнение операции, указанной с данным объектом(-ами)',
- '0012' => 'Возникла ошибка при просмотре рекламы',
- '0013' => 'Этот альбом заполнен',
- '0014' => 'Достигнут лимит количества альбомов',
- '0015' => 'Не удалось выполнить авторизацию приложения',
- '0016' => 'Это достижение уже разблокировано',
- '0017' => 'Подписка находится в статусе недействительной',
- '0018' => 'Подписка не найдена',
- '0019' => 'Обработка... Попробуйте позже',
- '0020' => 'Не удалось выполнить авторизацию пользователя',
- '0021' => 'Слишком много попыток авторизации, повторите попытку позже',
- '0022' => 'Не удалось выполнить HTTP-авторизацию',
- '0023' => 'Требуется проверка',
- '0024' => 'Карта подключена к посту',
- '0025' => 'Карта не найдена',
- '0026' => 'Слишком много карт',
- '0027' => 'Каталог недоступен для этого пользователя',
- '0028' => 'Категории каталога недоступны для этого пользователя',
- '0029' => 'Невозможно добавить этого пользователя в друзья, так как вы внесли его в черный список',
- '0030' => 'Невозможно добавить этого пользователя в друзья, так как он занес вас в черный список',
- '0031' => 'Невозможно добавить этого пользователя в друзья, так как пользователь не найден',
- '0032' => 'Невозможно добавить в друзья самого себя',
- '0033' => 'Неверный идентификатор списка',
- '0034' => 'Достигнуто максимальное число списков',
- '0035' => 'Разрешение на выполнение этого действия разрешено только для автономных приложений и приложений с открытым API',
- '0036' => 'Этот способ был отключен',
- '0037' => 'Передан неизвестный метод',
- '0038' => 'Нестандартным приложениям отказано в разрешении на выполнение этого действия',
- '0039' => 'Неверный идентификатор альбома',
- '0040' => 'Неверный идентификатор API приложения',
- '0041' => 'Доступ к документу закрыт',
- '0042' => 'Доступ к удалению документов закрыт',
- '0043' => 'Неверный идентификатор документа',
- '0044' => 'Недопустимый заголовок документа',
- '0045' => 'Один из указанных параметров отсутствует или недействителен',
- '0046' => 'Неверный идентификатор группы',
- '0047' => 'Недопустимый хеш',
- '0048' => 'Запись не найдена',
- '0049' => 'Страница не найдена',
- '0050' => 'Неверный номер телефона',
- '0051' => 'Недопустимая фотография',
- '0052' => 'Недопустимые фотографии',
- '0053' => 'Недействительный сервер',
- '0054' => 'Недопустимая временная метка',
- '0055' => 'Недопустимое название',
- '0056' => 'Неверный идентификатор пользователя',
- '0057' => 'Доступ к опросу закрыт',
- '0058' => 'Доступ запрещен, пожалуйста, проголосуйте первым',
- '0059' => 'Неверный идентификатор ответа',
- '0060' => 'Неверный идентификатор опроса',
- '0061' => 'Срок действия истории истек',
- '0062' => 'Неправильная конфиденциальность ответа',
- '0063' => 'Это видео уже добавлено',
- '0064' => 'Комментарии к данному видео закрыты',
- '0065' => 'Недостаточное количество голосов',
- '0066' => 'Отказано в доступе. Вы должны включить обработку голосов в настройках приложения',
- '0067' => 'Доступ к ответам о состоянии запрещен',
- '0068' => 'Доступ к комментариям стены закрыт',
- '0069' => 'Доступ к постам стены закрыт',
- '0070' => 'Доступ к размещению комментариев запрещен',
- '0071' => 'Доступ к добавлению постов запрещен',
- '0072' => 'Слишком много рекламных постов',
- '0073' => 'Недавно был добавлен рекламный пост',
- '0074' => 'Гиперссылки запрещены',
- '0075' => 'Слишком большое количество ответов',
- '0076' => 'Слишком много получателей',
- '0077' => 'Приложение не установлено в сообществе',
- '0078' => 'Авторизация группы не удалась',
- '0079' => 'Невозможно отредактировать роль создателя',
- '0080' => 'Пользователю необходимо включить двухфакторную авторизацию для этого действия',
- '0081' => 'Вам необходимо включить двухфакторную авторизацию для этого действия',
- '0082' => 'Пользователь должен состоять в сообществе',
- '0083' => 'Слишком большое количество адресов в сообществе',
- '0084' => 'Слишком много должностных лиц в сообществе',
- '0085' => 'Альбом не найден',
- '0086' => 'Комментарии к данному товару закрыты',
- '0087' => 'Товар должен обладать отличными свойствами',
- '0088' => 'Группировка должна состоять из двух или более товаров',
- '0089' => 'Товар уже добавлен в альбом',
- '0090' => 'В описании товара есть неработающие ссылки',
- '0091' => 'Товар не найден',
- '0092' => 'Свойства не найдены',
- '0093' => 'Слишком поздно для восстановления',
- '0094' => 'Слишком большое количество альбомов',
- '0095' => 'Слишком большое количество товаров',
- '0096' => 'Слишком большое количество товаров в альбоме',
- '0097' => 'Вариант не обнаружен',
- "0098" => "Вы не можете изменить пригласительную ссылку для этого чата",
- "0099" => "Невозможно удалить это сообщение для всех",
- "0100" => "Невозможно переслать эти сообщения",
- "0101" => "Невозможно закрепить одноразовую историю",
- "0102" => "Вы не можете видеть пригласительную ссылку для этого чата",
- "0103" => "Это функция чат-бота, измените этот статус в настройках",
- "0104" => "Вы не являетесь администратором этого чата",
- "0105" => "Чата не существует",
- "0106" => "У вас нет доступа к этому чату",
- "0107" => "Пользователь в чате не найден",
- "0108" => "Контакт не найден",
- "0109" => "Невозможно отправлять сообщения пользователям, не давшим разрешение",
- "0110" => "Невозможно отредактировать это сообщение, потому что оно слишком старое",
- "0111" => "Невозможно отредактировать сообщение такого типа",
- "0112" => "Ваше сообщество не может взаимодействовать с этим диалогом",
- "0113" => "Недопустимый формат клавиатуры",
- "0114" => "Запрос на сообщение уже отправлен",
- "0115" => "Запрос на сообщение уже отправлен",
- "0116" => "Невозможно отправить сообщение этому пользователю из-за его настроек конфиденциальности",
- "0117" => "Невозможно отправить это сообщение, потому что оно слишком большое",
- "0118" => "Слишком много пересылаемых сообщений",
- "0119" => "Сообщение слишком длинное",
- "0120" => "Слишком много постов в сообщениях",
- "0121" => "Значение ts или pts слишком новое",
- "0122" => "Значение ts или pts слишком старое",
- "0123" => "Невозможно отправить сообщения для пользователей из черного списка",
- "0124" => "Необходимо ввести капчу",
- "0125" => "Невозможно выполнить действие",
- "0126" => "Контент заблокирован",
- "0127" => "Достигнут лимит количества серверов",
- "0128" => "Невозможно скомпилировать код",
- "0129" => "Приложение отключено. Включите приложение или используйте тестовый режим",
- "0130" => "В тестовом режиме приложение должно быть отключено или пользователь должен быть авторизован",
- "0131" => "Контроль потока",
- "0132" => "В приложении недостаточно средств",
- "0133" => "Недопустимое экранное имя",
- "0134" => "За пределами лимита",
- "0135" => "Мобильный номер пользователя неизвестен",
- "0136" => "Требуется подтверждение",
- "0137" => "Требуется подтверждение токена",
- "0138" => "Не найдено",
- "0139" => "В разрешении на выполнение этого действия отказано",
- "0140" => "Этот номер телефона используется другим пользователем",
- "0141" => "Оригинальное фото было изменено",
- "0142" => "Этот профиль является приватным",
- "0143" => "Достигнут предел скорости",
- "0144" => "Некорректный запрос",
- "0145" => "Во время применения кода возникла ошибка времени выполнения",
- "0146" => "Не удалось сохранить файл",
- "0147" => "Внутренняя ошибка сервера",
- "0148" => "Некорректная подпись",
- "0149" => "Трансляция названия трека отключена пользователем",
- "0150" => "Слишком много запросов в секунду",
- "0151" => "Слишком большой список каналов",
- "0152" => "Произошла неизвестная ошибка",
- "0153" => "Ошибка при загрузке",
- "0154" => "Пользователь был удален или заблокирован",
- "0155" => "Отказано в доступе. Вы запросили слишком много действий сегодня. Попробуйте позже.",
- "0156" => "Отказано в доступе. Секретный код события не прошел проверку подлинности. Проверьте настройки конфигурации.",
- "0157" => "Неизвестный идентификатор сообщества",
- "0158" => "Неизвестное событие"
+ 'Access denied' => 'Доступ запрещен',
+ 'Access to comment denied' => 'Доступ к комментариям закрыт',
+ 'Access to group denied' => 'Доступ в группу закрыт',
+ 'Access to the groups list is denied due to the user\'s privacy settings' => 'Доступ к списку групп закрыт из-за настроек конфиденциальности пользователя',
+ 'Access to the menu of the user denied' => 'Доступ к меню пользователя закрыт',
+ 'You can\'t comment this note' => 'Вы не можете комментировать эту запись',
+ 'Access to note denied' => 'Доступ к записи закрыт',
+ 'Access to page denied' => 'Доступ к странице запрещен',
+ 'Object deleted' => 'Объект удален',
+ 'Some part of the request has not been completed' => 'Некоторая часть запроса не была выполнена',
+ 'Permission denied. You have no access to operations specified with given object(s)' => 'Отказано в доступе. У вас нет прав на выполнение операции, указанной с данным объектом(-ами)',
+ 'Some ads error occurred' => 'Возникла ошибка при просмотре рекламы',
+ 'This album is full' => 'Этот альбом заполнен',
+ 'Albums number limit is reached' => 'Достигнут лимит количества альбомов',
+ 'Application authorization failed' => 'Не удалось выполнить авторизацию приложения',
+ 'This achievement is already unlocked' => 'Это достижение уже разблокировано',
+ 'Subscription is in invalid status' => 'Подписка находится в статусе недействительной',
+ 'Subscription not found' => 'Подписка не найдена',
+ 'Processing.. Try later' => 'Обработка... Попробуйте позже',
+ 'User authorization failed' => 'Не удалось выполнить авторизацию пользователя',
+ 'Too many auth attempts, try again later' => 'Слишком много попыток авторизации, повторите попытку позже',
+ 'HTTP authorization failed' => 'Не удалось выполнить HTTP-авторизацию',
+ 'Validation required' => 'Требуется проверка',
+ 'Card is connected to post' => 'Карта подключена к посту',
+ 'Card not found' => 'Карта не найдена',
+ 'Too many cards' => 'Слишком много карт',
+ 'Catalog is not available for this user' => 'Каталог недоступен для этого пользователя',
+ 'Catalog categories are not available for this user' => 'Категории каталога недоступны для этого пользователя',
+ 'Cannot add this user to friends as you put him on blacklist' => 'Невозможно добавить этого пользователя в друзья, так как вы внесли его в черный список',
+ 'Cannot add this user to friends as they have put you on their blacklist' => 'Невозможно добавить этого пользователя в друзья, так как он занес вас в черный список',
+ 'Cannot add this user to friends as user not found' => 'Невозможно добавить этого пользователя в друзья, так как пользователь не найден',
+ 'Cannot add user himself as friend' => 'Невозможно добавить в друзья самого себя',
+ 'Invalid list id' => 'Неверный идентификатор списка',
+ 'Reached the maximum number of lists' => 'Достигнуто максимальное число списков',
+ 'Permission to perform this action is allowed only for standalone and OpenAPI applications' => 'Разрешение на выполнение этого действия разрешено только для автономных приложений и приложений с открытым API',
+ 'This method was disabled' => 'Этот способ был отключен',
+ 'Unknown method passed' => 'Передан неизвестный метод',
+ 'Permission to perform this action is denied for non-standalone applications' => 'Нестандартным приложениям отказано в разрешении на выполнение этого действия',
+ 'Invalid album id' => 'Неверный идентификатор альбома',
+ 'Invalid application API ID' => 'Неверный идентификатор API приложения',
+ 'Access to document is denied' => 'Доступ к документу закрыт',
+ 'Access to document deleting is denied' => 'Доступ к удалению документов закрыт',
+ 'Invalid document id' => 'Неверный идентификатор документа',
+ 'Invalid document title' => 'Недопустимый заголовок документа',
+ 'One of the parameters specified was missing or invalid' => 'Один из указанных параметров отсутствует или недействителен',
+ 'Invalid group id' => 'Неверный идентификатор группы',
+ 'Invalid hash' => 'Недопустимый хеш',
+ 'Note not found' => 'Запись не найдена',
+ 'Page not found' => 'Страница не найдена',
+ 'Invalid phone number' => 'Неверный номер телефона',
+ 'Invalid photo' => 'Недопустимая фотография',
+ 'Invalid photos' => 'Недопустимые фотографии',
+ 'Invalid server' => 'Недействительный сервер',
+ 'Invalid timestamp' => 'Недопустимая временная метка',
+ 'Invalid title' => 'Недопустимое название',
+ 'Invalid user id' => 'Неверный идентификатор пользователя',
+ 'Access to poll denied' => 'Доступ к опросу закрыт',
+ 'Access denied, please vote first' => 'Доступ запрещен, пожалуйста, проголосуйте первым',
+ 'Invalid answer id' => 'Неверный идентификатор ответа',
+ 'Invalid poll id' => 'Неверный идентификатор опроса',
+ 'Story has already expired' => 'Срок действия истории истек',
+ 'Incorrect reply privacy' => 'Неправильная конфиденциальность ответа',
+ 'This video is already added' => 'Это видео уже добавлено',
+ 'Comments for this video are closed' => 'Комментарии к данному видео закрыты',
+ 'Not enough votes' => 'Недостаточное количество голосов',
+ 'Permission denied. You must enable votes processing in application settings' => 'Отказано в доступе. Вы должны включить обработку голосов в настройках приложения',
+ 'Access to status replies denied' => 'Доступ к ответам о состоянии запрещен',
+ 'Access to wall\'s comment denied' => 'Доступ к комментариям стены закрыт',
+ 'Access to wall\'s post denied' => 'Доступ к постам стены закрыт',
+ 'Access to post comments denied' => 'Доступ к размещению комментариев запрещен',
+ 'Access to adding post denied' => 'Доступ к добавлению постов запрещен',
+ 'Too many ads posts' => 'Слишком много рекламных постов',
+ 'Advertisement post was recently added' => 'Недавно был добавлен рекламный пост',
+ 'Hyperlinks are forbidden' => 'Гиперссылки запрещены',
+ 'Too many replies' => 'Слишком большое количество ответов',
+ 'Too many recipients' => 'Слишком много получателей',
+ 'Application is not installed in community' => 'Приложение не установлено в сообществе',
+ 'Group authorization failed' => 'Авторизация группы не удалась',
+ 'Cannot edit creator role' => 'Невозможно отредактировать роль создателя',
+ 'User needs to enable 2FA for this action' => 'Пользователю необходимо включить двухфакторную авторизацию для этого действия',
+ 'You need to enable 2FA for this action' => 'Вам необходимо включить двухфакторную авторизацию для этого действия',
+ 'User should be in club' => 'Пользователь должен состоять в сообществе',
+ 'Too many addresses in club' => 'Слишком большое количество адресов в сообществе',
+ 'Too many officers in club' => 'Слишком много должностных лиц в сообществе',
+ 'Album not found' => 'Альбом не найден',
+ 'Comments for this market are closed' => 'Комментарии к данному товару закрыты',
+ 'Item must have distinct properties' => 'Товар должен обладать отличными свойствами',
+ 'Grouping must have two or more items' => 'Группировка должна состоять из двух или более товаров',
+ 'Item already added to album' => 'Товар уже добавлен в альбом',
+ 'Item has bad links in description' => 'В описании товара есть неработающие ссылки',
+ 'Item not found' => 'Товар не найден',
+ 'Property not found' => 'Свойства не найдены',
+ 'Too late for restore' => 'Слишком поздно для восстановления',
+ 'Too many albums' => 'Слишком большое количество альбомов',
+ 'Too many items' => 'Слишком большое количество товаров',
+ 'Too many items in album' => 'Слишком большое количество товаров в альбоме',
+ 'Variant not found' => 'Вариант не обнаружен',
+ 'You can\'t change invite link for this chat' => 'Вы не можете изменить пригласительную ссылку для этого чата',
+ 'Can\'t delete this message for everybody' => 'Невозможно удалить это сообщение для всех',
+ 'Can\'t forward these messages' => 'Невозможно переслать эти сообщения',
+ 'Cannot pin one-time story' => 'Невозможно закрепить одноразовую историю',
+ 'You can\'t see invite link for this chat' => 'Вы не можете видеть пригласительную ссылку для этого чата',
+ 'This is a chat bot feature, change this status in settings' => 'Это функция чат-бота, измените этот статус в настройках',
+ 'You are not admin of this chat' => 'Вы не являетесь администратором этого чата',
+ 'Chat does not exist' => 'Чата не существует',
+ 'You don\'t have access to this chat' => 'У вас нет доступа к этому чату',
+ 'User not found in chat' => 'Пользователь в чате не найден',
+ 'Contact not found' => 'Контакт не найден',
+ 'Can\'t send messages for users without permission' => 'Невозможно отправлять сообщения пользователям, не давшим разрешение',
+ 'Can\'t edit this message, because it\'s too old' => 'Невозможно отредактировать это сообщение, потому что оно слишком старое',
+ 'Can\'t edit this kind of message' => 'Невозможно отредактировать сообщение такого типа',
+ 'Your community can\'t interact with this peer' => 'Ваше сообщество не может взаимодействовать с этим диалогом',
+ 'Keyboard format is invalid' => 'Недопустимый формат клавиатуры',
+ 'Message request already send' => 'Запрос на сообщение уже отправлен',
+ 'Message request already sent' => 'Запрос на сообщение уже отправлен',
+ 'Can\'t send messages to this user due to their privacy settings' => 'Невозможно отправить сообщение этому пользователю из-за его настроек конфиденциальности',
+ 'Can\'t sent this message, because it\'s too big' => 'Невозможно отправить это сообщение, потому что оно слишком большое',
+ 'Too many forwarded messages' => 'Слишком много пересылаемых сообщений',
+ 'Message is too long' => 'Сообщение слишком длинное',
+ 'Too many posts in messages' => 'Слишком много постов в сообщениях',
+ 'Value of ts or pts is too new' => 'Значение ts или pts слишком новое',
+ 'Value of ts or pts is too old' => 'Значение ts или pts слишком старое',
+ 'Can\'t send messages for users from blacklist' => 'Невозможно отправить сообщения для пользователей из черного списка',
+ 'Captcha needed' => 'Необходимо ввести капчу',
+ 'Unable to process action' => 'Невозможно выполнить действие',
+ 'Content blocked' => 'Контент заблокирован',
+ 'Servers number limit is reached' => 'Достигнут лимит количества серверов',
+ 'Unable to compile code' => 'Невозможно скомпилировать код',
+ 'Application is disabled. Enable your application or use test mode' => 'Приложение отключено. Включите приложение или используйте тестовый режим',
+ 'In test mode application should be disabled or user should be authorized' => 'В тестовом режиме приложение должно быть отключено или пользователь должен быть авторизован',
+ 'Flood control' => 'Контроль потока',
+ 'Application has insufficient funds' => 'В приложении недостаточно средств',
+ 'Invalid screen name' => 'Недопустимое экранное имя',
+ 'Out of limits' => 'За пределами лимита',
+ 'The mobile number of the user is unknown' => 'Мобильный номер пользователя неизвестен',
+ 'Confirmation required' => 'Требуется подтверждение',
+ 'Token confirmation required' => 'Требуется подтверждение токена',
+ 'Not found' => 'Не найдено',
+ 'Permission to perform this action is denied' => 'В разрешении на выполнение этого действия отказано',
+ 'This phone number is used by another user' => 'Этот номер телефона используется другим пользователем',
+ 'Original photo was changed' => 'Оригинальное фото было изменено',
+ 'This profile is private' => 'Этот профиль является приватным',
+ 'Rate limit reached' => 'Достигнут предел скорости',
+ 'Invalid request' => 'Некорректный запрос',
+ 'Runtime error occurred during code invocation' => 'Во время применения кода возникла ошибка времени выполнения',
+ 'Couldn\'t save file' => 'Не удалось сохранить файл',
+ 'Internal server error' => 'Внутренняя ошибка сервера',
+ 'Incorrect signature' => 'Некорректная подпись',
+ 'User disabled track name broadcast' => 'Трансляция названия трека отключена пользователем',
+ 'Too many requests per second' => 'Слишком много запросов в секунду',
+ 'Too many feed lists' => 'Слишком большой список каналов',
+ 'Unknown error occurred' => 'Произошла неизвестная ошибка',
+ 'Upload error' => 'Ошибка при загрузке',
+ 'User was deleted or banned' => 'Пользователь был удален или заблокирован',
+ 'Permission denied. You have requested too many actions this day. Try later.' => 'Отказано в доступе. Вы запросили слишком много действий сегодня. Попробуйте позже.',
+ 'Access denied. The secret code of the event was not authenticated. Check the configuration settings.' => 'Отказано в доступе. Секретный код события не прошел проверку подлинности. Проверьте настройки конфигурации.',
+ 'Unknown community id' => 'Неизвестный идентификатор сообщества',
+ 'Unknown callback event' => 'Неизвестное событие',
+ 'Invalid http status code' => 'Недопустимый код состояния http',
];
diff --git a/src/.root/routes/callbacks.php b/src/.root/routes/callbacks.php
index fc9d34f..1be1cf4 100644
--- a/src/.root/routes/callbacks.php
+++ b/src/.root/routes/callbacks.php
@@ -1,16 +1,25 @@
+| For fire this route, use
+|
+| See more: https://dev.vk.com/api/callback/getting-started
*/
-Route::prefix('api')->post(Configure::routes('entry'), function (CallbackEventService $callback) {
- return response($callback->division());
-})->name('api.entry');
+
+Route::prefix('api')->name('vk.')->group(function () {
+
+ Route::post(SdkConfig::routes('entry'), function (CallbackEventService $callback) {
+ return response($callback->division(), 200, ['content-type' => 'application/json;charset=utf-8', 'charset' => 'utf-8']);
+ })->name('entry');
+
+});
diff --git a/src/Contracts/CallbackEventsContract.php b/src/Contracts/CallbackEventsContract.php
index 3186de1..514e74c 100644
--- a/src/Contracts/CallbackEventsContract.php
+++ b/src/Contracts/CallbackEventsContract.php
@@ -2,230 +2,233 @@
namespace Hopex\VkSdk\Contracts;
-use Illuminate\Support\Collection;
+use Hopex\VkSdk\Foundation\Core\Callback\BaseEvent;
+/**
+ * Interface CallbackEventsContract
+ * @package Hopex\VkSdk\Contracts
+ */
interface CallbackEventsContract
{
/**
- * @param Collection $event
+ * @param BaseEvent $event
* @return void
*/
- public function message_new(Collection $event): void;
+ public function message_new(BaseEvent $event): void;
/**
- * @param Collection $event
+ * @param BaseEvent $event
* @return void
*/
- public function message_reply(Collection $event): void;
+ public function message_reply(BaseEvent $event): void;
/**
- * @param Collection $event
+ * @param BaseEvent $event
* @return void
*/
- public function message_allow(Collection $event): void;
+ public function message_allow(BaseEvent $event): void;
/**
- * @param Collection $event
+ * @param BaseEvent $event
* @return void
*/
- public function message_deny(Collection $event): void;
+ public function message_deny(BaseEvent $event): void;
/**
- * @param Collection $event
+ * @param BaseEvent $event
* @return void
*/
- public function photo_new(Collection $event): void;
+ public function photo_new(BaseEvent $event): void;
/**
- * @param Collection $event
+ * @param BaseEvent $event
* @return void
*/
- public function photo_comment_new(Collection $event): void;
+ public function photo_comment_new(BaseEvent $event): void;
/**
- * @param Collection $event
+ * @param BaseEvent $event
* @return void
*/
- public function photo_comment_edit(Collection $event): void;
+ public function photo_comment_edit(BaseEvent $event): void;
/**
- * @param Collection $event
+ * @param BaseEvent $event
* @return void
*/
- public function photo_comment_restore(Collection $event): void;
+ public function photo_comment_restore(BaseEvent $event): void;
/**
- * @param Collection $event
+ * @param BaseEvent $event
* @return void
*/
- public function photo_comment_delete(Collection $event): void;
+ public function photo_comment_delete(BaseEvent $event): void;
/**
- * @param Collection $event
+ * @param BaseEvent $event
* @return void
*/
- public function audio_new(Collection $event): void;
+ public function audio_new(BaseEvent $event): void;
/**
- * @param Collection $event
+ * @param BaseEvent $event
* @return void
*/
- public function video_new(Collection $event): void;
+ public function video_new(BaseEvent $event): void;
/**
- * @param Collection $event
+ * @param BaseEvent $event
* @return void
*/
- public function video_comment_new(Collection $event): void;
+ public function video_comment_new(BaseEvent $event): void;
/**
- * @param Collection $event
+ * @param BaseEvent $event
* @return void
*/
- public function video_comment_edit(Collection $event): void;
+ public function video_comment_edit(BaseEvent $event): void;
/**
- * @param Collection $event
+ * @param BaseEvent $event
* @return void
*/
- public function video_comment_restore(Collection $event): void;
+ public function video_comment_restore(BaseEvent $event): void;
/**
- * @param Collection $event
+ * @param BaseEvent $event
* @return void
*/
- public function video_comment_delete(Collection $event): void;
+ public function video_comment_delete(BaseEvent $event): void;
/**
- * @param Collection $event
+ * @param BaseEvent $event
* @return void
*/
- public function wall_post_new(Collection $event): void;
+ public function wall_post_new(BaseEvent $event): void;
/**
- * @param Collection $event
+ * @param BaseEvent $event
* @return void
*/
- public function wall_repost(Collection $event): void;
+ public function wall_repost(BaseEvent $event): void;
/**
- * @param Collection $event
+ * @param BaseEvent $event
* @return void
*/
- public function wall_reply_new(Collection $event): void;
+ public function wall_reply_new(BaseEvent $event): void;
/**
- * @param Collection $event
+ * @param BaseEvent $event
* @return void
*/
- public function wall_reply_edit(Collection $event): void;
+ public function wall_reply_edit(BaseEvent $event): void;
/**
- * @param Collection $event
+ * @param BaseEvent $event
* @return void
*/
- public function wall_reply_restore(Collection $event): void;
+ public function wall_reply_restore(BaseEvent $event): void;
/**
- * @param Collection $event
+ * @param BaseEvent $event
* @return void
*/
- public function wall_reply_delete(Collection $event): void;
+ public function wall_reply_delete(BaseEvent $event): void;
/**
- * @param Collection $event
+ * @param BaseEvent $event
* @return void
*/
- public function board_post_new(Collection $event): void;
+ public function board_post_new(BaseEvent $event): void;
/**
- * @param Collection $event
+ * @param BaseEvent $event
* @return void
*/
- public function board_post_edit(Collection $event): void;
+ public function board_post_edit(BaseEvent $event): void;
/**
- * @param Collection $event
+ * @param BaseEvent $event
* @return void
*/
- public function board_post_restore(Collection $event): void;
+ public function board_post_restore(BaseEvent $event): void;
/**
- * @param Collection $event
+ * @param BaseEvent $event
* @return void
*/
- public function board_post_delete(Collection $event): void;
+ public function board_post_delete(BaseEvent $event): void;
/**
- * @param Collection $event
+ * @param BaseEvent $event
* @return void
*/
- public function market_comment_new(Collection $event): void;
+ public function market_comment_new(BaseEvent $event): void;
/**
- * @param Collection $event
+ * @param BaseEvent $event
* @return void
*/
- public function market_comment_edit(Collection $event): void;
+ public function market_comment_edit(BaseEvent $event): void;
/**
- * @param Collection $event
+ * @param BaseEvent $event
* @return void
*/
- public function market_comment_restore(Collection $event): void;
+ public function market_comment_restore(BaseEvent $event): void;
/**
- * @param Collection $event
+ * @param BaseEvent $event
* @return void
*/
- public function market_comment_delete(Collection $event): void;
+ public function market_comment_delete(BaseEvent $event): void;
/**
- * @param Collection $event
+ * @param BaseEvent $event
* @return void
*/
- public function group_leave(Collection $event): void;
+ public function group_leave(BaseEvent $event): void;
/**
- * @param Collection $event
+ * @param BaseEvent $event
* @return void
*/
- public function group_join(Collection $event): void;
+ public function group_join(BaseEvent $event): void;
/**
- * @param Collection $event
+ * @param BaseEvent $event
* @return void
*/
- public function group_change_settings(Collection $event): void;
+ public function group_change_settings(BaseEvent $event): void;
/**
- * @param Collection $event
+ * @param BaseEvent $event
* @return void
*/
- public function group_change_photo(Collection $event): void;
+ public function group_change_photo(BaseEvent $event): void;
/**
- * @param Collection $event
+ * @param BaseEvent $event
* @return void
*/
- public function group_officers_edit(Collection $event): void;
+ public function group_officers_edit(BaseEvent $event): void;
/**
- * @param Collection $event
+ * @param BaseEvent $event
* @return void
*/
- public function poll_vote_new(Collection $event): void;
+ public function poll_vote_new(BaseEvent $event): void;
/**
- * @param Collection $event
+ * @param BaseEvent $event
* @return void
*/
- public function user_block(Collection $event): void;
+ public function user_block(BaseEvent $event): void;
/**
- * @param Collection $event
+ * @param BaseEvent $event
* @return void
*/
- public function user_unbloc(Collection $event): void;
-
+ public function user_unblock(BaseEvent $event): void;
}
diff --git a/src/Contracts/CanFormat.php b/src/Contracts/CanFormat.php
index b761160..38fa098 100644
--- a/src/Contracts/CanFormat.php
+++ b/src/Contracts/CanFormat.php
@@ -2,11 +2,14 @@
namespace Hopex\VkSdk\Contracts;
+/**
+ * Interface CanFormat
+ * @package Hopex\VkSdk\Contracts
+ */
interface CanFormat
{
/**
* @param $data
- * @return string
*/
public function format($data);
}
diff --git a/src/Exceptions/Api/Accesses/AccessAlbumException.php b/src/Exceptions/Api/Accesses/AccessAlbumException.php
deleted file mode 100644
index d490d4c..0000000
--- a/src/Exceptions/Api/Accesses/AccessAlbumException.php
+++ /dev/null
@@ -1,23 +0,0 @@
-error_code = isset($error[static::KEY_ERROR_CODE]) ? intval($error[static::KEY_ERROR_CODE]) : null;
- $this->error_msg = isset($error[static::KEY_ERROR_MSG]) ? strval($error[static::KEY_ERROR_MSG]) : null;
- $this->captcha_sid = isset($error[static::KEY_CAPTCHA_SID]) ? strval($error[static::KEY_CAPTCHA_SID]) : null;
- $this->captcha_img = isset($error[static::KEY_CAPTCHA_IMG]) ? strval($error[static::KEY_CAPTCHA_IMG]) : null;
- $this->confirmation_text = isset($error[static::KEY_CONFIRMATION_TEXT]) ? strval($error[static::KEY_CONFIRMATION_TEXT]) : null;
- $this->redirect_uri = isset($error[static::KEY_REDIRECT_URI]) ? strval($error[static::KEY_REDIRECT_URI]) : null;
- $this->request_params = isset($error[static::KEY_REQUEST_PARAMS]) ? ((array)$error[static::KEY_REQUEST_PARAMS]) : null;
- }
-
- /**
- * Код ошибки.
- *
- * @return int|null
- */
- public function getErrorCode(): ?int
- {
- return $this->error_code;
- }
-
- /**
- * Текст ошибки
- *
- * @return string|null
- */
- public function getErrorMsg(): ?string
- {
- return $this->error_msg;
- }
-
- /**
- * SID капчи.
- *
- * @return string|null
- */
- public function getCaptchaSid(): ?string
- {
- return $this->captcha_sid;
- }
-
- /**
- * Адрес изображения капчи.
- *
- * @return string|null
- */
- public function getCaptchaImg(): ?string
- {
- return $this->captcha_img;
- }
-
- /**
- * Текст подтверждения.
- *
- * @return string|null
- */
- public function getConfirmationText(): ?string
- {
- return $this->confirmation_text;
- }
-
- /**
- * URI перенаправления.
- *
- * @return string|null
- */
- public function getRedirectUri(): ?string
- {
- return $this->redirect_uri;
- }
-
- /**
- * Параметры запроса.
- *
- * @return array|null
- */
- public function getRequestParams(): ?array
- {
- return $this->request_params;
- }
-}
diff --git a/src/Exceptions/Api/ApiException.php b/src/Exceptions/Api/ApiException.php
index 1a1227d..78d67dc 100644
--- a/src/Exceptions/Api/ApiException.php
+++ b/src/Exceptions/Api/ApiException.php
@@ -2,73 +2,30 @@
namespace Hopex\VkSdk\Exceptions\Api;
-use Exception;
+use Hopex\VkSdk\Exceptions\SdkException;
+use Throwable;
/**
* Class ApiException
* @package Hopex\VkSdk\Exceptions\Api
*/
-class ApiException extends Exception
+class ApiException extends SdkException
{
- protected int $error_code;
- protected string $description;
- protected ?string $error_message;
- protected ApiError $error;
-
/**
* ApiException constructor.
*
- * @param int $error_code
- * @param string $description
- * @param ApiError $error
- */
- public function __construct(int $error_code, string $description, ApiError $error)
- {
- $this->error_code = $error_code;
- $this->description = $description;
- $this->error_message = $error->getErrorMsg();
- $this->error = $error;
-
- parent::__construct($error->getErrorMsg(), $error_code);
- }
-
- /**
- * Код ошибки.
- *
- * @return int
- */
- public function getErrorCode(): int
- {
- return $this->error_code;
- }
-
- /**
- * Описание ошибки.
- *
- * @return string
- */
- public function getDescription(): string
- {
- return $this->description;
- }
-
- /**
- * Сообщение об ошибке.
- *
- * @return string
- */
- public function getErrorMessage(): string
- {
- return $this->error_message;
- }
-
- /**
- * Объект ошибки.
- *
- * @return ApiError
+ * @param $message
+ * @param $code
+ * @param Throwable|null $previous
*/
- public function getError(): ApiError
+ public function __construct($message = null, $code = 400, Throwable $previous = null)
{
- return $this->error;
+ $commonError = ApiExceptionMapper::parse($code);
+ if ($commonError) {
+ $code = 400;
+ $message = $commonError;
+ }
+ $message = preg_replace('~vk-sdk\.~', '', __("vk-sdk.{$message}"));
+ parent::__construct("ApiException: {$message}", $code, $previous);
}
}
diff --git a/src/Exceptions/Api/ApiExceptionMapper.php b/src/Exceptions/Api/ApiExceptionMapper.php
index 741f81e..e99b475 100644
--- a/src/Exceptions/Api/ApiExceptionMapper.php
+++ b/src/Exceptions/Api/ApiExceptionMapper.php
@@ -3,7 +3,7 @@
namespace Hopex\VkSdk\Exceptions\Api;
use Exception;
-use Hopex\VkSdk\Facades\Configure;
+use Hopex\VkSdk\Facades\SdkConfig;
/**
* Class ApiExceptionMapper
@@ -11,18 +11,52 @@
*/
class ApiExceptionMapper
{
+ /** @var array|string[] */
+ private static array $errors = [
+ '1' => "Unknown error occurred",
+ '2' => "Application is disabled. Enable your application or use test mode",
+ '3' => "Unknown method passed",
+ '4' => "Incorrect signature",
+ '5' => "User authorization failed",
+ '6' => "Too many requests per second",
+ '7' => "Permission to perform this action is denied",
+ '8' => "Invalid request",
+ '9' => "Flood control",
+ '10' => "Internal server error",
+ '11' => "In test mode application should be disabled or user should be authorized",
+ '14' => "Captcha needed",
+ '15' => "Access denied",
+ '16' => "HTTP authorization failed",
+ '17' => "Validation required",
+ '18' => "User was deleted or banned",
+ '20' => "Permission to perform this action is denied for non-standalone applications",
+ '21' => "Permission to perform this action is allowed only for standalone and OpenAPI applications",
+ '23' => "This method was disabled",
+ '24' => "Confirmation required",
+ '25' => "Token confirmation required",
+ '27' => "Group authorization failed",
+ '28' => "Application authorization failed",
+ '29' => "Rate limit reached",
+ '30' => "This profile is private",
+ '100' => "One of the parameters specified was missing or invalid",
+ '101' => "Invalid application API ID",
+ '113' => "Invalid user id",
+ '150' => "Invalid timestamp",
+ '200' => "Access denied",
+ '201' => "Access denied",
+ '203' => "Access to group denied",
+ '300' => "This album is full",
+ '500' => "Permission denied. You must enable votes processing in application settings",
+ '600' => "Permission denied. You have no access to operations specified with given object(s)",
+ '603' => "Some ads error occurred",
+ ];
+
/**
- * Поиск возникшей ошибки среди базовых ошибок VK API.
- *
- * @param ApiError $error
- * @return Exception
+ * @param $code
+ * @return mixed|string|null
*/
- final public static function parse(ApiError $error): Exception
+ public static function parse($code): mixed
{
- if (Configure::errors($error->getErrorCode()) instanceof ApiException) {
- return new (Configure::errors($error->getErrorCode()))($error);
- } else {
- return new ApiException($error->getErrorCode(), $error->getErrorMsg(), $error);
- }
+ return self::$errors[$code] ?? null;
}
}
diff --git a/src/Exceptions/Api/Apps/AppAuthException.php b/src/Exceptions/Api/Apps/AppAuthException.php
deleted file mode 100644
index 7548420..0000000
--- a/src/Exceptions/Api/Apps/AppAuthException.php
+++ /dev/null
@@ -1,22 +0,0 @@
-report();
- }
-
- /**
- * Отчет об исключении.
- *
- * @return void
- */
- protected function report(): void
- {
- Log::build((array)Configure::logging('channels.exception'))
- ->warning($this->getMessage());
- }
-
- /**
- * Отображение сообщения об исключении в HTTP ответе.
- *
- * @param Request $request
- * @return JsonResponse
- */
- final public function render(Request $request): JsonResponse
+ public function __construct($message, $code = 400, Throwable $previous = null)
{
- return new JsonResponse(
- Format::with(JsonExceptionFormatter::class)->format($this),
- $this->getCode()
- );
+ parent::__construct("CallbackException: {$message}", $code, $previous);
}
}
diff --git a/src/Exceptions/SdkException.php b/src/Exceptions/SdkException.php
new file mode 100644
index 0000000..16c375d
--- /dev/null
+++ b/src/Exceptions/SdkException.php
@@ -0,0 +1,52 @@
+report();
+ }
+
+ /**
+ * @return void
+ */
+ protected function report(): void
+ {
+ Log::build((array)SdkConfig::logging('channels.exception'))->warning($this->getMessage());
+ }
+
+ /**
+ * @param Request $request
+ * @return JsonResponse|void
+ */
+ final public function render(Request $request)
+ {
+ if (env('LOG_LEVEL') === 'debug') {
+ return new JsonResponse(
+ Format::with(JsonExceptionFormatter::class)->format($this->getMessage()),
+ $this->getCode()
+ );
+ }
+ }
+}
diff --git a/src/Facades/Format.php b/src/Facades/Format.php
index 4dafa2d..24decb0 100644
--- a/src/Facades/Format.php
+++ b/src/Facades/Format.php
@@ -2,16 +2,19 @@
namespace Hopex\VkSdk\Facades;
-use Hopex\VkSdk\Foundation\Formatters\BaseFormatter;
use Illuminate\Support\Facades\Facade;
+/**
+ * Class Format
+ * @package Hopex\VkSdk\Facades
+ */
class Format extends Facade
{
/**
* @return string
*/
- protected static function getFacadeAccessor()
+ protected static function getFacadeAccessor(): string
{
- return BaseFormatter::class;
+ return \Hopex\VkSdk\Foundation\Format::class;
}
}
diff --git a/src/Facades/Group.php b/src/Facades/Group.php
deleted file mode 100644
index e469b7e..0000000
--- a/src/Facades/Group.php
+++ /dev/null
@@ -1,17 +0,0 @@
- $value) {
+ if (is_array($value)) {
+ $data[$key] = implode(',', $value);
+ } else if (is_bool($value)) {
+ $data[$key] = $value ? 1 : 0;
+ }
+ }
+ }
+ return $data;
+ }
+}
diff --git a/src/Formatters/ClearEmptiesParametersRequestFormatter.php b/src/Formatters/ClearEmptiesParametersRequestFormatter.php
new file mode 100644
index 0000000..5068bae
--- /dev/null
+++ b/src/Formatters/ClearEmptiesParametersRequestFormatter.php
@@ -0,0 +1,26 @@
+filter(function ($item) {
+ return !empty($item);
+ })
+ ->toArray();
+ }
+}
diff --git a/src/Formatters/JsonExceptionFormatter.php b/src/Formatters/JsonExceptionFormatter.php
index 8896035..467482d 100644
--- a/src/Formatters/JsonExceptionFormatter.php
+++ b/src/Formatters/JsonExceptionFormatter.php
@@ -3,6 +3,7 @@
namespace Hopex\VkSdk\Formatters;
use Hopex\VkSdk\Contracts\CanFormat;
+use Hopex\VkSdk\Exceptions\SdkException;
class JsonExceptionFormatter implements CanFormat
{
@@ -14,7 +15,7 @@ public function format($data): array
{
return [
'type' => 'error',
- 'message' => $data->getMessage()
+ 'message' => $data instanceof SdkException ? $data->getMessage() : $data
];
}
}
diff --git a/src/Formatters/JsonLogFormatter.php b/src/Formatters/JsonLogFormatter.php
index cee72e5..95aa4a5 100644
--- a/src/Formatters/JsonLogFormatter.php
+++ b/src/Formatters/JsonLogFormatter.php
@@ -2,12 +2,21 @@
namespace Hopex\VkSdk\Formatters;
+use Hopex\VkSdk\Contracts\CanFormat;
use Monolog\Formatter\LineFormatter;
use Monolog\Logger;
-class JsonLogFormatter
+class JsonLogFormatter implements CanFormat
{
public function __invoke(Logger $logger)
+ {
+ $this->format($logger);
+ }
+
+ /**
+ * @param $data
+ */
+ public function format($data)
{
$formatter = (new LineFormatter(
LineFormatter::SIMPLE_FORMAT,
@@ -15,11 +24,11 @@ public function __invoke(Logger $logger)
true,
true)
)
- ->setJsonPrettyPrint(true)
- ->addJsonEncodeOption(JSON_UNESCAPED_UNICODE)
- ->addJsonEncodeOption(JSON_UNESCAPED_SLASHES);
+ ->setJsonPrettyPrint(true)
+ ->addJsonEncodeOption(JSON_UNESCAPED_UNICODE)
+ ->addJsonEncodeOption(JSON_UNESCAPED_SLASHES);
- foreach ($logger->getHandlers() as $handler) {
+ foreach ($data->getHandlers() as $handler) {
if (method_exists($handler, 'setFormatter'))
$handler->setFormatter($formatter);
}
diff --git a/src/Foundation/Core/Api/Client.php b/src/Foundation/Core/Api/Client.php
new file mode 100644
index 0000000..469f1cb
--- /dev/null
+++ b/src/Foundation/Core/Api/Client.php
@@ -0,0 +1,41 @@
+get(
+ sprintf('%s/%s', SdkConfig::api('auth'), sprintf(self::SERVICE, $id, $secret, SdkConfig::api('version')))
+ );
+
+ throw_if(!empty($response->json('error_code')), new SdkException($response->json('error_msg'), $response->json('error_code')));
+ //Config::set("apps.$id.token", $response->json('access_token'));
+
+ return $response->json('access_token');
+ }
+
+ /**
+ * @param mixed|null $code
+ * @return mixed
+ */
+ public function getToken(mixed $code = null)
+ {
+ $response = Http::timeout(self::TIMEOUT)->get($this->makeAuthorizeUrl());
+
+// $data = collect(json_decode($response->body(), true));
+ dd($this->makeAuthorizeUrl(), $response->status(), $response->body());
+ if (isset($data['error'])) {
+ throw self::toException($data);
+ }
+
+ if (!isset($data['access_token'])) {
+ throw new VkException('The access token is not present in the API response.');
+ }
+
+ return $data['access_token'];
+ }
+
+ /**
+ * @return string
+ */
+ private function makeAuthorizeUrl(): string
+ {
+ return sprintf(
+ '%s/%s',
+ SdkConfig::api('auth'),
+ sprintf(
+ self::AUTHORIZE_URI,
+ $this->id,
+ $this->scope,
+ $this->redirect
+ )
+ );
+ }
+
+ /**
+ * @param mixed $code
+ * @return string
+ */
+ private function makeTokenUrl(mixed $code): string
+ {
+ return sprintf(
+ '%s/%s',
+ SdkConfig::api('auth'),
+ sprintf(
+ self::TOKEN_URI,
+ $this->id,
+ $this->scope,
+ $this->redirect,
+ $code
+ )
+ );
+ }
+}
diff --git a/src/Foundation/Core/Api/Request.php b/src/Foundation/Core/Api/Request.php
new file mode 100644
index 0000000..1c48bef
--- /dev/null
+++ b/src/Foundation/Core/Api/Request.php
@@ -0,0 +1,127 @@
+token = $token;
+ $this->version = $version ?? SdkConfig::api('version');
+ $this->language = $language ?? config('app.locale');
+ }
+
+ /**
+ * @param string $method
+ * @param array $args
+ * @return Collection
+ * @throws ApiException
+ * @throws Throwable
+ */
+ public function call(string $method, array $args = []): Collection
+ {
+ $arguments = Format::with(ClearEmptiesParametersRequestFormatter::class)
+ ->with(ArrayParametersRequestFormatter::class)
+ ->format($args);
+ $arguments['access_token'] = $arguments['access_token'] ?? $this->token;
+ $arguments['v'] = $arguments['v'] ?? $this->version;
+ $arguments['lang'] = $arguments['lang'] ?? $this->language;
+
+ try {
+ $response = Http::timeout(10)->get($this->makeUrl($method), $arguments);
+ } catch (RequestException $e) {
+ throw new SdkException($e->getMessage(), 500);
+ }
+
+ throw_if($response->status() != 200, HttpStatusCodeException::class);
+ $body = json_decode($response->body(), true);
+ $body = collect(is_array($body) ? $body : []);
+
+ if ($body->has('error')) {
+ throw new ApiException(code: $body->get('error')['error_code']);
+ }
+
+ return collect($body->has('response') ? $body->get('response') : $body);
+ }
+
+// public function upload(string $url, string $param, string $path)
+// {
+// Http::post($url);
+// try {
+// $response = $this->http_client->upload($url, $param, $path);
+// } catch (TransportRequestException $e) {
+// throw new VKClientException($e);
+// }
+//
+// return $this->parseResponse($response);
+// }
+
+ /**
+ * @param string $method
+ * @return string
+ */
+ private function makeUrl(string $method): string
+ {
+ return sprintf(
+ '%s/%s',
+ SdkConfig::api('endpoint'),
+ $method
+ );
+ }
+
+ /**
+ * @return string
+ */
+ public function getToken(): string
+ {
+ return $this->token;
+ }
+
+ /**
+ * @return array|string|null
+ */
+ public function getVersion(): array|string|null
+ {
+ return $this->version;
+ }
+
+ /**
+ * @return string
+ */
+ public function getLanguage(): string
+ {
+ return $this->language;
+ }
+}
diff --git a/src/Foundation/Core/Callback/BaseEvent.php b/src/Foundation/Core/Callback/BaseEvent.php
new file mode 100644
index 0000000..afdf07e
--- /dev/null
+++ b/src/Foundation/Core/Callback/BaseEvent.php
@@ -0,0 +1,84 @@
+event = $event;
+ $this->object = collect($this->event->get(self::OBJECT));
+ }
+
+ /**
+ * @return int
+ */
+ public function getGroupId(): int
+ {
+ return $this->event->get(self::GROUP_ID);
+ }
+
+ /**
+ * @return Collection
+ */
+ public function getObject(): Collection
+ {
+ return $this->object;
+ }
+
+ /**
+ * @return Collection
+ */
+ public function getEvent(): Collection
+ {
+ return $this->event;
+ }
+
+ /**
+ * @return MessageFields
+ */
+ public function getMessage(): MessageFields
+ {
+ return new MessageFields(collect($this->object->get(self::MESSAGE)));
+ }
+
+ /**
+ * @return ClientFields
+ */
+ public function getClient(): ClientFields
+ {
+ return new ClientFields(collect($this->object->get(self::CLIENT_INFO)));
+ }
+}
diff --git a/src/Foundation/Core/Callback/EventsHandler.php b/src/Foundation/Core/Callback/EventsHandler.php
new file mode 100644
index 0000000..062260d
--- /dev/null
+++ b/src/Foundation/Core/Callback/EventsHandler.php
@@ -0,0 +1,345 @@
+id;
- }
-
- /**
- * Название сообщества.
- *
- * @return int
- */
- protected function getName(): int
- {
- return $this->name;
- }
-
- /**
- * Короткий адрес, например, apiclub.
- *
- * @return string
- */
- protected function getScreenName(): string
- {
- return $this->screenName;
- }
-
- /**
- * Является ли сообщество закрытым.
- * Возможные значения:
- * 0 — открытое;
- * 1 — закрытое;
- * 2 — частное.
- *
- * @return int
- */
- protected function getIsClosed(): int
- {
- return $this->isClosed;
- }
-
- /**
- * Возвращается в случае, если сообщество удалено или заблокировано.
- * Возможные значения:
- * deleted — сообщество удалено;
- * banned — сообщество заблокировано;
- *
- * @return string
- */
- protected function getDeactivated(): string
- {
- return $this->deactivated;
- }
-
- /**
- * Требуется scope = groups.
- * Информация о том, является ли текущий пользователь руководителем.
- * Возможные значения:
- * 1 — является;
- * 0 — не является.
- *
- * @return int
- */
- protected function getIsAdmin(): int
- {
- return $this->isAdmin;
- }
-
- /**
- * Требуется scope = groups.
- * Уровень полномочий текущего пользователя (если $isAdmin = 1):
- * 1 — модератор;
- * 2 — редактор;
- * 3 — администратор.
- *
- * @return int
- */
- protected function getAdminLevel(): int
- {
- return $this->adminLevel;
- }
-
- /**
- * Требуется scope = groups.
- * Информация о том, является ли текущий пользователь участником.
- * Возможные значения:
- * 1 — является;
- * 0 — не является.
- *
- * @return int
- */
- protected function getIsMember(): int
- {
- return $this->isMember;
- }
-
- /**
- * Требуется scope = groups.
- * Информация о том, является ли текущий пользователь рекламодателем.
- * Возможные значения:
- * 1 — является;
- * 0 — не является.
- *
- * @return int
- */
- protected function getIsAdvertiser(): int
- {
- return $this->isAdvertiser;
- }
-
- /**
- * Требуется scope = groups.
- * Идентификатор пользователя, который отправил приглашение в сообщество.
- * Поле возвращается только для метода groups.getInvites.
- *
- * @return int
- */
- protected function getInvitedBy(): int
- {
- return $this->invitedBy;
- }
-
- /**
- * Тип сообщества:
- * group — группа;
- * page — публичная страница;
- * event — мероприятие.
- *
- * @return string
- */
- protected function getType(): string
- {
- return $this->type;
- }
-
- /**
- * URL главной фотографии с размером 50x50px.
- *
- * @return string
- */
- protected function getPhoto50(): string
- {
- return $this->photo50;
- }
-
- /**
- * URL главной фотографии с размером 100х100px.
- *
- * @return string
- */
- protected function getPhoto100(): string
- {
- return $this->photo100;
- }
-
- /**
- * URL главной фотографии в максимальном размере.
- *
- * @return string
- */
- protected function getPhoto200(): string
- {
- return $this->photo200;
- }
-
- /**
- * Строка тематики паблика.
- * У групп возвращается строковое значение,
- * открыта ли группа или нет, а у событий дата начала.
- *
- * @return string
- */
- protected function getActivity(): string
- {
- return $this->activity;
- }
-
- /**
- * Информация об адресах сообщества.
- * Возвращаются следующие поля:
- * is_enabled (boolean) — включен ли блок адресов в сообществе.
- * main_address_id (integer) — идентификатор основного адреса.
- *
- * @return mixed
- */
- protected function getAddresses()
- {
- return $this->addresses;
- }
-
- /**
- * Возрастное ограничение.
- * 1 — нет;
- * 2 — 16+;
- * 3 — 18+.
- *
- * @return int
- */
- protected function getAgeLimits(): int
- {
- return $this->ageLimits;
- }
-
- /**
- * Информация о занесении в черный список сообщества
- * (поле возвращается только при запросе информации об одном сообществе).
- * Объект, содержащий следующие поля:
- * end_date (integer) — срок окончания блокировки в формате unixtime;
- * comment (string) — комментарий к блокировке.
- *
- * @return mixed
- */
- protected function getBanInfo()
- {
- return $this->banInfo;
- }
-
- /**
- * Информация о том, может ли текущий пользователь
- * создать новое обсуждение в группе.
- * Возможные значения:
- * 1 — может;
- * 0 — не может.
- *
- * @return int
- */
- protected function getCanCreateTopic(): int
- {
- return $this->canCreateTopic;
- }
-
- /**
- * Информация о том, может ли текущий пользователь
- * написать сообщение сообществу.
- * Возможные значения:
- * 1 — может;
- * 0 — не может.
- *
- * @return int
- */
- protected function getCanMessage(): int
- {
- return $this->canMessage;
- }
-
- /**
- * Информация о том, может ли текущий пользователь оставлять записи на стене сообщества.
- * Возможные значения:
- * 1 — может;
- * 0 — не может.
- *
- * @return int
- */
- protected function getCanPost(): int
- {
- return $this->canPost;
- }
-
- /**
- * Информация о том, разрешено ли видеть чужие записи на стене группы.
- * Возможные значения:
- * 1 — может;
- * 0 — не может.
- *
- * @return int
- */
- protected function getCanSeeAllPosts(): int
- {
- return $this->canSeeAllPosts;
- }
-
- /**
- * Информация о том, может ли текущий пользователь загружать документы в группу.
- * Возможные значения:
- * 1 — может;
- * 0 — не может.
- *
- * @return int
- */
- protected function getCanUploadDoc(): int
- {
- return $this->canUploadDoc;
- }
-
- /**
- * Информация о том, может ли текущий пользователь загружать истории от имени сообщества:
- * 1 — может;
- * 0 — не может.
- *
- * @return int
- */
- protected function getCanUploadStory(): int
- {
- return $this->canUploadStory;
- }
-
- /**
- * Информация о том, может ли текущий пользователь загружать видеозаписи в группу.
- * Возможные значения:
- * 1 — может;
- * 0 — не может.
- *
- * @return int
- */
- protected function getCanUploadVideo(): int
- {
- return $this->canUploadVideo;
- }
-
- /**
- * Город, указанный в информации о сообществе. Объект, содержащий следующие поля:
- * id (integer) — идентификатор города;
- * title (string) — название города.
- *
- * @return mixed
- */
- protected function getCity()
- {
- return $this->city;
- }
-
- /**
- * Информация из блока контактов публичной страницы.
- * Массив объектов, каждый из которых может содержать поля:
- * user_id (integer) — идентификатор пользователя;
- * desc (string) — должность;
- * phone (string) — номер телефона;
- * email (string) — адрес e-mail.
- *
- * @return array
- */
- protected function getContacts(): array
- {
- return $this->contacts;
- }
-
- /**
- * Объект, содержащий счётчики сообщества, может включать
- * любой набор из следующих полей:
- * photos, albums, audios, videos, topics, docs.
- * Поле возвращается только при запросе данных об одном сообществе
- *
- * @return mixed
- */
- protected function getCounters()
- {
- return $this->counters;
- }
-
- /**
- * Страна, указанная в информации о сообществе.
- * Объект, содержащий следующие поля:
- * id (integer) — идентификатор страны;
- * title (string) — название страны.
- *
- * @return mixed
- */
- protected function getCountry()
- {
- return $this->country;
- }
-
- /**
- * Обложка сообщества.
- * Объект, который содержит следующие поля:
- * enabled (integer) — информация о том, включена ли обложка (1 — да, 0 — нет);
- * images (array) — копии изображений обложки.
- * Массив объектов, каждый из которых содержит следующие поля:
- * url (string) — URL копии;
- * width (integer) — ширина копии;
- * height (integer) — высота копии.
- *
- * @return mixed
- */
- protected function getCover()
- {
- return $this->cover;
- }
-
- /**
- * Возвращает данные о точках, по которым вырезаны
- * профильная и миниатюрная фотографии сообщества.
- * photo (object) — объект photo фотографии пользователя, из которой вырезается главное фото сообщества.
- * crop (object) — вырезанная фотография сообщества. Содержит следующие поля:
- * x (number) — координата X левого верхнего угла в процентах;
- * y (number) — координата Y левого верхнего угла в процентах;
- * x2 (number) — координата X правого нижнего угла в процентах;
- * y2 (number) — координата Y правого нижнего угла в процентах.
- * rect (object) — миниатюрная квадратная фотография, вырезанная из фотографии crop.
- * Содержит набор полей, аналогичный объекту crop.
- *
- * @return mixed
- */
- protected function getCropPhoto()
- {
- return $this->cropPhoto;
- }
-
- /**
- * Текст описания сообщества.
- *
- * @return string
- */
- protected function getDescription(): string
- {
- return $this->description;
- }
-
- /**
- * Идентификатор закрепленной записи.
- * Получить дополнительные данные о записи можно методом wall.getById,
- * передав в поле posts {group_id}{post_id}.
- *
- * @return int
- */
- protected function getFixedPost(): int
- {
- return $this->fixedPost;
- }
-
- /**
- * Информация о том, установлена ли у сообщества главная фотография.
- * Возможные значения:
- * 1 — установлена;
- * 0 — не установлена.
- *
- * @return int
- */
- protected function getHasPhoto(): int
- {
- return $this->hasPhoto;
- }
-
- /**
- * Информация о том, находится ли сообщество в закладках у текущего пользователя.
- * Возможные значения:
- * 1 — находится;
- * 0 — не находится.
- *
- * @return int
- */
- protected function getIsFavorite(): int
- {
- return $this->isFavorite;
- }
-
- /**
- * Информация о том, скрыто ли сообщество из ленты новостей текущего пользователя.
- * Возможные значения:
- * 1 — скрыто;
- * 0 — не скрыто.
- *
- * @return int
- */
- protected function getIsHiddenFromFeed(): int
- {
- return $this->isHiddenFromFeed;
- }
-
- /**
- * Информация о том, заблокированы ли сообщения
- * от этого сообщества (для текущего пользователя).
- *
- * @return int
- */
- protected function getIsMessagesBlocked(): int
- {
- return $this->isMessagesBlocked;
- }
-
- /**
- * Информация из блока ссылок сообщества.
- * Поле возвращается только при запросе данных об одном сообществе.
- * Массив объектов, каждый из которых содержит следующие поля:
- * id (integer) — идентификатор ссылки;
- * url (string) — URL;
- * name (string) — название ссылки;
- * desc (string) — описание ссылки;
- * photo_50 (string) — URL изображения-превью шириной 50px;
- * photo_100 (string) — URL изображения-превью шириной 100px.
- *
- * @return Links
- */
- protected function getLinks(): Links
- {
- return $this->links;
- }
-
- /**
- * Идентификатор основного фотоальбома.
- *
- * @return int
- */
- protected function getMainAlbumId(): int
- {
- return $this->mainAlbumId;
- }
-
- /**
- * Информация о главной секции. Возможные значения:
- * 0 — отсутствует;
- * 1 — фотографии;
- * 2 — обсуждения;
- * 3 — аудиозаписи;
- * 4 — видеозаписи;
- * 5 — товары.
- *
- * @return int
- */
- protected function getMainSection(): int
- {
- return $this->mainSection;
- }
-
- /**
- * Информация о магазине.
- * Объект, содержащий следующие поля:
- * enabled (integer) — информация о том, включен ли блок товаров в сообществе.
- * Возможные значения:
- * 1 — включен;
- * 0 — выключен. Если enabled = 0, объект не содержит других полей.
- * type (string) — информация о типе магазина.
- * Возвращается, если в группе включен раздел "Товары".
- * Возможные значения:
- * basic — базовые товары;
- * advanced — расширенные товары.
- * price_min (integer) — минимальная цена товаров;
- * price_max (integer)— максимальная цена товаров;
- * main_album_id (integer) — идентификатор главной подборки товаров;
- * contact_id (integer) — идентификатор контактного лица для связи с продавцом.
- * Возвращается отрицательное значение, если для связи с продавцом используются сообщения сообщества;
- * currency (object) — информация о валюте.
- * Объект, содержащий поля:
- * id (integer) — идентификатор валюты;
- * name (string) — символьное обозначение;
- * currency_text (string) — строковое обозначение.
- *
- * @return mixed
- */
- protected function getMarket()
- {
- return $this->market;
- }
-
- /**
- * Требуется scope = groups.
- * Статус участника текущего пользователя.
- * Возможные значения:
- * 0 — не является участником;
- * 1 — является участником;
- * 2 — не уверен, что посетит мероприятие;
- * 3 — отклонил приглашение;
- * 4 — запрос на вступление отправлен;
- * 5 — приглашен.
- *
- * @return int
- */
- protected function getMemberStatus(): int
- {
- return $this->memberStatus;
- }
-
- /**
- * Количество участников в сообществе.
- *
- * @return int
- */
- protected function getMembersCount(): int
- {
- return $this->membersCount;
- }
-
- /**
- * Место, указанное в информации о сообществе.
- * Объект, содержащий следующие поля:
- * id (integer) — идентификатор места;
- * title (string) — название места;
- * latitude (number) — географическая широта в градусах (от -90 до 90);
- * longitude (number) — географическая долгота в градусах (от -180 до 180);
- * type (string) — тип места;
- * country (integer) — идентификатор страны;
- * city (integer) — идентификатор города;
- * address (string) — адрес.
- *
- * @return mixed
- */
- protected function getPlace()
- {
- return $this->place;
- }
-
- /**
- * Возвращается для публичных страниц.
- * Текст описания для поля startDate.
- *
- * @return string
- */
- protected function getPublicDateLabel(): string
- {
- return $this->publicDateLabel;
- }
-
- /**
- * Адрес сайта из поля «веб-сайт» в описании сообщества.
- *
- * @return string
- */
- protected function getSite(): string
- {
- return $this->site;
- }
-
- /**
- * Для встреч содержит время начала встречи в формате unixtime.
- *
- * @return int
- */
- protected function getStartDate(): int
- {
- return $this->startDate;
- }
-
- /**
- * Для встреч содержит время окончания встречи в формате unixtime.
- * Для публичных страниц содержит только время начала — дата основания в формате YYYYMMDD.
- *
- * @return int
- */
- protected function getFinishDate(): int
- {
- return $this->finishDate;
- }
-
- /**
- * Статус сообщества.
- *
- * @return string
- */
- protected function getStatus(): string
- {
- return $this->status;
- }
-
- /**
- * Информация о том, есть ли у сообщества «огонёк».
- *
- * @return int
- */
- protected function getTrending(): int
- {
- return $this->trending;
- }
-
- /**
- * Информация о том, верифицировано ли сообщество.
- * Возможные значения:
- * 1 — является;
- * 0 — не является.
- *
- * @return int
- */
- protected function getVerified(): int
- {
- return $this->verified;
- }
-
- /**
- * Стена.
- * Возможные значения:
- * 0 — выключена;
- * 1 — открытая;
- * 2 — ограниченная;
- * 3 — закрытая.
- *
- * @return int
- */
- protected function getWall(): int
- {
- return $this->wall;
- }
-
- /**
- * Название главной вики-страницы.
- *
- * @return string
- */
- protected function getWikiPage(): string
- {
- return $this->wikiPage;
- }
-
- #endregion
-}
diff --git a/src/Foundation/Core/Community/Links.php b/src/Foundation/Core/Community/Links.php
deleted file mode 100644
index 146e829..0000000
--- a/src/Foundation/Core/Community/Links.php
+++ /dev/null
@@ -1,127 +0,0 @@
-id;
- }
-
- /**
- * URL.
- *
- * @return string
- */
- public function getUrl(): string
- {
- return $this->url;
- }
-
- /**
- * Название ссылки.
- *
- * @return string
- */
- public function getName(): string
- {
- return $this->name;
- }
-
- /**
- * Описание ссылки.
- *
- * @return string
- */
- public function getDescription(): string
- {
- return $this->description;
- }
-
- /**
- * URL изображения-превью шириной 50px.
- *
- * @return string
- */
- public function getPhoto50(): string
- {
- return $this->photo50;
- }
-
- /**
- * @return string
- */
- public function getPhoto100(): string
- {
- return $this->photo100;
- }
-
- #endregion
-
- public function __construct(array $links)
- {
- $this->id = $links['id'];
- $this->url = $links['url'];
- $this->name = $links['name'];
- $this->description = $links['desc'];
- $this->photo50 = $links['photo_50'];
- $this->photo100 = $links['photo_100'];
- }
-}
diff --git a/src/Foundation/Core/GroupInstance.php b/src/Foundation/Core/GroupInstance.php
deleted file mode 100644
index 73720be..0000000
--- a/src/Foundation/Core/GroupInstance.php
+++ /dev/null
@@ -1,8 +0,0 @@
-client = $client;
+ }
+
+ /**
+ * @return Collection
+ */
+ public function getInfo(): Collection
+ {
+ return $this->client;
+ }
+
+ /**
+ * @return Collection
+ */
+ public function getButtonActions(): Collection
+ {
+ return $this->client->get(self::BUTTON_ACTIONS);
+ }
+
+ /**
+ * @return bool
+ */
+ public function isKeyboard(): bool
+ {
+ return $this->client->get(self::KEYBOARD);
+ }
+
+ /**
+ * @return bool
+ */
+ public function isInlineKeyboard(): bool
+ {
+ return $this->client->get(self::INLINE_KEYBOARD);
+ }
+
+ /**
+ * @return bool
+ */
+ public function isCarousel(): bool
+ {
+ return $this->client->get(self::CAROUSEL);
+ }
+
+ /**
+ * @return int
+ */
+ public function getLangId(): int
+ {
+ return $this->client->get(self::LANG_ID);
+ }
+}
diff --git a/src/Foundation/Core/Models/Groups/AddressWorkInfoStatus.php b/src/Foundation/Core/Models/Groups/AddressWorkInfoStatus.php
new file mode 100644
index 0000000..d2c286a
--- /dev/null
+++ b/src/Foundation/Core/Models/Groups/AddressWorkInfoStatus.php
@@ -0,0 +1,16 @@
+call(self::SCOPE . 'addAddress', $args);
+ }
+
+ public function addCallbackServer(array $args = []) {
+ return $this->call(self::SCOPE . 'addCallbackServer', $args);
+ }
+
+ public function addLink(array $args = []) {
+ return $this->call(self::SCOPE . 'addLink', $args);
+ }
+
+ public function approveRequest(array $args = []) {
+ return $this->call(self::SCOPE . 'approveRequest', $args);
+ }
+
+ public function ban(array $args = []) {
+ return $this->call(self::SCOPE . 'ban', $args);
+ }
+
+ public function create(array $args = []) {
+ return $this->call(self::SCOPE . 'create', $args);
+ }
+
+ public function deleteCallbackServer(array $args = []) {
+ return $this->call(self::SCOPE . 'deleteCallbackServer', $args);
+ }
+
+ public function deleteLink(array $args = []) {
+ return $this->call(self::SCOPE . 'deleteLink', $args);
+ }
+
+ public function disableOnline(array $args = []) {
+ return $this->call(self::SCOPE . 'disableOnline', $args);
+ }
+ public function edit(array $args = []) {
+ return $this->call(self::SCOPE . 'edit', $args);
+ }
+
+ public function editAddress(array $args = []) {
+ return $this->call(self::SCOPE . 'editAddress', $args);
+ }
+
+ public function editCallbackServer(array $args = []) {
+ return $this->call(self::SCOPE . 'editCallbackServer', $args);
+ }
+
+ public function editLink(array $args = []) {
+ return $this->call(self::SCOPE . 'editLink', $args);
+ }
+ public function editManager(array $args = []) {
+ return $this->call(self::SCOPE . 'editManager', $args);
+ }
+
+ public function enableOnline(array $args = []) {
+ return $this->call(self::SCOPE . 'enableOnline', $args);
+ }
+
+// public function get(array $args = []) {
+// return $this->call(self::SCOPE . 'get', $args);
+// }
+
+ public function getAddresses(array $args = [])
+ {
+ return $this->call(self::SCOPE . 'getAddresses', $args);
+ }
+
+ public function getBanned(array $args = []) {
+ return $this->call(self::SCOPE . 'getBanned', $args);
+ }
+
+ public function getById(array $args = []) {
+ return $this->call(self::SCOPE . 'getById', $args);
+ }
+
+ public function getCallbackConfirmationCode(array $args = []) {
+ return $this->call(self::SCOPE . 'getCallbackConfirmationCode', $args);
+ }
+
+ public function getCallbackServers(array $args = []) {
+ return $this->call(self::SCOPE . 'getCallbackServers', $args);
+ }
+
+ public function getCallbackSettings(array $args = []) {
+ return $this->call(self::SCOPE . 'getCallbackSettings', $args);
+ }
+ public function getCatalog(array $args = []) {
+ return $this->call(self::SCOPE . 'getCatalog', $args);
+ }
+ public function getCatalogInfo(array $args = []) {
+ return $this->call(self::SCOPE . 'getCatalogInfo', $args);
+ }
+
+ public function getInvitedUsers(array $args = []) {
+ return $this->call(self::SCOPE . 'getInvitedUsers', $args);
+ }
+
+ public function getInvites(array $args = []) {
+ return $this->call(self::SCOPE . 'getInvites', $args);
+ }
+
+ public function getLongPollServer(array $args = []) {
+ return $this->call(self::SCOPE . 'getLongPollServer', $args);
+ }
+
+ public function getLongPollSettings(array $args = []) {
+ return $this->call(self::SCOPE . 'getLongPollSettings', $args);
+ }
+ public function getMembers(array $args = []) {
+ return $this->call(self::SCOPE . 'getMembers', $args);
+ }
+
+ public function getRequests(array $args = []) {
+ return $this->call(self::SCOPE . 'getRequests', $args);
+ }
+
+ public function getSettings(array $args = []) {
+ return $this->call(self::SCOPE . 'getSettings', $args);
+ }
+
+ public function getTokenPermissions($access_token) {
+ return $this->call(self::SCOPE . 'getTokenPermissions');
+ }
+
+ public function invite(array $args = []) {
+ return $this->call(self::SCOPE . 'invite', $args);
+ }
+
+ public function isMember(array $args = []) {
+ return $this->call(self::SCOPE . 'isMember', $args);
+ }
+
+ public function join(array $args = []) {
+ return $this->call(self::SCOPE . 'join', $args);
+ }
+
+ public function leave(array $args = []) {
+ return $this->call(self::SCOPE . 'leave', $args);
+ }
+
+ public function removeUser(array $args = []) {
+ return $this->call(self::SCOPE . 'removeUser', $args);
+ }
+
+ public function reorderLink(array $args = []) {
+ return $this->call(self::SCOPE . 'reorderLink', $args);
+ }
+ public function search(array $args = []) {
+ return $this->call(self::SCOPE . 'search', $args);
+ }
+ public function setCallbackSettings(array $args = []) {
+ return $this->call(self::SCOPE . 'setCallbackSettings', $args);
+ }
+ public function setLongPollSettings(array $args = []) {
+ return $this->call(self::SCOPE . 'setLongPollSettings', $args);
+ }
+
+ public function unban(array $args = []) {
+ return $this->call(self::SCOPE . 'unban', $args);
+ }
+}
diff --git a/src/Foundation/Core/Models/Groups/GroupAccess.php b/src/Foundation/Core/Models/Groups/GroupAccess.php
new file mode 100644
index 0000000..d04d1d2
--- /dev/null
+++ b/src/Foundation/Core/Models/Groups/GroupAccess.php
@@ -0,0 +1,14 @@
+call(self::SCOPE . 'addChatUser', $args);
+ }
+
+ public function allowMessagesFromGroup(array $args = [])
+ {
+ return $this->call(self::SCOPE . 'allowMessagesFromGroup', $args);
+ }
+
+ public function createChat(array $args = [])
+ {
+ return $this->call(self::SCOPE . 'createChat', $args);
+ }
+
+ public function delete(array $args = [])
+ {
+ return $this->call(self::SCOPE . 'delete', $args);
+ }
+
+ public function deleteChatPhoto(array $args = [])
+ {
+ return $this->call(self::SCOPE . 'deleteChatPhoto', $args);
+ }
+
+ public function deleteConversation(array $args = [])
+ {
+ return $this->call(self::SCOPE . 'deleteConversation', $args);
+ }
+
+ public function denyMessagesFromGroup(array $args = [])
+ {
+ return $this->call(self::SCOPE . 'denyMessagesFromGroup', $args);
+ }
+
+ public function edit(array $args = [])
+ {
+ return $this->call(self::SCOPE . 'edit', $args);
+ }
+
+ public function editChat(array $args = [])
+ {
+ return $this->call(self::SCOPE . 'editChat', $args);
+ }
+
+ public function getByConversationMessageId(array $args = [])
+ {
+ return $this->call(self::SCOPE . 'getByConversationMessageId', $args);
+ }
+
+ public function getById(array $args = [])
+ {
+ return $this->call(self::SCOPE . 'getById', $args);
+ }
+
+ public function getChatPreview(array $args = [])
+ {
+ return $this->call(self::SCOPE . 'getChatPreview', $args);
+ }
+
+ public function getConversationMembers(array $args = [])
+ {
+ return $this->call(self::SCOPE . 'getConversationMembers', $args);
+ }
+
+ public function getConversations(array $args = [])
+ {
+ return $this->call(self::SCOPE . 'getConversations', $args);
+ }
+
+ public function getConversationsById(array $args = [])
+ {
+ return $this->call(self::SCOPE . 'getConversationsById', $args);
+ }
+
+ public function getHistory(array $args = [])
+ {
+ return $this->call(self::SCOPE . 'getHistory', $args);
+ }
+
+ public function getHistoryAttachments(array $args = [])
+ {
+ return $this->call(self::SCOPE . 'getHistoryAttachments', $args);
+ }
+
+ public function getInviteLink(array $args = [])
+ {
+ return $this->call(self::SCOPE . 'getInviteLink', $args);
+ }
+
+ public function getLastActivity(array $args = [])
+ {
+ return $this->call(self::SCOPE . 'getLastActivity', $args);
+ }
+
+ public function getLongPollHistory(array $args = [])
+ {
+ return $this->call(self::SCOPE . 'getLongPollHistory', $args);
+ }
+
+ public function getLongPollServer(array $args = [])
+ {
+ return $this->call(self::SCOPE . 'getLongPollServer', $args);
+ }
+
+ public function isMessagesFromGroupAllowed(array $args = [])
+ {
+ return $this->call(self::SCOPE . 'isMessagesFromGroupAllowed', $args);
+ }
+
+ public function joinChatByInviteLink(array $args = [])
+ {
+ return $this->call(self::SCOPE . 'joinChatByInviteLink', $args);
+ }
+
+ public function markAsAnsweredConversation(array $args = [])
+ {
+ return $this->call(self::SCOPE . 'markAsAnsweredConversation', $args);
+ }
+
+ public function markAsImportant(array $args = [])
+ {
+ return $this->call(self::SCOPE . 'markAsImportant', $args);
+ }
+
+ public function markAsImportantConversation(array $args = [])
+ {
+ return $this->call(self::SCOPE . 'markAsImportantConversation', $args);
+ }
+
+ public function markAsRead(array $args = [])
+ {
+ return $this->call(self::SCOPE . 'markAsRead', $args);
+ }
+
+ public function pin(array $args = [])
+ {
+ return $this->call(self::SCOPE . 'pin', $args);
+ }
+
+ public function removeChatUser(array $args = [])
+ {
+ return $this->call(self::SCOPE . 'removeChatUser', $args);
+ }
+
+ public function restore(array $args = [])
+ {
+ return $this->call(self::SCOPE . 'restore', $args);
+ }
+
+ public function search(array $args = [])
+ {
+ return $this->call(self::SCOPE . 'search', $args);
+ }
+
+ public function searchConversations(array $args = [])
+ {
+ return $this->call(self::SCOPE . 'searchConversations', $args);
+ }
+
+ public function send(MessageRequestFields $messageProperties): Collection
+ {
+ return $this->call(self::SCOPE . 'send', get_object_vars($messageProperties));
+ }
+
+ public function setActivity(array $args = [])
+ {
+ return $this->call(self::SCOPE . 'setActivity', $args);
+ }
+
+ public function setChatPhoto(array $args = [])
+ {
+ return $this->call(self::SCOPE . 'setChatPhoto', $args);
+ }
+
+ public function unpin(array $args = [])
+ {
+ return $this->call(self::SCOPE . 'unpin', $args);
+ }
+}
diff --git a/src/Foundation/Core/Models/Messages/MessageFields.php b/src/Foundation/Core/Models/Messages/MessageFields.php
new file mode 100644
index 0000000..17a004d
--- /dev/null
+++ b/src/Foundation/Core/Models/Messages/MessageFields.php
@@ -0,0 +1,160 @@
+message = $message;
+ }
+
+ /**
+ * @return Collection
+ */
+ public function getMessage(): Collection
+ {
+ return $this->message;
+ }
+
+ /**
+ * @return Carbon
+ */
+ public function getDate(): Carbon
+ {
+ return new Carbon($this->message->get(self::DATE));
+ }
+
+ /**
+ * @param string $token
+ * @param array $userProfileFields
+ * @return UserFields
+ * @throws ApiException
+ * @throws Throwable
+ */
+ public function getFromUser(string $token, array $userProfileFields = []): UserFields
+ {
+ return new UserFields(collect(VkApi::user($token)
+ ->get((new UserRequestFields())
+ ->setUserIds([
+ $this->message->get(self::FROM_ID)
+ ])
+ ->setFields($userProfileFields)
+ )->first()));
+ }
+
+ /**
+ * @return int
+ */
+ public function getId(): int
+ {
+ return $this->message->get(self::ID);
+ }
+
+ /**
+ * @return int
+ */
+ public function getOut(): int
+ {
+ return $this->message->get(self::OUT);
+ }
+
+ /**
+ * @return array
+ */
+ public function getAttachments(): array
+ {
+ // TODO: добавить сущность
+ return $this->message->get(self::ATTACHMENTS);
+ }
+
+ /**
+ * @return int
+ */
+ public function getConversationMessageId(): int
+ {
+ return $this->message->get(self::CONVERSATION_MESSAGE_ID);
+ }
+
+ /**
+ * @return array
+ */
+ public function getForwardMessages(): array
+ {
+ return $this->message->get(self::FORWARD_MESSAGES);
+ }
+
+ /**
+ * @return bool
+ */
+ public function isImportant(): bool
+ {
+ return $this->message->get(self::IMPORTANT);
+ }
+
+ /**
+ * @return bool
+ */
+ public function isHidden(): bool
+ {
+ return $this->message->get(self::IS_HIDDEN);
+ }
+
+ /**
+ * @return int
+ */
+ public function getPeerId(): int
+ {
+ return $this->message->get(self::PEER_ID);
+ }
+
+ /**
+ * @return int
+ */
+ public function getRandomId(): int
+ {
+ return $this->message->get(self::RANDOM_ID);
+ }
+
+ /**
+ * @return string
+ */
+ public function getText(): string
+ {
+ return $this->message->get(self::TEXT);
+ }
+}
diff --git a/src/Foundation/Core/Models/Messages/MessageRequestFields.php b/src/Foundation/Core/Models/Messages/MessageRequestFields.php
new file mode 100644
index 0000000..1086080
--- /dev/null
+++ b/src/Foundation/Core/Models/Messages/MessageRequestFields.php
@@ -0,0 +1,393 @@
+setRandomId();
+ }
+
+ /**
+ * @param int|null $user_id
+ * @return MessageRequestFields
+ */
+ public function setUserId(?int $user_id): MessageRequestFields
+ {
+ $this->user_id = $user_id;
+ return $this;
+ }
+
+ /**
+ * @return MessageRequestFields
+ */
+ public function setRandomId(): MessageRequestFields
+ {
+ $this->random_id = (int)now()->timestamp;
+ return $this;
+ }
+
+ /**
+ * @param int|null $peer_id
+ * @return MessageRequestFields
+ */
+ public function setPeerId(?int $peer_id): MessageRequestFields
+ {
+ $this->peer_id = $peer_id;
+ return $this;
+ }
+
+ /**
+ * @param array $peer_ids
+ * @return MessageRequestFields
+ */
+ public function setPeerIds(array $peer_ids): MessageRequestFields
+ {
+ $this->peer_ids = $peer_ids;
+ return $this;
+ }
+
+ /**
+ * @param string|null $domain
+ * @return MessageRequestFields
+ */
+ public function setDomain(?string $domain): MessageRequestFields
+ {
+ $this->domain = $domain;
+ return $this;
+ }
+
+ /**
+ * @param int|null $chat_id
+ * @return MessageRequestFields
+ */
+ public function setChatId(?int $chat_id): MessageRequestFields
+ {
+ $this->chat_id = $chat_id;
+ return $this;
+ }
+
+ /**
+ * @param array $user_ids
+ * @return MessageRequestFields
+ */
+ public function setUserIds(array $user_ids): MessageRequestFields
+ {
+ $this->user_ids = $user_ids;
+ return $this;
+ }
+
+ /**
+ * @param string|null $message
+ * @return MessageRequestFields
+ */
+ public function setMessage(?string $message): MessageRequestFields
+ {
+ $this->message = $message;
+ return $this;
+ }
+
+ /**
+ * @param int|null $guid
+ * @return MessageRequestFields
+ */
+ public function setGuid(?int $guid): MessageRequestFields
+ {
+ $this->guid = $guid;
+ return $this;
+ }
+
+ /**
+ * @param float|null $lat
+ * @return MessageRequestFields
+ */
+ public function setLat(?float $lat): MessageRequestFields
+ {
+ $this->lat = $lat;
+ return $this;
+ }
+
+ /**
+ * @param float|null $long
+ * @return MessageRequestFields
+ */
+ public function setLong(?float $long): MessageRequestFields
+ {
+ $this->long = $long;
+ return $this;
+ }
+
+ /**
+ * @param string|null $attachment
+ * @return MessageRequestFields
+ */
+ public function setAttachment(?string $attachment): MessageRequestFields
+ {
+ $this->attachment = $attachment;
+ return $this;
+ }
+
+ /**
+ * @param int|null $reply_to
+ * @return MessageRequestFields
+ */
+ public function setReplyTo(?int $reply_to): MessageRequestFields
+ {
+ $this->reply_to = $reply_to;
+ return $this;
+ }
+
+ /**
+ * @param array $forward_messages
+ * @return MessageRequestFields
+ */
+ public function setForwardMessages(array $forward_messages): MessageRequestFields
+ {
+ $this->forward_messages = $forward_messages;
+ return $this;
+ }
+
+ /**
+ * @param string|null $forward
+ * @return MessageRequestFields
+ */
+ public function setForward(?string $forward): MessageRequestFields
+ {
+ $this->forward = $forward;
+ return $this;
+ }
+
+ /**
+ * @param array $sticker_id
+ * @return MessageRequestFields
+ */
+ public function setStickerId(array $sticker_id): MessageRequestFields
+ {
+ $this->sticker_id = $sticker_id;
+ return $this;
+ }
+
+ /**
+ * @param int|null $group_id
+ * @return MessageRequestFields
+ */
+ public function setGroupId(?int $group_id): MessageRequestFields
+ {
+ $this->group_id = $group_id;
+ return $this;
+ }
+
+ /**
+ * @param string|null $keyboard
+ * @return MessageRequestFields
+ */
+ public function setKeyboard(?string $keyboard): MessageRequestFields
+ {
+ $this->keyboard = $keyboard;
+ return $this;
+ }
+
+ /**
+ * @param string|null $template
+ * @return MessageRequestFields
+ */
+ public function setTemplate(?string $template): MessageRequestFields
+ {
+ $this->template = $template;
+ return $this;
+ }
+
+ /**
+ * @param string|null $payload
+ * @return MessageRequestFields
+ */
+ public function setPayload(?string $payload): MessageRequestFields
+ {
+ $this->payload = $payload;
+ return $this;
+ }
+
+ /**
+ * @param string|null $content_source
+ * @return MessageRequestFields
+ */
+ public function setContentSource(?string $content_source): MessageRequestFields
+ {
+ $this->content_source = $content_source;
+ return $this;
+ }
+
+ /**
+ * @param bool|null $dont_parse_links
+ * @return MessageRequestFields
+ */
+ public function setDontParseLinks(?bool $dont_parse_links): MessageRequestFields
+ {
+ $this->dont_parse_links = $dont_parse_links;
+ return $this;
+ }
+
+ /**
+ * @param bool|null $disable_mentions
+ * @return MessageRequestFields
+ */
+ public function setDisableMentions(?bool $disable_mentions): MessageRequestFields
+ {
+ $this->disable_mentions = $disable_mentions;
+ return $this;
+ }
+
+ /**
+ * @param string|null $intent
+ * @return MessageRequestFields
+ */
+ public function setIntent(?string $intent): MessageRequestFields
+ {
+ $this->intent = $intent;
+ return $this;
+ }
+
+ /**
+ * @param int|null $subscribe_id
+ * @return MessageRequestFields
+ */
+ public function setSubscribeId(?int $subscribe_id): MessageRequestFields
+ {
+ $this->subscribe_id = $subscribe_id;
+ return $this;
+ }
+}
diff --git a/src/Foundation/Core/Models/Owner/Owner.php b/src/Foundation/Core/Models/Owner/Owner.php
new file mode 100644
index 0000000..dc38127
--- /dev/null
+++ b/src/Foundation/Core/Models/Owner/Owner.php
@@ -0,0 +1,19 @@
+call(self::SCOPE . 'get', get_object_vars($requestFields));
+ }
+
+ public function getFollowers()
+ {
+
+ }
+
+ public function getSubscriptions()
+ {
+
+ }
+
+ public function report()
+ {
+
+ }
+
+ public function search()
+ {
+
+ }
+}
diff --git a/src/Foundation/Core/Models/Users/UserFields.php b/src/Foundation/Core/Models/Users/UserFields.php
new file mode 100644
index 0000000..e397a6f
--- /dev/null
+++ b/src/Foundation/Core/Models/Users/UserFields.php
@@ -0,0 +1,95 @@
+user = $user;
+ }
+
+ /**
+ * @return Collection
+ */
+ public function getUser(): Collection
+ {
+ return $this->user;
+ }
+
+ /**
+ * @return int
+ */
+ public function getId(): int
+ {
+ return $this->user->get(UserProfileFields::ID);
+ }
+
+ /**
+ * @return string
+ */
+ public function getName(): string
+ {
+ return $this->user->get(UserProfileFields::FIRST_NAME);
+ }
+
+ /**
+ * @return string
+ */
+ public function getSurname(): string
+ {
+ return $this->user->get(UserProfileFields::LAST_NAME);
+ }
+
+ /**
+ * @return string
+ */
+ public function getFullName(): string
+ {
+ return sprintf(
+ '%s %s',
+ $this->user->get(UserProfileFields::FIRST_NAME),
+ $this->user->get(UserProfileFields::LAST_NAME)
+ );
+ }
+
+ /**
+ * @return bool
+ */
+ public function isAccessClosed(): bool
+ {
+ return $this->user->get(UserProfileFields::CAN_ACCESS_CLOSED);
+ }
+
+ /**
+ * @return bool
+ */
+ public function isClosed(): bool
+ {
+ return $this->user->get(UserProfileFields::IS_CLOSED);
+ }
+
+ /**
+ * @param string $key
+ * @return mixed
+ */
+ public function get(string $key): mixed
+ {
+ return $this->user->get($key);
+ }
+}
diff --git a/src/Foundation/Core/Models/Users/UserNameCases.php b/src/Foundation/Core/Models/Users/UserNameCases.php
new file mode 100644
index 0000000..98d654f
--- /dev/null
+++ b/src/Foundation/Core/Models/Users/UserNameCases.php
@@ -0,0 +1,18 @@
+user_ids = $user_ids;
+ return $this;
+ }
+
+ /**
+ * @param array $fields
+ * @return UserRequestFields
+ */
+ public function setFields(array $fields): UserRequestFields
+ {
+ $this->fields = $fields;
+ return $this;
+ }
+
+ /**
+ * @param string $name_case
+ * @return UserRequestFields
+ */
+ public function setNameCase(string $name_case): UserRequestFields
+ {
+ $this->name_case = $name_case;
+ return $this;
+ }
+}
diff --git a/src/Foundation/Core/PrivateMessage.php b/src/Foundation/Core/PrivateMessage.php
deleted file mode 100644
index a396eac..0000000
--- a/src/Foundation/Core/PrivateMessage.php
+++ /dev/null
@@ -1,199 +0,0 @@
-text;
- }
-}
diff --git a/src/Formatters/BaseFormatter.php b/src/Foundation/Format.php
similarity index 83%
rename from src/Formatters/BaseFormatter.php
rename to src/Foundation/Format.php
index fabaf28..6faac79 100644
--- a/src/Formatters/BaseFormatter.php
+++ b/src/Foundation/Format.php
@@ -1,10 +1,14 @@
query(self::CONFIG_ROUTES . (!$key ? null : ".$key"));
}
@@ -44,9 +41,9 @@ public function routes(string $key = null): array|string|Collection|null
* Конфигурация логирования.
*
* @param string|null $key
- * @return array|string|Collection|null
+ * @return array|string|null
*/
- public function logging(string $key = null): array|string|Collection|null
+ public function logging(string $key = null): array|string|null
{
return $this->query(self::CONFIG_LOGGING . (!$key ? null : ".$key"));
}
@@ -55,9 +52,9 @@ public function logging(string $key = null): array|string|Collection|null
* Конфигурация подключения к API.
*
* @param string|null $key
- * @return array|string|Collection|null
+ * @return array|string|null
*/
- public function api(string $key = null): array|string|Collection|null
+ public function api(string $key = null): array|string|null
{
return $this->query(self::CONFIG_API . (!$key ? null : ".$key"));
}
@@ -66,22 +63,21 @@ public function api(string $key = null): array|string|Collection|null
* Конфигурация групп.
*
* @param string|null $key
- * @return array|string|Collection|null
+ * @return array|string|null
*/
- public function groups(string $key = null): array|string|Collection|null
+ public function groups(string $key = null): array|string|null
{
return $this->query(self::CONFIG_GROUPS . (!$key ? null : ".$key"));
}
/**
- * Конфигурация ошибок API.
+ * Конфигурация приложений.
*
* @param string|null $key
- * @param bool $needCollection
- * @return array|string|Collection|null
+ * @return array|string|null
*/
- public function errors(string $key = null): array|string|Collection|null
+ public function apps(string $key = null): array|string|null
{
- return $this->query(self::CONFIG_ERRORS . (!$key ? null : ".$key"));
+ return $this->query(self::CONFIG_APPS . (!$key ? null : ".$key"));
}
}
diff --git a/src/Models/Event.php b/src/Models/Event.php
new file mode 100644
index 0000000..c52e07f
--- /dev/null
+++ b/src/Models/Event.php
@@ -0,0 +1,21 @@
+app->bind(CallbackEventService::class);
- $this->app->bind('configure', Configure::class);
- $this->app->bind('format', BaseFormatter::class);
- $this->app->bind('group', GroupInstance::class);
+ $this->app->bind('sdkconfig', SdkConfig::class);
+ $this->app->bind('format', Format::class);
+ $this->app->bind('vkapi', Client::class);
}
/**
@@ -37,8 +37,9 @@ public function boot(): void
$this->publishes([
__DIR__ . '/../.root/lang/ru.php' => $this->app->langPath('ru/vk-sdk.php'),
- __DIR__ . '/../.root/lang/en.php' => $this->app->langPath('en/vk-sdk.php'),
- ], 'vk-sdk-lang');
+ ], 'vk-sdk-lang-ru');
+
+ $this->loadMigrationsFrom(__DIR__.'/../.root/database/migrations');
$this->loadRoutesFrom(__DIR__ . '/../.root/routes/callbacks.php');
}
diff --git a/src/Services/CallbackEventService.php b/src/Services/CallbackEventService.php
index 6e0231b..a7ccca5 100644
--- a/src/Services/CallbackEventService.php
+++ b/src/Services/CallbackEventService.php
@@ -6,22 +6,21 @@
use Hopex\VkSdk\Exceptions\Callback\SecretException;
use Hopex\VkSdk\Exceptions\Callback\UnknownEventException;
use Hopex\VkSdk\Exceptions\Callback\UnknownGroupIdException;
-use Hopex\VkSdk\Facades\Configure;
+use Hopex\VkSdk\Facades\SdkConfig;
+use Hopex\VkSdk\Foundation\Core\Callback\BaseEvent;
+use Hopex\VkSdk\Models\Event;
use Illuminate\Http\Request;
use Throwable;
class CallbackEventService
{
/**
- * Входящий запрос.
- *
* @var Request
*/
- private Request $request;
+ public Request $request;
/**
* CallbackEventService constructor.
- *
* @param Request $request
* @throws Throwable
*/
@@ -38,22 +37,29 @@ public function __construct(Request $request)
public function division(): mixed
{
$groupId = $this->request->json('group_id');
+ $eventId = $this->request->json('event_id');
$event = $this->request->json('type');
+ if (SdkConfig::groups("$groupId.allow_retry_events") || !Event::where('event_id', $eventId)->first()) {
+ Event::updateOrCreate($this->request->only('group_id', 'type', 'event_id'));
+ } else {
+ return 'ok';
+ }
+
switch ($event) {
case 'confirmation':
- $code = Configure::groups("{$groupId}.confirmation");
+ $code = SdkConfig::groups("$groupId.confirmation");
throw_if(empty($code), UnknownGroupIdException::class);
return $code;
default:
throw_if(!method_exists(CallbackEventsContract::class, $event), UnknownEventException::class);
throw_if(
- Configure::groups("{$groupId}.secret.verify") && Configure::groups("{$groupId}.secret.code") != $this->request->json('secret'),
+ SdkConfig::groups("$groupId.secret.verify") && SdkConfig::groups("{$groupId}.secret.code") != $this->request->json('secret'),
SecretException::class
);
return call_user_func(
- [new (Configure::groups("{$groupId}.events")), $event],
- collect($this->request->only(['group_id', 'object']))
+ [new (SdkConfig::groups("$groupId.events")), $event],
+ new BaseEvent(collect($this->request->only(['group_id', 'object'])))
);
}
}
From 61432f74c9159dfef49a1c41c034b55ab2496d2a Mon Sep 17 00:00:00 2001
From: Schizo
Date: Sun, 23 Oct 2022 21:14:13 +0300
Subject: [PATCH 02/24] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB?=
=?UTF-8?q?=D0=B5=D0=BD=D1=8B=20=D0=B2=D1=81=D0=B5=20=D0=BF=D0=BE=D0=BB?=
=?UTF-8?q?=D1=8F=20=D0=BF=D1=80=D0=BE=D1=84=D0=B8=D0=BB=D1=8F=20=D0=BF?=
=?UTF-8?q?=D0=BE=D0=BB=D1=8C=D0=B7=D0=BE=D0=B2=D0=B0=D1=82=D0=B5=D0=BB?=
=?UTF-8?q?=D1=8F=20=D1=81=20=D0=B7=D0=B0=D0=B2=D0=B8=D1=81=D0=B8=D0=BC?=
=?UTF-8?q?=D0=BE=D1=81=D1=82=D1=8F=D0=BC=D0=B8=20=D1=81=D1=82=D1=80=D0=B0?=
=?UTF-8?q?=D0=BD=20=D0=B8=20=D0=B3=D0=BE=D1=80=D0=BE=D0=B4=D0=BE=D0=B2=20?=
=?UTF-8?q?=D0=BE=D1=82=20=D0=B8=D1=85=20ID?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
src/.root/lang/ru.php | 5 +
src/Exceptions/Api/ApiException.php | 4 +-
src/Foundation/Core/Api/Client.php | 10 +
.../Core/Models/Database/Database.php | 40 ++
.../Core/Models/Messages/Message.php | 2 -
.../Core/Models/Messages/MessageFields.php | 10 +-
.../Users/ProfileFields/CareerField.php | 105 ++++
.../Models/Users/ProfileFields/CityField.php | 61 ++
.../Users/ProfileFields/CountryField.php | 61 ++
.../Users/ProfileFields/EducationField.php | 136 +++++
.../Users/ProfileFields/LastSeenField.php | 50 ++
.../Users/ProfileFields/MilitaryField.php | 81 +++
.../Users/ProfileFields/RelativeField.php | 64 ++
.../Users/ProfileFields/SchoolField.php | 186 ++++++
.../Core/Models/Users/UserFields.php | 95 ---
.../Core/Models/Users/UserProfileFields.php | 578 +++++++++++++++++-
.../Core/Models/Users/UserRequestFields.php | 2 +-
17 files changed, 1383 insertions(+), 107 deletions(-)
create mode 100644 src/Foundation/Core/Models/Database/Database.php
create mode 100644 src/Foundation/Core/Models/Users/ProfileFields/CareerField.php
create mode 100644 src/Foundation/Core/Models/Users/ProfileFields/CityField.php
create mode 100644 src/Foundation/Core/Models/Users/ProfileFields/CountryField.php
create mode 100644 src/Foundation/Core/Models/Users/ProfileFields/EducationField.php
create mode 100644 src/Foundation/Core/Models/Users/ProfileFields/LastSeenField.php
create mode 100644 src/Foundation/Core/Models/Users/ProfileFields/MilitaryField.php
create mode 100644 src/Foundation/Core/Models/Users/ProfileFields/RelativeField.php
create mode 100644 src/Foundation/Core/Models/Users/ProfileFields/SchoolField.php
delete mode 100644 src/Foundation/Core/Models/Users/UserFields.php
diff --git a/src/.root/lang/ru.php b/src/.root/lang/ru.php
index 3f015ef..92fea56 100644
--- a/src/.root/lang/ru.php
+++ b/src/.root/lang/ru.php
@@ -1,6 +1,11 @@
'Брат/сестра',
+ 'parent' => 'Папа/Мама',
+ 'grandparent' => 'Дедушка/бабушка',
+ 'child' => 'Ребенок',
+ 'grandchild' => 'Внук/внучка',
'Access denied' => 'Доступ запрещен',
'Access to comment denied' => 'Доступ к комментариям закрыт',
'Access to group denied' => 'Доступ в группу закрыт',
diff --git a/src/Exceptions/Api/ApiException.php b/src/Exceptions/Api/ApiException.php
index 78d67dc..b1bcadf 100644
--- a/src/Exceptions/Api/ApiException.php
+++ b/src/Exceptions/Api/ApiException.php
@@ -25,7 +25,7 @@ public function __construct($message = null, $code = 400, Throwable $previous =
$code = 400;
$message = $commonError;
}
- $message = preg_replace('~vk-sdk\.~', '', __("vk-sdk.{$message}"));
- parent::__construct("ApiException: {$message}", $code, $previous);
+ $message = preg_replace('~vk-sdk\.~', '', __("vk-sdk.$message"));
+ parent::__construct("ApiException: $message", $code, $previous);
}
}
diff --git a/src/Foundation/Core/Api/Client.php b/src/Foundation/Core/Api/Client.php
index 469f1cb..4012f2f 100644
--- a/src/Foundation/Core/Api/Client.php
+++ b/src/Foundation/Core/Api/Client.php
@@ -2,6 +2,7 @@
namespace Hopex\VkSdk\Foundation\Core\Api;
+use Hopex\VkSdk\Foundation\Core\Models\Database\Database;
use Hopex\VkSdk\Foundation\Core\Models\Groups\Group;
use Hopex\VkSdk\Foundation\Core\Models\Messages\Message;
use Hopex\VkSdk\Foundation\Core\Models\Users\User;
@@ -38,4 +39,13 @@ public function user(string $token): User
{
return new User($token);
}
+
+ /**
+ * @param string $token
+ * @return Database
+ */
+ public function database(string $token): Database
+ {
+ return new Database($token);
+ }
}
diff --git a/src/Foundation/Core/Models/Database/Database.php b/src/Foundation/Core/Models/Database/Database.php
new file mode 100644
index 0000000..c1335aa
--- /dev/null
+++ b/src/Foundation/Core/Models/Database/Database.php
@@ -0,0 +1,40 @@
+call(self::SCOPE . 'getCitiesById', $args);
+ }
+
+ /**
+ * @param array $args
+ * @return Collection
+ * @throws ApiException
+ * @throws Throwable
+ */
+ public function getCountriesById(array $args = []): Collection
+ {
+ return $this->call(self::SCOPE . 'getCountriesById', $args);
+ }
+}
diff --git a/src/Foundation/Core/Models/Messages/Message.php b/src/Foundation/Core/Models/Messages/Message.php
index faba3ce..8200714 100644
--- a/src/Foundation/Core/Models/Messages/Message.php
+++ b/src/Foundation/Core/Models/Messages/Message.php
@@ -2,10 +2,8 @@
namespace Hopex\VkSdk\Foundation\Core\Models\Messages;
-use Hopex\VkSdk\Exceptions\Api\ApiException;
use Hopex\VkSdk\Foundation\Core\Api\Request;
use Illuminate\Support\Collection;
-use Throwable;
/**
* Class Message
diff --git a/src/Foundation/Core/Models/Messages/MessageFields.php b/src/Foundation/Core/Models/Messages/MessageFields.php
index 17a004d..740cf35 100644
--- a/src/Foundation/Core/Models/Messages/MessageFields.php
+++ b/src/Foundation/Core/Models/Messages/MessageFields.php
@@ -5,7 +5,7 @@
use Carbon\Carbon;
use Hopex\VkSdk\Exceptions\Api\ApiException;
use Hopex\VkSdk\Facades\VkApi;
-use Hopex\VkSdk\Foundation\Core\Models\Users\UserFields;
+use Hopex\VkSdk\Foundation\Core\Models\Users\UserProfileFields;
use Hopex\VkSdk\Foundation\Core\Models\Users\UserRequestFields;
use Illuminate\Support\Collection;
use Throwable;
@@ -62,18 +62,18 @@ public function getDate(): Carbon
/**
* @param string $token
* @param array $userProfileFields
- * @return UserFields
+ * @return UserProfileFields
* @throws ApiException
* @throws Throwable
*/
- public function getFromUser(string $token, array $userProfileFields = []): UserFields
+ public function getSender(string $token, array $userProfileFields = []): UserProfileFields
{
- return new UserFields(collect(VkApi::user($token)
+ return new UserProfileFields(collect(VkApi::user($token)
->get((new UserRequestFields())
->setUserIds([
$this->message->get(self::FROM_ID)
])
- ->setFields($userProfileFields)
+ ->setProfileFields($userProfileFields)
)->first()));
}
diff --git a/src/Foundation/Core/Models/Users/ProfileFields/CareerField.php b/src/Foundation/Core/Models/Users/ProfileFields/CareerField.php
new file mode 100644
index 0000000..aade987
--- /dev/null
+++ b/src/Foundation/Core/Models/Users/ProfileFields/CareerField.php
@@ -0,0 +1,105 @@
+cityId = $career->has(self::CITY_ID) ? $career->get(self::CITY_ID) : null;
+ $this->countryId = $career->has(self::COUNTRY_ID) ? $career->get(self::COUNTRY_ID) : null;
+ $this->from = $career->has(self::FROM) ? $career->get(self::FROM) : null;
+ $this->groupId = $career->has(self::GROUP_ID) ? $career->get(self::GROUP_ID) : null;
+ $this->position = $career->has(self::POSITION) ? $career->get(self::POSITION) : null;
+ } else {
+ $this->cityId = $career[self::CITY_ID] ?? null;
+ $this->countryId = $career[self::COUNTRY_ID] ?? null;
+ $this->from = $career[self::FROM] ?? null;
+ $this->groupId = $career[self::GROUP_ID] ?? null;
+ $this->position = $career[self::POSITION] ?? null;
+ }
+ }
+
+ /**
+ * @return int|null
+ */
+ public function getCityId(): ?int
+ {
+ return $this->cityId;
+ }
+
+ /**
+ * @return int|null
+ */
+ public function getCountryId(): ?int
+ {
+ return $this->countryId;
+ }
+
+ /**
+ * @return int|null
+ */
+ public function getFrom(): ?int
+ {
+ return $this->from;
+ }
+
+ /**
+ * @return int|null
+ */
+ public function getGroupId(): ?int
+ {
+ // TODO: добавить сущность
+ return $this->groupId;
+ }
+
+ /**
+ * @return string|null
+ */
+ public function getPosition(): ?string
+ {
+ return $this->position;
+ }
+}
diff --git a/src/Foundation/Core/Models/Users/ProfileFields/CityField.php b/src/Foundation/Core/Models/Users/ProfileFields/CityField.php
new file mode 100644
index 0000000..a046b61
--- /dev/null
+++ b/src/Foundation/Core/Models/Users/ProfileFields/CityField.php
@@ -0,0 +1,61 @@
+city = $city;
+ } elseif (is_a($city, 'array')) {
+ $this->city = collect($city);
+ } else {
+ $this->city = collect(VkApi::database($token)->getCitiesById([self::CITY_IDS => $city])->first());
+ }
+ }
+
+ /**
+ * @return int
+ */
+ public function getId(): int
+ {
+ return $this->city->get(self::ID);
+ }
+
+ /**
+ * @return string
+ */
+ public function getTitle(): string
+ {
+ return $this->city->get(self::TITLE);
+ }
+}
diff --git a/src/Foundation/Core/Models/Users/ProfileFields/CountryField.php b/src/Foundation/Core/Models/Users/ProfileFields/CountryField.php
new file mode 100644
index 0000000..1ac2752
--- /dev/null
+++ b/src/Foundation/Core/Models/Users/ProfileFields/CountryField.php
@@ -0,0 +1,61 @@
+country = $country;
+ } elseif (is_a($country, 'array')) {
+ $this->country = collect($country);
+ } else {
+ $this->country = collect(VkApi::database($token)->getCountriesById([self::COUNTRY_IDS => $country])->first());
+ }
+ }
+
+ /**
+ * @return int
+ */
+ public function getId(): int
+ {
+ return $this->country->get(self::ID);
+ }
+
+ /**
+ * @return string
+ */
+ public function getTitle(): string
+ {
+ return $this->country->get(self::TITLE);
+ }
+}
diff --git a/src/Foundation/Core/Models/Users/ProfileFields/EducationField.php b/src/Foundation/Core/Models/Users/ProfileFields/EducationField.php
new file mode 100644
index 0000000..17893ef
--- /dev/null
+++ b/src/Foundation/Core/Models/Users/ProfileFields/EducationField.php
@@ -0,0 +1,136 @@
+university = $city->has(self::UNIVERSITY) ? $city->get(self::UNIVERSITY) : null;
+ $this->universityName = $city->has(self::UNIVERSITY_NAME) ? $city->get(self::UNIVERSITY_NAME) : null;
+ $this->faculty = $city->has(self::FACULTY) ? $city->get(self::FACULTY) : null;
+ $this->facultyName = $city->has(self::FACULTY_NAME) ? $city->get(self::FACULTY_NAME) : null;
+ $this->graduation = $city->has(self::GRADUATION) ? $city->get(self::GRADUATION) : null;
+ $this->educationForm = $city->has(self::EDUCATION_FORM) ? $city->get(self::EDUCATION_FORM) : null;
+ $this->educationStatus = $city->has(self::EDUCATION_STATUS) ? $city->get(self::EDUCATION_STATUS) : null;
+ } else {
+ $this->university = $city[self::UNIVERSITY] ?? null;
+ $this->universityName = $city[self::UNIVERSITY_NAME] ?? null;
+ $this->faculty = $city[self::FACULTY] ?? null;
+ $this->facultyName = $city[self::FACULTY_NAME] ?? null;
+ $this->graduation = $city[self::GRADUATION] ?? null;
+ $this->educationForm = $city[self::EDUCATION_FORM] ?? null;
+ $this->educationStatus = $city[self::EDUCATION_STATUS] ?? null;
+ }
+ }
+
+ /**
+ * @return int
+ */
+ public function getUniversity(): int
+ {
+ return $this->university;
+ }
+
+ /**
+ * @return string
+ */
+ public function getUniversityName(): string
+ {
+ return $this->universityName;
+ }
+
+ /**
+ * @return int
+ */
+ public function getFaculty(): int
+ {
+ return $this->faculty;
+ }
+
+ /**
+ * @return string
+ */
+ public function getFacultyName(): string
+ {
+ return $this->facultyName;
+ }
+
+ /**
+ * @return int
+ */
+ public function getGraduation(): int
+ {
+ return $this->graduation;
+ }
+
+ /**
+ * @return string
+ */
+ public function getEducationForm(): string
+ {
+ return $this->educationForm;
+ }
+
+ /**
+ * @return string
+ */
+ public function getEducationStatus(): string
+ {
+ return $this->educationStatus;
+ }
+}
diff --git a/src/Foundation/Core/Models/Users/ProfileFields/LastSeenField.php b/src/Foundation/Core/Models/Users/ProfileFields/LastSeenField.php
new file mode 100644
index 0000000..5cbd948
--- /dev/null
+++ b/src/Foundation/Core/Models/Users/ProfileFields/LastSeenField.php
@@ -0,0 +1,50 @@
+lastSeen = $lastSeen;
+ } else {
+ $this->lastSeen = collect($lastSeen);
+ }
+ }
+
+ /**
+ * @return int|null
+ */
+ public function getPlatform(): ?int
+ {
+ return $this->lastSeen->get(self::PLATFORM);
+ }
+
+ /**
+ * @return Carbon
+ */
+ public function getTime(): Carbon
+ {
+ return new Carbon($this->lastSeen->get(self::TIME));
+ }
+}
diff --git a/src/Foundation/Core/Models/Users/ProfileFields/MilitaryField.php b/src/Foundation/Core/Models/Users/ProfileFields/MilitaryField.php
new file mode 100644
index 0000000..a583694
--- /dev/null
+++ b/src/Foundation/Core/Models/Users/ProfileFields/MilitaryField.php
@@ -0,0 +1,81 @@
+military = $military;
+ } else {
+ $this->military = collect($military);
+ }
+ }
+
+ /**
+ * @param string $token
+ * @return CountryField
+ * @throws ApiException
+ * @throws Throwable
+ */
+ public function getCountry(string $token): CountryField
+ {
+ return new CountryField($this->military->get(self::COUNTRY_ID), $token);
+ }
+
+ /**
+ * @return int
+ */
+ public function getUnit(): int
+ {
+ return $this->military->get(self::UNIT);
+ }
+
+ /**
+ * @return int
+ */
+ public function getUnitId(): int
+ {
+ return $this->military->get(self::UNIT_ID);
+ }
+
+ /**
+ * @return int
+ */
+ public function getFrom(): int
+ {
+ return $this->military->get(self::FROM);
+ }
+
+ /**
+ * @return int
+ */
+ public function getUntil(): int
+ {
+ return $this->military->get(self::UNTIL);
+ }
+}
diff --git a/src/Foundation/Core/Models/Users/ProfileFields/RelativeField.php b/src/Foundation/Core/Models/Users/ProfileFields/RelativeField.php
new file mode 100644
index 0000000..287b4f2
--- /dev/null
+++ b/src/Foundation/Core/Models/Users/ProfileFields/RelativeField.php
@@ -0,0 +1,64 @@
+relative = $relative;
+ } else {
+ $this->relative = collect($relative);
+ }
+ }
+
+ /**
+ * @param string $token
+ * @param array $userProfileFields
+ * @return UserProfileFields
+ * @throws ApiException
+ * @throws Throwable
+ */
+ public function getRelative(string $token, array $userProfileFields = []): UserProfileFields
+ {
+ return new UserProfileFields(collect(VkApi::user($token)
+ ->get((new UserRequestFields())
+ ->setUserIds([
+ $this->relative->get(self::ID)
+ ])
+ ->setProfileFields($userProfileFields)
+ )->first()));
+ }
+
+ /**
+ * @return string
+ */
+ public function getType(): string
+ {
+ return preg_replace('~vk-sdk\.~', '', __('vk-sdk.' . $this->relative->get(self::TYPE)));
+ }
+}
diff --git a/src/Foundation/Core/Models/Users/ProfileFields/SchoolField.php b/src/Foundation/Core/Models/Users/ProfileFields/SchoolField.php
new file mode 100644
index 0000000..1df7085
--- /dev/null
+++ b/src/Foundation/Core/Models/Users/ProfileFields/SchoolField.php
@@ -0,0 +1,186 @@
+city = $school->has(self::CITY) ? $school->get(self::CITY) : null;
+ $this->country = $school->has(self::COUNTRY) ? $school->get(self::COUNTRY) : null;
+ $this->id = $school->has(self::ID) ? $school->get(self::ID) : null;
+ $this->name = $school->has(self::NAME) ? $school->get(self::NAME) : null;
+ $this->type = $school->has(self::TYPE) ? $school->get(self::TYPE) : null;
+ $this->typeStr = $school->has(self::TYPE_STR) ? $school->get(self::TYPE_STR) : null;
+ $this->yearFrom = $school->has(self::YEAR_FROM) ? $school->get(self::YEAR_FROM) : null;
+ $this->yearGraduated = $school->has(self::YEAR_GRADUATED) ? $school->get(self::YEAR_GRADUATED) : null;
+ $this->yearTo = $school->has(self::YEAR_TO) ? $school->get(self::YEAR_TO) : null;
+ $this->speciality = $school->has(self::SPECIALITY) ? $school->get(self::SPECIALITY) : null;
+ } else {
+ $this->city = $school[self::CITY] ?? null;
+ $this->country = $school[self::COUNTRY] ?? null;
+ $this->id = $school[self::ID] ?? null;
+ $this->name = $school[self::NAME] ?? null;
+ $this->type = $school[self::TYPE] ?? null;
+ $this->typeStr = $school[self::TYPE_STR] ?? null;
+ $this->yearFrom = $school[self::YEAR_FROM] ?? null;
+ $this->yearGraduated = $school[self::YEAR_GRADUATED] ?? null;
+ $this->yearTo = $school[self::YEAR_TO] ?? null;
+ $this->speciality = $school[self::SPECIALITY] ?? null;
+ }
+ }
+
+ /**
+ * @return int|null
+ */
+ public function getCity(): ?int
+ {
+ return $this->city;
+ }
+
+ /**
+ * @return int|null
+ */
+ public function getCountry(): ?int
+ {
+ return $this->country;
+ }
+
+ /**
+ * @return int|null
+ */
+ public function getId(): ?int
+ {
+ return $this->id;
+ }
+
+ /**
+ * @return string|null
+ */
+ public function getName(): ?string
+ {
+ return $this->name;
+ }
+
+ /**
+ * @return int|null
+ */
+ public function getType(): ?int
+ {
+ return $this->type;
+ }
+
+ /**
+ * @return string|null
+ */
+ public function getTypeStr(): ?string
+ {
+ return $this->typeStr;
+ }
+
+ /**
+ * @return int|null
+ */
+ public function getYearFrom(): ?int
+ {
+ return $this->yearFrom;
+ }
+
+ /**
+ * @return int|null
+ */
+ public function getYearGraduated(): ?int
+ {
+ return $this->yearGraduated;
+ }
+
+ /**
+ * @return int|null
+ */
+ public function getYearTo(): ?int
+ {
+ return $this->yearTo;
+ }
+
+ /**
+ * @return string|null
+ */
+ public function getSpeciality(): ?string
+ {
+ return $this->speciality;
+ }
+}
diff --git a/src/Foundation/Core/Models/Users/UserFields.php b/src/Foundation/Core/Models/Users/UserFields.php
deleted file mode 100644
index e397a6f..0000000
--- a/src/Foundation/Core/Models/Users/UserFields.php
+++ /dev/null
@@ -1,95 +0,0 @@
-user = $user;
- }
-
- /**
- * @return Collection
- */
- public function getUser(): Collection
- {
- return $this->user;
- }
-
- /**
- * @return int
- */
- public function getId(): int
- {
- return $this->user->get(UserProfileFields::ID);
- }
-
- /**
- * @return string
- */
- public function getName(): string
- {
- return $this->user->get(UserProfileFields::FIRST_NAME);
- }
-
- /**
- * @return string
- */
- public function getSurname(): string
- {
- return $this->user->get(UserProfileFields::LAST_NAME);
- }
-
- /**
- * @return string
- */
- public function getFullName(): string
- {
- return sprintf(
- '%s %s',
- $this->user->get(UserProfileFields::FIRST_NAME),
- $this->user->get(UserProfileFields::LAST_NAME)
- );
- }
-
- /**
- * @return bool
- */
- public function isAccessClosed(): bool
- {
- return $this->user->get(UserProfileFields::CAN_ACCESS_CLOSED);
- }
-
- /**
- * @return bool
- */
- public function isClosed(): bool
- {
- return $this->user->get(UserProfileFields::IS_CLOSED);
- }
-
- /**
- * @param string $key
- * @return mixed
- */
- public function get(string $key): mixed
- {
- return $this->user->get($key);
- }
-}
diff --git a/src/Foundation/Core/Models/Users/UserProfileFields.php b/src/Foundation/Core/Models/Users/UserProfileFields.php
index 1de503f..a711f3f 100644
--- a/src/Foundation/Core/Models/Users/UserProfileFields.php
+++ b/src/Foundation/Core/Models/Users/UserProfileFields.php
@@ -2,6 +2,19 @@
namespace Hopex\VkSdk\Foundation\Core\Models\Users;
+use Carbon\Carbon;
+use Hopex\VkSdk\Exceptions\Api\ApiException;
+use Hopex\VkSdk\Foundation\Core\Models\Users\ProfileFields\CareerField;
+use Hopex\VkSdk\Foundation\Core\Models\Users\ProfileFields\CityField;
+use Hopex\VkSdk\Foundation\Core\Models\Users\ProfileFields\CountryField;
+use Hopex\VkSdk\Foundation\Core\Models\Users\ProfileFields\EducationField;
+use Hopex\VkSdk\Foundation\Core\Models\Users\ProfileFields\LastSeenField;
+use Hopex\VkSdk\Foundation\Core\Models\Users\ProfileFields\MilitaryField;
+use Hopex\VkSdk\Foundation\Core\Models\Users\ProfileFields\RelativeField;
+use Hopex\VkSdk\Foundation\Core\Models\Users\ProfileFields\SchoolField;
+use Illuminate\Support\Collection;
+use Throwable;
+
/**
* Class UserProfileFields
* @package Hopex\VkSdk\Foundation\Core\Models\Users
@@ -14,6 +27,7 @@ class UserProfileFields
public const LAST_NAME = 'last_name';
public const CAN_ACCESS_CLOSED = 'can_access_closed';
public const IS_CLOSED = 'is_closed';
+
public const ACTIVITIES = 'activities';
public const ABOUT = 'about';
public const BLACKLISTED = 'blacklisted';
@@ -27,8 +41,6 @@ class UserProfileFields
public const CAN_SEND_FRIEND_REQUEST = 'can_send_friend_request';
public const CAN_WRITE_PRIVATE_MESSAGE = 'can_write_private_message';
public const CAREER = 'career';
- public const COMMON_COUNT = 'common_count';
- public const CONNECTIONS = 'connections';
public const CONTACTS = 'contacts';
public const CITY = 'city';
public const COUNTRY = 'country';
@@ -75,4 +87,566 @@ class UserProfileFields
public const TIMEZONE = 'timezone';
public const TV = 'tv';
public const UNIVERSITIES = 'universities';
+
+ /**
+ * @var Collection
+ */
+ public Collection $user;
+
+ /**
+ * UserFields constructor.
+ * @param Collection $user
+ */
+ public function __construct(Collection $user)
+ {
+ $this->user = $user;
+ }
+
+ /**
+ * @return Collection
+ */
+ public function getUser(): Collection
+ {
+ return $this->user;
+ }
+
+ /**
+ * @return int
+ */
+ public function getId(): int
+ {
+ return $this->user->get(UserProfileFields::ID);
+ }
+
+ /**
+ * @return string
+ */
+ public function getFirstName(): string
+ {
+ return $this->user->get(UserProfileFields::FIRST_NAME);
+ }
+
+ /**
+ * @return string
+ */
+ public function getLastName(): string
+ {
+ return $this->user->get(UserProfileFields::LAST_NAME);
+ }
+
+ /**
+ * @return string
+ */
+ public function getFullName(): string
+ {
+ return sprintf(
+ '%s %s',
+ $this->user->get(UserProfileFields::FIRST_NAME),
+ $this->user->get(UserProfileFields::LAST_NAME)
+ );
+ }
+
+ /**
+ * @return bool
+ */
+ public function isAccessClosed(): bool
+ {
+ return $this->user->get(UserProfileFields::CAN_ACCESS_CLOSED);
+ }
+
+ /**
+ * @return bool
+ */
+ public function isClosed(): bool
+ {
+ return $this->user->get(UserProfileFields::IS_CLOSED);
+ }
+
+ /**
+ * @return string
+ */
+ public function getActivities(): string
+ {
+ return $this->user->get(UserProfileFields::ACTIVITIES);
+ }
+
+ /**
+ * @return string
+ */
+ public function getAbout(): string
+ {
+ return $this->user->get(UserProfileFields::ABOUT);
+ }
+
+ /**
+ * @return bool
+ */
+ public function getBlacklisted(): bool
+ {
+ return $this->user->get(UserProfileFields::BLACKLISTED);
+ }
+
+ /**
+ * @return bool
+ */
+ public function getBlacklistedByMe(): bool
+ {
+ return $this->user->get(UserProfileFields::BLACKLISTED_BY_ME);
+ }
+
+ /**
+ * @return string
+ */
+ public function getBooks(): string
+ {
+ return $this->user->get(UserProfileFields::BOOKS);
+ }
+
+ /**
+ * @return Carbon
+ */
+ public function getBdate(): Carbon
+ {
+ $bdate = new Carbon();
+ if ($this->user->has(UserProfileFields::BDATE)) {
+ $date = explode('.', $this->user->get(UserProfileFields::BDATE));
+ $bdate->setDate($date[2] ?? 1970, $date[1], $date[0]);
+ }
+
+ return $bdate;
+ }
+
+ /**
+ * @return bool
+ */
+ public function getCanBeInvitedGroup(): bool
+ {
+ return $this->user->get(UserProfileFields::CAN_BE_INVITED_GROUP);
+ }
+
+ /**
+ * @return bool
+ */
+ public function getCanPost(): bool
+ {
+ return $this->user->get(UserProfileFields::CAN_POST);
+ }
+
+ /**
+ * @return bool
+ */
+ public function getCanSeeAllPosts(): bool
+ {
+ return $this->user->get(UserProfileFields::CAN_SEE_ALL_POSTS);
+ }
+
+ /**
+ * @return bool
+ */
+ public function getCanSeeAudio(): bool
+ {
+ return $this->user->get(UserProfileFields::CAN_SEE_AUDIO);
+ }
+
+ /**
+ * @return bool
+ */
+ public function getCanSendFriendRequest(): bool
+ {
+ return $this->user->get(UserProfileFields::CAN_SEND_FRIEND_REQUEST);
+ }
+
+ /**
+ * @return bool
+ */
+ public function getCanWritePrivateMessage(): bool
+ {
+ return $this->user->get(UserProfileFields::CAN_WRITE_PRIVATE_MESSAGE);
+ }
+
+ /**
+ * @return Collection
+ */
+ public function getCareer(): Collection
+ {
+ return collect($this->user->get(UserProfileFields::CAREER))
+ ->map(function ($item) {
+ return new CareerField($item);
+ });
+ }
+
+ /**
+ * @param string|null $token
+ * @return CityField
+ * @throws ApiException
+ * @throws Throwable
+ */
+ public function getCity(string $token = null): CityField
+ {
+ return new CityField($this->user->get(UserProfileFields::CITY), $token);
+ }
+
+ /**
+ * @param string|null $token
+ * @return CountryField
+ * @throws ApiException
+ * @throws Throwable
+ */
+ public function getCountry(string $token = null): CountryField
+ {
+ return new CountryField($this->user->get(UserProfileFields::COUNTRY), $token);
+ }
+
+ /**
+ * @return Collection
+ */
+ public function getCropPhoto(): Collection
+ {
+ return $this->user->get(UserProfileFields::CROP_PHOTO);
+ }
+
+ /**
+ * @return string
+ */
+ public function getDomain(): string
+ {
+ return $this->user->get(UserProfileFields::DOMAIN);
+ }
+
+ /**
+ * @return EducationField
+ */
+ public function getEducation(): EducationField
+ {
+ return new EducationField($this->user);
+ }
+
+ /**
+ * @return mixed
+ */
+ public function getExports(): mixed
+ {
+ return $this->user->get(UserProfileFields::EXPORTS);
+ }
+
+ /**
+ * @return int
+ */
+ public function getFollowersCount(): int
+ {
+ return $this->user->get(UserProfileFields::FOLLOWERS_COUNT);
+ }
+
+ /**
+ * @return bool
+ */
+ public function getFriendStatus(): bool
+ {
+ return $this->user->get(UserProfileFields::FRIEND_STATUS);
+ }
+
+ /**
+ * @return bool
+ */
+ public function getHasPhoto(): bool
+ {
+ return $this->user->get(UserProfileFields::HAS_PHOTO);
+ }
+
+ /**
+ * @return bool
+ */
+ public function getHasMobile(): bool
+ {
+ return $this->user->get(UserProfileFields::HAS_MOBILE);
+ }
+
+ /**
+ * @return string
+ */
+ public function getHomeTown(): string
+ {
+ return $this->user->get(UserProfileFields::HOME_TOWN);
+ }
+
+ /**
+ * @return string
+ */
+ public function getPhoto100(): string
+ {
+ return $this->user->get(UserProfileFields::PHOTO_100);
+ }
+
+ /**
+ * @return string
+ */
+ public function getPhoto200(): string
+ {
+ return $this->user->get(UserProfileFields::PHOTO_200);
+ }
+
+ /**
+ * @return string
+ */
+ public function getPhoto200Orig(): string
+ {
+ return $this->user->get(UserProfileFields::PHOTO_200_ORIG);
+ }
+
+ /**
+ * @return string
+ */
+ public function getPhoto400Orig(): string
+ {
+ return $this->user->get(UserProfileFields::PHOTO_400_ORIG);
+ }
+
+ /**
+ * @return string
+ */
+ public function getPhoto50(): string
+ {
+ return $this->user->get(UserProfileFields::PHOTO_50);
+ }
+
+ /**
+ * @return int
+ */
+ public function getSex(): int
+ {
+ return $this->user->get(UserProfileFields::SEX);
+ }
+
+ /**
+ * @return string
+ */
+ public function getSite(): string
+ {
+ return $this->user->get(UserProfileFields::SITE);
+ }
+
+ /**
+ * @return Collection
+ */
+ public function getSchools(): Collection
+ {
+ return collect($this->user->get(UserProfileFields::SCHOOLS))
+ ->map(function ($item) {
+ return new SchoolField($item);
+ });
+ }
+
+ /**
+ * @return string
+ */
+ public function getScreenName(): string
+ {
+ return $this->user->get(UserProfileFields::SCREEN_NAME);
+ }
+
+ /**
+ * @return string
+ */
+ public function getStatus(): string
+ {
+ return $this->user->get(UserProfileFields::STATUS);
+ }
+
+ /**
+ * @return bool
+ */
+ public function getVerified(): bool
+ {
+ return $this->user->get(UserProfileFields::VERIFIED);
+ }
+
+ /**
+ * @return string
+ */
+ public function getGames(): string
+ {
+ return $this->user->get(UserProfileFields::GAMES);
+ }
+
+ /**
+ * @return string
+ */
+ public function getInterests(): string
+ {
+ return $this->user->get(UserProfileFields::INTERESTS);
+ }
+
+ /**
+ * @return bool
+ */
+ public function getIsFavorite(): bool
+ {
+ return $this->user->get(UserProfileFields::IS_FAVORITE);
+ }
+
+ /**
+ * @return bool
+ */
+ public function getIsFriend(): bool
+ {
+ return $this->user->get(UserProfileFields::IS_FRIEND);
+ }
+
+ /**
+ * @return bool
+ */
+ public function getIsHiddenFromFeed(): bool
+ {
+ return $this->user->get(UserProfileFields::IS_HIDDEN_FROM_FEED);
+ }
+
+ /**
+ * @return LastSeenField
+ */
+ public function getLastSeen(): LastSeenField
+ {
+ return new LastSeenField($this->user->get(UserProfileFields::LAST_SEEN));
+ }
+
+ /**
+ * @return string
+ */
+ public function getMaidenName(): string
+ {
+ return $this->user->get(UserProfileFields::MAIDEN_NAME);
+ }
+
+ /**
+ * @return Collection
+ */
+ public function getMilitary(): Collection
+ {
+ return collect($this->user->get(UserProfileFields::MILITARY))
+ ->map(function ($item) {
+ return new MilitaryField($item);
+ });
+ }
+
+ /**
+ * @return string
+ */
+ public function getMovies(): string
+ {
+ return $this->user->get(UserProfileFields::MOVIES);
+ }
+
+ /**
+ * @return string
+ */
+ public function getMusic(): string
+ {
+ return $this->user->get(UserProfileFields::MUSIC);
+ }
+
+ /**
+ * @return string
+ */
+ public function getNickname(): string
+ {
+ return $this->user->get(UserProfileFields::NICKNAME);
+ }
+
+ /**
+ * @return Collection
+ */
+ public function getOccupation(): Collection
+ {
+ return $this->user->get(UserProfileFields::OCCUPATION);
+ }
+
+ /**
+ * @return bool
+ */
+ public function getOnline(): bool
+ {
+ return $this->user->get(UserProfileFields::ONLINE);
+ }
+
+ /**
+ * @return Collection
+ */
+ public function getPersonal(): Collection
+ {
+ return $this->user->get(UserProfileFields::PERSONAL);
+ }
+
+ /**
+ * @return string
+ */
+ public function getPhotoId(): string
+ {
+ return $this->user->get(UserProfileFields::PHOTO_ID);
+ }
+
+ /**
+ * @return string
+ */
+ public function getPhotoMax(): string
+ {
+ return $this->user->get(UserProfileFields::PHOTO_MAX);
+ }
+
+ /**
+ * @return string
+ */
+ public function getPhotoMaxOrig(): string
+ {
+ return $this->user->get(UserProfileFields::PHOTO_MAX_ORIG);
+ }
+
+ /**
+ * @return string
+ */
+ public function getQuotes(): string
+ {
+ return $this->user->get(UserProfileFields::QUOTES);
+ }
+
+ /**
+ * @return int
+ */
+ public function getRelation(): int
+ {
+ return $this->user->get(UserProfileFields::RELATION);
+ }
+
+ /**
+ * @return Collection
+ */
+ public function getRelatives(): Collection
+ {
+ return collect($this->user->get(UserProfileFields::RELATIVES))
+ ->map(function ($item) {
+ return new RelativeField($item);
+ });
+ }
+
+ /**
+ * @return mixed
+ */
+ public function getTimezone(): mixed
+ {
+ return $this->user->get(UserProfileFields::TIMEZONE);
+ }
+
+ /**
+ * @return string
+ */
+ public function getTv(): string
+ {
+ return $this->user->get(UserProfileFields::TV);
+ }
+
+ /**
+ * @return Collection
+ */
+ public function getUniversities(): Collection
+ {
+ return $this->user->get(UserProfileFields::UNIVERSITIES);
+ }
}
diff --git a/src/Foundation/Core/Models/Users/UserRequestFields.php b/src/Foundation/Core/Models/Users/UserRequestFields.php
index 3fd2394..74088c0 100644
--- a/src/Foundation/Core/Models/Users/UserRequestFields.php
+++ b/src/Foundation/Core/Models/Users/UserRequestFields.php
@@ -37,7 +37,7 @@ public function setUserIds(array $user_ids): UserRequestFields
* @param array $fields
* @return UserRequestFields
*/
- public function setFields(array $fields): UserRequestFields
+ public function setProfileFields(array $fields): UserRequestFields
{
$this->fields = $fields;
return $this;
From 8c15f21e058876658944b5e43d9e275880e41b0b Mon Sep 17 00:00:00 2001
From: Schizo
Date: Mon, 24 Oct 2022 14:28:17 +0300
Subject: [PATCH 03/24] =?UTF-8?q?=D0=9E=D0=BF=D1=82=D0=B8=D0=BC=D0=B8?=
=?UTF-8?q?=D0=B7=D0=B8=D1=80=D0=BE=D0=B2=D0=B0=D0=BD=D1=8B=20=D0=BF=D0=BE?=
=?UTF-8?q?=D0=BB=D1=8F=20=D0=BF=D0=BE=D0=BB=D1=8C=D0=B7=D0=BE=D0=B2=D0=B0?=
=?UTF-8?q?=D1=82=D0=B5=D0=BB=D1=8F,=20=D0=B4=D0=BE=D0=B1=D0=B0=D0=B2?=
=?UTF-8?q?=D0=BB=D0=B5=D0=BD=D1=8B=203=20=D0=BC=D0=B5=D1=82=D0=BE=D0=B4?=
=?UTF-8?q?=D0=B0=20API?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
src/Foundation/Core/Api/Client.php | 18 +--
.../Core/Models/Messages/MessageFields.php | 16 +--
.../Users/ProfileFields/CareerField.php | 68 +++++-----
.../Models/Users/ProfileFields/CityField.php | 7 +-
.../Users/ProfileFields/CountryField.php | 7 +-
.../Users/ProfileFields/EducationField.php | 70 ++--------
.../Users/ProfileFields/MilitaryField.php | 10 +-
.../Users/ProfileFields/RelativeField.php | 20 ++-
.../Users/ProfileFields/SchoolField.php | 124 ++++++------------
src/Foundation/Core/Models/Users/User.php | 35 ++++-
.../Core/Models/Users/UserReportTypes.php | 16 +++
.../Core/Models/Users/UserRequestFields.php | 90 +++++++++++++
12 files changed, 276 insertions(+), 205 deletions(-)
create mode 100644 src/Foundation/Core/Models/Users/UserReportTypes.php
diff --git a/src/Foundation/Core/Api/Client.php b/src/Foundation/Core/Api/Client.php
index 4012f2f..eb18ea5 100644
--- a/src/Foundation/Core/Api/Client.php
+++ b/src/Foundation/Core/Api/Client.php
@@ -14,12 +14,12 @@
class Client
{
/**
- * @param string $token
+ * @param string $userOrGroupToken
* @return Group
*/
- public function group(string $token): Group
+ public function group(string $userOrGroupToken): Group
{
- return new Group($token);
+ return new Group($userOrGroupToken);
}
/**
@@ -32,20 +32,20 @@ public function message(string $token): Message
}
/**
- * @param string $token
+ * @param string $userOrServiceToken
* @return User
*/
- public function user(string $token): User
+ public function user(string $userOrServiceToken): User
{
- return new User($token);
+ return new User($userOrServiceToken);
}
/**
- * @param string $token
+ * @param string $userOrServiceToken
* @return Database
*/
- public function database(string $token): Database
+ public function database(string $userOrServiceToken): Database
{
- return new Database($token);
+ return new Database($userOrServiceToken);
}
}
diff --git a/src/Foundation/Core/Models/Messages/MessageFields.php b/src/Foundation/Core/Models/Messages/MessageFields.php
index 740cf35..6eafe58 100644
--- a/src/Foundation/Core/Models/Messages/MessageFields.php
+++ b/src/Foundation/Core/Models/Messages/MessageFields.php
@@ -43,14 +43,6 @@ public function __construct(Collection $message)
$this->message = $message;
}
- /**
- * @return Collection
- */
- public function getMessage(): Collection
- {
- return $this->message;
- }
-
/**
* @return Carbon
*/
@@ -77,6 +69,14 @@ public function getSender(string $token, array $userProfileFields = []): UserPro
)->first()));
}
+ /**
+ * @return int
+ */
+ public function getSenderId(): int
+ {
+ return $this->message->get(self::FROM_ID);
+ }
+
/**
* @return int
*/
diff --git a/src/Foundation/Core/Models/Users/ProfileFields/CareerField.php b/src/Foundation/Core/Models/Users/ProfileFields/CareerField.php
index aade987..d33588e 100644
--- a/src/Foundation/Core/Models/Users/ProfileFields/CareerField.php
+++ b/src/Foundation/Core/Models/Users/ProfileFields/CareerField.php
@@ -2,7 +2,9 @@
namespace Hopex\VkSdk\Foundation\Core\Models\Users\ProfileFields;
+use Hopex\VkSdk\Exceptions\Api\ApiException;
use Illuminate\Support\Collection;
+use Throwable;
/**
* Class CareerField
@@ -17,29 +19,9 @@ class CareerField
private const POSITION = 'position';
/**
- * @var int|null
+ * @var Collection
*/
- public ?int $cityId;
-
- /**
- * @var int|null
- */
- public ?int $countryId;
-
- /**
- * @var int|null
- */
- public ?int $from;
-
- /**
- * @var int|null
- */
- public ?int $groupId;
-
- /**
- * @var string|null
- */
- public ?string $position;
+ private Collection $career;
/**
* CareerField constructor.
@@ -48,26 +30,38 @@ class CareerField
public function __construct(array|Collection $career)
{
if ($career instanceof Collection) {
- $this->cityId = $career->has(self::CITY_ID) ? $career->get(self::CITY_ID) : null;
- $this->countryId = $career->has(self::COUNTRY_ID) ? $career->get(self::COUNTRY_ID) : null;
- $this->from = $career->has(self::FROM) ? $career->get(self::FROM) : null;
- $this->groupId = $career->has(self::GROUP_ID) ? $career->get(self::GROUP_ID) : null;
- $this->position = $career->has(self::POSITION) ? $career->get(self::POSITION) : null;
+ $this->career = $career;
} else {
- $this->cityId = $career[self::CITY_ID] ?? null;
- $this->countryId = $career[self::COUNTRY_ID] ?? null;
- $this->from = $career[self::FROM] ?? null;
- $this->groupId = $career[self::GROUP_ID] ?? null;
- $this->position = $career[self::POSITION] ?? null;
+ $this->career = collect($career);
}
}
+ /**
+ * @return CityField
+ * @throws ApiException
+ * @throws Throwable
+ */
+ public function getCity(): CityField
+ {
+ return new CityField($this->getCityId());
+ }
+
/**
* @return int|null
*/
public function getCityId(): ?int
{
- return $this->cityId;
+ return $this->career->get(self::CITY_ID);
+ }
+
+ /**
+ * @return CountryField
+ * @throws ApiException
+ * @throws Throwable
+ */
+ public function getCountry(): CountryField
+ {
+ return new CountryField($this->getCountryId());
}
/**
@@ -75,7 +69,7 @@ public function getCityId(): ?int
*/
public function getCountryId(): ?int
{
- return $this->countryId;
+ return $this->career->get(self::COUNTRY_ID);
}
/**
@@ -83,7 +77,7 @@ public function getCountryId(): ?int
*/
public function getFrom(): ?int
{
- return $this->from;
+ return $this->career->get(self::FROM);
}
/**
@@ -92,7 +86,7 @@ public function getFrom(): ?int
public function getGroupId(): ?int
{
// TODO: добавить сущность
- return $this->groupId;
+ return $this->career->get(self::GROUP_ID);
}
/**
@@ -100,6 +94,6 @@ public function getGroupId(): ?int
*/
public function getPosition(): ?string
{
- return $this->position;
+ return $this->career->get(self::POSITION);
}
}
diff --git a/src/Foundation/Core/Models/Users/ProfileFields/CityField.php b/src/Foundation/Core/Models/Users/ProfileFields/CityField.php
index a046b61..20da003 100644
--- a/src/Foundation/Core/Models/Users/ProfileFields/CityField.php
+++ b/src/Foundation/Core/Models/Users/ProfileFields/CityField.php
@@ -39,7 +39,12 @@ public function __construct(int|array|Collection $city, string $token = null)
} elseif (is_a($city, 'array')) {
$this->city = collect($city);
} else {
- $this->city = collect(VkApi::database($token)->getCitiesById([self::CITY_IDS => $city])->first());
+ $this->city = collect(VkApi::database($token)
+ ->getCitiesById([
+ self::CITY_IDS => $city
+ ])
+ ->first()
+ );
}
}
diff --git a/src/Foundation/Core/Models/Users/ProfileFields/CountryField.php b/src/Foundation/Core/Models/Users/ProfileFields/CountryField.php
index 1ac2752..4d2ff82 100644
--- a/src/Foundation/Core/Models/Users/ProfileFields/CountryField.php
+++ b/src/Foundation/Core/Models/Users/ProfileFields/CountryField.php
@@ -39,7 +39,12 @@ public function __construct(int|array|Collection $country, string $token = null)
} elseif (is_a($country, 'array')) {
$this->country = collect($country);
} else {
- $this->country = collect(VkApi::database($token)->getCountriesById([self::COUNTRY_IDS => $country])->first());
+ $this->country = collect(VkApi::database($token)
+ ->getCountriesById([
+ self::COUNTRY_IDS => $country
+ ])
+ ->first()
+ );
}
}
diff --git a/src/Foundation/Core/Models/Users/ProfileFields/EducationField.php b/src/Foundation/Core/Models/Users/ProfileFields/EducationField.php
index 17893ef..96b5234 100644
--- a/src/Foundation/Core/Models/Users/ProfileFields/EducationField.php
+++ b/src/Foundation/Core/Models/Users/ProfileFields/EducationField.php
@@ -19,62 +19,20 @@ class EducationField
private const EDUCATION_STATUS = 'education_status';
/**
- * @var int|null
+ * @var Collection
*/
- public ?int $university;
-
- /**
- * @var string|null
- */
- public ?string $universityName;
-
- /**
- * @var int|null
- */
- public ?int $faculty;
-
- /**
- * @var string|null
- */
- public ?string $facultyName;
-
- /**
- * @var int|null
- */
- public ?int $graduation;
-
- /**
- * @var string|null
- */
- public ?string $educationForm;
-
- /**
- * @var string|null
- */
- public ?string $educationStatus;
+ private Collection $education;
/**
* EducationField constructor.
- * @param array|Collection $city
+ * @param array|Collection $education
*/
- public function __construct(array|Collection $city)
+ public function __construct(array|Collection $education)
{
- if ($city instanceof Collection) {
- $this->university = $city->has(self::UNIVERSITY) ? $city->get(self::UNIVERSITY) : null;
- $this->universityName = $city->has(self::UNIVERSITY_NAME) ? $city->get(self::UNIVERSITY_NAME) : null;
- $this->faculty = $city->has(self::FACULTY) ? $city->get(self::FACULTY) : null;
- $this->facultyName = $city->has(self::FACULTY_NAME) ? $city->get(self::FACULTY_NAME) : null;
- $this->graduation = $city->has(self::GRADUATION) ? $city->get(self::GRADUATION) : null;
- $this->educationForm = $city->has(self::EDUCATION_FORM) ? $city->get(self::EDUCATION_FORM) : null;
- $this->educationStatus = $city->has(self::EDUCATION_STATUS) ? $city->get(self::EDUCATION_STATUS) : null;
+ if ($education instanceof Collection) {
+ $this->education = $education;
} else {
- $this->university = $city[self::UNIVERSITY] ?? null;
- $this->universityName = $city[self::UNIVERSITY_NAME] ?? null;
- $this->faculty = $city[self::FACULTY] ?? null;
- $this->facultyName = $city[self::FACULTY_NAME] ?? null;
- $this->graduation = $city[self::GRADUATION] ?? null;
- $this->educationForm = $city[self::EDUCATION_FORM] ?? null;
- $this->educationStatus = $city[self::EDUCATION_STATUS] ?? null;
+ $this->education = collect($education);
}
}
@@ -83,7 +41,7 @@ public function __construct(array|Collection $city)
*/
public function getUniversity(): int
{
- return $this->university;
+ return $this->education->get(self::UNIVERSITY);
}
/**
@@ -91,7 +49,7 @@ public function getUniversity(): int
*/
public function getUniversityName(): string
{
- return $this->universityName;
+ return $this->education->get(self::UNIVERSITY_NAME);
}
/**
@@ -99,7 +57,7 @@ public function getUniversityName(): string
*/
public function getFaculty(): int
{
- return $this->faculty;
+ return $this->education->get(self::FACULTY);
}
/**
@@ -107,7 +65,7 @@ public function getFaculty(): int
*/
public function getFacultyName(): string
{
- return $this->facultyName;
+ return $this->education->get(self::FACULTY_NAME);
}
/**
@@ -115,7 +73,7 @@ public function getFacultyName(): string
*/
public function getGraduation(): int
{
- return $this->graduation;
+ return $this->education->get(self::GRADUATION);
}
/**
@@ -123,7 +81,7 @@ public function getGraduation(): int
*/
public function getEducationForm(): string
{
- return $this->educationForm;
+ return $this->education->get(self::EDUCATION_FORM);
}
/**
@@ -131,6 +89,6 @@ public function getEducationForm(): string
*/
public function getEducationStatus(): string
{
- return $this->educationStatus;
+ return $this->education->get(self::EDUCATION_STATUS);
}
}
diff --git a/src/Foundation/Core/Models/Users/ProfileFields/MilitaryField.php b/src/Foundation/Core/Models/Users/ProfileFields/MilitaryField.php
index a583694..7aa3b59 100644
--- a/src/Foundation/Core/Models/Users/ProfileFields/MilitaryField.php
+++ b/src/Foundation/Core/Models/Users/ProfileFields/MilitaryField.php
@@ -36,6 +36,14 @@ public function __construct(array|Collection $military)
}
}
+ /**
+ * @return int
+ */
+ public function getCountryId(): int
+ {
+ return $this->military->get(self::COUNTRY_ID);
+ }
+
/**
* @param string $token
* @return CountryField
@@ -44,7 +52,7 @@ public function __construct(array|Collection $military)
*/
public function getCountry(string $token): CountryField
{
- return new CountryField($this->military->get(self::COUNTRY_ID), $token);
+ return new CountryField($this->getCountryId(), $token);
}
/**
diff --git a/src/Foundation/Core/Models/Users/ProfileFields/RelativeField.php b/src/Foundation/Core/Models/Users/ProfileFields/RelativeField.php
index 287b4f2..1779a7e 100644
--- a/src/Foundation/Core/Models/Users/ProfileFields/RelativeField.php
+++ b/src/Foundation/Core/Models/Users/ProfileFields/RelativeField.php
@@ -36,6 +36,14 @@ public function __construct(array|Collection $relative)
}
}
+ /**
+ * @return int
+ */
+ public function getRelativeId(): int
+ {
+ return $this->relative->get(self::ID);
+ }
+
/**
* @param string $token
* @param array $userProfileFields
@@ -48,7 +56,7 @@ public function getRelative(string $token, array $userProfileFields = []): UserP
return new UserProfileFields(collect(VkApi::user($token)
->get((new UserRequestFields())
->setUserIds([
- $this->relative->get(self::ID)
+ $this->getRelativeId()
])
->setProfileFields($userProfileFields)
)->first()));
@@ -59,6 +67,14 @@ public function getRelative(string $token, array $userProfileFields = []): UserP
*/
public function getType(): string
{
- return preg_replace('~vk-sdk\.~', '', __('vk-sdk.' . $this->relative->get(self::TYPE)));
+ return $this->relative->get(self::TYPE);
+ }
+
+ /**
+ * @return string
+ */
+ public function getTranslationType(): string
+ {
+ return preg_replace('~vk-sdk\.~', '', __('vk-sdk.' . $this->getType()));
}
}
diff --git a/src/Foundation/Core/Models/Users/ProfileFields/SchoolField.php b/src/Foundation/Core/Models/Users/ProfileFields/SchoolField.php
index 1df7085..9b29238 100644
--- a/src/Foundation/Core/Models/Users/ProfileFields/SchoolField.php
+++ b/src/Foundation/Core/Models/Users/ProfileFields/SchoolField.php
@@ -2,8 +2,9 @@
namespace Hopex\VkSdk\Foundation\Core\Models\Users\ProfileFields;
-use Carbon\Carbon;
+use Hopex\VkSdk\Exceptions\Api\ApiException;
use Illuminate\Support\Collection;
+use Throwable;
/**
* Class SchoolField
@@ -11,8 +12,8 @@
*/
class SchoolField
{
- private const CITY = 'city';
- private const COUNTRY = 'country';
+ private const CITY_ID = 'city';
+ private const COUNTRY_ID = 'country';
private const ID = 'id';
private const NAME = 'name';
private const TYPE = 'type';
@@ -23,55 +24,9 @@ class SchoolField
private const SPECIALITY = 'speciality';
/**
- * @var int|null
+ * @var Collection
*/
- public ?int $city;
-
- /**
- * @var int|null
- */
- public ?int $country;
-
- /**
- * @var int|null
- */
- public ?int $id;
-
- /**
- * @var string|null
- */
- public ?string $name;
-
- /**
- * @var int|null
- */
- public ?int $type;
-
- /**
- * @var string|null
- */
- public ?string $typeStr;
-
- /**
- * @var int|null
- */
- public ?int $yearFrom;
-
- /**
- * @var int|null
- */
- public ?int $yearGraduated;
-
- /**
- * @var int|null
- */
- public ?int $yearTo;
-
- /**
- * @var string|null
- */
- public ?string $speciality;
-
+ private Collection $school;
/**
* SchoolField constructor.
@@ -80,44 +35,47 @@ class SchoolField
public function __construct(array|Collection $school)
{
if ($school instanceof Collection) {
- $this->city = $school->has(self::CITY) ? $school->get(self::CITY) : null;
- $this->country = $school->has(self::COUNTRY) ? $school->get(self::COUNTRY) : null;
- $this->id = $school->has(self::ID) ? $school->get(self::ID) : null;
- $this->name = $school->has(self::NAME) ? $school->get(self::NAME) : null;
- $this->type = $school->has(self::TYPE) ? $school->get(self::TYPE) : null;
- $this->typeStr = $school->has(self::TYPE_STR) ? $school->get(self::TYPE_STR) : null;
- $this->yearFrom = $school->has(self::YEAR_FROM) ? $school->get(self::YEAR_FROM) : null;
- $this->yearGraduated = $school->has(self::YEAR_GRADUATED) ? $school->get(self::YEAR_GRADUATED) : null;
- $this->yearTo = $school->has(self::YEAR_TO) ? $school->get(self::YEAR_TO) : null;
- $this->speciality = $school->has(self::SPECIALITY) ? $school->get(self::SPECIALITY) : null;
+ $this->school = $school;
} else {
- $this->city = $school[self::CITY] ?? null;
- $this->country = $school[self::COUNTRY] ?? null;
- $this->id = $school[self::ID] ?? null;
- $this->name = $school[self::NAME] ?? null;
- $this->type = $school[self::TYPE] ?? null;
- $this->typeStr = $school[self::TYPE_STR] ?? null;
- $this->yearFrom = $school[self::YEAR_FROM] ?? null;
- $this->yearGraduated = $school[self::YEAR_GRADUATED] ?? null;
- $this->yearTo = $school[self::YEAR_TO] ?? null;
- $this->speciality = $school[self::SPECIALITY] ?? null;
+ $this->school = collect($school);
}
}
/**
* @return int|null
*/
- public function getCity(): ?int
+ public function getCityId(): ?int
{
- return $this->city;
+ return $this->school->get(self::CITY_ID);
}
+ /**
+ * @return CityField
+ * @throws ApiException
+ * @throws Throwable
+ */
+ public function getCity(): CityField
+ {
+ return new CityField($this->getCityId());
+ }
+
+
/**
* @return int|null
*/
- public function getCountry(): ?int
+ public function getCountryId(): ?int
+ {
+ return $this->school->get(self::COUNTRY_ID);
+ }
+
+ /**
+ * @return CountryField
+ * @throws ApiException
+ * @throws Throwable
+ */
+ public function getCountry(): CountryField
{
- return $this->country;
+ return new CountryField($this->getCountryId());
}
/**
@@ -125,7 +83,7 @@ public function getCountry(): ?int
*/
public function getId(): ?int
{
- return $this->id;
+ return $this->school->get(self::ID);
}
/**
@@ -133,7 +91,7 @@ public function getId(): ?int
*/
public function getName(): ?string
{
- return $this->name;
+ return $this->school->get(self::NAME);
}
/**
@@ -141,7 +99,7 @@ public function getName(): ?string
*/
public function getType(): ?int
{
- return $this->type;
+ return $this->school->get(self::TYPE);
}
/**
@@ -149,7 +107,7 @@ public function getType(): ?int
*/
public function getTypeStr(): ?string
{
- return $this->typeStr;
+ return $this->school->get(self::TYPE_STR);
}
/**
@@ -157,7 +115,7 @@ public function getTypeStr(): ?string
*/
public function getYearFrom(): ?int
{
- return $this->yearFrom;
+ return $this->school->get(self::YEAR_FROM);
}
/**
@@ -165,7 +123,7 @@ public function getYearFrom(): ?int
*/
public function getYearGraduated(): ?int
{
- return $this->yearGraduated;
+ return $this->school->get(self::YEAR_GRADUATED);
}
/**
@@ -173,7 +131,7 @@ public function getYearGraduated(): ?int
*/
public function getYearTo(): ?int
{
- return $this->yearTo;
+ return $this->school->get(self::YEAR_TO);
}
/**
@@ -181,6 +139,6 @@ public function getYearTo(): ?int
*/
public function getSpeciality(): ?string
{
- return $this->speciality;
+ return $this->school->get(self::SPECIALITY);
}
}
diff --git a/src/Foundation/Core/Models/Users/User.php b/src/Foundation/Core/Models/Users/User.php
index b998437..2143096 100644
--- a/src/Foundation/Core/Models/Users/User.php
+++ b/src/Foundation/Core/Models/Users/User.php
@@ -22,29 +22,50 @@ class User extends Request
* @return Collection
* @throws ApiException
* @throws Throwable
+ * @see https://dev.vk.com/method/users.get
*/
public function get(UserRequestFields $requestFields): Collection
{
return $this->call(self::SCOPE . 'get', get_object_vars($requestFields));
}
- public function getFollowers()
+ /**
+ * @param UserRequestFields $requestFields
+ * @return Collection
+ * @throws ApiException
+ * @throws Throwable
+ * @see https://dev.vk.com/method/users.getFollowers
+ */
+ public function getFollowers(UserRequestFields $requestFields): Collection
{
-
+ return $this->call(self::SCOPE . 'getFollowers', get_object_vars($requestFields));
}
- public function getSubscriptions()
+ /**
+ * @param UserRequestFields $requestFields
+ * @return Collection
+ * @throws ApiException
+ * @throws Throwable
+ * @see https://dev.vk.com/method/users.getSubscriptions
+ */
+ public function getSubscriptions(UserRequestFields $requestFields): Collection
{
-
+ return $this->call(self::SCOPE . 'getSubscriptions', get_object_vars($requestFields));
}
- public function report()
+ /**
+ * @param UserRequestFields $requestFields
+ * @return Collection
+ * @throws ApiException
+ * @throws Throwable
+ */
+ public function report(UserRequestFields $requestFields): Collection
{
-
+ return $this->call(self::SCOPE . 'report', get_object_vars($requestFields));
}
public function search()
{
-
+ // TODO: добавить реализацию
}
}
diff --git a/src/Foundation/Core/Models/Users/UserReportTypes.php b/src/Foundation/Core/Models/Users/UserReportTypes.php
new file mode 100644
index 0000000..c3585fc
--- /dev/null
+++ b/src/Foundation/Core/Models/Users/UserReportTypes.php
@@ -0,0 +1,16 @@
+user_id = $user_id;
+ return $this;
+ }
+
+ /**
+ * @param bool $extended
+ * @return UserRequestFields
+ */
+ public function setExtended(bool $extended): UserRequestFields
+ {
+ $this->extended = $extended;
+ return $this;
+ }
+
+ /**
+ * @param string|null $type
+ * @return UserRequestFields
+ */
+ public function setReportType(?string $type): UserRequestFields
+ {
+ $this->type = $type;
+ return $this;
+ }
+
+ /**
+ * @param string|null $comment
+ * @return UserRequestFields
+ */
+ public function setComment(?string $comment): UserRequestFields
+ {
+ $this->comment = $comment;
+ return $this;
+ }
+
+ /**
+ * @param int|null $offset
+ * @return UserRequestFields
+ */
+ public function setOffset(?int $offset): UserRequestFields
+ {
+ $this->offset = $offset;
+ return $this;
+ }
+
+ /**
+ * @param int|null $count
+ * @return UserRequestFields
+ */
+ public function setCount(?int $count): UserRequestFields
+ {
+ $this->count = $count;
+ return $this;
+ }
+
/**
* @param array $fields
* @return UserRequestFields
From 7e63bd7ed344ab0ba16374f243c9c8cd98094d96 Mon Sep 17 00:00:00 2001
From: Schizo
Date: Mon, 24 Oct 2022 14:32:31 +0300
Subject: [PATCH 04/24] =?UTF-8?q?=D0=9E=D0=BF=D1=82=D0=B8=D0=BC=D0=B8?=
=?UTF-8?q?=D0=B7=D0=B8=D1=80=D0=BE=D0=B2=D0=B0=D0=BD=D1=8B=20=D0=B8=D0=BC?=
=?UTF-8?q?=D0=BF=D0=BE=D1=80=D1=82=D1=8B?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
src/Exceptions/Api/ApiExceptionMapper.php | 3 ---
src/Exceptions/Callback/SecretException.php | 2 --
.../Callback/UnknownEventException.php | 2 --
.../Callback/UnknownGroupIdException.php | 2 --
src/Exceptions/SdkException.php | 2 +-
...ClearEmptiesParametersRequestFormatter.php | 1 -
src/Foundation/Core/Api/OAuth.php | 1 -
src/Foundation/Core/Models/Owner/Owner.php | 19 -------------------
.../Models/Users/ProfileFields/CityField.php | 1 -
.../Users/ProfileFields/CountryField.php | 1 -
.../Core/Models/Users/UserRequestFields.php | 1 +
src/Providers/ServiceProvider.php | 2 +-
12 files changed, 3 insertions(+), 34 deletions(-)
delete mode 100644 src/Foundation/Core/Models/Owner/Owner.php
diff --git a/src/Exceptions/Api/ApiExceptionMapper.php b/src/Exceptions/Api/ApiExceptionMapper.php
index e99b475..6568d24 100644
--- a/src/Exceptions/Api/ApiExceptionMapper.php
+++ b/src/Exceptions/Api/ApiExceptionMapper.php
@@ -2,9 +2,6 @@
namespace Hopex\VkSdk\Exceptions\Api;
-use Exception;
-use Hopex\VkSdk\Facades\SdkConfig;
-
/**
* Class ApiExceptionMapper
* @package Hopex\VkSdk\Exceptions\Api
diff --git a/src/Exceptions/Callback/SecretException.php b/src/Exceptions/Callback/SecretException.php
index 1e3f58f..ba0a270 100644
--- a/src/Exceptions/Callback/SecretException.php
+++ b/src/Exceptions/Callback/SecretException.php
@@ -2,8 +2,6 @@
namespace Hopex\VkSdk\Exceptions\Callback;
-use Throwable;
-
/**
* Class SecretException
* @package Hopex\VkSdk\Exceptions\Callback
diff --git a/src/Exceptions/Callback/UnknownEventException.php b/src/Exceptions/Callback/UnknownEventException.php
index 25d80b9..acd1d7b 100644
--- a/src/Exceptions/Callback/UnknownEventException.php
+++ b/src/Exceptions/Callback/UnknownEventException.php
@@ -2,8 +2,6 @@
namespace Hopex\VkSdk\Exceptions\Callback;
-use Throwable;
-
/**
* Class UndefinedEventException
* @package Hopex\VkSdk\Exceptions\Callback
diff --git a/src/Exceptions/Callback/UnknownGroupIdException.php b/src/Exceptions/Callback/UnknownGroupIdException.php
index d49417e..e204d70 100644
--- a/src/Exceptions/Callback/UnknownGroupIdException.php
+++ b/src/Exceptions/Callback/UnknownGroupIdException.php
@@ -2,8 +2,6 @@
namespace Hopex\VkSdk\Exceptions\Callback;
-use Throwable;
-
/**
* Class UnknownGroupIdException
* @package Hopex\VkSdk\Exceptions\Callback
diff --git a/src/Exceptions/SdkException.php b/src/Exceptions/SdkException.php
index 16c375d..29682b2 100644
--- a/src/Exceptions/SdkException.php
+++ b/src/Exceptions/SdkException.php
@@ -3,8 +3,8 @@
namespace Hopex\VkSdk\Exceptions;
use Exception;
-use Hopex\VkSdk\Facades\SdkConfig;
use Hopex\VkSdk\Facades\Format;
+use Hopex\VkSdk\Facades\SdkConfig;
use Hopex\VkSdk\Formatters\JsonExceptionFormatter;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
diff --git a/src/Formatters/ClearEmptiesParametersRequestFormatter.php b/src/Formatters/ClearEmptiesParametersRequestFormatter.php
index 5068bae..c4526df 100644
--- a/src/Formatters/ClearEmptiesParametersRequestFormatter.php
+++ b/src/Formatters/ClearEmptiesParametersRequestFormatter.php
@@ -3,7 +3,6 @@
namespace Hopex\VkSdk\Formatters;
use Hopex\VkSdk\Contracts\CanFormat;
-use Hopex\VkSdk\Exceptions\SdkException;
/**
* Class ClearEmptiesParametersRequestFormatter
diff --git a/src/Foundation/Core/Api/OAuth.php b/src/Foundation/Core/Api/OAuth.php
index 4ac0b38..8bddbc2 100644
--- a/src/Foundation/Core/Api/OAuth.php
+++ b/src/Foundation/Core/Api/OAuth.php
@@ -4,7 +4,6 @@
use Hopex\VkSdk\Exceptions\SdkException;
use Hopex\VkSdk\Facades\SdkConfig;
-use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Http;
use Throwable;
diff --git a/src/Foundation/Core/Models/Owner/Owner.php b/src/Foundation/Core/Models/Owner/Owner.php
deleted file mode 100644
index dc38127..0000000
--- a/src/Foundation/Core/Models/Owner/Owner.php
+++ /dev/null
@@ -1,19 +0,0 @@
-
Date: Mon, 24 Oct 2022 16:20:55 +0300
Subject: [PATCH 05/24] =?UTF-8?q?=D0=9F=D0=BE=D0=BB=D1=8F=20=D1=81=D1=82?=
=?UTF-8?q?=D1=80=D0=B0=D0=BD=D1=8B=20=D0=B8=20=D0=B3=D0=BE=D1=80=D0=BE?=
=?UTF-8?q?=D0=B4=D0=B0=20=D0=BF=D0=B5=D1=80=D0=B5=D0=BD=D0=B5=D1=81=D0=B5?=
=?UTF-8?q?=D0=BD=D1=8B=20=D0=B8=D0=B7=20Users=20=D0=B2=20Database?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
.../Core/Models/Database/Database.php | 41 +++-
.../Fields}/CityField.php | 18 +-
.../Fields}/CountryField.php | 12 +-
.../Models/Groups/AddressWorkInfoStatus.php | 16 --
src/Foundation/Core/Models/Groups/Group.php | 1 +
.../Core/Models/Groups/GroupAccess.php | 14 --
.../Core/Models/Groups/GroupAgeLimits.php | 14 --
.../Core/Models/Groups/GroupAudio.php | 14 --
.../Core/Models/Groups/GroupDocs.php | 20 --
.../Models/Groups/GroupMarketCurrency.php | 28 ---
.../Core/Models/Groups/GroupPhotos.php | 20 --
.../Core/Models/Groups/GroupRole.php | 20 --
.../Core/Models/Groups/GroupSubject.php | 176 ------------------
.../Core/Models/Groups/GroupTopics.php | 20 --
.../Core/Models/Groups/GroupVideo.php | 20 --
.../Core/Models/Groups/GroupWall.php | 24 ---
.../Core/Models/Groups/GroupWiki.php | 20 --
.../Core/Models/Messages/Message.php | 1 +
.../Core/Models/Users/UserProfileFields.php | 4 +-
19 files changed, 51 insertions(+), 432 deletions(-)
rename src/Foundation/Core/Models/{Users/ProfileFields => Database/Fields}/CityField.php (68%)
rename src/Foundation/Core/Models/{Users/ProfileFields => Database/Fields}/CountryField.php (75%)
delete mode 100644 src/Foundation/Core/Models/Groups/AddressWorkInfoStatus.php
delete mode 100644 src/Foundation/Core/Models/Groups/GroupAccess.php
delete mode 100644 src/Foundation/Core/Models/Groups/GroupAgeLimits.php
delete mode 100644 src/Foundation/Core/Models/Groups/GroupAudio.php
delete mode 100644 src/Foundation/Core/Models/Groups/GroupDocs.php
delete mode 100644 src/Foundation/Core/Models/Groups/GroupMarketCurrency.php
delete mode 100644 src/Foundation/Core/Models/Groups/GroupPhotos.php
delete mode 100644 src/Foundation/Core/Models/Groups/GroupRole.php
delete mode 100644 src/Foundation/Core/Models/Groups/GroupSubject.php
delete mode 100644 src/Foundation/Core/Models/Groups/GroupTopics.php
delete mode 100644 src/Foundation/Core/Models/Groups/GroupVideo.php
delete mode 100644 src/Foundation/Core/Models/Groups/GroupWall.php
delete mode 100644 src/Foundation/Core/Models/Groups/GroupWiki.php
diff --git a/src/Foundation/Core/Models/Database/Database.php b/src/Foundation/Core/Models/Database/Database.php
index c1335aa..d103a14 100644
--- a/src/Foundation/Core/Models/Database/Database.php
+++ b/src/Foundation/Core/Models/Database/Database.php
@@ -4,6 +4,8 @@
use Hopex\VkSdk\Exceptions\Api\ApiException;
use Hopex\VkSdk\Foundation\Core\Api\Request;
+use Hopex\VkSdk\Foundation\Core\Models\Databse\Fields\CityField;
+use Hopex\VkSdk\Foundation\Core\Models\Users\ProfileFields\CountryField;
use Illuminate\Support\Collection;
use Throwable;
@@ -13,8 +15,9 @@
*/
class Database extends Request
{
- /** @var string */
private const SCOPE = 'database.';
+ private const CITY_IDS = 'city_ids';
+ private const COUNTRY_IDS = 'country_ids';
/**
* @param array $args
@@ -24,7 +27,23 @@ class Database extends Request
*/
public function getCitiesById(array $args = []): Collection
{
- return $this->call(self::SCOPE . 'getCitiesById', $args);
+ return collect($this->call(self::SCOPE . 'getCitiesById', $args))
+ ->map(function ($item) {
+ return new CityField($item);
+ });
+ }
+
+ /**
+ * @param int $cityId
+ * @return Collection
+ * @throws ApiException
+ * @throws Throwable
+ */
+ public function getCityById(int $cityId): Collection
+ {
+ return $this->getCitiesById([
+ self::CITY_IDS => $cityId
+ ])->first();
}
/**
@@ -35,6 +54,22 @@ public function getCitiesById(array $args = []): Collection
*/
public function getCountriesById(array $args = []): Collection
{
- return $this->call(self::SCOPE . 'getCountriesById', $args);
+ return collect($this->call(self::SCOPE . 'getCountriesById', $args))
+ ->map(function ($item) {
+ return new CountryField($item);
+ });
+ }
+
+ /**
+ * @param int $countryId
+ * @return Collection
+ * @throws ApiException
+ * @throws Throwable
+ */
+ public function getCountryById(int $countryId): Collection
+ {
+ return $this->getCountriesById([
+ self::COUNTRY_IDS => $countryId
+ ])->first();
}
}
diff --git a/src/Foundation/Core/Models/Users/ProfileFields/CityField.php b/src/Foundation/Core/Models/Database/Fields/CityField.php
similarity index 68%
rename from src/Foundation/Core/Models/Users/ProfileFields/CityField.php
rename to src/Foundation/Core/Models/Database/Fields/CityField.php
index 1688bb0..bb04752 100644
--- a/src/Foundation/Core/Models/Users/ProfileFields/CityField.php
+++ b/src/Foundation/Core/Models/Database/Fields/CityField.php
@@ -1,6 +1,6 @@
city = $city;
} elseif (is_a($city, 'array')) {
$this->city = collect($city);
} else {
- $this->city = collect(VkApi::database($token)
- ->getCitiesById([
- self::CITY_IDS => $city
- ])
- ->first()
- );
+ $this->city = VkApi::database($userOrServiceToken)->getCityById($city);
}
}
diff --git a/src/Foundation/Core/Models/Users/ProfileFields/CountryField.php b/src/Foundation/Core/Models/Database/Fields/CountryField.php
similarity index 75%
rename from src/Foundation/Core/Models/Users/ProfileFields/CountryField.php
rename to src/Foundation/Core/Models/Database/Fields/CountryField.php
index 777c974..6d2ac73 100644
--- a/src/Foundation/Core/Models/Users/ProfileFields/CountryField.php
+++ b/src/Foundation/Core/Models/Database/Fields/CountryField.php
@@ -1,6 +1,6 @@
country = collect($country);
} else {
- $this->country = collect(VkApi::database($token)
- ->getCountriesById([
- self::COUNTRY_IDS => $country
- ])
- ->first()
- );
+ $this->country = VkApi::database($token)->getCountryById($country);
}
}
diff --git a/src/Foundation/Core/Models/Groups/AddressWorkInfoStatus.php b/src/Foundation/Core/Models/Groups/AddressWorkInfoStatus.php
deleted file mode 100644
index d2c286a..0000000
--- a/src/Foundation/Core/Models/Groups/AddressWorkInfoStatus.php
+++ /dev/null
@@ -1,16 +0,0 @@
-
Date: Mon, 24 Oct 2022 16:21:48 +0300
Subject: [PATCH 06/24] =?UTF-8?q?=D0=9E=D0=BF=D1=82=D0=B8=D0=BC=D0=B8?=
=?UTF-8?q?=D0=B7=D0=B8=D1=80=D0=BE=D0=B2=D0=B0=D0=BD=20=D0=B8=D0=BC=D0=BF?=
=?UTF-8?q?=D0=BE=D1=80=D1=82?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
src/Foundation/Core/Models/Database/Database.php | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/Foundation/Core/Models/Database/Database.php b/src/Foundation/Core/Models/Database/Database.php
index d103a14..6a1b480 100644
--- a/src/Foundation/Core/Models/Database/Database.php
+++ b/src/Foundation/Core/Models/Database/Database.php
@@ -5,7 +5,7 @@
use Hopex\VkSdk\Exceptions\Api\ApiException;
use Hopex\VkSdk\Foundation\Core\Api\Request;
use Hopex\VkSdk\Foundation\Core\Models\Databse\Fields\CityField;
-use Hopex\VkSdk\Foundation\Core\Models\Users\ProfileFields\CountryField;
+use Hopex\VkSdk\Foundation\Core\Models\Databse\Fields\CountryField;
use Illuminate\Support\Collection;
use Throwable;
From 95a4a4d1761881c287d33626cea4630f76c5e268 Mon Sep 17 00:00:00 2001
From: Schizo
Date: Tue, 25 Oct 2022 15:28:16 +0300
Subject: [PATCH 07/24] =?UTF-8?q?=D0=9F=D0=BE=D0=B4=D0=B3=D0=BE=D1=82?=
=?UTF-8?q?=D0=BE=D0=B2=D0=BA=D0=B0=20=D0=BA=20ORG-3:=20External=20//=20Gr?=
=?UTF-8?q?oups?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
src/Foundation/Core/Models/Groups/Group.php | 177 --------------------
1 file changed, 177 deletions(-)
delete mode 100644 src/Foundation/Core/Models/Groups/Group.php
diff --git a/src/Foundation/Core/Models/Groups/Group.php b/src/Foundation/Core/Models/Groups/Group.php
deleted file mode 100644
index ac13460..0000000
--- a/src/Foundation/Core/Models/Groups/Group.php
+++ /dev/null
@@ -1,177 +0,0 @@
-call(self::SCOPE . 'addAddress', $args);
- }
-
- public function addCallbackServer(array $args = []) {
- return $this->call(self::SCOPE . 'addCallbackServer', $args);
- }
-
- public function addLink(array $args = []) {
- return $this->call(self::SCOPE . 'addLink', $args);
- }
-
- public function approveRequest(array $args = []) {
- return $this->call(self::SCOPE . 'approveRequest', $args);
- }
-
- public function ban(array $args = []) {
- return $this->call(self::SCOPE . 'ban', $args);
- }
-
- public function create(array $args = []) {
- return $this->call(self::SCOPE . 'create', $args);
- }
-
- public function deleteCallbackServer(array $args = []) {
- return $this->call(self::SCOPE . 'deleteCallbackServer', $args);
- }
-
- public function deleteLink(array $args = []) {
- return $this->call(self::SCOPE . 'deleteLink', $args);
- }
-
- public function disableOnline(array $args = []) {
- return $this->call(self::SCOPE . 'disableOnline', $args);
- }
- public function edit(array $args = []) {
- return $this->call(self::SCOPE . 'edit', $args);
- }
-
- public function editAddress(array $args = []) {
- return $this->call(self::SCOPE . 'editAddress', $args);
- }
-
- public function editCallbackServer(array $args = []) {
- return $this->call(self::SCOPE . 'editCallbackServer', $args);
- }
-
- public function editLink(array $args = []) {
- return $this->call(self::SCOPE . 'editLink', $args);
- }
- public function editManager(array $args = []) {
- return $this->call(self::SCOPE . 'editManager', $args);
- }
-
- public function enableOnline(array $args = []) {
- return $this->call(self::SCOPE . 'enableOnline', $args);
- }
-
-// public function get(array $args = []) {
-// return $this->call(self::SCOPE . 'get', $args);
-// }
-
- public function getAddresses(array $args = [])
- {
- return $this->call(self::SCOPE . 'getAddresses', $args);
- }
-
- public function getBanned(array $args = []) {
- return $this->call(self::SCOPE . 'getBanned', $args);
- }
-
- public function getById(array $args = []) {
- return $this->call(self::SCOPE . 'getById', $args);
- }
-
- public function getCallbackConfirmationCode(array $args = []) {
- return $this->call(self::SCOPE . 'getCallbackConfirmationCode', $args);
- }
-
- public function getCallbackServers(array $args = []) {
- return $this->call(self::SCOPE . 'getCallbackServers', $args);
- }
-
- public function getCallbackSettings(array $args = []) {
- return $this->call(self::SCOPE . 'getCallbackSettings', $args);
- }
- public function getCatalog(array $args = []) {
- return $this->call(self::SCOPE . 'getCatalog', $args);
- }
- public function getCatalogInfo(array $args = []) {
- return $this->call(self::SCOPE . 'getCatalogInfo', $args);
- }
-
- public function getInvitedUsers(array $args = []) {
- return $this->call(self::SCOPE . 'getInvitedUsers', $args);
- }
-
- public function getInvites(array $args = []) {
- return $this->call(self::SCOPE . 'getInvites', $args);
- }
-
- public function getLongPollServer(array $args = []) {
- return $this->call(self::SCOPE . 'getLongPollServer', $args);
- }
-
- public function getLongPollSettings(array $args = []) {
- return $this->call(self::SCOPE . 'getLongPollSettings', $args);
- }
- public function getMembers(array $args = []) {
- return $this->call(self::SCOPE . 'getMembers', $args);
- }
-
- public function getRequests(array $args = []) {
- return $this->call(self::SCOPE . 'getRequests', $args);
- }
-
- public function getSettings(array $args = []) {
- return $this->call(self::SCOPE . 'getSettings', $args);
- }
-
- public function getTokenPermissions($access_token) {
- return $this->call(self::SCOPE . 'getTokenPermissions');
- }
-
- public function invite(array $args = []) {
- return $this->call(self::SCOPE . 'invite', $args);
- }
-
- public function isMember(array $args = []) {
- return $this->call(self::SCOPE . 'isMember', $args);
- }
-
- public function join(array $args = []) {
- return $this->call(self::SCOPE . 'join', $args);
- }
-
- public function leave(array $args = []) {
- return $this->call(self::SCOPE . 'leave', $args);
- }
-
- public function removeUser(array $args = []) {
- return $this->call(self::SCOPE . 'removeUser', $args);
- }
-
- public function reorderLink(array $args = []) {
- return $this->call(self::SCOPE . 'reorderLink', $args);
- }
- public function search(array $args = []) {
- return $this->call(self::SCOPE . 'search', $args);
- }
- public function setCallbackSettings(array $args = []) {
- return $this->call(self::SCOPE . 'setCallbackSettings', $args);
- }
- public function setLongPollSettings(array $args = []) {
- return $this->call(self::SCOPE . 'setLongPollSettings', $args);
- }
-
- public function unban(array $args = []) {
- return $this->call(self::SCOPE . 'unban', $args);
- }
-}
From 094921fe409c4058e5302c10fa97283654058bb4 Mon Sep 17 00:00:00 2001
From: Schizo
Date: Tue, 25 Oct 2022 15:35:23 +0300
Subject: [PATCH 08/24] =?UTF-8?q?=D0=98=D0=BD=D0=B8=D1=86=D0=B8=D0=B0?=
=?UTF-8?q?=D0=BB=D0=B8=D0=B7=D0=B0=D1=86=D0=B8=D1=8F=20ORG-3:=20External?=
=?UTF-8?q?=20//=20Groups?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
src/Foundation/Core/Models/Groups/Group.php | 176 +++++++++++++++
.../Core/Models/Groups/GroupFields.php | 170 ++++++++++++++
.../Core/Models/Groups/GroupRequestFields.php | 213 ++++++++++++++++++
3 files changed, 559 insertions(+)
create mode 100644 src/Foundation/Core/Models/Groups/Group.php
create mode 100644 src/Foundation/Core/Models/Groups/GroupFields.php
create mode 100644 src/Foundation/Core/Models/Groups/GroupRequestFields.php
diff --git a/src/Foundation/Core/Models/Groups/Group.php b/src/Foundation/Core/Models/Groups/Group.php
new file mode 100644
index 0000000..cebf6ca
--- /dev/null
+++ b/src/Foundation/Core/Models/Groups/Group.php
@@ -0,0 +1,176 @@
+call(self::SCOPE . 'addAddress', $args);
+ }
+
+ public function addCallbackServer(array $args = []) {
+ return $this->call(self::SCOPE . 'addCallbackServer', $args);
+ }
+
+ public function addLink(array $args = []) {
+ return $this->call(self::SCOPE . 'addLink', $args);
+ }
+
+ public function approveRequest(array $args = []) {
+ return $this->call(self::SCOPE . 'approveRequest', $args);
+ }
+
+ public function ban(array $args = []) {
+ return $this->call(self::SCOPE . 'ban', $args);
+ }
+
+ public function create(array $args = []) {
+ return $this->call(self::SCOPE . 'create', $args);
+ }
+
+ public function deleteCallbackServer(array $args = []) {
+ return $this->call(self::SCOPE . 'deleteCallbackServer', $args);
+ }
+
+ public function deleteLink(array $args = []) {
+ return $this->call(self::SCOPE . 'deleteLink', $args);
+ }
+
+ public function disableOnline(array $args = []) {
+ return $this->call(self::SCOPE . 'disableOnline', $args);
+ }
+ public function edit(array $args = []) {
+ return $this->call(self::SCOPE . 'edit', $args);
+ }
+
+ public function editAddress(array $args = []) {
+ return $this->call(self::SCOPE . 'editAddress', $args);
+ }
+
+ public function editCallbackServer(array $args = []) {
+ return $this->call(self::SCOPE . 'editCallbackServer', $args);
+ }
+
+ public function editLink(array $args = []) {
+ return $this->call(self::SCOPE . 'editLink', $args);
+ }
+ public function editManager(array $args = []) {
+ return $this->call(self::SCOPE . 'editManager', $args);
+ }
+
+ public function enableOnline(array $args = []) {
+ return $this->call(self::SCOPE . 'enableOnline', $args);
+ }
+
+// public function get(array $args = []) {
+// return $this->call(self::SCOPE . 'get', $args);
+// }
+
+ public function getAddresses(array $args = [])
+ {
+ return $this->call(self::SCOPE . 'getAddresses', $args);
+ }
+
+ public function getBanned(array $args = []) {
+ return $this->call(self::SCOPE . 'getBanned', $args);
+ }
+
+ public function getById(array $args = []) {
+ return $this->call(self::SCOPE . 'getById', $args);
+ }
+
+ public function getCallbackConfirmationCode(array $args = []) {
+ return $this->call(self::SCOPE . 'getCallbackConfirmationCode', $args);
+ }
+
+ public function getCallbackServers(array $args = []) {
+ return $this->call(self::SCOPE . 'getCallbackServers', $args);
+ }
+
+ public function getCallbackSettings(array $args = []) {
+ return $this->call(self::SCOPE . 'getCallbackSettings', $args);
+ }
+ public function getCatalog(array $args = []) {
+ return $this->call(self::SCOPE . 'getCatalog', $args);
+ }
+ public function getCatalogInfo(array $args = []) {
+ return $this->call(self::SCOPE . 'getCatalogInfo', $args);
+ }
+
+ public function getInvitedUsers(array $args = []) {
+ return $this->call(self::SCOPE . 'getInvitedUsers', $args);
+ }
+
+ public function getInvites(array $args = []) {
+ return $this->call(self::SCOPE . 'getInvites', $args);
+ }
+
+ public function getLongPollServer(array $args = []) {
+ return $this->call(self::SCOPE . 'getLongPollServer', $args);
+ }
+
+ public function getLongPollSettings(array $args = []) {
+ return $this->call(self::SCOPE . 'getLongPollSettings', $args);
+ }
+ public function getMembers(array $args = []) {
+ return $this->call(self::SCOPE . 'getMembers', $args);
+ }
+
+ public function getRequests(array $args = []) {
+ return $this->call(self::SCOPE . 'getRequests', $args);
+ }
+
+ public function getSettings(array $args = []) {
+ return $this->call(self::SCOPE . 'getSettings', $args);
+ }
+
+ public function getTokenPermissions($access_token) {
+ return $this->call(self::SCOPE . 'getTokenPermissions');
+ }
+
+ public function invite(array $args = []) {
+ return $this->call(self::SCOPE . 'invite', $args);
+ }
+
+ public function isMember(array $args = []) {
+ return $this->call(self::SCOPE . 'isMember', $args);
+ }
+
+ public function join(array $args = []) {
+ return $this->call(self::SCOPE . 'join', $args);
+ }
+
+ public function leave(array $args = []) {
+ return $this->call(self::SCOPE . 'leave', $args);
+ }
+
+ public function removeUser(array $args = []) {
+ return $this->call(self::SCOPE . 'removeUser', $args);
+ }
+
+ public function reorderLink(array $args = []) {
+ return $this->call(self::SCOPE . 'reorderLink', $args);
+ }
+ public function search(array $args = []) {
+ return $this->call(self::SCOPE . 'search', $args);
+ }
+ public function setCallbackSettings(array $args = []) {
+ return $this->call(self::SCOPE . 'setCallbackSettings', $args);
+ }
+ public function setLongPollSettings(array $args = []) {
+ return $this->call(self::SCOPE . 'setLongPollSettings', $args);
+ }
+
+ public function unban(array $args = []) {
+ return $this->call(self::SCOPE . 'unban', $args);
+ }
+}
diff --git a/src/Foundation/Core/Models/Groups/GroupFields.php b/src/Foundation/Core/Models/Groups/GroupFields.php
new file mode 100644
index 0000000..3be725b
--- /dev/null
+++ b/src/Foundation/Core/Models/Groups/GroupFields.php
@@ -0,0 +1,170 @@
+group = $group instanceof Collection ? $group : collect($group);
+ }
+
+ /**
+ * @return int
+ */
+ public function getGroupId(): int
+ {
+ return $this->group->get(self::GROUP_ID);
+ }
+
+ /**
+ * @return string
+ */
+ public function getTitle(): string
+ {
+ return $this->group->get(self::TITLE);
+ }
+
+ /**
+ * @return string
+ */
+ public function getAddress(): string
+ {
+ return $this->group->get(self::ADDRESS);
+ }
+
+ /**
+ * @return string
+ */
+ public function getAdditionalAddress(): string
+ {
+ return $this->group->get(self::ADDITIONAL_ADDRESS);
+ }
+
+ /**
+ * @return int
+ */
+ public function getCountryId(): int
+ {
+ return $this->group->get(self::COUNTRY_ID);
+ }
+
+ /**
+ * @return CountryField
+ * @throws ApiException
+ * @throws Throwable
+ */
+ public function getCountry(): CountryField
+ {
+ return new CountryField($this->getCountryId());
+ }
+
+ /**
+ * @return int
+ */
+ public function getCityId(): int
+ {
+ return $this->group->get(self::CITY_ID);
+ }
+
+ /**
+ * @return CityField
+ * @throws ApiException
+ * @throws Throwable
+ */
+ public function getCity(): CityField
+ {
+ return new CityField($this->getCityId());
+ }
+
+ /**
+ * @return int
+ */
+ public function getMetroId(): int
+ {
+ // TODO: добавить метод getMetro(): MetroField
+ return $this->group->get(self::METRO_ID);
+ }
+
+ /**
+ * @return float
+ */
+ public function getLatitude(): float
+ {
+ return $this->group->get(self::LATITUDE);
+ }
+
+ /**
+ * @return float
+ */
+ public function getLongitude(): float
+ {
+ return $this->group->get(self::LONGITUDE);
+ }
+
+ /**
+ * @return string
+ */
+ public function getPhone(): string
+ {
+ return $this->group->get(self::PHONE);
+ }
+
+ /**
+ * @return string
+ */
+ public function getWorkInfoStatus(): string
+ {
+ return $this->group->get(self::WORK_INFO_STATUS);
+ }
+
+ /**
+ * @return string
+ */
+ public function getTimetable(): string
+ {
+ return $this->group->get(self::TIMETABLE);
+ }
+
+ /**
+ * @return bool
+ */
+ public function isMainAddress(): bool
+ {
+ return $this->group->get(self::IS_MAIN_ADDRESS);
+ }
+}
diff --git a/src/Foundation/Core/Models/Groups/GroupRequestFields.php b/src/Foundation/Core/Models/Groups/GroupRequestFields.php
new file mode 100644
index 0000000..3eeecbd
--- /dev/null
+++ b/src/Foundation/Core/Models/Groups/GroupRequestFields.php
@@ -0,0 +1,213 @@
+setCityId(int|CityField $city)
+ $this->groupId = $groupId;
+ return $this;
+ }
+
+ /**
+ * @param string $title
+ * @return GroupRequestFields
+ */
+ public function setTitle(string $title): GroupRequestFields
+ {
+ $this->title = $title;
+ return $this;
+ }
+
+ /**
+ * @param string $address
+ * @return GroupRequestFields
+ */
+ public function setAddress(string $address): GroupRequestFields
+ {
+ $this->address = $address;
+ return $this;
+ }
+
+ /**
+ * @param string $additionalAddress
+ * @return GroupRequestFields
+ */
+ public function setAdditionalAddress(string $additionalAddress): GroupRequestFields
+ {
+ $this->additionalAddress = $additionalAddress;
+ return $this;
+ }
+
+ /**
+ * @param int|CountryField $country
+ * @return GroupRequestFields
+ */
+ public function setCountryId(int|CountryField $country): GroupRequestFields
+ {
+ $this->countryId = $country instanceof CountryField ? $country->getId() : $country;
+ return $this;
+ }
+
+ /**
+ * @param int|CityField $city
+ * @return GroupRequestFields
+ */
+ public function setCityId(int|CityField $city): GroupRequestFields
+ {
+ $this->cityId = $city instanceof CityField ? $city->getId() : $city;
+ return $this;
+ }
+
+ /**
+ * @param int $metroId
+ * @return GroupRequestFields
+ */
+ public function setMetroId(int $metroId): GroupRequestFields
+ {
+ // TODO: добавить MetroField
+ $this->metroId = $metroId;
+ return $this;
+ }
+
+ /**
+ * @param float $latitude
+ * @return GroupRequestFields
+ */
+ public function setLatitude(float $latitude): GroupRequestFields
+ {
+ $this->latitude = $latitude;
+ return $this;
+ }
+
+ /**
+ * @param float $longitude
+ * @return GroupRequestFields
+ */
+ public function setLongitude(float $longitude): GroupRequestFields
+ {
+ $this->longitude = $longitude;
+ return $this;
+ }
+
+ /**
+ * @param string $phone
+ * @return GroupRequestFields
+ */
+ public function setPhone(string $phone): GroupRequestFields
+ {
+ $this->phone = $phone;
+ return $this;
+ }
+
+ /**
+ * @param string $workInfoStatus
+ * @return GroupRequestFields
+ */
+ public function setWorkInfoStatus(string $workInfoStatus): GroupRequestFields
+ {
+ $this->workInfoStatus = $workInfoStatus;
+ return $this;
+ }
+
+ /**
+ * @param string $timetable
+ * @return GroupRequestFields
+ */
+ public function setTimetable(string $timetable): GroupRequestFields
+ {
+ $this->timetable = $timetable;
+ return $this;
+ }
+
+ /**
+ * @param bool $isMainAddress
+ * @return GroupRequestFields
+ */
+ public function setIsMainAddress(bool $isMainAddress): GroupRequestFields
+ {
+ $this->isMainAddress = $isMainAddress;
+ return $this;
+ }
+}
From af465c6ac558c3a61512a0c1eaa6c64b55b7acd2 Mon Sep 17 00:00:00 2001
From: Schizo
Date: Sat, 29 Oct 2022 02:57:44 +0300
Subject: [PATCH 09/24] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB?=
=?UTF-8?q?=D0=B5=D0=BD=D1=8B=20=D0=B2=D1=81=D0=B5=20=D0=BC=D0=B5=D1=82?=
=?UTF-8?q?=D0=BE=D0=B4=D1=8B=20=D1=81=D0=B5=D0=BA=D1=86=D0=B8=D0=B8=20Dat?=
=?UTF-8?q?abase?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
src/Exceptions/Callback/CallbackException.php | 2 +-
src/Foundation/Core/Api/Client.php | 29 ++-
src/Foundation/Core/Api/Languages.php | 16 +-
src/Foundation/Core/Api/Request.php | 19 +-
.../Core/Models/Database/Database.php | 209 ++++++++++++++++--
.../Models/Database/DatabaseCollection.php | 53 +++++
.../Core/Models/Database/DatabaseField.php | 54 +++++
.../Database/Fields/Chair/ChairField.php | 49 ++++
.../Fields/Chair/ChairFieldsCollection.php | 17 ++
.../Fields/Chair/ChairRequestFields.php | 29 +++
.../Models/Database/Fields/City/CityField.php | 14 ++
.../Fields/City/CityFieldsCollection.php | 17 ++
.../Fields/City/CityRequestFields.php | 76 +++++++
.../Core/Models/Database/Fields/CityField.php | 59 -----
.../Database/Fields/Country/CountryField.php | 14 ++
.../Country/CountryFieldsCollection.php | 17 ++
.../Fields/Country/CountryRequestFields.php | 59 +++++
.../Models/Database/Fields/CountryField.php | 59 -----
.../Database/Fields/Faculty/FacultyField.php | 14 ++
.../Faculty/FacultyFieldsCollection.php | 17 ++
.../Fields/Faculty/FacultyRequestFields.php | 29 +++
.../Fields/Metro/MetroStationField.php | 23 ++
.../Metro/MetroStationFieldsCollection.php | 17 ++
.../Metro/MetroStationRequestFields.php | 46 ++++
.../Database/Fields/Region/RegionField.php | 14 ++
.../Fields/Region/RegionFieldsCollection.php | 17 ++
.../Fields/Region/RegionRequestFields.php | 31 +++
.../School/SchoolClasses/SchoolClassField.php | 27 +++
.../SchoolClassFieldsCollection.php | 31 +++
.../SchoolClassRequestFields.php | 25 +++
.../Database/Fields/School/SchoolField.php | 14 ++
.../Fields/School/SchoolFieldsCollection.php | 17 ++
.../Fields/School/SchoolRequestFields.php | 31 +++
.../Fields/University/UniversityField.php | 14 ++
.../University/UniversityFieldsCollection.php | 18 ++
.../University/UniversityRequestFields.php | 46 ++++
.../Traits/DatabaseCanExtendRequest.php | 25 +++
.../Traits/DatabaseEnumerableRequest.php | 40 ++++
.../Traits/DatabaseSearchableRequest.php | 25 +++
.../Core/Models/Users/UserProfileFields.php | 20 +-
src/Services/CallbackEventService.php | 7 +-
41 files changed, 1169 insertions(+), 171 deletions(-)
create mode 100644 src/Foundation/Core/Models/Database/DatabaseCollection.php
create mode 100644 src/Foundation/Core/Models/Database/DatabaseField.php
create mode 100644 src/Foundation/Core/Models/Database/Fields/Chair/ChairField.php
create mode 100644 src/Foundation/Core/Models/Database/Fields/Chair/ChairFieldsCollection.php
create mode 100644 src/Foundation/Core/Models/Database/Fields/Chair/ChairRequestFields.php
create mode 100644 src/Foundation/Core/Models/Database/Fields/City/CityField.php
create mode 100644 src/Foundation/Core/Models/Database/Fields/City/CityFieldsCollection.php
create mode 100644 src/Foundation/Core/Models/Database/Fields/City/CityRequestFields.php
delete mode 100644 src/Foundation/Core/Models/Database/Fields/CityField.php
create mode 100644 src/Foundation/Core/Models/Database/Fields/Country/CountryField.php
create mode 100644 src/Foundation/Core/Models/Database/Fields/Country/CountryFieldsCollection.php
create mode 100644 src/Foundation/Core/Models/Database/Fields/Country/CountryRequestFields.php
delete mode 100644 src/Foundation/Core/Models/Database/Fields/CountryField.php
create mode 100644 src/Foundation/Core/Models/Database/Fields/Faculty/FacultyField.php
create mode 100644 src/Foundation/Core/Models/Database/Fields/Faculty/FacultyFieldsCollection.php
create mode 100644 src/Foundation/Core/Models/Database/Fields/Faculty/FacultyRequestFields.php
create mode 100644 src/Foundation/Core/Models/Database/Fields/Metro/MetroStationField.php
create mode 100644 src/Foundation/Core/Models/Database/Fields/Metro/MetroStationFieldsCollection.php
create mode 100644 src/Foundation/Core/Models/Database/Fields/Metro/MetroStationRequestFields.php
create mode 100644 src/Foundation/Core/Models/Database/Fields/Region/RegionField.php
create mode 100644 src/Foundation/Core/Models/Database/Fields/Region/RegionFieldsCollection.php
create mode 100644 src/Foundation/Core/Models/Database/Fields/Region/RegionRequestFields.php
create mode 100644 src/Foundation/Core/Models/Database/Fields/School/SchoolClasses/SchoolClassField.php
create mode 100644 src/Foundation/Core/Models/Database/Fields/School/SchoolClasses/SchoolClassFieldsCollection.php
create mode 100644 src/Foundation/Core/Models/Database/Fields/School/SchoolClasses/SchoolClassRequestFields.php
create mode 100644 src/Foundation/Core/Models/Database/Fields/School/SchoolField.php
create mode 100644 src/Foundation/Core/Models/Database/Fields/School/SchoolFieldsCollection.php
create mode 100644 src/Foundation/Core/Models/Database/Fields/School/SchoolRequestFields.php
create mode 100644 src/Foundation/Core/Models/Database/Fields/University/UniversityField.php
create mode 100644 src/Foundation/Core/Models/Database/Fields/University/UniversityFieldsCollection.php
create mode 100644 src/Foundation/Core/Models/Database/Fields/University/UniversityRequestFields.php
create mode 100644 src/Foundation/Core/Models/Database/Traits/DatabaseCanExtendRequest.php
create mode 100644 src/Foundation/Core/Models/Database/Traits/DatabaseEnumerableRequest.php
create mode 100644 src/Foundation/Core/Models/Database/Traits/DatabaseSearchableRequest.php
diff --git a/src/Exceptions/Callback/CallbackException.php b/src/Exceptions/Callback/CallbackException.php
index 4b88f10..b96c029 100644
--- a/src/Exceptions/Callback/CallbackException.php
+++ b/src/Exceptions/Callback/CallbackException.php
@@ -18,6 +18,6 @@ class CallbackException extends SdkException
*/
public function __construct($message, $code = 400, Throwable $previous = null)
{
- parent::__construct("CallbackException: {$message}", $code, $previous);
+ parent::__construct("CallbackException: $message", $code, $previous);
}
}
diff --git a/src/Foundation/Core/Api/Client.php b/src/Foundation/Core/Api/Client.php
index eb18ea5..eae1747 100644
--- a/src/Foundation/Core/Api/Client.php
+++ b/src/Foundation/Core/Api/Client.php
@@ -15,37 +15,46 @@ class Client
{
/**
* @param string $userOrGroupToken
+ * @param string|null $version
+ * @param string|null $language
* @return Group
*/
- public function group(string $userOrGroupToken): Group
+ public function group(string $userOrGroupToken, string $version = null, string $language = null): Group
{
- return new Group($userOrGroupToken);
+ return new Group($userOrGroupToken, $version, $language);
}
/**
- * @param string $token
+ * @param string $userOrGroupToken
+ * @param string|null $version
+ * @param string|null $language
* @return Message
*/
- public function message(string $token): Message
+ public function message(string $userOrGroupToken, string $version = null, string $language = null): Message
{
- return new Message($token);
+ return new Message($userOrGroupToken, $version, $language);
}
/**
- * @param string $userOrServiceToken
+ * @param string $token
+ * @param string|null $version
+ * @param string|null $language
* @return User
*/
- public function user(string $userOrServiceToken): User
+ public function user(string $token, string $version = null, string $language = null): User
{
- return new User($userOrServiceToken);
+ return new User($token, $version, $language);
}
/**
* @param string $userOrServiceToken
+ * @param string|null $version
+ * @param string|null $language
* @return Database
*/
- public function database(string $userOrServiceToken): Database
+ public function database(string $userOrServiceToken, string $version = null, string $language = null): Database
{
- return new Database($userOrServiceToken);
+// dd($userOrServiceToken);
+ return new Database($userOrServiceToken, $version, $language);
}
}
diff --git a/src/Foundation/Core/Api/Languages.php b/src/Foundation/Core/Api/Languages.php
index 60d0eba..c9190fc 100644
--- a/src/Foundation/Core/Api/Languages.php
+++ b/src/Foundation/Core/Api/Languages.php
@@ -6,16 +6,16 @@
* Class Languages
* @package Hopex\VkSdk\Foundation\Core\Api
*/
-enum Languages: string
+class Languages
{
- case Russian = 'ru';
- case English = 'en';
+ public const RUSSIAN = 'ru';
+ public const ENGLISH = 'en';
// TODO: Добавить транслитерацию для остальных языков
- // case Belorussian = 'be';
- // case Spanish = 'es';
- // case Finnish = 'fi';
- // case German = 'de';
- // case Italian = 'it';
+ // public const Belorussian = 'be';
+ // public const Spanish = 'es';
+ // public const Finnish = 'fi';
+ // public const German = 'de';
+ // public const Italian = 'it';
}
diff --git a/src/Foundation/Core/Api/Request.php b/src/Foundation/Core/Api/Request.php
index 1c48bef..3a2782e 100644
--- a/src/Foundation/Core/Api/Request.php
+++ b/src/Foundation/Core/Api/Request.php
@@ -5,6 +5,7 @@
use GuzzleHttp\Exception\RequestException;
use Hopex\VkSdk\Exceptions\Api\ApiException;
use Hopex\VkSdk\Exceptions\Api\HttpStatusCodeException;
+use Hopex\VkSdk\Exceptions\Callback\UnknownEventException;
use Hopex\VkSdk\Exceptions\SdkException;
use Hopex\VkSdk\Facades\Format;
use Hopex\VkSdk\Facades\SdkConfig;
@@ -22,21 +23,27 @@
*/
class Request
{
- /** @var string */
+ /**
+ * @var string
+ */
private string $token;
- /** @var string|array|null */
- private string|null|array $version;
+ /**
+ * @var string|float
+ */
+ private string|float $version;
- /** @var string|Repository|Application|mixed */
+ /**
+ * @var string
+ */
private string $language;
/**
* @param string $token
- * @param string|null $version
+ * @param string|float|null $version
* @param string|null $language
*/
- public function __construct(string $token, string $version = null, string $language = null)
+ public function __construct(string $token, string|float $version = null, string $language = null)
{
$this->token = $token;
$this->version = $version ?? SdkConfig::api('version');
diff --git a/src/Foundation/Core/Models/Database/Database.php b/src/Foundation/Core/Models/Database/Database.php
index 6a1b480..3770ebf 100644
--- a/src/Foundation/Core/Models/Database/Database.php
+++ b/src/Foundation/Core/Models/Database/Database.php
@@ -4,8 +4,28 @@
use Hopex\VkSdk\Exceptions\Api\ApiException;
use Hopex\VkSdk\Foundation\Core\Api\Request;
-use Hopex\VkSdk\Foundation\Core\Models\Databse\Fields\CityField;
-use Hopex\VkSdk\Foundation\Core\Models\Databse\Fields\CountryField;
+use Hopex\VkSdk\Foundation\Core\Models\Database\Fields\Chair\ChairField;
+use Hopex\VkSdk\Foundation\Core\Models\Database\Fields\Chair\ChairFieldsCollection;
+use Hopex\VkSdk\Foundation\Core\Models\Database\Fields\Chair\ChairRequestFields;
+use Hopex\VkSdk\Foundation\Core\Models\Database\Fields\City\CityField;
+use Hopex\VkSdk\Foundation\Core\Models\Database\Fields\City\CityFieldsCollection;
+use Hopex\VkSdk\Foundation\Core\Models\Database\Fields\City\CityRequestFields;
+use Hopex\VkSdk\Foundation\Core\Models\Database\Fields\Country\CountryField;
+use Hopex\VkSdk\Foundation\Core\Models\Database\Fields\Country\CountryFieldsCollection;
+use Hopex\VkSdk\Foundation\Core\Models\Database\Fields\Country\CountryRequestFields;
+use Hopex\VkSdk\Foundation\Core\Models\Database\Fields\Faculty\FacultyFieldsCollection;
+use Hopex\VkSdk\Foundation\Core\Models\Database\Fields\Faculty\FacultyRequestFields;
+use Hopex\VkSdk\Foundation\Core\Models\Database\Fields\Metro\MetroStationField;
+use Hopex\VkSdk\Foundation\Core\Models\Database\Fields\Metro\MetroStationFieldsCollection;
+use Hopex\VkSdk\Foundation\Core\Models\Database\Fields\Metro\MetroStationRequestFields;
+use Hopex\VkSdk\Foundation\Core\Models\Database\Fields\Region\RegionFieldsCollection;
+use Hopex\VkSdk\Foundation\Core\Models\Database\Fields\Region\RegionRequestFields;
+use Hopex\VkSdk\Foundation\Core\Models\Database\Fields\School\SchoolClasses\SchoolClassField;
+use Hopex\VkSdk\Foundation\Core\Models\Database\Fields\School\SchoolClasses\SchoolClassFieldsCollection;
+use Hopex\VkSdk\Foundation\Core\Models\Database\Fields\School\SchoolClasses\SchoolClassRequestFields;
+use Hopex\VkSdk\Foundation\Core\Models\Database\Fields\School\SchoolField;
+use Hopex\VkSdk\Foundation\Core\Models\Database\Fields\School\SchoolFieldsCollection;
+use Hopex\VkSdk\Foundation\Core\Models\Database\Fields\School\SchoolRequestFields;
use Illuminate\Support\Collection;
use Throwable;
@@ -16,60 +36,201 @@
class Database extends Request
{
private const SCOPE = 'database.';
- private const CITY_IDS = 'city_ids';
- private const COUNTRY_IDS = 'country_ids';
/**
- * @param array $args
+ * @param CityRequestFields $cityRequestFields
+ * @return CityFieldsCollection
+ * @throws ApiException
+ * @throws Throwable
+ */
+ public function getCities(CityRequestFields $cityRequestFields): CityFieldsCollection
+ {
+ return new CityFieldsCollection($this->call(self::SCOPE . 'getCities', get_object_vars($cityRequestFields)));
+ }
+
+ /**
+ * @param CityRequestFields $cityRequestFields
* @return Collection
* @throws ApiException
* @throws Throwable
*/
- public function getCitiesById(array $args = []): Collection
+ public function getCitiesById(CityRequestFields $cityRequestFields): Collection
{
- return collect($this->call(self::SCOPE . 'getCitiesById', $args))
- ->map(function ($item) {
- return new CityField($item);
- });
+ return collect($this->call(self::SCOPE . 'getCitiesById', get_object_vars($cityRequestFields))
+ ->map(function ($city) {
+ return new CityField($city);
+ }));
}
/**
* @param int $cityId
- * @return Collection
+ * @return ChairField
+ * @throws ApiException
+ * @throws Throwable
+ */
+ public function getCityById(int $cityId): ChairField
+ {
+ return $this->getCitiesById((new CityRequestFields())->setCityIds([$cityId]))->first();
+ }
+
+ /**
+ * @param CountryRequestFields $countryRequestFields
+ * @return CountryFieldsCollection
* @throws ApiException
* @throws Throwable
*/
- public function getCityById(int $cityId): Collection
+ public function getCountries(CountryRequestFields $countryRequestFields): CountryFieldsCollection
{
- return $this->getCitiesById([
- self::CITY_IDS => $cityId
- ])->first();
+ return new CountryFieldsCollection($this->call(self::SCOPE . 'getCountries', get_object_vars($countryRequestFields)));
}
/**
- * @param array $args
+ * @param CountryRequestFields $countryRequestFields
* @return Collection
* @throws ApiException
* @throws Throwable
*/
- public function getCountriesById(array $args = []): Collection
+ public function getCountriesById(CountryRequestFields $countryRequestFields): Collection
{
- return collect($this->call(self::SCOPE . 'getCountriesById', $args))
- ->map(function ($item) {
- return new CountryField($item);
+ return collect($this->call(self::SCOPE . 'getCountriesById', get_object_vars($countryRequestFields)))
+ ->map(function ($country) {
+ return new CountryField($country);
});
}
/**
* @param int $countryId
+ * @return CountryField
+ * @throws ApiException
+ * @throws Throwable
+ */
+ public function getCountryById(int $countryId): CountryField
+ {
+ return $this->getCountriesById((new CountryRequestFields())->setCountryIds([$countryId]))->first();
+ }
+
+ /**
+ * @param ChairRequestFields $chairRequestFields
+ * @return ChairFieldsCollection
+ * @throws ApiException
+ * @throws Throwable
+ */
+ public function getChairs(ChairRequestFields $chairRequestFields): ChairFieldsCollection
+ {
+ return new ChairFieldsCollection($this->call(self::SCOPE . 'getChairs', get_object_vars($chairRequestFields)));
+ }
+
+ /**
+ * @param MetroStationRequestFields $metroStationRequestFields
+ * @return MetroStationFieldsCollection
+ * @throws ApiException
+ * @throws Throwable
+ */
+ public function getMetroStations(MetroStationRequestFields $metroStationRequestFields): MetroStationFieldsCollection
+ {
+ return new MetroStationFieldsCollection($this->call(self::SCOPE . 'getMetroStations', get_object_vars($metroStationRequestFields)));
+ }
+
+ /**
+ * @param MetroStationRequestFields $metroStationRequestFields
* @return Collection
* @throws ApiException
* @throws Throwable
*/
- public function getCountryById(int $countryId): Collection
+ public function getMetroStationsById(MetroStationRequestFields $metroStationRequestFields): Collection
+ {
+ return collect($this->call(self::SCOPE . 'getMetroStationsById', get_object_vars($metroStationRequestFields))
+ ->map(function ($city) {
+ return new MetroStationField($city);
+ }));
+ }
+
+ /**
+ * @param int $stationId
+ * @return MetroStationField
+ * @throws ApiException
+ * @throws Throwable
+ */
+ public function getMetroStationById(int $stationId): MetroStationField
{
- return $this->getCountriesById([
- self::COUNTRY_IDS => $countryId
- ])->first();
+ return $this->getMetroStationsById((new MetroStationRequestFields())->setStationIds([$stationId]))->first();
+ }
+
+ /**
+ * @param FacultyRequestFields $facultyRequestFields
+ * @return FacultyFieldsCollection
+ * @throws ApiException
+ * @throws Throwable
+ */
+ public function getFaculties(FacultyRequestFields $facultyRequestFields): FacultyFieldsCollection
+ {
+ return new FacultyFieldsCollection($this->call(self::SCOPE . 'getFaculties', get_object_vars($facultyRequestFields)));
+ }
+
+ /**
+ * @param RegionRequestFields $regionRequestFields
+ * @return RegionFieldsCollection
+ * @throws ApiException
+ * @throws Throwable
+ */
+ public function getRegions(RegionRequestFields $regionRequestFields): RegionFieldsCollection
+ {
+ return new RegionFieldsCollection($this->call(self::SCOPE . 'getRegions', get_object_vars($regionRequestFields)));
+ }
+
+ /**
+ * @param SchoolRequestFields $schoolRequestFields
+ * @return SchoolFieldsCollection
+ * @throws ApiException
+ * @throws Throwable
+ */
+ public function getSchools(SchoolRequestFields $schoolRequestFields): SchoolFieldsCollection
+ {
+ return new SchoolFieldsCollection($this->call(self::SCOPE . 'getSchools', get_object_vars($schoolRequestFields)));
+ }
+
+ /**
+ * @param SchoolRequestFields $schoolRequestFields
+ * @param int $schoolId
+ * @return SchoolField
+ * @throws ApiException
+ * @throws Throwable
+ */
+ public function getSchoolByIds(SchoolRequestFields $schoolRequestFields, int $schoolId): SchoolField
+ {
+ return $this
+ ->getSchools($schoolRequestFields)
+ ->getItems()
+ ->first(function (SchoolField $school) use ($schoolId) {
+ return $school->getId() == $schoolId;
+ });
+ }
+
+ /**
+ * @param SchoolClassRequestFields $schoolClassRequestFields
+ * @return SchoolClassFieldsCollection
+ * @throws ApiException
+ * @throws Throwable
+ */
+ public function getSchoolClasses(SchoolClassRequestFields $schoolClassRequestFields): SchoolClassFieldsCollection
+ {
+ return new SchoolClassFieldsCollection($this->call(self::SCOPE . 'getSchoolClasses', get_object_vars($schoolClassRequestFields)));
+ }
+
+ /**
+ * @param SchoolClassRequestFields $schoolClassRequestFields
+ * @param int $schoolClassId
+ * @return SchoolClassField
+ * @throws ApiException
+ * @throws Throwable
+ */
+ public function getSchoolClassById(SchoolClassRequestFields $schoolClassRequestFields, int $schoolClassId): SchoolClassField
+ {
+ return $this
+ ->getSchoolClasses($schoolClassRequestFields)
+ ->getItems()
+ ->first(function (SchoolClassField $class) use ($schoolClassId) {
+ return $class->getId() == $schoolClassId;
+ });
}
}
diff --git a/src/Foundation/Core/Models/Database/DatabaseCollection.php b/src/Foundation/Core/Models/Database/DatabaseCollection.php
new file mode 100644
index 0000000..be59702
--- /dev/null
+++ b/src/Foundation/Core/Models/Database/DatabaseCollection.php
@@ -0,0 +1,53 @@
+fieldsCollection = $fieldsCollection instanceof Collection ? $fieldsCollection : collect($fieldsCollection);
+ }
+
+ /**
+ * @return int
+ */
+ final public function getCount(): int
+ {
+ return $this->fieldsCollection->get(self::COUNT);
+ }
+
+ /**
+ * @return Collection
+ */
+ public function getItems(): Collection
+ {
+ return collect($this->fieldsCollection->get(self::ITEMS))
+ ->map(function ($field) {
+ return new $this->fieldType($field);
+ });
+ }
+}
diff --git a/src/Foundation/Core/Models/Database/DatabaseField.php b/src/Foundation/Core/Models/Database/DatabaseField.php
new file mode 100644
index 0000000..317ec99
--- /dev/null
+++ b/src/Foundation/Core/Models/Database/DatabaseField.php
@@ -0,0 +1,54 @@
+currentField = $currentField instanceof Collection ? $currentField : collect($currentField);
+ }
+
+ /**
+ * @param array|Collection $currentField
+ * @return DatabaseField
+ */
+ public function __invoke(array|Collection $currentField): DatabaseField
+ {
+ return $this->__construct($currentField);
+ }
+
+ /**
+ * @return int
+ */
+ public function getId(): int
+ {
+ return $this->currentField->get(self::ID);
+ }
+
+ /**
+ * @return string
+ */
+ public function getTitle(): string
+ {
+ return $this->currentField->get(self::TITLE);
+ }
+}
diff --git a/src/Foundation/Core/Models/Database/Fields/Chair/ChairField.php b/src/Foundation/Core/Models/Database/Fields/Chair/ChairField.php
new file mode 100644
index 0000000..3fc2f62
--- /dev/null
+++ b/src/Foundation/Core/Models/Database/Fields/Chair/ChairField.php
@@ -0,0 +1,49 @@
+chair = $chair;
+ } else {
+ $this->chair = collect($chair);
+ }
+ }
+
+ /**
+ * @return int
+ */
+ public function getId(): int
+ {
+ return $this->chair->get(self::ID);
+ }
+
+ /**
+ * @return string
+ */
+ public function getTitle(): string
+ {
+ return $this->chair->get(self::TITLE);
+ }
+}
diff --git a/src/Foundation/Core/Models/Database/Fields/Chair/ChairFieldsCollection.php b/src/Foundation/Core/Models/Database/Fields/Chair/ChairFieldsCollection.php
new file mode 100644
index 0000000..156680e
--- /dev/null
+++ b/src/Foundation/Core/Models/Database/Fields/Chair/ChairFieldsCollection.php
@@ -0,0 +1,17 @@
+faculty_id = $faculty_id;
+ return $this;
+ }
+}
diff --git a/src/Foundation/Core/Models/Database/Fields/City/CityField.php b/src/Foundation/Core/Models/Database/Fields/City/CityField.php
new file mode 100644
index 0000000..a6771ba
--- /dev/null
+++ b/src/Foundation/Core/Models/Database/Fields/City/CityField.php
@@ -0,0 +1,14 @@
+city_ids = $city_ids;
+ return $this;
+ }
+
+ /**
+ * @param int $country_id
+ * @return CityRequestFields
+ */
+ public function setCountryId(int $country_id): CityRequestFields
+ {
+ $this->country_id = $country_id;
+ return $this;
+ }
+
+ /**
+ * @param int $region_id
+ * @return CityRequestFields
+ */
+ public function setRegionId(int $region_id): CityRequestFields
+ {
+ $this->region_id = $region_id;
+ return $this;
+ }
+
+ /**
+ * @param bool $need_all
+ * @return CityRequestFields
+ */
+ public function setNeedAll(bool $need_all): CityRequestFields
+ {
+ $this->need_all = $need_all;
+ return $this;
+ }
+}
diff --git a/src/Foundation/Core/Models/Database/Fields/CityField.php b/src/Foundation/Core/Models/Database/Fields/CityField.php
deleted file mode 100644
index bb04752..0000000
--- a/src/Foundation/Core/Models/Database/Fields/CityField.php
+++ /dev/null
@@ -1,59 +0,0 @@
-city = $city;
- } elseif (is_a($city, 'array')) {
- $this->city = collect($city);
- } else {
- $this->city = VkApi::database($userOrServiceToken)->getCityById($city);
- }
- }
-
- /**
- * @return int
- */
- public function getId(): int
- {
- return $this->city->get(self::ID);
- }
-
- /**
- * @return string
- */
- public function getTitle(): string
- {
- return $this->city->get(self::TITLE);
- }
-}
diff --git a/src/Foundation/Core/Models/Database/Fields/Country/CountryField.php b/src/Foundation/Core/Models/Database/Fields/Country/CountryField.php
new file mode 100644
index 0000000..0b2b245
--- /dev/null
+++ b/src/Foundation/Core/Models/Database/Fields/Country/CountryField.php
@@ -0,0 +1,14 @@
+country_ids = $country_ids;
+ return $this;
+ }
+
+ /**
+ * @param bool $need_all
+ * @return CountryRequestFields
+ */
+ public function setNeedAll(bool $need_all): CountryRequestFields
+ {
+ $this->need_all = $need_all;
+ return $this;
+ }
+
+ /**
+ * @param string $code
+ * @return CountryRequestFields
+ */
+ public function setCode(string $code): CountryRequestFields
+ {
+ $this->code = $code;
+ return $this;
+ }
+}
diff --git a/src/Foundation/Core/Models/Database/Fields/CountryField.php b/src/Foundation/Core/Models/Database/Fields/CountryField.php
deleted file mode 100644
index 6d2ac73..0000000
--- a/src/Foundation/Core/Models/Database/Fields/CountryField.php
+++ /dev/null
@@ -1,59 +0,0 @@
-country = $country;
- } elseif (is_a($country, 'array')) {
- $this->country = collect($country);
- } else {
- $this->country = VkApi::database($token)->getCountryById($country);
- }
- }
-
- /**
- * @return int
- */
- public function getId(): int
- {
- return $this->country->get(self::ID);
- }
-
- /**
- * @return string
- */
- public function getTitle(): string
- {
- return $this->country->get(self::TITLE);
- }
-}
diff --git a/src/Foundation/Core/Models/Database/Fields/Faculty/FacultyField.php b/src/Foundation/Core/Models/Database/Fields/Faculty/FacultyField.php
new file mode 100644
index 0000000..89c1d8a
--- /dev/null
+++ b/src/Foundation/Core/Models/Database/Fields/Faculty/FacultyField.php
@@ -0,0 +1,14 @@
+university_id = $university_id;
+ return $this;
+ }
+}
diff --git a/src/Foundation/Core/Models/Database/Fields/Metro/MetroStationField.php b/src/Foundation/Core/Models/Database/Fields/Metro/MetroStationField.php
new file mode 100644
index 0000000..105aabe
--- /dev/null
+++ b/src/Foundation/Core/Models/Database/Fields/Metro/MetroStationField.php
@@ -0,0 +1,23 @@
+currentField->get(self::COLOR);
+ }
+}
diff --git a/src/Foundation/Core/Models/Database/Fields/Metro/MetroStationFieldsCollection.php b/src/Foundation/Core/Models/Database/Fields/Metro/MetroStationFieldsCollection.php
new file mode 100644
index 0000000..2dcc955
--- /dev/null
+++ b/src/Foundation/Core/Models/Database/Fields/Metro/MetroStationFieldsCollection.php
@@ -0,0 +1,17 @@
+station_ids = $station_ids;
+ return $this;
+ }
+
+ /**
+ * @param array $city_ids
+ * @return MetroStationRequestFields
+ */
+ public function setCityIds(array $city_ids): MetroStationRequestFields
+ {
+ $this->city_ids = $city_ids;
+ return $this;
+ }
+}
diff --git a/src/Foundation/Core/Models/Database/Fields/Region/RegionField.php b/src/Foundation/Core/Models/Database/Fields/Region/RegionField.php
new file mode 100644
index 0000000..b135866
--- /dev/null
+++ b/src/Foundation/Core/Models/Database/Fields/Region/RegionField.php
@@ -0,0 +1,14 @@
+country_id = $country_id;
+ return $this;
+ }
+}
diff --git a/src/Foundation/Core/Models/Database/Fields/School/SchoolClasses/SchoolClassField.php b/src/Foundation/Core/Models/Database/Fields/School/SchoolClasses/SchoolClassField.php
new file mode 100644
index 0000000..fd411ae
--- /dev/null
+++ b/src/Foundation/Core/Models/Database/Fields/School/SchoolClasses/SchoolClassField.php
@@ -0,0 +1,27 @@
+ $class->first(),
+ 'title' => $class->last()
+ ])
+ );
+ }
+}
diff --git a/src/Foundation/Core/Models/Database/Fields/School/SchoolClasses/SchoolClassFieldsCollection.php b/src/Foundation/Core/Models/Database/Fields/School/SchoolClasses/SchoolClassFieldsCollection.php
new file mode 100644
index 0000000..7b2e8b9
--- /dev/null
+++ b/src/Foundation/Core/Models/Database/Fields/School/SchoolClasses/SchoolClassFieldsCollection.php
@@ -0,0 +1,31 @@
+ count($blocks),
+ 'items' => $blocks
+ ]));
+ }
+}
diff --git a/src/Foundation/Core/Models/Database/Fields/School/SchoolClasses/SchoolClassRequestFields.php b/src/Foundation/Core/Models/Database/Fields/School/SchoolClasses/SchoolClassRequestFields.php
new file mode 100644
index 0000000..1dd5f61
--- /dev/null
+++ b/src/Foundation/Core/Models/Database/Fields/School/SchoolClasses/SchoolClassRequestFields.php
@@ -0,0 +1,25 @@
+country_id = $country_id;
+ return $this;
+ }
+}
diff --git a/src/Foundation/Core/Models/Database/Fields/School/SchoolField.php b/src/Foundation/Core/Models/Database/Fields/School/SchoolField.php
new file mode 100644
index 0000000..061900d
--- /dev/null
+++ b/src/Foundation/Core/Models/Database/Fields/School/SchoolField.php
@@ -0,0 +1,14 @@
+city_id = $city_id;
+ return $this;
+ }
+}
diff --git a/src/Foundation/Core/Models/Database/Fields/University/UniversityField.php b/src/Foundation/Core/Models/Database/Fields/University/UniversityField.php
new file mode 100644
index 0000000..95577e1
--- /dev/null
+++ b/src/Foundation/Core/Models/Database/Fields/University/UniversityField.php
@@ -0,0 +1,14 @@
+country_id = $country_id;
+ return $this;
+ }
+
+ /**
+ * @param int $city_id
+ * @return UniversityRequestFields
+ */
+ public function setCityId(int $city_id): UniversityRequestFields
+ {
+ $this->city_id = $city_id;
+ return $this;
+ }
+}
diff --git a/src/Foundation/Core/Models/Database/Traits/DatabaseCanExtendRequest.php b/src/Foundation/Core/Models/Database/Traits/DatabaseCanExtendRequest.php
new file mode 100644
index 0000000..a389056
--- /dev/null
+++ b/src/Foundation/Core/Models/Database/Traits/DatabaseCanExtendRequest.php
@@ -0,0 +1,25 @@
+extended = $extended;
+ return $this;
+ }
+}
diff --git a/src/Foundation/Core/Models/Database/Traits/DatabaseEnumerableRequest.php b/src/Foundation/Core/Models/Database/Traits/DatabaseEnumerableRequest.php
new file mode 100644
index 0000000..c72ca21
--- /dev/null
+++ b/src/Foundation/Core/Models/Database/Traits/DatabaseEnumerableRequest.php
@@ -0,0 +1,40 @@
+offset = $offset;
+ return $this;
+ }
+
+ /**
+ * @param int $count
+ * @return DatabaseEnumerableRequest
+ */
+ public function setCount(int $count): static
+ {
+ $this->count = $count;
+ return $this;
+ }
+}
diff --git a/src/Foundation/Core/Models/Database/Traits/DatabaseSearchableRequest.php b/src/Foundation/Core/Models/Database/Traits/DatabaseSearchableRequest.php
new file mode 100644
index 0000000..aa51d75
--- /dev/null
+++ b/src/Foundation/Core/Models/Database/Traits/DatabaseSearchableRequest.php
@@ -0,0 +1,25 @@
+q = $q;
+ return $this;
+ }
+}
diff --git a/src/Foundation/Core/Models/Users/UserProfileFields.php b/src/Foundation/Core/Models/Users/UserProfileFields.php
index 172186e..eaeda22 100644
--- a/src/Foundation/Core/Models/Users/UserProfileFields.php
+++ b/src/Foundation/Core/Models/Users/UserProfileFields.php
@@ -4,8 +4,8 @@
use Carbon\Carbon;
use Hopex\VkSdk\Exceptions\Api\ApiException;
-use Hopex\VkSdk\Foundation\Core\Models\Databse\Fields\CityField;
-use Hopex\VkSdk\Foundation\Core\Models\Databse\Fields\CountryField;
+use Hopex\VkSdk\Foundation\Core\Models\Database\Fields\CityField;
+use Hopex\VkSdk\Foundation\Core\Models\Database\Fields\CountryField;
use Hopex\VkSdk\Foundation\Core\Models\Users\ProfileFields\CareerField;
use Hopex\VkSdk\Foundation\Core\Models\Users\ProfileFields\EducationField;
use Hopex\VkSdk\Foundation\Core\Models\Users\ProfileFields\LastSeenField;
@@ -286,6 +286,14 @@ public function getCity(string $token = null): CityField
return new CityField($this->user->get(UserProfileFields::CITY), $token);
}
+ /**
+ * @return int
+ */
+ public function getCityId(): int
+ {
+ return $this->user->get(UserProfileFields::CITY)[self::ID];
+ }
+
/**
* @param string|null $token
* @return CountryField
@@ -297,6 +305,14 @@ public function getCountry(string $token = null): CountryField
return new CountryField($this->user->get(UserProfileFields::COUNTRY), $token);
}
+ /**
+ * @return int
+ */
+ public function getCountryId(): int
+ {
+ return $this->user->get(UserProfileFields::COUNTRY)[self::ID];
+ }
+
/**
* @return Collection
*/
diff --git a/src/Services/CallbackEventService.php b/src/Services/CallbackEventService.php
index a7ccca5..f330d73 100644
--- a/src/Services/CallbackEventService.php
+++ b/src/Services/CallbackEventService.php
@@ -14,6 +14,8 @@
class CallbackEventService
{
+ private const OK = 'ok';
+
/**
* @var Request
*/
@@ -54,13 +56,14 @@ public function division(): mixed
default:
throw_if(!method_exists(CallbackEventsContract::class, $event), UnknownEventException::class);
throw_if(
- SdkConfig::groups("$groupId.secret.verify") && SdkConfig::groups("{$groupId}.secret.code") != $this->request->json('secret'),
+ SdkConfig::groups("$groupId.secret.verify") && SdkConfig::groups("$groupId.secret.code") != $this->request->json('secret'),
SecretException::class
);
- return call_user_func(
+ call_user_func(
[new (SdkConfig::groups("$groupId.events")), $event],
new BaseEvent(collect($this->request->only(['group_id', 'object'])))
);
+ return self::OK;
}
}
}
From fb71674f81befd0067624c7486ce51f978c2b3ab Mon Sep 17 00:00:00 2001
From: Schizo
Date: Sat, 29 Oct 2022 13:34:14 +0300
Subject: [PATCH 10/24] =?UTF-8?q?=D0=98=D1=81=D0=BF=D1=80=D0=B0=D0=B2?=
=?UTF-8?q?=D0=BB=D0=B5=D0=BD=D1=8B=20=D1=82=D0=B5=D1=81=D0=BA=D1=81=D1=82?=
=?UTF-8?q?=D1=8B=20Callback=20=D0=B8=D1=81=D0=BA=D0=BB=D1=8E=D1=87=D0=B5?=
=?UTF-8?q?=D0=BD=D0=B8=D0=B9?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
src/Exceptions/Callback/CallbackException.php | 1 +
src/Exceptions/Callback/SecretException.php | 2 +-
src/Exceptions/Callback/UnknownEventException.php | 2 +-
src/Exceptions/Callback/UnknownGroupIdException.php | 2 +-
4 files changed, 4 insertions(+), 3 deletions(-)
diff --git a/src/Exceptions/Callback/CallbackException.php b/src/Exceptions/Callback/CallbackException.php
index b96c029..e129cf0 100644
--- a/src/Exceptions/Callback/CallbackException.php
+++ b/src/Exceptions/Callback/CallbackException.php
@@ -18,6 +18,7 @@ class CallbackException extends SdkException
*/
public function __construct($message, $code = 400, Throwable $previous = null)
{
+ $message = preg_replace('~vk-sdk\.~', '', __("vk-sdk.$message"));
parent::__construct("CallbackException: $message", $code, $previous);
}
}
diff --git a/src/Exceptions/Callback/SecretException.php b/src/Exceptions/Callback/SecretException.php
index ba0a270..ebc4d0b 100644
--- a/src/Exceptions/Callback/SecretException.php
+++ b/src/Exceptions/Callback/SecretException.php
@@ -10,6 +10,6 @@ class SecretException extends CallbackException
{
public function __construct()
{
- parent::__construct(__("vk-sdk.0156"), 403);
+ parent::__construct("Access denied. The secret code of the event was not authenticated. Check the configuration settings.", 403);
}
}
diff --git a/src/Exceptions/Callback/UnknownEventException.php b/src/Exceptions/Callback/UnknownEventException.php
index acd1d7b..320e573 100644
--- a/src/Exceptions/Callback/UnknownEventException.php
+++ b/src/Exceptions/Callback/UnknownEventException.php
@@ -10,6 +10,6 @@ class UnknownEventException extends CallbackException
{
public function __construct()
{
- parent::__construct(__("vk-sdk.0158"), 403);
+ parent::__construct("Unknown callback event", 403);
}
}
diff --git a/src/Exceptions/Callback/UnknownGroupIdException.php b/src/Exceptions/Callback/UnknownGroupIdException.php
index e204d70..9b23f52 100644
--- a/src/Exceptions/Callback/UnknownGroupIdException.php
+++ b/src/Exceptions/Callback/UnknownGroupIdException.php
@@ -10,6 +10,6 @@ class UnknownGroupIdException extends CallbackException
{
public function __construct()
{
- parent::__construct(__("vk-sdk.0157"));
+ parent::__construct("Unknown community id");
}
}
From 4f989fe241a4e3744f26e3953cd293b324424930 Mon Sep 17 00:00:00 2001
From: Schizo
Date: Sun, 30 Oct 2022 20:47:02 +0300
Subject: [PATCH 11/24] =?UTF-8?q?=D0=9F=D0=BB=D0=B0=D0=BD=D0=BE=D0=B2?=
=?UTF-8?q?=D1=8B=D0=B9=20=D1=80=D0=B5=D1=84=D0=B0=D0=BA=D1=82=D0=BE=D1=80?=
=?UTF-8?q?=D0=B8=D0=BD=D0=B3?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
.../{CanFormat.php => CanFormatContract.php} | 2 +-
src/Contracts/HasRequestFieldsContract.php | 12 ++++++++++++
src/Formatters/ArrayParametersRequestFormatter.php | 4 ++--
.../ClearEmptiesParametersRequestFormatter.php | 4 ++--
src/Formatters/JsonExceptionFormatter.php | 4 ++--
src/Formatters/JsonLogFormatter.php | 4 ++--
src/Foundation/Core/Callback/EventsHandler.php | 1 +
.../Database/Fields/University/UniversityField.php | 2 +-
.../Fields/University/UniversityFieldsCollection.php | 2 +-
.../Core/Models/Users/UserRequestFields.php | 10 +++++-----
src/Foundation/Format.php | 4 ++--
src/Providers/ServiceProvider.php | 2 ++
12 files changed, 33 insertions(+), 18 deletions(-)
rename src/Contracts/{CanFormat.php => CanFormatContract.php} (86%)
create mode 100644 src/Contracts/HasRequestFieldsContract.php
diff --git a/src/Contracts/CanFormat.php b/src/Contracts/CanFormatContract.php
similarity index 86%
rename from src/Contracts/CanFormat.php
rename to src/Contracts/CanFormatContract.php
index 38fa098..3910996 100644
--- a/src/Contracts/CanFormat.php
+++ b/src/Contracts/CanFormatContract.php
@@ -6,7 +6,7 @@
* Interface CanFormat
* @package Hopex\VkSdk\Contracts
*/
-interface CanFormat
+interface CanFormatContract
{
/**
* @param $data
diff --git a/src/Contracts/HasRequestFieldsContract.php b/src/Contracts/HasRequestFieldsContract.php
new file mode 100644
index 0000000..f7ae587
--- /dev/null
+++ b/src/Contracts/HasRequestFieldsContract.php
@@ -0,0 +1,12 @@
+
Date: Mon, 31 Oct 2022 22:56:50 +0300
Subject: [PATCH 12/24] =?UTF-8?q?=D0=98=D0=B7=D0=BC=D0=B5=D0=BD=D0=B5?=
=?UTF-8?q?=D0=BD=D0=B0=20=D0=BB=D0=BE=D0=B3=D0=B8=D0=BA=D0=B0=20=D0=BE?=
=?UTF-8?q?=D0=B1=D1=8A=D1=8F=D0=B2=D0=BB=D0=B5=D0=BD=D0=B8=D1=8F=20=D0=BF?=
=?UTF-8?q?=D0=B0=D1=80=D0=B0=D0=BC=D0=B5=D1=82=D1=80=D0=BE=D0=B2=20=D0=B7?=
=?UTF-8?q?=D0=B0=D0=BF=D1=80=D0=BE=D1=81=D0=B0=20=D0=BD=D0=B0=20=D1=84?=
=?UTF-8?q?=D0=B0=D1=81=D0=B0=D0=B4=D0=BD=D1=83=D1=8E?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
composer.json | 3 +-
src/Facades/RequestFields.php | 20 +++
.../Core/Models/Database/Database.php | 4 +-
.../Core/Models/Messages/MessageFields.php | 17 +--
src/Foundation/Core/Models/RequestFields.php | 119 ++++++++++++++++++
.../Users/{ => Enums}/UserNameCases.php | 5 +-
.../Users/{ => Enums}/UserReportTypes.php | 5 +-
.../Core/Models/Users/UserProfileFields.php | 33 ++---
src/Providers/ServiceProvider.php | 2 +
9 files changed, 171 insertions(+), 37 deletions(-)
create mode 100644 src/Facades/RequestFields.php
create mode 100644 src/Foundation/Core/Models/RequestFields.php
rename src/Foundation/Core/Models/Users/{ => Enums}/UserNameCases.php (65%)
rename src/Foundation/Core/Models/Users/{ => Enums}/UserReportTypes.php (58%)
diff --git a/composer.json b/composer.json
index 3e476a6..aa726e3 100644
--- a/composer.json
+++ b/composer.json
@@ -32,7 +32,8 @@
"aliases": {
"VkApi": "Hopex\\VkSdk\\Facades\\VkApi",
"Format": "Hopex\\VkSdk\\Facades\\Format",
- "SdkConfig": "Hopex\\VkSdk\\Facades\\SdkConfig"
+ "SdkConfig": "Hopex\\VkSdk\\Facades\\SdkConfig",
+ "RequestFields": "Hopex\\VkSdk\\Facades\\RequestFields"
}
}
},
diff --git a/src/Facades/RequestFields.php b/src/Facades/RequestFields.php
new file mode 100644
index 0000000..6b37c98
--- /dev/null
+++ b/src/Facades/RequestFields.php
@@ -0,0 +1,20 @@
+getCitiesById((new CityRequestFields())->setCityIds([$cityId]))->first();
}
diff --git a/src/Foundation/Core/Models/Messages/MessageFields.php b/src/Foundation/Core/Models/Messages/MessageFields.php
index 6eafe58..eaf7d88 100644
--- a/src/Foundation/Core/Models/Messages/MessageFields.php
+++ b/src/Foundation/Core/Models/Messages/MessageFields.php
@@ -58,15 +58,16 @@ public function getDate(): Carbon
* @throws ApiException
* @throws Throwable
*/
- public function getSender(string $token, array $userProfileFields = []): UserProfileFields
+ public function getSender(string $token, UserRequestFields $userRequestFields): UserProfileFields
{
- return new UserProfileFields(collect(VkApi::user($token)
- ->get((new UserRequestFields())
- ->setUserIds([
- $this->message->get(self::FROM_ID)
- ])
- ->setProfileFields($userProfileFields)
- )->first()));
+ return new UserProfileFields([]);
+// return new UserProfileFields(collect(VkApi::user($token)
+// ->get((new UserRequestFields())
+// ->setUserIds([
+// $this->getSenderId()
+// ])
+// ->setProfileFields($userRequestFields->)
+// )->first()));
}
/**
diff --git a/src/Foundation/Core/Models/RequestFields.php b/src/Foundation/Core/Models/RequestFields.php
new file mode 100644
index 0000000..7966c8b
--- /dev/null
+++ b/src/Foundation/Core/Models/RequestFields.php
@@ -0,0 +1,119 @@
+user = $user;
- }
-
- /**
- * @return Collection
- */
- public function getUser(): Collection
- {
- return $this->user;
+ $this->user = $user instanceof Collection ? $user : collect($user);
}
/**
@@ -276,14 +269,14 @@ public function getCareer(): Collection
}
/**
- * @param string|null $token
+ * @param string $userOrServiceToken
* @return CityField
* @throws ApiException
* @throws Throwable
*/
- public function getCity(string $token = null): CityField
+ public function getCity(string $userOrServiceToken): CityField
{
- return new CityField($this->user->get(UserProfileFields::CITY), $token);
+ return VkApi::database($userOrServiceToken)->getCityById($this->getCityId());
}
/**
@@ -295,14 +288,14 @@ public function getCityId(): int
}
/**
- * @param string|null $token
+ * @param string $userOrServiceToken
* @return CountryField
* @throws ApiException
* @throws Throwable
*/
- public function getCountry(string $token = null): CountryField
+ public function getCountry(string $userOrServiceToken): CountryField
{
- return new CountryField($this->user->get(UserProfileFields::COUNTRY), $token);
+ return VkApi::database($userOrServiceToken)->getCountryById($this->getCountryId());
}
/**
diff --git a/src/Providers/ServiceProvider.php b/src/Providers/ServiceProvider.php
index b447260..9c9aa72 100644
--- a/src/Providers/ServiceProvider.php
+++ b/src/Providers/ServiceProvider.php
@@ -5,6 +5,7 @@
use Hopex\VkSdk\Contracts\HasRequestFieldsContract;
use Hopex\VkSdk\Foundation\Core\Api\Client;
use Hopex\VkSdk\Foundation\Core\Models\Database\Fields\School\SchoolRequestFields;
+use Hopex\VkSdk\Foundation\Core\Models\RequestFields;
use Hopex\VkSdk\Foundation\Format;
use Hopex\VkSdk\Foundation\SdkConfig;
use Hopex\VkSdk\Services\CallbackEventService;
@@ -24,6 +25,7 @@ public function register(): void
$this->app->bind('sdkconfig', SdkConfig::class);
$this->app->bind('format', Format::class);
$this->app->bind('vkapi', Client::class);
+ $this->app->bind('requestfields', RequestFields::class);
}
/**
From fa9ec1d0a594ee52540ea7c66845906f9ec26307 Mon Sep 17 00:00:00 2001
From: Schizo
Date: Tue, 3 Jan 2023 22:10:57 +0300
Subject: [PATCH 13/24] =?UTF-8?q?=D0=98=D1=81=D0=BF=D1=80=D0=B0=D0=B2?=
=?UTF-8?q?=D0=BB=D0=B5=D0=BD=20=D0=B4=D0=BE=D0=BF=D1=83=D1=81=D0=BA=20?=
=?UTF-8?q?=D0=BF=D1=83=D1=81=D1=82=D0=BE=D0=B3=D0=BE=20=D0=B7=D0=BD=D0=B0?=
=?UTF-8?q?=D1=87=D0=B5=D0=BD=D0=B8=D1=8F=20=D0=B4=D0=BB=D1=8F=20=D0=B8?=
=?UTF-8?q?=D0=B4=D0=B5=D0=BD=D1=82=D0=B8=D1=84=D0=B8=D0=BA=D0=B0=D1=82?=
=?UTF-8?q?=D0=BE=D1=80=D0=B0=20=D1=81=D0=BE=D0=B1=D1=8B=D1=82=D0=B8=D1=8F?=
=?UTF-8?q?=20=D0=B2=20=D1=82=D0=B0=D0=B1=D0=BB=D0=B8=D1=86=D0=B5=20=D1=81?=
=?UTF-8?q?=D0=BE=D0=B1=D1=8B=D1=82=D0=B8=D0=B9=20=D0=B8=20=D0=BE=D0=BF?=
=?UTF-8?q?=D1=82=D0=B8=D0=BC=D0=B8=D0=B7=D0=B8=D1=80=D0=BE=D0=B2=D0=B0?=
=?UTF-8?q?=D0=BD=D1=8B=20=D0=B8=D0=BC=D0=BF=D0=BE=D1=80=D1=82=D1=8B?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
.../database/migrations/create_events_table.php | 2 +-
src/.root/routes/callbacks.php | 17 ++++-------------
src/Foundation/Core/Api/Request.php | 3 ---
src/Foundation/Core/Callback/EventsHandler.php | 1 -
.../Core/Models/Database/Database.php | 1 -
.../Core/Models/Groups/GroupFields.php | 1 -
.../Core/Models/Groups/GroupRequestFields.php | 1 -
.../Core/Models/Messages/MessageFields.php | 1 -
src/Providers/ServiceProvider.php | 2 --
9 files changed, 5 insertions(+), 24 deletions(-)
diff --git a/src/.root/database/migrations/create_events_table.php b/src/.root/database/migrations/create_events_table.php
index d61e76e..08b963d 100644
--- a/src/.root/database/migrations/create_events_table.php
+++ b/src/.root/database/migrations/create_events_table.php
@@ -15,7 +15,7 @@ public function up(): void
$table->id();
$table->unsignedBigInteger('group_id');
$table->string('type');
- $table->string('event_id')->unique();
+ $table->string('event_id')->unique()->nullable();
$table->timestamps();
});
}
diff --git a/src/.root/routes/callbacks.php b/src/.root/routes/callbacks.php
index 1be1cf4..9191825 100644
--- a/src/.root/routes/callbacks.php
+++ b/src/.root/routes/callbacks.php
@@ -4,22 +4,13 @@
use Hopex\VkSdk\Services\CallbackEventService;
use Illuminate\Support\Facades\Route;
-/*
-|--------------------------------------------------------------------------
-| The entry point for VK API Callback POST requests.
-|--------------------------------------------------------------------------
-| The address is extracted from the configuration file. By default, 'connect'.
-| Example your default endpoint: https://example.com/api/connect
-| For check this, use command:
-| For fire this route, use
-|
-| See more: https://dev.vk.com/api/callback/getting-started
- */
-
Route::prefix('api')->name('vk.')->group(function () {
Route::post(SdkConfig::routes('entry'), function (CallbackEventService $callback) {
- return response($callback->division(), 200, ['content-type' => 'application/json;charset=utf-8', 'charset' => 'utf-8']);
+ return response($callback->division(), 200, [
+ 'content-type' => 'application/json;charset=utf-8',
+ 'charset' => 'utf-8'
+ ]);
})->name('entry');
});
diff --git a/src/Foundation/Core/Api/Request.php b/src/Foundation/Core/Api/Request.php
index 3a2782e..3d7821e 100644
--- a/src/Foundation/Core/Api/Request.php
+++ b/src/Foundation/Core/Api/Request.php
@@ -5,14 +5,11 @@
use GuzzleHttp\Exception\RequestException;
use Hopex\VkSdk\Exceptions\Api\ApiException;
use Hopex\VkSdk\Exceptions\Api\HttpStatusCodeException;
-use Hopex\VkSdk\Exceptions\Callback\UnknownEventException;
use Hopex\VkSdk\Exceptions\SdkException;
use Hopex\VkSdk\Facades\Format;
use Hopex\VkSdk\Facades\SdkConfig;
use Hopex\VkSdk\Formatters\ArrayParametersRequestFormatter;
use Hopex\VkSdk\Formatters\ClearEmptiesParametersRequestFormatter;
-use Illuminate\Config\Repository;
-use Illuminate\Contracts\Foundation\Application;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Http;
use Throwable;
diff --git a/src/Foundation/Core/Callback/EventsHandler.php b/src/Foundation/Core/Callback/EventsHandler.php
index 89a0bca..062260d 100644
--- a/src/Foundation/Core/Callback/EventsHandler.php
+++ b/src/Foundation/Core/Callback/EventsHandler.php
@@ -3,7 +3,6 @@
namespace Hopex\VkSdk\Foundation\Core\Callback;
use Hopex\VkSdk\Contracts\CallbackEventsContract;
-use Hopex\VkSdk\Contracts\HasRequestFieldsContract;
/**
* Class EventsHandler
diff --git a/src/Foundation/Core/Models/Database/Database.php b/src/Foundation/Core/Models/Database/Database.php
index 1d7841f..727d87a 100644
--- a/src/Foundation/Core/Models/Database/Database.php
+++ b/src/Foundation/Core/Models/Database/Database.php
@@ -4,7 +4,6 @@
use Hopex\VkSdk\Exceptions\Api\ApiException;
use Hopex\VkSdk\Foundation\Core\Api\Request;
-use Hopex\VkSdk\Foundation\Core\Models\Database\Fields\Chair\ChairField;
use Hopex\VkSdk\Foundation\Core\Models\Database\Fields\Chair\ChairFieldsCollection;
use Hopex\VkSdk\Foundation\Core\Models\Database\Fields\Chair\ChairRequestFields;
use Hopex\VkSdk\Foundation\Core\Models\Database\Fields\City\CityField;
diff --git a/src/Foundation/Core/Models/Groups/GroupFields.php b/src/Foundation/Core/Models/Groups/GroupFields.php
index 3be725b..61ba760 100644
--- a/src/Foundation/Core/Models/Groups/GroupFields.php
+++ b/src/Foundation/Core/Models/Groups/GroupFields.php
@@ -3,7 +3,6 @@
namespace Hopex\VkSdk\Foundation\Core\Models\Groups;
use Hopex\VkSdk\Exceptions\Api\ApiException;
-use Hopex\VkSdk\Foundation\Core\Api\Request;
use Hopex\VkSdk\Foundation\Core\Models\Databse\Fields\CityField;
use Hopex\VkSdk\Foundation\Core\Models\Databse\Fields\CountryField;
use Illuminate\Support\Collection;
diff --git a/src/Foundation/Core/Models/Groups/GroupRequestFields.php b/src/Foundation/Core/Models/Groups/GroupRequestFields.php
index 3eeecbd..f83e29e 100644
--- a/src/Foundation/Core/Models/Groups/GroupRequestFields.php
+++ b/src/Foundation/Core/Models/Groups/GroupRequestFields.php
@@ -2,7 +2,6 @@
namespace Hopex\VkSdk\Foundation\Core\Models\Groups;
-use Hopex\VkSdk\Foundation\Core\Api\Request;
use Hopex\VkSdk\Foundation\Core\Models\Databse\Fields\CityField;
use Hopex\VkSdk\Foundation\Core\Models\Databse\Fields\CountryField;
diff --git a/src/Foundation/Core/Models/Messages/MessageFields.php b/src/Foundation/Core/Models/Messages/MessageFields.php
index eaf7d88..05a7242 100644
--- a/src/Foundation/Core/Models/Messages/MessageFields.php
+++ b/src/Foundation/Core/Models/Messages/MessageFields.php
@@ -4,7 +4,6 @@
use Carbon\Carbon;
use Hopex\VkSdk\Exceptions\Api\ApiException;
-use Hopex\VkSdk\Facades\VkApi;
use Hopex\VkSdk\Foundation\Core\Models\Users\UserProfileFields;
use Hopex\VkSdk\Foundation\Core\Models\Users\UserRequestFields;
use Illuminate\Support\Collection;
diff --git a/src/Providers/ServiceProvider.php b/src/Providers/ServiceProvider.php
index 9c9aa72..61e065d 100644
--- a/src/Providers/ServiceProvider.php
+++ b/src/Providers/ServiceProvider.php
@@ -2,9 +2,7 @@
namespace Hopex\VkSdk\Providers;
-use Hopex\VkSdk\Contracts\HasRequestFieldsContract;
use Hopex\VkSdk\Foundation\Core\Api\Client;
-use Hopex\VkSdk\Foundation\Core\Models\Database\Fields\School\SchoolRequestFields;
use Hopex\VkSdk\Foundation\Core\Models\RequestFields;
use Hopex\VkSdk\Foundation\Format;
use Hopex\VkSdk\Foundation\SdkConfig;
From 5078c6c69f9e02296f653d2f162ef0e74bc273cb Mon Sep 17 00:00:00 2001
From: Schizo
Date: Tue, 3 Jan 2023 23:09:12 +0300
Subject: [PATCH 14/24] =?UTF-8?q?=D0=9F=D1=80=D0=BE=D0=BC=D0=B5=D0=B6?=
=?UTF-8?q?=D1=83=D1=82=D0=BE=D1=87=D0=BD=D0=B0=D1=8F=20=D1=84=D0=B8=D0=BA?=
=?UTF-8?q?=D1=81=D0=B0=D1=86=D0=B8=D1=8F.=20=D0=A0=D0=B5=D1=84=D0=B0?=
=?UTF-8?q?=D0=BA=D1=82=D0=BE=D1=80=D0=B8=D0=BD=D0=B3=20=D0=B8=D1=81=D0=BA?=
=?UTF-8?q?=D0=BB=D1=8E=D1=87=D0=B5=D0=BD=D0=B8=D0=B9?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
composer.json | 7 +------
src/.root/lang/ru.php | 1 +
src/Exceptions/Api/ApiException.php | 2 --
.../Database/TableNotFoundException.php | 15 +++++++++++++++
src/Exceptions/SdkException.php | 19 +++++++++----------
src/Services/CallbackEventService.php | 14 ++++++++++----
6 files changed, 36 insertions(+), 22 deletions(-)
create mode 100644 src/Exceptions/Database/TableNotFoundException.php
diff --git a/composer.json b/composer.json
index aa726e3..fcb9747 100644
--- a/composer.json
+++ b/composer.json
@@ -12,6 +12,7 @@
"homepage": "https://github.com/H0pex"
}
],
+ "repository": "https://github.com/Hopex-Development/laravel-vk-sdk",
"require": {
"php": "^8",
"ext-json": "*"
@@ -37,12 +38,6 @@
}
}
},
- "repositories": [
- {
- "type": "git",
- "url": "https://github.com/H0pex/laravel-vk-sdk"
- }
- ],
"config": {
"optimize-autoloader": true
},
diff --git a/src/.root/lang/ru.php b/src/.root/lang/ru.php
index 92fea56..8b8bc13 100644
--- a/src/.root/lang/ru.php
+++ b/src/.root/lang/ru.php
@@ -165,4 +165,5 @@
'Unknown community id' => 'Неизвестный идентификатор сообщества',
'Unknown callback event' => 'Неизвестное событие',
'Invalid http status code' => 'Недопустимый код состояния http',
+ 'Base table or view not found' => 'Базовая таблица или представление не найдены. Попробуйте выполнить команду php artisan migrate',
];
diff --git a/src/Exceptions/Api/ApiException.php b/src/Exceptions/Api/ApiException.php
index b1bcadf..8daf575 100644
--- a/src/Exceptions/Api/ApiException.php
+++ b/src/Exceptions/Api/ApiException.php
@@ -12,8 +12,6 @@
class ApiException extends SdkException
{
/**
- * ApiException constructor.
- *
* @param $message
* @param $code
* @param Throwable|null $previous
diff --git a/src/Exceptions/Database/TableNotFoundException.php b/src/Exceptions/Database/TableNotFoundException.php
new file mode 100644
index 0000000..5b7e61a
--- /dev/null
+++ b/src/Exceptions/Database/TableNotFoundException.php
@@ -0,0 +1,15 @@
+message = preg_replace("~vk-sdk\.~", '', __("vk-sdk.{$this->getMessage()}"));
$this->report();
+
+ parent::__construct();
}
/**
@@ -33,14 +33,13 @@ public function __construct($message, $code = 500, Throwable $previous = null)
*/
protected function report(): void
{
- Log::build((array)SdkConfig::logging('channels.exception'))->warning($this->getMessage());
+ Log::build((array)SdkConfig::logging(self::LOG_CHANNEL))->warning($this->getMessage());
}
/**
- * @param Request $request
* @return JsonResponse|void
*/
- final public function render(Request $request)
+ final public function render()
{
if (env('LOG_LEVEL') === 'debug') {
return new JsonResponse(
diff --git a/src/Services/CallbackEventService.php b/src/Services/CallbackEventService.php
index f330d73..1ec10d5 100644
--- a/src/Services/CallbackEventService.php
+++ b/src/Services/CallbackEventService.php
@@ -4,11 +4,13 @@
use Hopex\VkSdk\Contracts\CallbackEventsContract;
use Hopex\VkSdk\Exceptions\Callback\SecretException;
+use Hopex\VkSdk\Exceptions\Callback\TableNotFoundException;
use Hopex\VkSdk\Exceptions\Callback\UnknownEventException;
use Hopex\VkSdk\Exceptions\Callback\UnknownGroupIdException;
use Hopex\VkSdk\Facades\SdkConfig;
use Hopex\VkSdk\Foundation\Core\Callback\BaseEvent;
use Hopex\VkSdk\Models\Event;
+use Illuminate\Database\QueryException;
use Illuminate\Http\Request;
use Throwable;
@@ -42,10 +44,14 @@ public function division(): mixed
$eventId = $this->request->json('event_id');
$event = $this->request->json('type');
- if (SdkConfig::groups("$groupId.allow_retry_events") || !Event::where('event_id', $eventId)->first()) {
- Event::updateOrCreate($this->request->only('group_id', 'type', 'event_id'));
- } else {
- return 'ok';
+ try {
+ if (SdkConfig::groups("$groupId.allow_retry_events") || !Event::where('event_id', $eventId)->first()) {
+ Event::updateOrCreate($this->request->only('group_id', 'type', 'event_id'));
+ } else {
+ return 'ok';
+ }
+ } catch (QueryException) {
+ throw new TableNotFoundException();
}
switch ($event) {
From 2403cc65585f151edad935eea171608b45ed3c8f Mon Sep 17 00:00:00 2001
From: Schizo
Date: Wed, 4 Jan 2023 03:17:15 +0300
Subject: [PATCH 15/24] =?UTF-8?q?=D0=98=D1=81=D0=BF=D1=80=D0=B0=D0=B2?=
=?UTF-8?q?=D0=BB=D0=B5=D0=BD=20=D1=84=D0=B0=D1=81=D0=B0=D0=B4=20=D1=84?=
=?UTF-8?q?=D0=BE=D1=80=D0=BC=D0=B0=D1=82=D0=B8=D1=80=D0=BE=D0=B2=D0=B0?=
=?UTF-8?q?=D0=BD=D0=B8=D1=8F.=20=D0=97=D0=B0=D0=BA=D0=BE=D0=BD=D1=87?=
=?UTF-8?q?=D0=B5=D0=BD=20=D1=80=D0=B5=D1=84=D0=B0=D0=BA=D1=82=D0=BE=D1=80?=
=?UTF-8?q?=D0=B8=D0=BD=D0=B3=20=D0=B8=D1=81=D0=BA=D0=BB=D1=8E=D1=87=D0=B5?=
=?UTF-8?q?=D0=BD=D0=B8=D0=B9.=20=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB?=
=?UTF-8?q?=D0=B5=D0=BD=D0=B0=20=D0=BE=D0=B1=D1=80=D0=B0=D0=B1=D0=BE=D1=82?=
=?UTF-8?q?=D0=BA=D0=B0=20=D0=BE=D1=88=D0=B8=D0=B1=D0=BA=D0=B8=20=D0=B7?=
=?UTF-8?q?=D0=B0=D0=BF=D1=80=D0=BE=D1=81=D0=B0=20=D0=B2=20=D0=B1=D0=B0?=
=?UTF-8?q?=D0=B7=D1=83=20=D0=B4=D0=B0=D0=BD=D0=BD=D1=8B=D1=85=20=D0=BF?=
=?UTF-8?q?=D1=80=D0=B8=20=D0=B7=D0=B0=D0=BF=D0=B8=D1=81=D0=B8=20=D0=B2?=
=?UTF-8?q?=D1=85=D0=BE=D0=B4=D1=8F=D1=89=D0=B5=D0=B3=D0=BE=20=D1=81=D0=BE?=
=?UTF-8?q?=D0=B1=D1=8B=D1=82=D0=B8=D1=8F.=20=D0=98=D1=81=D0=BF=D1=80?=
=?UTF-8?q?=D0=B0=D0=B2=D0=BB=D0=B5=D0=BD=20=D0=B1=D0=B0=D0=B3=20=D0=BD?=
=?UTF-8?q?=D0=B5=D0=BF=D1=80=D0=B8=D0=BD=D1=8F=D1=82=D0=B8=D1=8F=20=D0=B7?=
=?UTF-8?q?=D0=B0=D0=BF=D1=80=D0=BE=D1=81=D0=B0=20=D0=B1=D0=B5=D0=B7=20?=
=?UTF-8?q?=D0=B8=D0=B4=D0=B5=D0=BD=D1=82=D0=B8=D1=84=D0=B8=D0=BA=D0=B0?=
=?UTF-8?q?=D1=82=D1=80=D0=B0=20=D1=81=D0=BE=D0=B1=D1=8B=D1=82=D0=B8=D1=8F?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
src/.root/lang/ru.php | 2 +-
src/Exceptions/Api/ApiException.php | 17 ++++------
.../Api/HttpStatusCodeException.php | 11 ++-----
src/Exceptions/Callback/CallbackException.php | 24 --------------
src/Exceptions/Callback/SecretException.php | 9 +++---
.../Callback/UnknownEventException.php | 11 +++----
.../Callback/UnknownGroupIdException.php | 9 +++---
.../DatabaseOrTableNotFoundException.php | 15 +++++++++
.../Database/TableNotFoundException.php | 15 ---------
src/Exceptions/SdkException.php | 4 +--
src/Formatters/JsonExceptionFormatter.php | 2 +-
src/Foundation/Core/Api/Request.php | 31 +++++--------------
src/Foundation/Format.php | 2 +-
src/Foundation/SdkConfig.php | 24 ++++----------
src/Services/CallbackEventService.php | 12 ++++---
15 files changed, 62 insertions(+), 126 deletions(-)
delete mode 100644 src/Exceptions/Callback/CallbackException.php
create mode 100644 src/Exceptions/Database/DatabaseOrTableNotFoundException.php
delete mode 100644 src/Exceptions/Database/TableNotFoundException.php
diff --git a/src/.root/lang/ru.php b/src/.root/lang/ru.php
index 8b8bc13..9c1dd54 100644
--- a/src/.root/lang/ru.php
+++ b/src/.root/lang/ru.php
@@ -165,5 +165,5 @@
'Unknown community id' => 'Неизвестный идентификатор сообщества',
'Unknown callback event' => 'Неизвестное событие',
'Invalid http status code' => 'Недопустимый код состояния http',
- 'Base table or view not found' => 'Базовая таблица или представление не найдены. Попробуйте выполнить команду php artisan migrate',
+ 'Database or table not found' => 'База данных или таблица не найдены',
];
diff --git a/src/Exceptions/Api/ApiException.php b/src/Exceptions/Api/ApiException.php
index 8daf575..82e046b 100644
--- a/src/Exceptions/Api/ApiException.php
+++ b/src/Exceptions/Api/ApiException.php
@@ -11,19 +11,14 @@
*/
class ApiException extends SdkException
{
+ public $message = 'Unknown api exception';
+
/**
- * @param $message
- * @param $code
- * @param Throwable|null $previous
+ * @param int $code
*/
- public function __construct($message = null, $code = 400, Throwable $previous = null)
+ public function __construct(int $code = 1)
{
- $commonError = ApiExceptionMapper::parse($code);
- if ($commonError) {
- $code = 400;
- $message = $commonError;
- }
- $message = preg_replace('~vk-sdk\.~', '', __("vk-sdk.$message"));
- parent::__construct("ApiException: $message", $code, $previous);
+ $this->message = ApiExceptionMapper::parse($code) ?? $this->message;
+ parent::__construct();
}
}
diff --git a/src/Exceptions/Api/HttpStatusCodeException.php b/src/Exceptions/Api/HttpStatusCodeException.php
index dd09f66..98ee51c 100644
--- a/src/Exceptions/Api/HttpStatusCodeException.php
+++ b/src/Exceptions/Api/HttpStatusCodeException.php
@@ -4,16 +4,9 @@
/**
* Class HttpStatusCodeException
- * @package Hopex\VkSdk\Exceptions\Api\Common
+ * @package Hopex\VkSdk\Exceptions\Api
*/
class HttpStatusCodeException extends ApiException
{
- /**
- * HttpStatusCodeException constructor.
- */
- public function __construct()
- {
- parent::__construct('Invalid http status code');
- }
+ public $message = 'Invalid http status code';
}
-
diff --git a/src/Exceptions/Callback/CallbackException.php b/src/Exceptions/Callback/CallbackException.php
deleted file mode 100644
index e129cf0..0000000
--- a/src/Exceptions/Callback/CallbackException.php
+++ /dev/null
@@ -1,24 +0,0 @@
-warning($this->getMessage());
+ Log::build((array)SdkConfig::logging(self::LOG_CHANNEL))->error($this->getMessage());
}
/**
@@ -44,7 +44,7 @@ final public function render()
if (env('LOG_LEVEL') === 'debug') {
return new JsonResponse(
Format::with(JsonExceptionFormatter::class)->format($this->getMessage()),
- $this->getCode()
+ 500
);
}
}
diff --git a/src/Formatters/JsonExceptionFormatter.php b/src/Formatters/JsonExceptionFormatter.php
index edf99ed..8e3a6e9 100644
--- a/src/Formatters/JsonExceptionFormatter.php
+++ b/src/Formatters/JsonExceptionFormatter.php
@@ -15,7 +15,7 @@ public function format($data): array
{
return [
'type' => 'error',
- 'message' => $data instanceof SdkException ? $data->getMessage() : $data
+ 'message' => $data
];
}
}
diff --git a/src/Foundation/Core/Api/Request.php b/src/Foundation/Core/Api/Request.php
index 3d7821e..53524ef 100644
--- a/src/Foundation/Core/Api/Request.php
+++ b/src/Foundation/Core/Api/Request.php
@@ -5,7 +5,6 @@
use GuzzleHttp\Exception\RequestException;
use Hopex\VkSdk\Exceptions\Api\ApiException;
use Hopex\VkSdk\Exceptions\Api\HttpStatusCodeException;
-use Hopex\VkSdk\Exceptions\SdkException;
use Hopex\VkSdk\Facades\Format;
use Hopex\VkSdk\Facades\SdkConfig;
use Hopex\VkSdk\Formatters\ArrayParametersRequestFormatter;
@@ -59,14 +58,14 @@ public function call(string $method, array $args = []): Collection
$arguments = Format::with(ClearEmptiesParametersRequestFormatter::class)
->with(ArrayParametersRequestFormatter::class)
->format($args);
- $arguments['access_token'] = $arguments['access_token'] ?? $this->token;
- $arguments['v'] = $arguments['v'] ?? $this->version;
- $arguments['lang'] = $arguments['lang'] ?? $this->language;
+ $arguments['access_token'] = $arguments['access_token'] ?? $this->getToken();
+ $arguments['v'] = $arguments['v'] ?? $this->getVersion();
+ $arguments['lang'] = $arguments['lang'] ?? $this->getLanguage();
try {
$response = Http::timeout(10)->get($this->makeUrl($method), $arguments);
- } catch (RequestException $e) {
- throw new SdkException($e->getMessage(), 500);
+ } catch (RequestException) {
+ throw new ApiException();
}
throw_if($response->status() != 200, HttpStatusCodeException::class);
@@ -74,35 +73,19 @@ public function call(string $method, array $args = []): Collection
$body = collect(is_array($body) ? $body : []);
if ($body->has('error')) {
- throw new ApiException(code: $body->get('error')['error_code']);
+ throw new ApiException((int)$body->get('error')['error_code']);
}
return collect($body->has('response') ? $body->get('response') : $body);
}
-// public function upload(string $url, string $param, string $path)
-// {
-// Http::post($url);
-// try {
-// $response = $this->http_client->upload($url, $param, $path);
-// } catch (TransportRequestException $e) {
-// throw new VKClientException($e);
-// }
-//
-// return $this->parseResponse($response);
-// }
-
/**
* @param string $method
* @return string
*/
private function makeUrl(string $method): string
{
- return sprintf(
- '%s/%s',
- SdkConfig::api('endpoint'),
- $method
- );
+ return sprintf('%s/%s', SdkConfig::api('endpoint'), $method);
}
/**
diff --git a/src/Foundation/Format.php b/src/Foundation/Format.php
index 2517565..709f2ad 100644
--- a/src/Foundation/Format.php
+++ b/src/Foundation/Format.php
@@ -20,7 +20,7 @@ class Format implements CanFormatContract
public function with(string $formatter): static
{
$formatter = new $formatter();
- if ($formatter instanceof CanFormat) {
+ if ($formatter instanceof CanFormatContract) {
$this->formatters[] = $formatter;
}
return $this;
diff --git a/src/Foundation/SdkConfig.php b/src/Foundation/SdkConfig.php
index 1bc58d6..6d0dc1a 100644
--- a/src/Foundation/SdkConfig.php
+++ b/src/Foundation/SdkConfig.php
@@ -8,16 +8,14 @@
*/
class SdkConfig
{
- private const CONFIG_PREFIX = 'vk-sdk';
- private const CONFIG_ROUTES = 'routes';
- private const CONFIG_API = 'api';
- private const CONFIG_GROUPS = 'groups';
- private const CONFIG_LOGGING = 'logging';
- private const CONFIG_APPS = 'apps';
+ private const CONFIG_PREFIX = 'vk-sdk';
+ private const CONFIG_ROUTES = 'routes';
+ private const CONFIG_API = 'api';
+ private const CONFIG_GROUPS = 'groups';
+ private const CONFIG_LOGGING = 'logging';
+ private const CONFIG_APPS = 'apps';
/**
- * Общий запрос к конфигурации.
- *
* @param string|null $key
* @return array|string|null
*/
@@ -27,8 +25,6 @@ public function query(string $key = null): array|string|null
}
/**
- * Конфигурация маршрутизации.
- *
* @param string|null $key
* @return array|string|null
*/
@@ -38,8 +34,6 @@ public function routes(string $key = null): array|string|null
}
/**
- * Конфигурация логирования.
- *
* @param string|null $key
* @return array|string|null
*/
@@ -49,8 +43,6 @@ public function logging(string $key = null): array|string|null
}
/**
- * Конфигурация подключения к API.
- *
* @param string|null $key
* @return array|string|null
*/
@@ -60,8 +52,6 @@ public function api(string $key = null): array|string|null
}
/**
- * Конфигурация групп.
- *
* @param string|null $key
* @return array|string|null
*/
@@ -71,8 +61,6 @@ public function groups(string $key = null): array|string|null
}
/**
- * Конфигурация приложений.
- *
* @param string|null $key
* @return array|string|null
*/
diff --git a/src/Services/CallbackEventService.php b/src/Services/CallbackEventService.php
index 1ec10d5..841c6d9 100644
--- a/src/Services/CallbackEventService.php
+++ b/src/Services/CallbackEventService.php
@@ -4,9 +4,9 @@
use Hopex\VkSdk\Contracts\CallbackEventsContract;
use Hopex\VkSdk\Exceptions\Callback\SecretException;
-use Hopex\VkSdk\Exceptions\Callback\TableNotFoundException;
use Hopex\VkSdk\Exceptions\Callback\UnknownEventException;
use Hopex\VkSdk\Exceptions\Callback\UnknownGroupIdException;
+use Hopex\VkSdk\Exceptions\Database\DatabaseOrTableNotFoundException;
use Hopex\VkSdk\Facades\SdkConfig;
use Hopex\VkSdk\Foundation\Core\Callback\BaseEvent;
use Hopex\VkSdk\Models\Event;
@@ -45,13 +45,17 @@ public function division(): mixed
$event = $this->request->json('type');
try {
- if (SdkConfig::groups("$groupId.allow_retry_events") || !Event::where('event_id', $eventId)->first()) {
+ if (
+ SdkConfig::groups("$groupId.allow_retry_events") ||
+ !Event::where('event_id', $eventId)->first() ||
+ !$eventId
+ ) {
Event::updateOrCreate($this->request->only('group_id', 'type', 'event_id'));
} else {
- return 'ok';
+ return self::OK;
}
} catch (QueryException) {
- throw new TableNotFoundException();
+ throw new DatabaseOrTableNotFoundException();
}
switch ($event) {
From 4eca36a53e1b19cf6c1bdb84a14b552942fa877c Mon Sep 17 00:00:00 2001
From: Schizo
Date: Wed, 4 Jan 2023 07:25:04 +0300
Subject: [PATCH 16/24] =?UTF-8?q?=D0=98=D1=81=D0=BF=D1=80=D0=B0=D0=B2?=
=?UTF-8?q?=D0=BB=D0=B5=D0=BD=20=D0=B1=D0=B0=D0=B3=20=D1=81=20SSL=20=D1=81?=
=?UTF-8?q?=D0=B5=D1=80=D1=82=D0=B8=D1=84=D0=B8=D0=B0=D1=82=D0=BE=D0=BC.?=
=?UTF-8?q?=20=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB=D0=B5=D0=BD=D0=B0=20?=
=?UTF-8?q?=D0=B4=D0=B8=D0=BD=D0=B0=D0=BC=D0=B8=D1=87=D0=B5=D1=81=D0=BA?=
=?UTF-8?q?=D0=B0=D1=8F=20=D0=B8=D0=BD=D0=B8=D1=86=D0=B8=D0=BB=D0=B8=D0=B7?=
=?UTF-8?q?=D0=B0=D1=86=D0=B8=D1=8F=20=D1=81=D1=83=D1=89=D0=BD=D0=BE=D1=81?=
=?UTF-8?q?=D1=82=D0=B8=20=D1=81=D0=BE=D0=B1=D1=8B=D1=82=D0=B8=D1=8F?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
README_RU.md | 8 +-
composer.json | 11 +-
src/.root/config/vk-sdk.php | 13 +-
.../migrations/create_events_table.php | 3 +-
src/.root/lang/ru.php | 2 +
src/Contracts/CallbackEventsContract.php | 442 +++++++++---------
src/Exceptions/Api/ApiException.php | 1 -
src/Exceptions/Api/ApiExceptionMapper.php | 2 +-
.../Callback/UnknownEntityException.php | 14 +
.../DatabaseOrTableNotFoundException.php | 1 -
src/Exceptions/SdkException.php | 4 +-
src/Facades/RequestFields.php | 2 +-
src/Facades/VkApi.php | 3 +-
src/Formatters/JsonExceptionFormatter.php | 1 -
src/Formatters/JsonLogFormatter.php | 6 +-
src/Foundation/Core/Api/Client.php | 8 +-
src/Foundation/Core/Api/OAuth.php | 6 +-
src/Foundation/Core/Api/Request.php | 53 ++-
src/Foundation/Core/Callback/BaseEvent.php | 12 +-
.../Core/Callback/EventsHandler.php | 328 +------------
.../Client/ClientFields.php | 14 +-
.../Database/Database.php | 136 +++---
.../Database/DatabaseCollection.php | 4 +-
.../Database/DatabaseField.php | 16 +-
.../Database/Fields/Chair/ChairField.php | 4 +-
.../Fields/Chair/ChairFieldsCollection.php | 17 +
.../Fields/Chair/ChairRequestFields.php | 6 +-
.../Database/Fields/City/CityField.php | 14 +
.../Fields/City/CityFieldsCollection.php | 17 +
.../Fields/City/CityRequestFields.php | 8 +-
.../Database/Fields/Country/CountryField.php | 14 +
.../Country/CountryFieldsCollection.php | 17 +
.../Fields/Country/CountryRequestFields.php | 6 +-
.../Database/Fields/Faculty/FacultyField.php | 14 +
.../Faculty/FacultyFieldsCollection.php | 17 +
.../Fields/Faculty/FacultyRequestFields.php | 6 +-
.../Fields/Metro/MetroStationField.php | 6 +-
.../Metro/MetroStationFieldsCollection.php | 6 +-
.../Metro/MetroStationRequestFields.php | 8 +-
.../Database/Fields/Region/RegionField.php | 14 +
.../Fields/Region/RegionFieldsCollection.php | 17 +
.../Fields/Region/RegionRequestFields.php | 8 +-
.../School/SchoolClasses/SchoolClassField.php | 6 +-
.../SchoolClassFieldsCollection.php | 6 +-
.../SchoolClassRequestFields.php | 4 +-
.../Database/Fields/School/SchoolField.php | 14 +
.../Fields/School/SchoolFieldsCollection.php | 17 +
.../Fields/School/SchoolRequestFields.php | 8 +-
.../Fields/University/UniversityField.php | 14 +
.../University/UniversityFieldsCollection.php | 18 +
.../University/UniversityRequestFields.php | 8 +-
.../Traits/DatabaseCanExtendRequest.php | 4 +-
.../Traits/DatabaseEnumerableRequest.php | 4 +-
.../Traits/DatabaseSearchableRequest.php | 4 +-
src/Foundation/Core/Entities/Groups/Group.php | 224 +++++++++
.../Groups/GroupFields.php | 28 +-
.../Groups/GroupRequestFields.php | 8 +-
.../Messages/Attachments/Audio/Audio.php | 46 ++
.../Entities/Messages/Attachments/Photo.php | 81 ++++
.../Core/Entities/Messages/Message.php | 342 ++++++++++++++
.../Messages/MessageFields.php | 32 +-
.../Messages/MessageRequestFields.php | 14 +-
.../{Models => Entities}/RequestFields.php | 28 +-
.../Users/Enums/UserNameCases.php | 4 +-
.../Users/Enums/UserReportTypes.php | 4 +-
.../Users/ProfileFields/CareerField.php | 4 +-
.../Users/ProfileFields/EducationField.php | 4 +-
.../Users/ProfileFields/LastSeenField.php | 4 +-
.../Users/ProfileFields/MilitaryField.php | 20 +-
.../Users/ProfileFields/RelativeField.php | 30 +-
.../Users/ProfileFields/SchoolField.php | 25 +-
.../Core/{Models => Entities}/Users/User.php | 6 +-
.../Users/UserProfileFields.php | 22 +-
.../Users/UserRequestFields.php | 4 +-
.../Fields/Chair/ChairFieldsCollection.php | 17 -
.../Models/Database/Fields/City/CityField.php | 14 -
.../Fields/City/CityFieldsCollection.php | 17 -
.../Database/Fields/Country/CountryField.php | 14 -
.../Country/CountryFieldsCollection.php | 17 -
.../Database/Fields/Faculty/FacultyField.php | 14 -
.../Faculty/FacultyFieldsCollection.php | 17 -
.../Database/Fields/Region/RegionField.php | 14 -
.../Fields/Region/RegionFieldsCollection.php | 17 -
.../Database/Fields/School/SchoolField.php | 14 -
.../Fields/School/SchoolFieldsCollection.php | 17 -
.../Fields/University/UniversityField.php | 14 -
.../University/UniversityFieldsCollection.php | 18 -
src/Foundation/Core/Models/Groups/Group.php | 176 -------
.../Messages/Attachments/Audio/Audio.php | 46 --
.../Models/Messages/Attachments/Photo.php | 81 ----
.../Core/Models/Messages/Message.php | 197 --------
src/Foundation/Format.php | 2 +-
src/Foundation/SdkConfig.php | 8 +-
src/Models/Event.php | 4 +-
src/Providers/ServiceProvider.php | 4 +-
src/Services/CallbackEventService.php | 50 +-
96 files changed, 1523 insertions(+), 1575 deletions(-)
create mode 100644 src/Exceptions/Callback/UnknownEntityException.php
rename src/Foundation/Core/{Models => Entities}/Client/ClientFields.php (76%)
rename src/Foundation/Core/{Models => Entities}/Database/Database.php (78%)
rename src/Foundation/Core/{Models => Entities}/Database/DatabaseCollection.php (90%)
rename src/Foundation/Core/{Models => Entities}/Database/DatabaseField.php (90%)
rename src/Foundation/Core/{Models => Entities}/Database/Fields/Chair/ChairField.php (84%)
create mode 100644 src/Foundation/Core/Entities/Database/Fields/Chair/ChairFieldsCollection.php
rename src/Foundation/Core/{Models => Entities}/Database/Fields/Chair/ChairRequestFields.php (64%)
create mode 100644 src/Foundation/Core/Entities/Database/Fields/City/CityField.php
create mode 100644 src/Foundation/Core/Entities/Database/Fields/City/CityFieldsCollection.php
rename src/Foundation/Core/{Models => Entities}/Database/Fields/City/CityRequestFields.php (81%)
create mode 100644 src/Foundation/Core/Entities/Database/Fields/Country/CountryField.php
create mode 100644 src/Foundation/Core/Entities/Database/Fields/Country/CountryFieldsCollection.php
rename src/Foundation/Core/{Models => Entities}/Database/Fields/Country/CountryRequestFields.php (81%)
create mode 100644 src/Foundation/Core/Entities/Database/Fields/Faculty/FacultyField.php
create mode 100644 src/Foundation/Core/Entities/Database/Fields/Faculty/FacultyFieldsCollection.php
rename src/Foundation/Core/{Models => Entities}/Database/Fields/Faculty/FacultyRequestFields.php (65%)
rename src/Foundation/Core/{Models => Entities}/Database/Fields/Metro/MetroStationField.php (59%)
rename src/Foundation/Core/{Models => Entities}/Database/Fields/Metro/MetroStationFieldsCollection.php (50%)
rename src/Foundation/Core/{Models => Entities}/Database/Fields/Metro/MetroStationRequestFields.php (72%)
create mode 100644 src/Foundation/Core/Entities/Database/Fields/Region/RegionField.php
create mode 100644 src/Foundation/Core/Entities/Database/Fields/Region/RegionFieldsCollection.php
rename src/Foundation/Core/{Models => Entities}/Database/Fields/Region/RegionRequestFields.php (59%)
rename src/Foundation/Core/{Models => Entities}/Database/Fields/School/SchoolClasses/SchoolClassField.php (70%)
rename src/Foundation/Core/{Models => Entities}/Database/Fields/School/SchoolClasses/SchoolClassFieldsCollection.php (75%)
rename src/Foundation/Core/{Models => Entities}/Database/Fields/School/SchoolClasses/SchoolClassRequestFields.php (70%)
create mode 100644 src/Foundation/Core/Entities/Database/Fields/School/SchoolField.php
create mode 100644 src/Foundation/Core/Entities/Database/Fields/School/SchoolFieldsCollection.php
rename src/Foundation/Core/{Models => Entities}/Database/Fields/School/SchoolRequestFields.php (58%)
create mode 100644 src/Foundation/Core/Entities/Database/Fields/University/UniversityField.php
create mode 100644 src/Foundation/Core/Entities/Database/Fields/University/UniversityFieldsCollection.php
rename src/Foundation/Core/{Models => Entities}/Database/Fields/University/UniversityRequestFields.php (70%)
rename src/Foundation/Core/{Models => Entities}/Database/Traits/DatabaseCanExtendRequest.php (74%)
rename src/Foundation/Core/{Models => Entities}/Database/Traits/DatabaseEnumerableRequest.php (82%)
rename src/Foundation/Core/{Models => Entities}/Database/Traits/DatabaseSearchableRequest.php (72%)
create mode 100644 src/Foundation/Core/Entities/Groups/Group.php
rename src/Foundation/Core/{Models => Entities}/Groups/GroupFields.php (93%)
rename src/Foundation/Core/{Models => Entities}/Groups/GroupRequestFields.php (94%)
create mode 100644 src/Foundation/Core/Entities/Messages/Attachments/Audio/Audio.php
create mode 100644 src/Foundation/Core/Entities/Messages/Attachments/Photo.php
create mode 100644 src/Foundation/Core/Entities/Messages/Message.php
rename src/Foundation/Core/{Models => Entities}/Messages/MessageFields.php (75%)
rename src/Foundation/Core/{Models => Entities}/Messages/MessageRequestFields.php (98%)
rename src/Foundation/Core/{Models => Entities}/RequestFields.php (64%)
rename src/Foundation/Core/{Models => Entities}/Users/Enums/UserNameCases.php (69%)
rename src/Foundation/Core/{Models => Entities}/Users/Enums/UserReportTypes.php (64%)
rename src/Foundation/Core/{Models => Entities}/Users/ProfileFields/CareerField.php (93%)
rename src/Foundation/Core/{Models => Entities}/Users/ProfileFields/EducationField.php (93%)
rename src/Foundation/Core/{Models => Entities}/Users/ProfileFields/LastSeenField.php (86%)
rename src/Foundation/Core/{Models => Entities}/Users/ProfileFields/MilitaryField.php (92%)
rename src/Foundation/Core/{Models => Entities}/Users/ProfileFields/RelativeField.php (86%)
rename src/Foundation/Core/{Models => Entities}/Users/ProfileFields/SchoolField.php (95%)
rename src/Foundation/Core/{Models => Entities}/Users/User.php (93%)
rename src/Foundation/Core/{Models => Entities}/Users/UserProfileFields.php (94%)
rename src/Foundation/Core/{Models => Entities}/Users/UserRequestFields.php (96%)
delete mode 100644 src/Foundation/Core/Models/Database/Fields/Chair/ChairFieldsCollection.php
delete mode 100644 src/Foundation/Core/Models/Database/Fields/City/CityField.php
delete mode 100644 src/Foundation/Core/Models/Database/Fields/City/CityFieldsCollection.php
delete mode 100644 src/Foundation/Core/Models/Database/Fields/Country/CountryField.php
delete mode 100644 src/Foundation/Core/Models/Database/Fields/Country/CountryFieldsCollection.php
delete mode 100644 src/Foundation/Core/Models/Database/Fields/Faculty/FacultyField.php
delete mode 100644 src/Foundation/Core/Models/Database/Fields/Faculty/FacultyFieldsCollection.php
delete mode 100644 src/Foundation/Core/Models/Database/Fields/Region/RegionField.php
delete mode 100644 src/Foundation/Core/Models/Database/Fields/Region/RegionFieldsCollection.php
delete mode 100644 src/Foundation/Core/Models/Database/Fields/School/SchoolField.php
delete mode 100644 src/Foundation/Core/Models/Database/Fields/School/SchoolFieldsCollection.php
delete mode 100644 src/Foundation/Core/Models/Database/Fields/University/UniversityField.php
delete mode 100644 src/Foundation/Core/Models/Database/Fields/University/UniversityFieldsCollection.php
delete mode 100644 src/Foundation/Core/Models/Groups/Group.php
delete mode 100644 src/Foundation/Core/Models/Messages/Attachments/Audio/Audio.php
delete mode 100644 src/Foundation/Core/Models/Messages/Attachments/Photo.php
delete mode 100644 src/Foundation/Core/Models/Messages/Message.php
diff --git a/README_RU.md b/README_RU.md
index 8b57491..ffc1744 100644
--- a/README_RU.md
+++ b/README_RU.md
@@ -12,21 +12,26 @@
> #### You can read the [English version](https://github.com/H0pex/laravel-vk-sdk/README_EN)
-[Laravel](https://github.com/laravel/laravel) библиотека для упрощенного использования API модулей социальной сети ВКонтакте.
+[Laravel](https://github.com/laravel/laravel) библиотека для упрощенного использования API модулей социальной сети
+ВКонтакте.
Предназначена для быстрого развертывания приложений-ботов, а также использования VK API в одностороннем порядке.
# Установка
+
Осуществить установку можно используя [composer](https://getcomposer.org/):
+
```
composer require hopex/vk-api-sdk
```
Публикация необходимых ресурсов:
+
```
php artisan vendor:publish --tag=vk-sdk-config --tag=vk-sdk-lang
```
Провайдер и фасады будут автоматически зарегистрированы, однако вы можете вручную добавить их в `config/app.php`.
+
```php
'providers' => [
// ...
@@ -41,4 +46,5 @@ php artisan vendor:publish --tag=vk-sdk-config --tag=vk-sdk-lang
```
# Лицензия
+
[MIT License](https://github.com/H0pex/vk-api-sdk/LICENSE)
diff --git a/composer.json b/composer.json
index fcb9747..acf3d45 100644
--- a/composer.json
+++ b/composer.json
@@ -4,7 +4,13 @@
"type": "library",
"license": "MIT",
"version": "0.0.2",
- "keywords": ["php", "laravel", "vk", "api", "sdk"],
+ "keywords": [
+ "php",
+ "laravel",
+ "vk",
+ "api",
+ "sdk"
+ ],
"authors": [
{
"name": "Schizo",
@@ -17,9 +23,6 @@
"php": "^8",
"ext-json": "*"
},
- "require-dev": {
- "barryvdh/laravel-ide-helper": "^2.12"
- },
"autoload": {
"psr-4": {
"Hopex\\VkSdk\\": "src/"
diff --git a/src/.root/config/vk-sdk.php b/src/.root/config/vk-sdk.php
index c8c8aec..33b77ba 100644
--- a/src/.root/config/vk-sdk.php
+++ b/src/.root/config/vk-sdk.php
@@ -1,5 +1,8 @@
[
- 'auth' => 'https://oauth.vk.com',
- 'endpoint' => 'https://api.vk.com/method',
- 'version' => '5.131',
+ 'auth' => 'https://oauth.vk.com',
+ 'endpoint' => 'https://api.vk.com/method',
+ 'version' => '5.131',
],
'groups' => [
@@ -69,7 +72,7 @@
'code' => '745cc77d276cf36c694e',
'verify' => true,
],
- 'events' => \App\VK\Chat::class,
+ 'events' => Chat::class,
'allow_retry_events' => true,
],
],
@@ -107,7 +110,7 @@
'permissions' => 0755,
'locking' => true,
'days' => 30,
- 'tap' => \Hopex\VkSdk\Formatters\JsonLogFormatter::class,
+ 'tap' => JsonLogFormatter::class,
],
],
],
diff --git a/src/.root/database/migrations/create_events_table.php b/src/.root/database/migrations/create_events_table.php
index 08b963d..2b93944 100644
--- a/src/.root/database/migrations/create_events_table.php
+++ b/src/.root/database/migrations/create_events_table.php
@@ -4,8 +4,7 @@
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
-return new class extends Migration
-{
+return new class extends Migration {
/**
* @return void
*/
diff --git a/src/.root/lang/ru.php b/src/.root/lang/ru.php
index 9c1dd54..9fb7c06 100644
--- a/src/.root/lang/ru.php
+++ b/src/.root/lang/ru.php
@@ -166,4 +166,6 @@
'Unknown callback event' => 'Неизвестное событие',
'Invalid http status code' => 'Недопустимый код состояния http',
'Database or table not found' => 'База данных или таблица не найдены',
+ 'Unknown or unsupported entity used' => 'Используется неизвестная или не поддерживаямая сущность',
+ 'Unknown api exception' => 'Неизвестное исключение API',
];
diff --git a/src/Contracts/CallbackEventsContract.php b/src/Contracts/CallbackEventsContract.php
index 514e74c..a4ba9a6 100644
--- a/src/Contracts/CallbackEventsContract.php
+++ b/src/Contracts/CallbackEventsContract.php
@@ -2,7 +2,7 @@
namespace Hopex\VkSdk\Contracts;
-use Hopex\VkSdk\Foundation\Core\Callback\BaseEvent;
+use Hopex\VkSdk\Foundation\Core\Entities\Messages\MessageFields;
/**
* Interface CallbackEventsContract
@@ -11,224 +11,224 @@
interface CallbackEventsContract
{
/**
- * @param BaseEvent $event
- * @return void
- */
- public function message_new(BaseEvent $event): void;
-
- /**
- * @param BaseEvent $event
- * @return void
- */
- public function message_reply(BaseEvent $event): void;
-
- /**
- * @param BaseEvent $event
- * @return void
- */
- public function message_allow(BaseEvent $event): void;
-
- /**
- * @param BaseEvent $event
- * @return void
- */
- public function message_deny(BaseEvent $event): void;
-
- /**
- * @param BaseEvent $event
- * @return void
- */
- public function photo_new(BaseEvent $event): void;
-
- /**
- * @param BaseEvent $event
- * @return void
- */
- public function photo_comment_new(BaseEvent $event): void;
-
- /**
- * @param BaseEvent $event
- * @return void
- */
- public function photo_comment_edit(BaseEvent $event): void;
-
- /**
- * @param BaseEvent $event
- * @return void
- */
- public function photo_comment_restore(BaseEvent $event): void;
-
- /**
- * @param BaseEvent $event
- * @return void
- */
- public function photo_comment_delete(BaseEvent $event): void;
-
- /**
- * @param BaseEvent $event
- * @return void
- */
- public function audio_new(BaseEvent $event): void;
-
- /**
- * @param BaseEvent $event
- * @return void
- */
- public function video_new(BaseEvent $event): void;
-
- /**
- * @param BaseEvent $event
- * @return void
- */
- public function video_comment_new(BaseEvent $event): void;
-
- /**
- * @param BaseEvent $event
- * @return void
- */
- public function video_comment_edit(BaseEvent $event): void;
-
- /**
- * @param BaseEvent $event
- * @return void
- */
- public function video_comment_restore(BaseEvent $event): void;
-
- /**
- * @param BaseEvent $event
- * @return void
- */
- public function video_comment_delete(BaseEvent $event): void;
-
- /**
- * @param BaseEvent $event
- * @return void
- */
- public function wall_post_new(BaseEvent $event): void;
-
- /**
- * @param BaseEvent $event
- * @return void
- */
- public function wall_repost(BaseEvent $event): void;
-
- /**
- * @param BaseEvent $event
- * @return void
- */
- public function wall_reply_new(BaseEvent $event): void;
-
- /**
- * @param BaseEvent $event
- * @return void
- */
- public function wall_reply_edit(BaseEvent $event): void;
-
- /**
- * @param BaseEvent $event
- * @return void
- */
- public function wall_reply_restore(BaseEvent $event): void;
-
- /**
- * @param BaseEvent $event
- * @return void
- */
- public function wall_reply_delete(BaseEvent $event): void;
-
- /**
- * @param BaseEvent $event
- * @return void
- */
- public function board_post_new(BaseEvent $event): void;
-
- /**
- * @param BaseEvent $event
- * @return void
- */
- public function board_post_edit(BaseEvent $event): void;
-
- /**
- * @param BaseEvent $event
- * @return void
- */
- public function board_post_restore(BaseEvent $event): void;
-
- /**
- * @param BaseEvent $event
- * @return void
- */
- public function board_post_delete(BaseEvent $event): void;
-
- /**
- * @param BaseEvent $event
- * @return void
- */
- public function market_comment_new(BaseEvent $event): void;
-
- /**
- * @param BaseEvent $event
- * @return void
- */
- public function market_comment_edit(BaseEvent $event): void;
-
- /**
- * @param BaseEvent $event
- * @return void
- */
- public function market_comment_restore(BaseEvent $event): void;
-
- /**
- * @param BaseEvent $event
- * @return void
- */
- public function market_comment_delete(BaseEvent $event): void;
-
- /**
- * @param BaseEvent $event
- * @return void
- */
- public function group_leave(BaseEvent $event): void;
-
- /**
- * @param BaseEvent $event
- * @return void
- */
- public function group_join(BaseEvent $event): void;
-
- /**
- * @param BaseEvent $event
- * @return void
- */
- public function group_change_settings(BaseEvent $event): void;
-
- /**
- * @param BaseEvent $event
- * @return void
- */
- public function group_change_photo(BaseEvent $event): void;
-
- /**
- * @param BaseEvent $event
- * @return void
- */
- public function group_officers_edit(BaseEvent $event): void;
-
- /**
- * @param BaseEvent $event
- * @return void
- */
- public function poll_vote_new(BaseEvent $event): void;
-
- /**
- * @param BaseEvent $event
- * @return void
- */
- public function user_block(BaseEvent $event): void;
-
- /**
- * @param BaseEvent $event
- * @return void
- */
- public function user_unblock(BaseEvent $event): void;
+ * @param MessageFields $message
+ * @return void
+ */
+ public function message_new(MessageFields $message): void;
+
+ /**
+ * @param MessageFields $message
+ * @return void
+ */
+ public function message_reply(MessageFields $message): void;
+
+ /**
+ * @param MessageFields $message
+ * @return void
+ */
+ public function message_allow(MessageFields $message): void;
+
+ /**
+ * @param MessageFields $message
+ * @return void
+ */
+ public function message_deny(MessageFields $message): void;
+
+// /**
+// * @param BaseEvent $event
+// * @return void
+// */
+// public function photo_new(BaseEvent $event): void;
+//
+// /**
+// * @param BaseEvent $event
+// * @return void
+// */
+// public function photo_comment_new(BaseEvent $event): void;
+//
+// /**
+// * @param BaseEvent $event
+// * @return void
+// */
+// public function photo_comment_edit(BaseEvent $event): void;
+//
+// /**
+// * @param BaseEvent $event
+// * @return void
+// */
+// public function photo_comment_restore(BaseEvent $event): void;
+//
+// /**
+// * @param BaseEvent $event
+// * @return void
+// */
+// public function photo_comment_delete(BaseEvent $event): void;
+//
+// /**
+// * @param BaseEvent $event
+// * @return void
+// */
+// public function audio_new(BaseEvent $event): void;
+//
+// /**
+// * @param BaseEvent $event
+// * @return void
+// */
+// public function video_new(BaseEvent $event): void;
+//
+// /**
+// * @param BaseEvent $event
+// * @return void
+// */
+// public function video_comment_new(BaseEvent $event): void;
+//
+// /**
+// * @param BaseEvent $event
+// * @return void
+// */
+// public function video_comment_edit(BaseEvent $event): void;
+//
+// /**
+// * @param BaseEvent $event
+// * @return void
+// */
+// public function video_comment_restore(BaseEvent $event): void;
+//
+// /**
+// * @param BaseEvent $event
+// * @return void
+// */
+// public function video_comment_delete(BaseEvent $event): void;
+//
+// /**
+// * @param BaseEvent $event
+// * @return void
+// */
+// public function wall_post_new(BaseEvent $event): void;
+//
+// /**
+// * @param BaseEvent $event
+// * @return void
+// */
+// public function wall_repost(BaseEvent $event): void;
+//
+// /**
+// * @param BaseEvent $event
+// * @return void
+// */
+// public function wall_reply_new(BaseEvent $event): void;
+//
+// /**
+// * @param BaseEvent $event
+// * @return void
+// */
+// public function wall_reply_edit(BaseEvent $event): void;
+//
+// /**
+// * @param BaseEvent $event
+// * @return void
+// */
+// public function wall_reply_restore(BaseEvent $event): void;
+//
+// /**
+// * @param BaseEvent $event
+// * @return void
+// */
+// public function wall_reply_delete(BaseEvent $event): void;
+//
+// /**
+// * @param BaseEvent $event
+// * @return void
+// */
+// public function board_post_new(BaseEvent $event): void;
+//
+// /**
+// * @param BaseEvent $event
+// * @return void
+// */
+// public function board_post_edit(BaseEvent $event): void;
+//
+// /**
+// * @param BaseEvent $event
+// * @return void
+// */
+// public function board_post_restore(BaseEvent $event): void;
+//
+// /**
+// * @param BaseEvent $event
+// * @return void
+// */
+// public function board_post_delete(BaseEvent $event): void;
+//
+// /**
+// * @param BaseEvent $event
+// * @return void
+// */
+// public function market_comment_new(BaseEvent $event): void;
+//
+// /**
+// * @param BaseEvent $event
+// * @return void
+// */
+// public function market_comment_edit(BaseEvent $event): void;
+//
+// /**
+// * @param BaseEvent $event
+// * @return void
+// */
+// public function market_comment_restore(BaseEvent $event): void;
+//
+// /**
+// * @param BaseEvent $event
+// * @return void
+// */
+// public function market_comment_delete(BaseEvent $event): void;
+//
+// /**
+// * @param BaseEvent $event
+// * @return void
+// */
+// public function group_leave(BaseEvent $event): void;
+//
+// /**
+// * @param BaseEvent $event
+// * @return void
+// */
+// public function group_join(BaseEvent $event): void;
+//
+// /**
+// * @param BaseEvent $event
+// * @return void
+// */
+// public function group_change_settings(BaseEvent $event): void;
+//
+// /**
+// * @param BaseEvent $event
+// * @return void
+// */
+// public function group_change_photo(BaseEvent $event): void;
+//
+// /**
+// * @param BaseEvent $event
+// * @return void
+// */
+// public function group_officers_edit(BaseEvent $event): void;
+//
+// /**
+// * @param BaseEvent $event
+// * @return void
+// */
+// public function poll_vote_new(BaseEvent $event): void;
+//
+// /**
+// * @param BaseEvent $event
+// * @return void
+// */
+// public function user_block(BaseEvent $event): void;
+//
+// /**
+// * @param BaseEvent $event
+// * @return void
+// */
+// public function user_unblock(BaseEvent $event): void;
}
diff --git a/src/Exceptions/Api/ApiException.php b/src/Exceptions/Api/ApiException.php
index 82e046b..503b16c 100644
--- a/src/Exceptions/Api/ApiException.php
+++ b/src/Exceptions/Api/ApiException.php
@@ -3,7 +3,6 @@
namespace Hopex\VkSdk\Exceptions\Api;
use Hopex\VkSdk\Exceptions\SdkException;
-use Throwable;
/**
* Class ApiException
diff --git a/src/Exceptions/Api/ApiExceptionMapper.php b/src/Exceptions/Api/ApiExceptionMapper.php
index 6568d24..91aa6fa 100644
--- a/src/Exceptions/Api/ApiExceptionMapper.php
+++ b/src/Exceptions/Api/ApiExceptionMapper.php
@@ -8,7 +8,7 @@
*/
class ApiExceptionMapper
{
- /** @var array|string[] */
+ /** @var array|string[] */
private static array $errors = [
'1' => "Unknown error occurred",
'2' => "Application is disabled. Enable your application or use test mode",
diff --git a/src/Exceptions/Callback/UnknownEntityException.php b/src/Exceptions/Callback/UnknownEntityException.php
new file mode 100644
index 0000000..661f601
--- /dev/null
+++ b/src/Exceptions/Callback/UnknownEntityException.php
@@ -0,0 +1,14 @@
+setJsonPrettyPrint(true)
- ->addJsonEncodeOption(JSON_UNESCAPED_UNICODE)
- ->addJsonEncodeOption(JSON_UNESCAPED_SLASHES);
+ ->setJsonPrettyPrint(true)
+ ->addJsonEncodeOption(JSON_UNESCAPED_UNICODE)
+ ->addJsonEncodeOption(JSON_UNESCAPED_SLASHES);
foreach ($data->getHandlers() as $handler) {
if (method_exists($handler, 'setFormatter'))
diff --git a/src/Foundation/Core/Api/Client.php b/src/Foundation/Core/Api/Client.php
index eae1747..fe5bee5 100644
--- a/src/Foundation/Core/Api/Client.php
+++ b/src/Foundation/Core/Api/Client.php
@@ -2,10 +2,10 @@
namespace Hopex\VkSdk\Foundation\Core\Api;
-use Hopex\VkSdk\Foundation\Core\Models\Database\Database;
-use Hopex\VkSdk\Foundation\Core\Models\Groups\Group;
-use Hopex\VkSdk\Foundation\Core\Models\Messages\Message;
-use Hopex\VkSdk\Foundation\Core\Models\Users\User;
+use Hopex\VkSdk\Foundation\Core\Entities\Database\Database;
+use Hopex\VkSdk\Foundation\Core\Entities\Groups\Group;
+use Hopex\VkSdk\Foundation\Core\Entities\Messages\Message;
+use Hopex\VkSdk\Foundation\Core\Entities\Users\User;
/**
* Class ApiClient
diff --git a/src/Foundation/Core/Api/OAuth.php b/src/Foundation/Core/Api/OAuth.php
index 8bddbc2..48b65ab 100644
--- a/src/Foundation/Core/Api/OAuth.php
+++ b/src/Foundation/Core/Api/OAuth.php
@@ -14,10 +14,10 @@
class OAuth
{
const SERVICE = 'access_token?client_id=%s&client_secret=%s&v=%s&grant_type=client_credentials';
- const AUTHORIZE_URI = 'authorize?client_id=%s&scope=%s&redirect_uri=%s&response_type=code&display=mobile';
+ const AUTHORIZE_URI = 'authorize?client_id=%s&scope=%s&redirect_uri=%s&response_type=code&display=mobile';
// const AUTHORIZE_URI = 'authorize?client_id=%s&scope=%s&redirect_uri=%s&response_type=token&display=mobile';
- const TOKEN_URI = 'access_token?client_id=%s&client_secret=%s&redirect_uri=%s&code=%s';
- const TIMEOUT = 30;
+ const TOKEN_URI = 'access_token?client_id=%s&client_secret=%s&redirect_uri=%s&code=%s';
+ const TIMEOUT = 30;
protected int $id;
protected string $secret;
diff --git a/src/Foundation/Core/Api/Request.php b/src/Foundation/Core/Api/Request.php
index 53524ef..10ef067 100644
--- a/src/Foundation/Core/Api/Request.php
+++ b/src/Foundation/Core/Api/Request.php
@@ -2,6 +2,7 @@
namespace Hopex\VkSdk\Foundation\Core\Api;
+use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use Hopex\VkSdk\Exceptions\Api\ApiException;
use Hopex\VkSdk\Exceptions\Api\HttpStatusCodeException;
@@ -9,6 +10,8 @@
use Hopex\VkSdk\Facades\SdkConfig;
use Hopex\VkSdk\Formatters\ArrayParametersRequestFormatter;
use Hopex\VkSdk\Formatters\ClearEmptiesParametersRequestFormatter;
+use Illuminate\Config\Repository;
+use Illuminate\Contracts\Foundation\Application;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Http;
use Throwable;
@@ -17,23 +20,20 @@
* Class Request
* @package Hopex\VkSdk\Foundation\Core\Api
*/
-class Request
+abstract class Request
{
- /**
- * @var string
- */
+ /** @var string */
private string $token;
- /**
- * @var string|float
- */
- private string|float $version;
+ /** @var string|float|array|null */
+ private string|float|null|array $version;
- /**
- * @var string
- */
+ /** @var string|Repository|Application|mixed */
private string $language;
+ /** @var Client */
+ private Client $HttpClient;
+
/**
* @param string $token
* @param string|float|null $version
@@ -44,14 +44,15 @@ public function __construct(string $token, string|float $version = null, string
$this->token = $token;
$this->version = $version ?? SdkConfig::api('version');
$this->language = $language ?? config('app.locale');
+ $this->HttpClient = new Client(['verify' => false]);
}
/**
* @param string $method
* @param array $args
* @return Collection
- * @throws ApiException
* @throws Throwable
+ * @throws ApiException
*/
public function call(string $method, array $args = []): Collection
{
@@ -63,8 +64,10 @@ public function call(string $method, array $args = []): Collection
$arguments['lang'] = $arguments['lang'] ?? $this->getLanguage();
try {
- $response = Http::timeout(10)->get($this->makeUrl($method), $arguments);
- } catch (RequestException) {
+ $response = Http::setClient($this->HttpClient)
+ ->timeout(10)
+ ->get($this->makeUrl($method), $arguments);
+ } catch (RequestException $e) {
throw new ApiException();
}
@@ -80,35 +83,35 @@ public function call(string $method, array $args = []): Collection
}
/**
- * @param string $method
* @return string
*/
- private function makeUrl(string $method): string
+ private function getToken(): string
{
- return sprintf('%s/%s', SdkConfig::api('endpoint'), $method);
+ return $this->token;
}
/**
- * @return string
+ * @return array|string|null
*/
- public function getToken(): string
+ private function getVersion(): array|string|null
{
- return $this->token;
+ return $this->version;
}
/**
- * @return array|string|null
+ * @return string
*/
- public function getVersion(): array|string|null
+ private function getLanguage(): string
{
- return $this->version;
+ return $this->language;
}
/**
+ * @param string $method
* @return string
*/
- public function getLanguage(): string
+ private function makeUrl(string $method): string
{
- return $this->language;
+ return sprintf('%s/%s', SdkConfig::api('endpoint'), $method);
}
}
diff --git a/src/Foundation/Core/Callback/BaseEvent.php b/src/Foundation/Core/Callback/BaseEvent.php
index afdf07e..a8bdfab 100644
--- a/src/Foundation/Core/Callback/BaseEvent.php
+++ b/src/Foundation/Core/Callback/BaseEvent.php
@@ -2,8 +2,8 @@
namespace Hopex\VkSdk\Foundation\Core\Callback;
-use Hopex\VkSdk\Foundation\Core\Models\Client\ClientFields;
-use Hopex\VkSdk\Foundation\Core\Models\Messages\MessageFields;
+use Hopex\VkSdk\Foundation\Core\Entities\Client\ClientFields;
+use Hopex\VkSdk\Foundation\Core\Entities\Messages\MessageFields;
use Illuminate\Support\Collection;
/**
@@ -12,10 +12,10 @@
*/
class BaseEvent
{
- private const GROUP_ID = 'group_id';
- private const OBJECT = 'object';
- private const MESSAGE = 'message';
- private const CLIENT_INFO = 'client_info';
+ private const GROUP_ID = 'group_id';
+ private const OBJECT = 'object';
+ private const MESSAGE = 'message';
+ private const CLIENT_INFO = 'client_info';
/**
* @var int
diff --git a/src/Foundation/Core/Callback/EventsHandler.php b/src/Foundation/Core/Callback/EventsHandler.php
index 062260d..d155b02 100644
--- a/src/Foundation/Core/Callback/EventsHandler.php
+++ b/src/Foundation/Core/Callback/EventsHandler.php
@@ -3,343 +3,43 @@
namespace Hopex\VkSdk\Foundation\Core\Callback;
use Hopex\VkSdk\Contracts\CallbackEventsContract;
+use Hopex\VkSdk\Foundation\Core\Entities\Messages\MessageFields;
/**
* Class EventsHandler
* @package Hopex\VkSdk\Foundation\Core\Callback
*/
-class EventsHandler implements CallbackEventsContract
+abstract class EventsHandler implements CallbackEventsContract
{
/**
- * @param BaseEvent $event
- * @return void
+ * @inheritDoc
*/
- public function message_new(BaseEvent $event): void
+ public function message_new(MessageFields $message): void
{
- //
+ // TODO: Implement message_new() method.
}
/**
- * @param BaseEvent $event
- * @return void
+ * @inheritDoc
*/
- public function message_reply(BaseEvent $event): void
+ public function message_reply(MessageFields $message): void
{
- //
+ // TODO: Implement message_reply() method.
}
/**
- * @param BaseEvent $event
- * @return void
+ * @inheritDoc
*/
- public function message_allow(BaseEvent $event): void
+ public function message_allow(MessageFields $message): void
{
- //
+ // TODO: Implement message_allow() method.
}
/**
- * @param BaseEvent $event
- * @return void
+ * @inheritDoc
*/
- public function message_deny(BaseEvent $event): void
+ public function message_deny(MessageFields $message): void
{
- //
- }
-
- /**
- * @param BaseEvent $event
- * @return void
- */
- public function photo_new(BaseEvent $event): void
- {
- //
- }
-
- /**
- * @param BaseEvent $event
- * @return void
- */
- public function photo_comment_new(BaseEvent $event): void
- {
- //
- }
-
- /**
- * @param BaseEvent $event
- * @return void
- */
- public function photo_comment_edit(BaseEvent $event): void
- {
- //
- }
-
- /**
- * @param BaseEvent $event
- * @return void
- */
- public function photo_comment_restore(BaseEvent $event): void
- {
- //
- }
-
- /**
- * @param BaseEvent $event
- * @return void
- */
- public function photo_comment_delete(BaseEvent $event): void
- {
- //
- }
-
- /**
- * @param BaseEvent $event
- * @return void
- */
- public function audio_new(BaseEvent $event): void
- {
- //
- }
-
- /**
- * @param BaseEvent $event
- * @return void
- */
- public function video_new(BaseEvent $event): void
- {
- //
- }
-
- /**
- * @param BaseEvent $event
- * @return void
- */
- public function video_comment_new(BaseEvent $event): void
- {
- //
- }
-
- /**
- * @param BaseEvent $event
- * @return void
- */
- public function video_comment_edit(BaseEvent $event): void
- {
- //
- }
-
- /**
- * @param BaseEvent $event
- * @return void
- */
- public function video_comment_restore(BaseEvent $event): void
- {
- //
- }
-
- /**
- * @param BaseEvent $event
- * @return void
- */
- public function video_comment_delete(BaseEvent $event): void
- {
- //
- }
-
- /**
- * @param BaseEvent $event
- * @return void
- */
- public function wall_post_new(BaseEvent $event): void
- {
- //
- }
-
- /**
- * @param BaseEvent $event
- * @return void
- */
- public function wall_repost(BaseEvent $event): void
- {
- //
- }
-
- /**
- * @param BaseEvent $event
- * @return void
- */
- public function wall_reply_new(BaseEvent $event): void
- {
- //
- }
-
- /**
- * @param BaseEvent $event
- * @return void
- */
- public function wall_reply_edit(BaseEvent $event): void
- {
- //
- }
-
- /**
- * @param BaseEvent $event
- * @return void
- */
- public function wall_reply_restore(BaseEvent $event): void
- {
- //
- }
-
- /**
- * @param BaseEvent $event
- * @return void
- */
- public function wall_reply_delete(BaseEvent $event): void
- {
- //
- }
-
- /**
- * @param BaseEvent $event
- * @return void
- */
- public function board_post_new(BaseEvent $event): void
- {
- //
- }
-
- /**
- * @param BaseEvent $event
- * @return void
- */
- public function board_post_edit(BaseEvent $event): void
- {
- //
- }
-
- /**
- * @param BaseEvent $event
- * @return void
- */
- public function board_post_restore(BaseEvent $event): void
- {
- //
- }
-
- /**
- * @param BaseEvent $event
- * @return void
- */
- public function board_post_delete(BaseEvent $event): void
- {
- //
- }
-
- /**
- * @param BaseEvent $event
- * @return void
- */
- public function market_comment_new(BaseEvent $event): void
- {
- //
- }
-
- /**
- * @param BaseEvent $event
- * @return void
- */
- public function market_comment_edit(BaseEvent $event): void
- {
- //
- }
-
- /**
- * @param BaseEvent $event
- * @return void
- */
- public function market_comment_restore(BaseEvent $event): void
- {
- //
- }
-
- /**
- * @param BaseEvent $event
- * @return void
- */
- public function market_comment_delete(BaseEvent $event): void
- {
- //
- }
-
- /**
- * @param BaseEvent $event
- * @return void
- */
- public function group_leave(BaseEvent $event): void
- {
- //
- }
-
- /**
- * @param BaseEvent $event
- * @return void
- */
- public function group_join(BaseEvent $event): void
- {
- //
- }
-
- /**
- * @param BaseEvent $event
- * @return void
- */
- public function group_change_settings(BaseEvent $event): void
- {
- //
- }
-
- /**
- * @param BaseEvent $event
- * @return void
- */
- public function group_change_photo(BaseEvent $event): void
- {
- //
- }
-
- /**
- * @param BaseEvent $event
- * @return void
- */
- public function group_officers_edit(BaseEvent $event): void
- {
- //
- }
-
- /**
- * @param BaseEvent $event
- * @return void
- */
- public function poll_vote_new(BaseEvent $event): void
- {
- //
- }
-
- /**
- * @param BaseEvent $event
- * @return void
- */
- public function user_block(BaseEvent $event): void
- {
- //
- }
-
- /**
- * @param BaseEvent $event
- * @return void
- */
- public function user_unblock(BaseEvent $event): void
- {
- //
+ // TODO: Implement message_deny() method.
}
}
diff --git a/src/Foundation/Core/Models/Client/ClientFields.php b/src/Foundation/Core/Entities/Client/ClientFields.php
similarity index 76%
rename from src/Foundation/Core/Models/Client/ClientFields.php
rename to src/Foundation/Core/Entities/Client/ClientFields.php
index 79850bb..7c5277f 100644
--- a/src/Foundation/Core/Models/Client/ClientFields.php
+++ b/src/Foundation/Core/Entities/Client/ClientFields.php
@@ -1,20 +1,20 @@
call(self::SCOPE . 'getCities', get_object_vars($cityRequestFields)));
}
+ /**
+ * @param int $cityId
+ * @return CityField
+ * @throws ApiException
+ * @throws Throwable
+ */
+ public function getCityById(int $cityId): CityField
+ {
+ return $this->getCitiesById((new CityRequestFields())->setCityIds([$cityId]))->first();
+ }
+
/**
* @param CityRequestFields $cityRequestFields
* @return Collection
@@ -62,25 +73,25 @@ public function getCitiesById(CityRequestFields $cityRequestFields): Collection
}
/**
- * @param int $cityId
- * @return CityField
+ * @param CountryRequestFields $countryRequestFields
+ * @return CountryFieldsCollection
* @throws ApiException
* @throws Throwable
*/
- public function getCityById(int $cityId): CityField
+ public function getCountries(CountryRequestFields $countryRequestFields): CountryFieldsCollection
{
- return $this->getCitiesById((new CityRequestFields())->setCityIds([$cityId]))->first();
+ return new CountryFieldsCollection($this->call(self::SCOPE . 'getCountries', get_object_vars($countryRequestFields)));
}
/**
- * @param CountryRequestFields $countryRequestFields
- * @return CountryFieldsCollection
+ * @param int $countryId
+ * @return CountryField
* @throws ApiException
* @throws Throwable
*/
- public function getCountries(CountryRequestFields $countryRequestFields): CountryFieldsCollection
+ public function getCountryById(int $countryId): CountryField
{
- return new CountryFieldsCollection($this->call(self::SCOPE . 'getCountries', get_object_vars($countryRequestFields)));
+ return $this->getCountriesById((new CountryRequestFields())->setCountryIds([$countryId]))->first();
}
/**
@@ -97,17 +108,6 @@ public function getCountriesById(CountryRequestFields $countryRequestFields): Co
});
}
- /**
- * @param int $countryId
- * @return CountryField
- * @throws ApiException
- * @throws Throwable
- */
- public function getCountryById(int $countryId): CountryField
- {
- return $this->getCountriesById((new CountryRequestFields())->setCountryIds([$countryId]))->first();
- }
-
/**
* @param ChairRequestFields $chairRequestFields
* @return ChairFieldsCollection
@@ -131,28 +131,28 @@ public function getMetroStations(MetroStationRequestFields $metroStationRequestF
}
/**
- * @param MetroStationRequestFields $metroStationRequestFields
- * @return Collection
+ * @param int $stationId
+ * @return MetroStationField
* @throws ApiException
* @throws Throwable
*/
- public function getMetroStationsById(MetroStationRequestFields $metroStationRequestFields): Collection
+ public function getMetroStationById(int $stationId): MetroStationField
{
- return collect($this->call(self::SCOPE . 'getMetroStationsById', get_object_vars($metroStationRequestFields))
- ->map(function ($city) {
- return new MetroStationField($city);
- }));
+ return $this->getMetroStationsById((new MetroStationRequestFields())->setStationIds([$stationId]))->first();
}
/**
- * @param int $stationId
- * @return MetroStationField
+ * @param MetroStationRequestFields $metroStationRequestFields
+ * @return Collection
* @throws ApiException
* @throws Throwable
*/
- public function getMetroStationById(int $stationId): MetroStationField
+ public function getMetroStationsById(MetroStationRequestFields $metroStationRequestFields): Collection
{
- return $this->getMetroStationsById((new MetroStationRequestFields())->setStationIds([$stationId]))->first();
+ return collect($this->call(self::SCOPE . 'getMetroStationsById', get_object_vars($metroStationRequestFields))
+ ->map(function ($city) {
+ return new MetroStationField($city);
+ }));
}
/**
@@ -177,17 +177,6 @@ public function getRegions(RegionRequestFields $regionRequestFields): RegionFiel
return new RegionFieldsCollection($this->call(self::SCOPE . 'getRegions', get_object_vars($regionRequestFields)));
}
- /**
- * @param SchoolRequestFields $schoolRequestFields
- * @return SchoolFieldsCollection
- * @throws ApiException
- * @throws Throwable
- */
- public function getSchools(SchoolRequestFields $schoolRequestFields): SchoolFieldsCollection
- {
- return new SchoolFieldsCollection($this->call(self::SCOPE . 'getSchools', get_object_vars($schoolRequestFields)));
- }
-
/**
* @param SchoolRequestFields $schoolRequestFields
* @param int $schoolId
@@ -206,14 +195,14 @@ public function getSchoolByIds(SchoolRequestFields $schoolRequestFields, int $sc
}
/**
- * @param SchoolClassRequestFields $schoolClassRequestFields
- * @return SchoolClassFieldsCollection
+ * @param SchoolRequestFields $schoolRequestFields
+ * @return SchoolFieldsCollection
* @throws ApiException
* @throws Throwable
*/
- public function getSchoolClasses(SchoolClassRequestFields $schoolClassRequestFields): SchoolClassFieldsCollection
+ public function getSchools(SchoolRequestFields $schoolRequestFields): SchoolFieldsCollection
{
- return new SchoolClassFieldsCollection($this->call(self::SCOPE . 'getSchoolClasses', get_object_vars($schoolClassRequestFields)));
+ return new SchoolFieldsCollection($this->call(self::SCOPE . 'getSchools', get_object_vars($schoolRequestFields)));
}
/**
@@ -232,4 +221,15 @@ public function getSchoolClassById(SchoolClassRequestFields $schoolClassRequestF
return $class->getId() == $schoolClassId;
});
}
+
+ /**
+ * @param SchoolClassRequestFields $schoolClassRequestFields
+ * @return SchoolClassFieldsCollection
+ * @throws ApiException
+ * @throws Throwable
+ */
+ public function getSchoolClasses(SchoolClassRequestFields $schoolClassRequestFields): SchoolClassFieldsCollection
+ {
+ return new SchoolClassFieldsCollection($this->call(self::SCOPE . 'getSchoolClasses', get_object_vars($schoolClassRequestFields)));
+ }
}
diff --git a/src/Foundation/Core/Models/Database/DatabaseCollection.php b/src/Foundation/Core/Entities/Database/DatabaseCollection.php
similarity index 90%
rename from src/Foundation/Core/Models/Database/DatabaseCollection.php
rename to src/Foundation/Core/Entities/Database/DatabaseCollection.php
index be59702..d909556 100644
--- a/src/Foundation/Core/Models/Database/DatabaseCollection.php
+++ b/src/Foundation/Core/Entities/Database/DatabaseCollection.php
@@ -1,12 +1,12 @@
currentField = $currentField instanceof Collection ? $currentField : collect($currentField);
+ return $this->__construct($currentField);
}
/**
+ * DatabaseField constructor.
* @param array|Collection $currentField
- * @return DatabaseField
*/
- public function __invoke(array|Collection $currentField): DatabaseField
+ public function __construct(array|Collection $currentField)
{
- return $this->__construct($currentField);
+ $this->currentField = $currentField instanceof Collection ? $currentField : collect($currentField);
}
/**
diff --git a/src/Foundation/Core/Models/Database/Fields/Chair/ChairField.php b/src/Foundation/Core/Entities/Database/Fields/Chair/ChairField.php
similarity index 84%
rename from src/Foundation/Core/Models/Database/Fields/Chair/ChairField.php
rename to src/Foundation/Core/Entities/Database/Fields/Chair/ChairField.php
index 3fc2f62..53bd289 100644
--- a/src/Foundation/Core/Models/Database/Fields/Chair/ChairField.php
+++ b/src/Foundation/Core/Entities/Database/Fields/Chair/ChairField.php
@@ -1,12 +1,12 @@
call(self::SCOPE . 'addAddress', $args);
+ }
+
+ public function addCallbackServer(array $args = [])
+ {
+ return $this->call(self::SCOPE . 'addCallbackServer', $args);
+ }
+
+ public function addLink(array $args = [])
+ {
+ return $this->call(self::SCOPE . 'addLink', $args);
+ }
+
+ public function approveRequest(array $args = [])
+ {
+ return $this->call(self::SCOPE . 'approveRequest', $args);
+ }
+
+ public function ban(array $args = [])
+ {
+ return $this->call(self::SCOPE . 'ban', $args);
+ }
+
+ public function create(array $args = [])
+ {
+ return $this->call(self::SCOPE . 'create', $args);
+ }
+
+ public function deleteCallbackServer(array $args = [])
+ {
+ return $this->call(self::SCOPE . 'deleteCallbackServer', $args);
+ }
+
+ public function deleteLink(array $args = [])
+ {
+ return $this->call(self::SCOPE . 'deleteLink', $args);
+ }
+
+ public function disableOnline(array $args = [])
+ {
+ return $this->call(self::SCOPE . 'disableOnline', $args);
+ }
+
+ public function edit(array $args = [])
+ {
+ return $this->call(self::SCOPE . 'edit', $args);
+ }
+
+ public function editAddress(array $args = [])
+ {
+ return $this->call(self::SCOPE . 'editAddress', $args);
+ }
+
+ public function editCallbackServer(array $args = [])
+ {
+ return $this->call(self::SCOPE . 'editCallbackServer', $args);
+ }
+
+ public function editLink(array $args = [])
+ {
+ return $this->call(self::SCOPE . 'editLink', $args);
+ }
+
+ public function editManager(array $args = [])
+ {
+ return $this->call(self::SCOPE . 'editManager', $args);
+ }
+
+ public function enableOnline(array $args = [])
+ {
+ return $this->call(self::SCOPE . 'enableOnline', $args);
+ }
+
+// public function get(array $args = []) {
+// return $this->call(self::SCOPE . 'get', $args);
+// }
+
+ public function getAddresses(array $args = [])
+ {
+ return $this->call(self::SCOPE . 'getAddresses', $args);
+ }
+
+ public function getBanned(array $args = [])
+ {
+ return $this->call(self::SCOPE . 'getBanned', $args);
+ }
+
+ public function getById(array $args = [])
+ {
+ return $this->call(self::SCOPE . 'getById', $args);
+ }
+
+ public function getCallbackConfirmationCode(array $args = [])
+ {
+ return $this->call(self::SCOPE . 'getCallbackConfirmationCode', $args);
+ }
+
+ public function getCallbackServers(array $args = [])
+ {
+ return $this->call(self::SCOPE . 'getCallbackServers', $args);
+ }
+
+ public function getCallbackSettings(array $args = [])
+ {
+ return $this->call(self::SCOPE . 'getCallbackSettings', $args);
+ }
+
+ public function getCatalog(array $args = [])
+ {
+ return $this->call(self::SCOPE . 'getCatalog', $args);
+ }
+
+ public function getCatalogInfo(array $args = [])
+ {
+ return $this->call(self::SCOPE . 'getCatalogInfo', $args);
+ }
+
+ public function getInvitedUsers(array $args = [])
+ {
+ return $this->call(self::SCOPE . 'getInvitedUsers', $args);
+ }
+
+ public function getInvites(array $args = [])
+ {
+ return $this->call(self::SCOPE . 'getInvites', $args);
+ }
+
+ public function getLongPollServer(array $args = [])
+ {
+ return $this->call(self::SCOPE . 'getLongPollServer', $args);
+ }
+
+ public function getLongPollSettings(array $args = [])
+ {
+ return $this->call(self::SCOPE . 'getLongPollSettings', $args);
+ }
+
+ public function getMembers(array $args = [])
+ {
+ return $this->call(self::SCOPE . 'getMembers', $args);
+ }
+
+ public function getRequests(array $args = [])
+ {
+ return $this->call(self::SCOPE . 'getRequests', $args);
+ }
+
+ public function getSettings(array $args = [])
+ {
+ return $this->call(self::SCOPE . 'getSettings', $args);
+ }
+
+ public function getTokenPermissions($access_token)
+ {
+ return $this->call(self::SCOPE . 'getTokenPermissions');
+ }
+
+ public function invite(array $args = [])
+ {
+ return $this->call(self::SCOPE . 'invite', $args);
+ }
+
+ public function isMember(array $args = [])
+ {
+ return $this->call(self::SCOPE . 'isMember', $args);
+ }
+
+ public function join(array $args = [])
+ {
+ return $this->call(self::SCOPE . 'join', $args);
+ }
+
+ public function leave(array $args = [])
+ {
+ return $this->call(self::SCOPE . 'leave', $args);
+ }
+
+ public function removeUser(array $args = [])
+ {
+ return $this->call(self::SCOPE . 'removeUser', $args);
+ }
+
+ public function reorderLink(array $args = [])
+ {
+ return $this->call(self::SCOPE . 'reorderLink', $args);
+ }
+
+ public function search(array $args = [])
+ {
+ return $this->call(self::SCOPE . 'search', $args);
+ }
+
+ public function setCallbackSettings(array $args = [])
+ {
+ return $this->call(self::SCOPE . 'setCallbackSettings', $args);
+ }
+
+ public function setLongPollSettings(array $args = [])
+ {
+ return $this->call(self::SCOPE . 'setLongPollSettings', $args);
+ }
+
+ public function unban(array $args = [])
+ {
+ return $this->call(self::SCOPE . 'unban', $args);
+ }
+}
diff --git a/src/Foundation/Core/Models/Groups/GroupFields.php b/src/Foundation/Core/Entities/Groups/GroupFields.php
similarity index 93%
rename from src/Foundation/Core/Models/Groups/GroupFields.php
rename to src/Foundation/Core/Entities/Groups/GroupFields.php
index 61ba760..e0e9e03 100644
--- a/src/Foundation/Core/Models/Groups/GroupFields.php
+++ b/src/Foundation/Core/Entities/Groups/GroupFields.php
@@ -1,16 +1,16 @@
group->get(self::ADDITIONAL_ADDRESS);
}
- /**
- * @return int
- */
- public function getCountryId(): int
- {
- return $this->group->get(self::COUNTRY_ID);
- }
-
/**
* @return CountryField
* @throws ApiException
@@ -95,9 +87,9 @@ public function getCountry(): CountryField
/**
* @return int
*/
- public function getCityId(): int
+ public function getCountryId(): int
{
- return $this->group->get(self::CITY_ID);
+ return $this->group->get(self::COUNTRY_ID);
}
/**
@@ -110,6 +102,14 @@ public function getCity(): CityField
return new CityField($this->getCityId());
}
+ /**
+ * @return int
+ */
+ public function getCityId(): int
+ {
+ return $this->group->get(self::CITY_ID);
+ }
+
/**
* @return int
*/
diff --git a/src/Foundation/Core/Models/Groups/GroupRequestFields.php b/src/Foundation/Core/Entities/Groups/GroupRequestFields.php
similarity index 94%
rename from src/Foundation/Core/Models/Groups/GroupRequestFields.php
rename to src/Foundation/Core/Entities/Groups/GroupRequestFields.php
index f83e29e..63add83 100644
--- a/src/Foundation/Core/Models/Groups/GroupRequestFields.php
+++ b/src/Foundation/Core/Entities/Groups/GroupRequestFields.php
@@ -1,13 +1,13 @@
call(self::SCOPE . 'addChatUser', $args);
+ }
+
+ /**
+ * @throws Throwable
+ * @throws ApiException
+ */
+ public function allowMessagesFromGroup(array $args = []): Collection
+ {
+ return $this->call(self::SCOPE . 'allowMessagesFromGroup', $args);
+ }
+
+ /**
+ * @throws Throwable
+ * @throws ApiException
+ */
+ public function createChat(array $args = []): Collection
+ {
+ return $this->call(self::SCOPE . 'createChat', $args);
+ }
+
+ /**
+ * @throws Throwable
+ * @throws ApiException
+ */
+ public function delete(array $args = []): Collection
+ {
+ return $this->call(self::SCOPE . 'delete', $args);
+ }
+
+ /**
+ * @throws ApiException
+ * @throws Throwable
+ */
+ public function deleteChatPhoto(array $args = []): Collection
+ {
+ return $this->call(self::SCOPE . 'deleteChatPhoto', $args);
+ }
+
+ /**
+ * @throws Throwable
+ * @throws ApiException
+ */
+ public function deleteConversation(array $args = []): Collection
+ {
+ return $this->call(self::SCOPE . 'deleteConversation', $args);
+ }
+
+ /**
+ * @throws ApiException
+ * @throws Throwable
+ */
+ public function denyMessagesFromGroup(array $args = []): Collection
+ {
+ return $this->call(self::SCOPE . 'denyMessagesFromGroup', $args);
+ }
+
+ /**
+ * @throws Throwable
+ * @throws ApiException
+ */
+ public function edit(array $args = []): Collection
+ {
+ return $this->call(self::SCOPE . 'edit', $args);
+ }
+
+ /**
+ * @throws Throwable
+ * @throws ApiException
+ */
+ public function editChat(array $args = []): Collection
+ {
+ return $this->call(self::SCOPE . 'editChat', $args);
+ }
+
+ /**
+ * @throws Throwable
+ * @throws ApiException
+ */
+ public function getByConversationMessageId(array $args = []): Collection
+ {
+ return $this->call(self::SCOPE . 'getByConversationMessageId', $args);
+ }
+
+ /**
+ * @throws ApiException
+ * @throws Throwable
+ */
+ public function getById(array $args = []): Collection
+ {
+ return $this->call(self::SCOPE . 'getById', $args);
+ }
+
+ /**
+ * @throws Throwable
+ * @throws ApiException
+ */
+ public function getChatPreview(array $args = []): Collection
+ {
+ return $this->call(self::SCOPE . 'getChatPreview', $args);
+ }
+
+ /**
+ * @throws Throwable
+ * @throws ApiException
+ */
+ public function getConversationMembers(array $args = []): Collection
+ {
+ return $this->call(self::SCOPE . 'getConversationMembers', $args);
+ }
+
+ /**
+ * @throws Throwable
+ * @throws ApiException
+ */
+ public function getConversations(array $args = []): Collection
+ {
+ return $this->call(self::SCOPE . 'getConversations', $args);
+ }
+
+ /**
+ * @throws Throwable
+ * @throws ApiException
+ */
+ public function getConversationsById(array $args = []): Collection
+ {
+ return $this->call(self::SCOPE . 'getConversationsById', $args);
+ }
+
+ /**
+ * @throws Throwable
+ * @throws ApiException
+ */
+ public function getHistory(array $args = []): Collection
+ {
+ return $this->call(self::SCOPE . 'getHistory', $args);
+ }
+
+ /**
+ * @throws ApiException
+ * @throws Throwable
+ */
+ public function getHistoryAttachments(array $args = []): Collection
+ {
+ return $this->call(self::SCOPE . 'getHistoryAttachments', $args);
+ }
+
+ /**
+ * @throws ApiException
+ * @throws Throwable
+ */
+ public function getInviteLink(array $args = []): Collection
+ {
+ return $this->call(self::SCOPE . 'getInviteLink', $args);
+ }
+
+ /**
+ * @throws ApiException
+ * @throws Throwable
+ */
+ public function getLastActivity(array $args = []): Collection
+ {
+ return $this->call(self::SCOPE . 'getLastActivity', $args);
+ }
+
+ /**
+ * @throws Throwable
+ * @throws ApiException
+ */
+ public function getLongPollHistory(array $args = []): Collection
+ {
+ return $this->call(self::SCOPE . 'getLongPollHistory', $args);
+ }
+
+ /**
+ * @throws ApiException
+ * @throws Throwable
+ */
+ public function getLongPollServer(array $args = []): Collection
+ {
+ return $this->call(self::SCOPE . 'getLongPollServer', $args);
+ }
+
+ /**
+ * @throws Throwable
+ * @throws ApiException
+ */
+ public function isMessagesFromGroupAllowed(array $args = []): Collection
+ {
+ return $this->call(self::SCOPE . 'isMessagesFromGroupAllowed', $args);
+ }
+
+ /**
+ * @throws Throwable
+ * @throws ApiException
+ */
+ public function joinChatByInviteLink(array $args = []): Collection
+ {
+ return $this->call(self::SCOPE . 'joinChatByInviteLink', $args);
+ }
+
+ /**
+ * @throws Throwable
+ * @throws ApiException
+ */
+ public function markAsAnsweredConversation(array $args = []): Collection
+ {
+ return $this->call(self::SCOPE . 'markAsAnsweredConversation', $args);
+ }
+
+ /**
+ * @throws ApiException
+ * @throws Throwable
+ */
+ public function markAsImportant(array $args = []): Collection
+ {
+ return $this->call(self::SCOPE . 'markAsImportant', $args);
+ }
+
+ /**
+ * @throws ApiException
+ * @throws Throwable
+ */
+ public function markAsImportantConversation(array $args = []): Collection
+ {
+ return $this->call(self::SCOPE . 'markAsImportantConversation', $args);
+ }
+
+ /**
+ * @throws Throwable
+ * @throws ApiException
+ */
+ public function markAsRead(array $args = []): Collection
+ {
+ return $this->call(self::SCOPE . 'markAsRead', $args);
+ }
+
+ /**
+ * @throws ApiException
+ * @throws Throwable
+ */
+ public function pin(array $args = []): Collection
+ {
+ return $this->call(self::SCOPE . 'pin', $args);
+ }
+
+ /**
+ * @throws Throwable
+ * @throws ApiException
+ */
+ public function removeChatUser(array $args = []): Collection
+ {
+ return $this->call(self::SCOPE . 'removeChatUser', $args);
+ }
+
+ /**
+ * @throws ApiException
+ * @throws Throwable
+ */
+ public function restore(array $args = []): Collection
+ {
+ return $this->call(self::SCOPE . 'restore', $args);
+ }
+
+ /**
+ * @throws Throwable
+ * @throws ApiException
+ */
+ public function search(array $args = []): Collection
+ {
+ return $this->call(self::SCOPE . 'search', $args);
+ }
+
+ /**
+ * @throws ApiException
+ * @throws Throwable
+ */
+ public function searchConversations(array $args = []): Collection
+ {
+ return $this->call(self::SCOPE . 'searchConversations', $args);
+ }
+
+ /**
+ * @throws Throwable
+ * @throws ApiException
+ */
+ public function send(MessageRequestFields $messageProperties): Collection
+ {
+ return $this->call(self::SCOPE . 'send', get_object_vars($messageProperties));
+ }
+
+ /**
+ * @throws ApiException
+ * @throws Throwable
+ */
+ public function setActivity(array $args = []): Collection
+ {
+ return $this->call(self::SCOPE . 'setActivity', $args);
+ }
+
+ /**
+ * @throws Throwable
+ * @throws ApiException
+ */
+ public function setChatPhoto(array $args = []): Collection
+ {
+ return $this->call(self::SCOPE . 'setChatPhoto', $args);
+ }
+
+ /**
+ * @throws ApiException
+ * @throws Throwable
+ */
+ public function unpin(array $args = []): Collection
+ {
+ return $this->call(self::SCOPE . 'unpin', $args);
+ }
+}
diff --git a/src/Foundation/Core/Models/Messages/MessageFields.php b/src/Foundation/Core/Entities/Messages/MessageFields.php
similarity index 75%
rename from src/Foundation/Core/Models/Messages/MessageFields.php
rename to src/Foundation/Core/Entities/Messages/MessageFields.php
index 05a7242..c6f320b 100644
--- a/src/Foundation/Core/Models/Messages/MessageFields.php
+++ b/src/Foundation/Core/Entities/Messages/MessageFields.php
@@ -1,32 +1,32 @@
user_id = $user_id;
+ $this->random_id = (int)now()->timestamp;
return $this;
}
/**
+ * @param int|null $user_id
* @return MessageRequestFields
*/
- public function setRandomId(): MessageRequestFields
+ public function setUserId(?int $user_id): MessageRequestFields
{
- $this->random_id = (int)now()->timestamp;
+ $this->user_id = $user_id;
return $this;
}
diff --git a/src/Foundation/Core/Models/RequestFields.php b/src/Foundation/Core/Entities/RequestFields.php
similarity index 64%
rename from src/Foundation/Core/Models/RequestFields.php
rename to src/Foundation/Core/Entities/RequestFields.php
index 7966c8b..7f38345 100644
--- a/src/Foundation/Core/Models/RequestFields.php
+++ b/src/Foundation/Core/Entities/RequestFields.php
@@ -1,23 +1,23 @@
military->get(self::COUNTRY_ID);
- }
-
/**
* @param string $token
* @return CountryField
@@ -55,6 +47,14 @@ public function getCountry(string $token): CountryField
return new CountryField($this->getCountryId(), $token);
}
+ /**
+ * @return int
+ */
+ public function getCountryId(): int
+ {
+ return $this->military->get(self::COUNTRY_ID);
+ }
+
/**
* @return int
*/
diff --git a/src/Foundation/Core/Models/Users/ProfileFields/RelativeField.php b/src/Foundation/Core/Entities/Users/ProfileFields/RelativeField.php
similarity index 86%
rename from src/Foundation/Core/Models/Users/ProfileFields/RelativeField.php
rename to src/Foundation/Core/Entities/Users/ProfileFields/RelativeField.php
index 1779a7e..00563a8 100644
--- a/src/Foundation/Core/Models/Users/ProfileFields/RelativeField.php
+++ b/src/Foundation/Core/Entities/Users/ProfileFields/RelativeField.php
@@ -1,17 +1,17 @@
relative->get(self::ID);
- }
-
/**
* @param string $token
* @param array $userProfileFields
@@ -63,11 +55,11 @@ public function getRelative(string $token, array $userProfileFields = []): UserP
}
/**
- * @return string
+ * @return int
*/
- public function getType(): string
+ public function getRelativeId(): int
{
- return $this->relative->get(self::TYPE);
+ return $this->relative->get(self::ID);
}
/**
@@ -77,4 +69,12 @@ public function getTranslationType(): string
{
return preg_replace('~vk-sdk\.~', '', __('vk-sdk.' . $this->getType()));
}
+
+ /**
+ * @return string
+ */
+ public function getType(): string
+ {
+ return $this->relative->get(self::TYPE);
+ }
}
diff --git a/src/Foundation/Core/Models/Users/ProfileFields/SchoolField.php b/src/Foundation/Core/Entities/Users/ProfileFields/SchoolField.php
similarity index 95%
rename from src/Foundation/Core/Models/Users/ProfileFields/SchoolField.php
rename to src/Foundation/Core/Entities/Users/ProfileFields/SchoolField.php
index 9b29238..f72ed9f 100644
--- a/src/Foundation/Core/Models/Users/ProfileFields/SchoolField.php
+++ b/src/Foundation/Core/Entities/Users/ProfileFields/SchoolField.php
@@ -1,6 +1,6 @@
school->get(self::CITY_ID);
- }
-
/**
* @return CityField
* @throws ApiException
@@ -59,13 +51,12 @@ public function getCity(): CityField
return new CityField($this->getCityId());
}
-
/**
* @return int|null
*/
- public function getCountryId(): ?int
+ public function getCityId(): ?int
{
- return $this->school->get(self::COUNTRY_ID);
+ return $this->school->get(self::CITY_ID);
}
/**
@@ -78,6 +69,14 @@ public function getCountry(): CountryField
return new CountryField($this->getCountryId());
}
+ /**
+ * @return int|null
+ */
+ public function getCountryId(): ?int
+ {
+ return $this->school->get(self::COUNTRY_ID);
+ }
+
/**
* @return int|null
*/
diff --git a/src/Foundation/Core/Models/Users/User.php b/src/Foundation/Core/Entities/Users/User.php
similarity index 93%
rename from src/Foundation/Core/Models/Users/User.php
rename to src/Foundation/Core/Entities/Users/User.php
index 2143096..9dea1a8 100644
--- a/src/Foundation/Core/Models/Users/User.php
+++ b/src/Foundation/Core/Entities/Users/User.php
@@ -1,6 +1,6 @@
user->get(UserProfileFields::RELATIVES))
+ return collect($this->user->get(UserProfileFields::RELATIVES))
->map(function ($item) {
return new RelativeField($item);
});
diff --git a/src/Foundation/Core/Models/Users/UserRequestFields.php b/src/Foundation/Core/Entities/Users/UserRequestFields.php
similarity index 96%
rename from src/Foundation/Core/Models/Users/UserRequestFields.php
rename to src/Foundation/Core/Entities/Users/UserRequestFields.php
index ff92c0b..258f133 100644
--- a/src/Foundation/Core/Models/Users/UserRequestFields.php
+++ b/src/Foundation/Core/Entities/Users/UserRequestFields.php
@@ -1,10 +1,10 @@
call(self::SCOPE . 'addAddress', $args);
- }
-
- public function addCallbackServer(array $args = []) {
- return $this->call(self::SCOPE . 'addCallbackServer', $args);
- }
-
- public function addLink(array $args = []) {
- return $this->call(self::SCOPE . 'addLink', $args);
- }
-
- public function approveRequest(array $args = []) {
- return $this->call(self::SCOPE . 'approveRequest', $args);
- }
-
- public function ban(array $args = []) {
- return $this->call(self::SCOPE . 'ban', $args);
- }
-
- public function create(array $args = []) {
- return $this->call(self::SCOPE . 'create', $args);
- }
-
- public function deleteCallbackServer(array $args = []) {
- return $this->call(self::SCOPE . 'deleteCallbackServer', $args);
- }
-
- public function deleteLink(array $args = []) {
- return $this->call(self::SCOPE . 'deleteLink', $args);
- }
-
- public function disableOnline(array $args = []) {
- return $this->call(self::SCOPE . 'disableOnline', $args);
- }
- public function edit(array $args = []) {
- return $this->call(self::SCOPE . 'edit', $args);
- }
-
- public function editAddress(array $args = []) {
- return $this->call(self::SCOPE . 'editAddress', $args);
- }
-
- public function editCallbackServer(array $args = []) {
- return $this->call(self::SCOPE . 'editCallbackServer', $args);
- }
-
- public function editLink(array $args = []) {
- return $this->call(self::SCOPE . 'editLink', $args);
- }
- public function editManager(array $args = []) {
- return $this->call(self::SCOPE . 'editManager', $args);
- }
-
- public function enableOnline(array $args = []) {
- return $this->call(self::SCOPE . 'enableOnline', $args);
- }
-
-// public function get(array $args = []) {
-// return $this->call(self::SCOPE . 'get', $args);
-// }
-
- public function getAddresses(array $args = [])
- {
- return $this->call(self::SCOPE . 'getAddresses', $args);
- }
-
- public function getBanned(array $args = []) {
- return $this->call(self::SCOPE . 'getBanned', $args);
- }
-
- public function getById(array $args = []) {
- return $this->call(self::SCOPE . 'getById', $args);
- }
-
- public function getCallbackConfirmationCode(array $args = []) {
- return $this->call(self::SCOPE . 'getCallbackConfirmationCode', $args);
- }
-
- public function getCallbackServers(array $args = []) {
- return $this->call(self::SCOPE . 'getCallbackServers', $args);
- }
-
- public function getCallbackSettings(array $args = []) {
- return $this->call(self::SCOPE . 'getCallbackSettings', $args);
- }
- public function getCatalog(array $args = []) {
- return $this->call(self::SCOPE . 'getCatalog', $args);
- }
- public function getCatalogInfo(array $args = []) {
- return $this->call(self::SCOPE . 'getCatalogInfo', $args);
- }
-
- public function getInvitedUsers(array $args = []) {
- return $this->call(self::SCOPE . 'getInvitedUsers', $args);
- }
-
- public function getInvites(array $args = []) {
- return $this->call(self::SCOPE . 'getInvites', $args);
- }
-
- public function getLongPollServer(array $args = []) {
- return $this->call(self::SCOPE . 'getLongPollServer', $args);
- }
-
- public function getLongPollSettings(array $args = []) {
- return $this->call(self::SCOPE . 'getLongPollSettings', $args);
- }
- public function getMembers(array $args = []) {
- return $this->call(self::SCOPE . 'getMembers', $args);
- }
-
- public function getRequests(array $args = []) {
- return $this->call(self::SCOPE . 'getRequests', $args);
- }
-
- public function getSettings(array $args = []) {
- return $this->call(self::SCOPE . 'getSettings', $args);
- }
-
- public function getTokenPermissions($access_token) {
- return $this->call(self::SCOPE . 'getTokenPermissions');
- }
-
- public function invite(array $args = []) {
- return $this->call(self::SCOPE . 'invite', $args);
- }
-
- public function isMember(array $args = []) {
- return $this->call(self::SCOPE . 'isMember', $args);
- }
-
- public function join(array $args = []) {
- return $this->call(self::SCOPE . 'join', $args);
- }
-
- public function leave(array $args = []) {
- return $this->call(self::SCOPE . 'leave', $args);
- }
-
- public function removeUser(array $args = []) {
- return $this->call(self::SCOPE . 'removeUser', $args);
- }
-
- public function reorderLink(array $args = []) {
- return $this->call(self::SCOPE . 'reorderLink', $args);
- }
- public function search(array $args = []) {
- return $this->call(self::SCOPE . 'search', $args);
- }
- public function setCallbackSettings(array $args = []) {
- return $this->call(self::SCOPE . 'setCallbackSettings', $args);
- }
- public function setLongPollSettings(array $args = []) {
- return $this->call(self::SCOPE . 'setLongPollSettings', $args);
- }
-
- public function unban(array $args = []) {
- return $this->call(self::SCOPE . 'unban', $args);
- }
-}
diff --git a/src/Foundation/Core/Models/Messages/Attachments/Audio/Audio.php b/src/Foundation/Core/Models/Messages/Attachments/Audio/Audio.php
deleted file mode 100644
index 68c6628..0000000
--- a/src/Foundation/Core/Models/Messages/Attachments/Audio/Audio.php
+++ /dev/null
@@ -1,46 +0,0 @@
-call(self::SCOPE . 'addChatUser', $args);
- }
-
- public function allowMessagesFromGroup(array $args = [])
- {
- return $this->call(self::SCOPE . 'allowMessagesFromGroup', $args);
- }
-
- public function createChat(array $args = [])
- {
- return $this->call(self::SCOPE . 'createChat', $args);
- }
-
- public function delete(array $args = [])
- {
- return $this->call(self::SCOPE . 'delete', $args);
- }
-
- public function deleteChatPhoto(array $args = [])
- {
- return $this->call(self::SCOPE . 'deleteChatPhoto', $args);
- }
-
- public function deleteConversation(array $args = [])
- {
- return $this->call(self::SCOPE . 'deleteConversation', $args);
- }
-
- public function denyMessagesFromGroup(array $args = [])
- {
- return $this->call(self::SCOPE . 'denyMessagesFromGroup', $args);
- }
-
- public function edit(array $args = [])
- {
- return $this->call(self::SCOPE . 'edit', $args);
- }
-
- public function editChat(array $args = [])
- {
- return $this->call(self::SCOPE . 'editChat', $args);
- }
-
- public function getByConversationMessageId(array $args = [])
- {
- return $this->call(self::SCOPE . 'getByConversationMessageId', $args);
- }
-
- public function getById(array $args = [])
- {
- return $this->call(self::SCOPE . 'getById', $args);
- }
-
- public function getChatPreview(array $args = [])
- {
- return $this->call(self::SCOPE . 'getChatPreview', $args);
- }
-
- public function getConversationMembers(array $args = [])
- {
- return $this->call(self::SCOPE . 'getConversationMembers', $args);
- }
-
- public function getConversations(array $args = [])
- {
- return $this->call(self::SCOPE . 'getConversations', $args);
- }
-
- public function getConversationsById(array $args = [])
- {
- return $this->call(self::SCOPE . 'getConversationsById', $args);
- }
-
- public function getHistory(array $args = [])
- {
- return $this->call(self::SCOPE . 'getHistory', $args);
- }
-
- public function getHistoryAttachments(array $args = [])
- {
- return $this->call(self::SCOPE . 'getHistoryAttachments', $args);
- }
-
- public function getInviteLink(array $args = [])
- {
- return $this->call(self::SCOPE . 'getInviteLink', $args);
- }
-
- public function getLastActivity(array $args = [])
- {
- return $this->call(self::SCOPE . 'getLastActivity', $args);
- }
-
- public function getLongPollHistory(array $args = [])
- {
- return $this->call(self::SCOPE . 'getLongPollHistory', $args);
- }
-
- public function getLongPollServer(array $args = [])
- {
- return $this->call(self::SCOPE . 'getLongPollServer', $args);
- }
-
- public function isMessagesFromGroupAllowed(array $args = [])
- {
- return $this->call(self::SCOPE . 'isMessagesFromGroupAllowed', $args);
- }
-
- public function joinChatByInviteLink(array $args = [])
- {
- return $this->call(self::SCOPE . 'joinChatByInviteLink', $args);
- }
-
- public function markAsAnsweredConversation(array $args = [])
- {
- return $this->call(self::SCOPE . 'markAsAnsweredConversation', $args);
- }
-
- public function markAsImportant(array $args = [])
- {
- return $this->call(self::SCOPE . 'markAsImportant', $args);
- }
-
- public function markAsImportantConversation(array $args = [])
- {
- return $this->call(self::SCOPE . 'markAsImportantConversation', $args);
- }
-
- public function markAsRead(array $args = [])
- {
- return $this->call(self::SCOPE . 'markAsRead', $args);
- }
-
- public function pin(array $args = [])
- {
- return $this->call(self::SCOPE . 'pin', $args);
- }
-
- public function removeChatUser(array $args = [])
- {
- return $this->call(self::SCOPE . 'removeChatUser', $args);
- }
-
- public function restore(array $args = [])
- {
- return $this->call(self::SCOPE . 'restore', $args);
- }
-
- public function search(array $args = [])
- {
- return $this->call(self::SCOPE . 'search', $args);
- }
-
- public function searchConversations(array $args = [])
- {
- return $this->call(self::SCOPE . 'searchConversations', $args);
- }
-
- public function send(MessageRequestFields $messageProperties): Collection
- {
- return $this->call(self::SCOPE . 'send', get_object_vars($messageProperties));
- }
-
- public function setActivity(array $args = [])
- {
- return $this->call(self::SCOPE . 'setActivity', $args);
- }
-
- public function setChatPhoto(array $args = [])
- {
- return $this->call(self::SCOPE . 'setChatPhoto', $args);
- }
-
- public function unpin(array $args = [])
- {
- return $this->call(self::SCOPE . 'unpin', $args);
- }
-}
diff --git a/src/Foundation/Format.php b/src/Foundation/Format.php
index 709f2ad..c8baeab 100644
--- a/src/Foundation/Format.php
+++ b/src/Foundation/Format.php
@@ -10,7 +10,7 @@
*/
class Format implements CanFormatContract
{
- /** @var array */
+ /** @var array */
private array $formatters = [];
/**
diff --git a/src/Foundation/SdkConfig.php b/src/Foundation/SdkConfig.php
index 6d0dc1a..f18b3be 100644
--- a/src/Foundation/SdkConfig.php
+++ b/src/Foundation/SdkConfig.php
@@ -19,18 +19,18 @@ class SdkConfig
* @param string|null $key
* @return array|string|null
*/
- public function query(string $key = null): array|string|null
+ public function routes(string $key = null): array|string|null
{
- return config(self::CONFIG_PREFIX . (!$key ? null : ".$key"));
+ return $this->query(self::CONFIG_ROUTES . (!$key ? null : ".$key"));
}
/**
* @param string|null $key
* @return array|string|null
*/
- public function routes(string $key = null): array|string|null
+ public function query(string $key = null): array|string|null
{
- return $this->query(self::CONFIG_ROUTES . (!$key ? null : ".$key"));
+ return config(self::CONFIG_PREFIX . (!$key ? null : ".$key"));
}
/**
diff --git a/src/Models/Event.php b/src/Models/Event.php
index c52e07f..db7b897 100644
--- a/src/Models/Event.php
+++ b/src/Models/Event.php
@@ -9,10 +9,10 @@ class Event extends Model
{
use HasFactory;
- /** @var string */
+ /** @var string */
protected $table = 'vk__events';
- /** @var string[] */
+ /** @var string[] */
protected $fillable = [
'group_id',
'type',
diff --git a/src/Providers/ServiceProvider.php b/src/Providers/ServiceProvider.php
index 61e065d..c77b411 100644
--- a/src/Providers/ServiceProvider.php
+++ b/src/Providers/ServiceProvider.php
@@ -3,7 +3,7 @@
namespace Hopex\VkSdk\Providers;
use Hopex\VkSdk\Foundation\Core\Api\Client;
-use Hopex\VkSdk\Foundation\Core\Models\RequestFields;
+use Hopex\VkSdk\Foundation\Core\Entities\RequestFields;
use Hopex\VkSdk\Foundation\Format;
use Hopex\VkSdk\Foundation\SdkConfig;
use Hopex\VkSdk\Services\CallbackEventService;
@@ -41,7 +41,7 @@ public function boot(): void
__DIR__ . '/../.root/lang/ru.php' => $this->app->langPath('ru/vk-sdk.php'),
], 'vk-sdk-lang-ru');
- $this->loadMigrationsFrom(__DIR__.'/../.root/database/migrations');
+ $this->loadMigrationsFrom(__DIR__ . '/../.root/database/migrations');
$this->loadRoutesFrom(__DIR__ . '/../.root/routes/callbacks.php');
}
diff --git a/src/Services/CallbackEventService.php b/src/Services/CallbackEventService.php
index 841c6d9..0f3bfce 100644
--- a/src/Services/CallbackEventService.php
+++ b/src/Services/CallbackEventService.php
@@ -3,25 +3,28 @@
namespace Hopex\VkSdk\Services;
use Hopex\VkSdk\Contracts\CallbackEventsContract;
+use Hopex\VkSdk\Contracts\EventEntityContract;
use Hopex\VkSdk\Exceptions\Callback\SecretException;
+use Hopex\VkSdk\Exceptions\Callback\UnknownEntityException;
use Hopex\VkSdk\Exceptions\Callback\UnknownEventException;
use Hopex\VkSdk\Exceptions\Callback\UnknownGroupIdException;
use Hopex\VkSdk\Exceptions\Database\DatabaseOrTableNotFoundException;
use Hopex\VkSdk\Facades\SdkConfig;
-use Hopex\VkSdk\Foundation\Core\Callback\BaseEvent;
+use Hopex\VkSdk\Foundation\Core\Entities\Messages\MessageFields;
use Hopex\VkSdk\Models\Event;
use Illuminate\Database\QueryException;
use Illuminate\Http\Request;
+use Illuminate\Support\Collection;
use Throwable;
class CallbackEventService
{
+ /** @var string */
private const OK = 'ok';
-
- /**
- * @var Request
- */
+ /** @var Request */
public Request $request;
+ /** @var Collection */
+ private Collection $entities;
/**
* CallbackEventService constructor.
@@ -30,15 +33,19 @@ class CallbackEventService
*/
public function __construct(Request $request)
{
+ $this->entities = new Collection([
+ 'message' => MessageFields::class
+ ]);
+
$this->request = $request;
}
/**
- * @return mixed
+ * @return string|array|null
* @throws Throwable
* @throws UnknownGroupIdException
*/
- public function division(): mixed
+ public function division(): string|array|null
{
$groupId = $this->request->json('group_id');
$eventId = $this->request->json('event_id');
@@ -64,16 +71,39 @@ public function division(): mixed
throw_if(empty($code), UnknownGroupIdException::class);
return $code;
default:
- throw_if(!method_exists(CallbackEventsContract::class, $event), UnknownEventException::class);
throw_if(
- SdkConfig::groups("$groupId.secret.verify") && SdkConfig::groups("$groupId.secret.code") != $this->request->json('secret'),
+ !method_exists(CallbackEventsContract::class, $event),
+ UnknownEventException::class
+ );
+ throw_if(
+ SdkConfig::groups("$groupId.secret.verify") &&
+ SdkConfig::groups("$groupId.secret.code") != $this->request->json('secret'),
SecretException::class
);
call_user_func(
[new (SdkConfig::groups("$groupId.events")), $event],
- new BaseEvent(collect($this->request->only(['group_id', 'object'])))
+// new BaseEvent(collect($this->request->only(['group_id', 'object'])))
+ $this->selectEntityByRequest()
);
+
return self::OK;
}
}
+
+ /**
+ * @return mixed
+ * @throws UnknownEntityException
+ */
+ public function selectEntityByRequest(): mixed
+ {
+ $object = collect($this->request->json('object'));
+ $entityType = $object->keys()->first();
+ $entityItems = collect($object->get($entityType));
+
+ if (!$this->entities->has($entityType)) {
+ throw new UnknownEntityException();
+ }
+
+ return new ($this->entities->get($entityType))($entityItems);
+ }
}
From acdc7d875c73876d226b37918d211a317d6fcc48 Mon Sep 17 00:00:00 2001
From: Schizo
Date: Sat, 7 Jan 2023 04:11:30 +0300
Subject: [PATCH 17/24] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB?=
=?UTF-8?q?=D0=B5=D0=BD=D0=B0=20=D0=BE=D0=B1=D1=80=D0=B0=D0=B1=D0=BE=D1=82?=
=?UTF-8?q?=D0=BA=D0=B0=20=D0=B7=D0=B0=D0=BF=D1=80=D0=BE=D1=81=D0=BE=D0=B2?=
=?UTF-8?q?=20=D1=81=D0=B5=D1=80=D0=B2=D0=B5=D1=80=D0=B0=20=D1=81=D0=BE=20?=
=?UTF-8?q?=D1=81=D1=82=D0=B0=D1=82=D0=B8=D1=81=D1=82=D0=B8=D0=BA=D0=BE?=
=?UTF-8?q?=D0=B9=20=D0=B8=20=D0=BF=D1=80=D0=BE=D1=81=D1=82=D0=BE=D0=B9=20?=
=?UTF-8?q?=D0=B2=D1=8B=D0=B2=D0=BE=D0=B4=20=D1=81=D0=BE=D0=BE=D0=B1=D1=89?=
=?UTF-8?q?=D0=B5=D0=BD=D0=B8=D0=B9?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
src/.root/config/vk-sdk.php | 86 ++++++++--
src/.root/lang/ru.php | 9 +-
src/.root/routes/api.php | 24 +++
src/.root/routes/callbacks.php | 16 --
src/.root/storage/sdk/keyboards/default.json | 14 ++
src/.root/storage/sdk/notes/help.md | 1 +
src/Exceptions/Callback/KeyboardException.php | 14 ++
src/Exceptions/Callback/NoteException.php | 14 ++
src/Exceptions/SdkException.php | 3 +-
.../AuthenticationSourceQueryException.php | 14 ++
.../InvalidArgumentSourceQueryException.php | 14 ++
.../InvalidPacketSourceQueryException.php | 14 ++
.../SocketSourceQueryException.php | 14 ++
src/Facades/Keyboard.php | 20 +++
src/Facades/Note.php | 20 +++
src/Facades/Server.php | 20 +++
src/Formatters/ClearInputMessageFormatter.php | 21 +++
src/Formatters/JsonExceptionFormatter.php | 4 +
src/Formatters/JsonLogFormatter.php | 4 +
src/Foundation/Core/Callback/BaseEvent.php | 84 ----------
.../Core/Callback/EventsHandler.php | 19 +++
.../Core/Callback/SessionTokens.php | 80 +++++++++
src/Foundation/Core/Sources/Keyboard.php | 32 ++++
src/Foundation/Core/Sources/Note.php | 32 ++++
src/Foundation/Core/Sources/Source.php | 19 +++
src/Foundation/Format.php | 2 +
src/Foundation/SdkConfig.php | 39 ++++-
src/Foundation/Server.php | 157 ++++++++++++++++++
src/Providers/ServiceProvider.php | 20 ++-
...tService.php => CallbackEventsService.php} | 38 +++--
src/Services/ServerEventsService.php | 61 +++++++
31 files changed, 778 insertions(+), 131 deletions(-)
create mode 100644 src/.root/routes/api.php
delete mode 100644 src/.root/routes/callbacks.php
create mode 100644 src/.root/storage/sdk/keyboards/default.json
create mode 100644 src/.root/storage/sdk/notes/help.md
create mode 100644 src/Exceptions/Callback/KeyboardException.php
create mode 100644 src/Exceptions/Callback/NoteException.php
create mode 100644 src/Exceptions/SourceQuery/AuthenticationSourceQueryException.php
create mode 100644 src/Exceptions/SourceQuery/InvalidArgumentSourceQueryException.php
create mode 100644 src/Exceptions/SourceQuery/InvalidPacketSourceQueryException.php
create mode 100644 src/Exceptions/SourceQuery/SocketSourceQueryException.php
create mode 100644 src/Facades/Keyboard.php
create mode 100644 src/Facades/Note.php
create mode 100644 src/Facades/Server.php
create mode 100644 src/Formatters/ClearInputMessageFormatter.php
delete mode 100644 src/Foundation/Core/Callback/BaseEvent.php
create mode 100644 src/Foundation/Core/Callback/SessionTokens.php
create mode 100644 src/Foundation/Core/Sources/Keyboard.php
create mode 100644 src/Foundation/Core/Sources/Note.php
create mode 100644 src/Foundation/Core/Sources/Source.php
create mode 100644 src/Foundation/Server.php
rename src/Services/{CallbackEventService.php => CallbackEventsService.php} (79%)
create mode 100644 src/Services/ServerEventsService.php
diff --git a/src/.root/config/vk-sdk.php b/src/.root/config/vk-sdk.php
index 33b77ba..bce27ab 100644
--- a/src/.root/config/vk-sdk.php
+++ b/src/.root/config/vk-sdk.php
@@ -1,6 +1,7 @@
- [
- 'entry' => 'connect',
+ 'group' => 'callbacks',
+ 'server' => 'requests',
],
/*
@@ -64,26 +66,70 @@
'version' => '5.131',
],
+ 'replacement' => [
+ 'replace_to' => '(🚫)',
+ 'forbidden' => [
+ '(@)',
+ '(\*)',
+ '(http)',
+ '(\.com)',
+ '(\.de)',
+ '(\.net)',
+ '(\.uk)',
+ '(\.cn)',
+ '(\.org)',
+ '(\.info)',
+ '(\.nl)',
+ '(\.eu)',
+ '(\.ru)',
+ '(\.co\.uk)',
+ '(\.me\.uk)',
+ '(\.org\.uk)',
+ '(\.sch\.uk)',
+ ],
+ ],
+
'groups' => [
- '84942932' => [
+ 84942932 => [
+ 'description' => 'Test service',
'confirmation' => '28ec36c3',
'token' => 'vk1.a.-U95XUjpt2OxcSqyPydks69FwG1fAHxY5CF7pUFC-d0oG9bY4ld2HO23VQCBF8xbrS2gLDE2QXyLSH6jsCaGw5lGc2M-n8aAbwToCGLp97LiS5Lf3Ha1En3LQshkdLlZkqKS80METKyr_3nSIBF4GJLAxZNvnSd12hXe3PYZAG0oTIkVPgdguVrbs8EEcAGv',
'secret' => [
'code' => '745cc77d276cf36c694e',
'verify' => true,
],
- 'events' => Chat::class,
+ 'server_peer_id' => 0,
+ 'target_server' => '',
+ 'events' => Tests::class,
'allow_retry_events' => true,
],
+ 205402271 => [
+ 'description' => 'Kult Game Project',
+ 'confirmation' => '1129612b',
+ 'token' => 'vk1.a.j-mrHaaBmC8Uq_GlAqwVjG2UALgWLYFqkq-Wgr2bGlO7LHZmT5km24yi2EZU2op1sAD4NHcFq2_KPo3IEwZCvMlywO6whuI8i00kFXBTM-w0lI1RVD534whyOPLZMoCoB2JMH12no5EC7dMUa3Jd63uc1DOlCKTV8GJQi2DG2piDsv_OfC3nrKBy0DQa3q-tr6Ei6HIZ-OW5EZaOw37nNg',
+ 'secret' => [
+ 'code' => 'ymUrvxeTHfUyRtdK',
+ 'verify' => true,
+ ],
+ 'server_peer_id' => 2000000002,
+ 'target_server' => '46.3.223.76:27015',
+ 'events' => EventsMapper::class,
+ 'allow_retry_events' => true
+ ],
],
- 'apps' => [
- '7967757' => [
- 'token' => 'b89c4892b89c4892b89c4892aeb8e5dc9fbb89cb89c4892d9c7b14801fb3358d6dcd092',
- 'secret' => 'OaQA1ddYuF2PLGAGKOjd',
+ 'servers' => [
+ '46-3-223-76-27015' => [
+ 'target_group_id' => 205402271,
+ 'rcon_password' => 'Nr8v6uxuCL8cA5NOx43cypz0DuaqCGP',
],
],
+ 'auth_app' => [
+ 'token' => 'b89c4892b89c4892b89c4892aeb8e5dc9fbb89cb89c4892d9c7b14801fb3358d6dcd092',
+ 'secret' => 'OaQA1ddYuF2PLGAGKOjd',
+ ],
+
/*
|--------------------------------------------------------------------------
| Логирование
@@ -103,7 +149,7 @@
'enabled' => true,
'channels' => [
'exception' => [
- 'name' => 'vk-sdk',
+ 'name' => 'vk-sdk-exception',
'driver' => 'daily',
'path' => storage_path('logs/vk-sdk/exceptions.log'),
'level' => env('LOG_LEVEL', 'debug'),
@@ -112,6 +158,26 @@
'days' => 30,
'tap' => JsonLogFormatter::class,
],
+ 'info' => [
+ 'name' => 'vk-sdk-infos',
+ 'driver' => 'daily',
+ 'path' => storage_path('logs/vk-sdk/infos.log'),
+ 'level' => env('LOG_LEVEL', 'debug'),
+ 'permissions' => 0755,
+ 'locking' => true,
+ 'days' => 30,
+ 'tap' => JsonLogFormatter::class,
+ ],
+ 'server' => [
+ 'name' => 'vk-sdk-server',
+ 'driver' => 'daily',
+ 'path' => storage_path('logs/vk-sdk/server.log'),
+ 'level' => env('LOG_LEVEL', 'debug'),
+ 'permissions' => 0755,
+ 'locking' => true,
+ 'days' => 30,
+ 'tap' => JsonLogFormatter::class,
+ ],
],
],
];
diff --git a/src/.root/lang/ru.php b/src/.root/lang/ru.php
index 9fb7c06..a0baa10 100644
--- a/src/.root/lang/ru.php
+++ b/src/.root/lang/ru.php
@@ -110,7 +110,7 @@
'You can\'t see invite link for this chat' => 'Вы не можете видеть пригласительную ссылку для этого чата',
'This is a chat bot feature, change this status in settings' => 'Это функция чат-бота, измените этот статус в настройках',
'You are not admin of this chat' => 'Вы не являетесь администратором этого чата',
- 'Chat does not exist' => 'Чата не существует',
+ 'Tests does not exist' => 'Чата не существует',
'You don\'t have access to this chat' => 'У вас нет доступа к этому чату',
'User not found in chat' => 'Пользователь в чате не найден',
'Contact not found' => 'Контакт не найден',
@@ -168,4 +168,11 @@
'Database or table not found' => 'База данных или таблица не найдены',
'Unknown or unsupported entity used' => 'Используется неизвестная или не поддерживаямая сущность',
'Unknown api exception' => 'Неизвестное исключение API',
+ 'Target keyboard source file not found' => 'Файл указанной клавиатуры не найден',
+ 'Target note source file not found' => 'Файл указанного текста не найден',
+ 'There are no players on the server!' => 'На сервере нет игроков!',
+ 'Invalid SourceQuery argument' => 'Неверный аргумент SourceQuery',
+ 'Failure socket connection' => 'Ошибка подключения к сокету',
+ 'Failure SourceQuery authentication' => 'Ошибка аутентификации SourceQuery',
+ 'Invalid SourceQuery packet' => 'Недопустимый пакет SourceQuery',
];
diff --git a/src/.root/routes/api.php b/src/.root/routes/api.php
new file mode 100644
index 0000000..dfd6385
--- /dev/null
+++ b/src/.root/routes/api.php
@@ -0,0 +1,24 @@
+name('vk.')->group(function () {
+
+ Route::post(SdkConfig::routes('group'), function (CallbackEventsService $callback) {
+ return response($callback->divide(), 200, [
+ 'content-type' => 'application/json;charset=utf-8',
+ 'charset' => 'utf-8'
+ ]);
+ })->name('group');
+
+ Route::post(SdkConfig::routes('server'), function (ServerEventsService $request) {
+ return response($request->divide(), 200, [
+ 'content-type' => 'application/json;charset=utf-8',
+ 'charset' => 'utf-8'
+ ]);
+ })->name('server');
+
+});
diff --git a/src/.root/routes/callbacks.php b/src/.root/routes/callbacks.php
deleted file mode 100644
index 9191825..0000000
--- a/src/.root/routes/callbacks.php
+++ /dev/null
@@ -1,16 +0,0 @@
-name('vk.')->group(function () {
-
- Route::post(SdkConfig::routes('entry'), function (CallbackEventService $callback) {
- return response($callback->division(), 200, [
- 'content-type' => 'application/json;charset=utf-8',
- 'charset' => 'utf-8'
- ]);
- })->name('entry');
-
-});
diff --git a/src/.root/storage/sdk/keyboards/default.json b/src/.root/storage/sdk/keyboards/default.json
new file mode 100644
index 0000000..6841df1
--- /dev/null
+++ b/src/.root/storage/sdk/keyboards/default.json
@@ -0,0 +1,14 @@
+{
+ "buttons": [
+ [
+ {
+ "action": {
+ "type": "text",
+ "label": "Помощь",
+ "payload": ""
+ },
+ "color": "primary"
+ }
+ ]
+ ]
+}
diff --git a/src/.root/storage/sdk/notes/help.md b/src/.root/storage/sdk/notes/help.md
new file mode 100644
index 0000000..6357269
--- /dev/null
+++ b/src/.root/storage/sdk/notes/help.md
@@ -0,0 +1 @@
+Общая информация
diff --git a/src/Exceptions/Callback/KeyboardException.php b/src/Exceptions/Callback/KeyboardException.php
new file mode 100644
index 0000000..2679869
--- /dev/null
+++ b/src/Exceptions/Callback/KeyboardException.php
@@ -0,0 +1,14 @@
+format($this->getMessage()),
+ (new JsonExceptionFormatter())->format($this->getMessage()),
500
);
}
diff --git a/src/Exceptions/SourceQuery/AuthenticationSourceQueryException.php b/src/Exceptions/SourceQuery/AuthenticationSourceQueryException.php
new file mode 100644
index 0000000..60e5e3c
--- /dev/null
+++ b/src/Exceptions/SourceQuery/AuthenticationSourceQueryException.php
@@ -0,0 +1,14 @@
+event = $event;
- $this->object = collect($this->event->get(self::OBJECT));
- }
-
- /**
- * @return int
- */
- public function getGroupId(): int
- {
- return $this->event->get(self::GROUP_ID);
- }
-
- /**
- * @return Collection
- */
- public function getObject(): Collection
- {
- return $this->object;
- }
-
- /**
- * @return Collection
- */
- public function getEvent(): Collection
- {
- return $this->event;
- }
-
- /**
- * @return MessageFields
- */
- public function getMessage(): MessageFields
- {
- return new MessageFields(collect($this->object->get(self::MESSAGE)));
- }
-
- /**
- * @return ClientFields
- */
- public function getClient(): ClientFields
- {
- return new ClientFields(collect($this->object->get(self::CLIENT_INFO)));
- }
-}
diff --git a/src/Foundation/Core/Callback/EventsHandler.php b/src/Foundation/Core/Callback/EventsHandler.php
index d155b02..ef42cb0 100644
--- a/src/Foundation/Core/Callback/EventsHandler.php
+++ b/src/Foundation/Core/Callback/EventsHandler.php
@@ -3,7 +3,10 @@
namespace Hopex\VkSdk\Foundation\Core\Callback;
use Hopex\VkSdk\Contracts\CallbackEventsContract;
+use Hopex\VkSdk\Facades\SdkConfig;
use Hopex\VkSdk\Foundation\Core\Entities\Messages\MessageFields;
+use Illuminate\Support\Facades\Log;
+use Psr\Log\LoggerInterface;
/**
* Class EventsHandler
@@ -11,6 +14,22 @@
*/
abstract class EventsHandler implements CallbackEventsContract
{
+ use SessionTokens {
+ SessionTokens::__construct as sessionsConstruct;
+ }
+
+ /** @var LoggerInterface */
+ protected LoggerInterface $logger;
+
+ /** @var string */
+ protected const SUCCESS = 'ok';
+
+ public function __construct()
+ {
+ $this->sessionsConstruct();
+ $this->logger = Log::build((array)SdkConfig::logging('channels.info'));
+ }
+
/**
* @inheritDoc
*/
diff --git a/src/Foundation/Core/Callback/SessionTokens.php b/src/Foundation/Core/Callback/SessionTokens.php
new file mode 100644
index 0000000..e62de1a
--- /dev/null
+++ b/src/Foundation/Core/Callback/SessionTokens.php
@@ -0,0 +1,80 @@
+setServiceToken(Session::get('service_token'));
+ $this->setGroupToken(Session::get('group_token'));
+ $this->setGroupId(Session::get('group_id'));
+ }
+
+ /**
+ * @return int
+ */
+ public function getGroupId(): int
+ {
+ return $this->groupId;
+ }
+
+ /**
+ * @param int $groupId
+ */
+ public function setGroupId(int $groupId): void
+ {
+ $this->groupId = $groupId;
+ }
+
+ /**
+ * @return string
+ */
+ public function getGroupToken(): string
+ {
+ return $this->groupToken;
+ }
+
+ /**
+ * @param string $groupToken
+ * @return void
+ */
+ public function setGroupToken(string $groupToken): void
+ {
+ $this->groupToken = $groupToken;
+ }
+
+ /**
+ * @return string
+ */
+ public function getServiceToken(): string
+ {
+ return $this->serviceToken;
+ }
+
+ /**
+ * @param string $serviceToken
+ * @return void
+ */
+ public function setServiceToken(string $serviceToken): void
+ {
+ $this->serviceToken = $serviceToken;
+ }
+}
diff --git a/src/Foundation/Core/Sources/Keyboard.php b/src/Foundation/Core/Sources/Keyboard.php
new file mode 100644
index 0000000..da2ff97
--- /dev/null
+++ b/src/Foundation/Core/Sources/Keyboard.php
@@ -0,0 +1,32 @@
+path, $key));
+
+ if (!file_exists($keyboard)) {
+ throw new KeyboardException();
+ }
+
+ return file_get_contents($keyboard);
+ }
+}
diff --git a/src/Foundation/Core/Sources/Note.php b/src/Foundation/Core/Sources/Note.php
new file mode 100644
index 0000000..7208b56
--- /dev/null
+++ b/src/Foundation/Core/Sources/Note.php
@@ -0,0 +1,32 @@
+path, $key));
+
+ if (!file_exists($keyboard)) {
+ throw new NoteException();
+ }
+
+ return file_get_contents($keyboard);
+ }
+}
diff --git a/src/Foundation/Core/Sources/Source.php b/src/Foundation/Core/Sources/Source.php
new file mode 100644
index 0000000..cda6257
--- /dev/null
+++ b/src/Foundation/Core/Sources/Source.php
@@ -0,0 +1,19 @@
+formatters[] = $formatter;
}
+
return $this;
}
@@ -35,6 +36,7 @@ public function format($data): mixed
foreach ($this->formatters as $formatter) {
$data = $formatter->format($data);
}
+
return $data;
}
}
diff --git a/src/Foundation/SdkConfig.php b/src/Foundation/SdkConfig.php
index f18b3be..bfd0e6c 100644
--- a/src/Foundation/SdkConfig.php
+++ b/src/Foundation/SdkConfig.php
@@ -8,12 +8,30 @@
*/
class SdkConfig
{
+ /** @var string */
private const CONFIG_PREFIX = 'vk-sdk';
+
+ /** @var string */
private const CONFIG_ROUTES = 'routes';
+
+ /** @var string */
+
private const CONFIG_API = 'api';
+
+ /** @var string */
+
private const CONFIG_GROUPS = 'groups';
+
+ /** @var string */
+ private const CONFIG_SERVERS = 'servers';
+
+ /** @var string */
+
private const CONFIG_LOGGING = 'logging';
- private const CONFIG_APPS = 'apps';
+
+ /** @var string */
+
+ private const CONFIG_AUTH_APP = 'auth_app';
/**
* @param string|null $key
@@ -60,12 +78,27 @@ public function groups(string $key = null): array|string|null
return $this->query(self::CONFIG_GROUPS . (!$key ? null : ".$key"));
}
+ /**
+ * @param string $ip
+ * @param int $port
+ * @param string|null $key
+ * @return array|string|null
+ */
+ public function servers(string $ip, int $port, string $key = null): array|string|null
+ {
+ return $this->query(
+ self::CONFIG_SERVERS . '.' .
+ str_replace('.', '-', $ip) . "-$port" .
+ (!$key ? null : ".$key")
+ );
+ }
+
/**
* @param string|null $key
* @return array|string|null
*/
- public function apps(string $key = null): array|string|null
+ public function authApp(string $key = null): array|string|null
{
- return $this->query(self::CONFIG_APPS . (!$key ? null : ".$key"));
+ return $this->query(self::CONFIG_AUTH_APP . (!$key ? null : ".$key"));
}
}
diff --git a/src/Foundation/Server.php b/src/Foundation/Server.php
new file mode 100644
index 0000000..9e3258a
--- /dev/null
+++ b/src/Foundation/Server.php
@@ -0,0 +1,157 @@
+Connect($ip, $port);
+ $sourceQuery->SetRconPassword($password);
+ $response = $sourceQuery->Rcon('sm_chat_stats');
+
+ if ($response && $response != 'ok') {
+ Log::build((array)SdkConfig::logging('channels.server'))->notice($response);
+ }
+ } catch (InvalidArgumentException) {
+ throw new InvalidArgumentSourceQueryException();
+ } catch (SocketException) {
+ throw new SocketSourceQueryException();
+ } catch (AuthenticationException) {
+ throw new AuthenticationSourceQueryException();
+ } catch (InvalidPacketException) {
+ throw new InvalidPacketSourceQueryException();
+ } finally {
+ $sourceQuery->Disconnect();
+ }
+ }
+
+ /**
+ * @param array $event
+ * @return void
+ * @throws ApiException
+ * @throws Throwable
+ */
+ public function reSendStatistics(array $event): void
+ {
+ Log::build((array)SdkConfig::logging('channels.server'))->notice($event);
+
+ $ip = $event['server_ip'];
+ $port = $event['server_port'];
+ $scoreTable[] = Note::get('score-table-header');
+ $row = Note::get('score-table-row');
+ $footer = Note::get('score-table-footer');
+
+ $groupId = SdkConfig::servers($ip, $port, 'target_group_id');
+ $groupServerPeerId = SdkConfig::groups("$groupId.server_peer_id");
+ $groupToken = SdkConfig::groups("$groupId.token");
+
+ if (count($event['players']) < 1) {
+ $scoreTable = array_merge($scoreTable, [
+ __('vk-sdk.There are no players on the server!')
+ ]);
+ } else {
+ foreach ($event['players'] as $player) {
+ $team = '4NO TEAM';
+ switch ($player['team']) {
+ case '1':
+ $team = '3SPEC';
+ break;
+ case '2':
+ $team = '2T';
+ break;
+ case '3':
+ $team = '1CT';
+ break;
+ }
+
+ $replacement = SdkConfig::query('replacement');
+ $forbidden = implode('|', $replacement['forbidden']);
+ $scoreTable = array_merge($scoreTable, [
+ str_replace([
+ '%COMMAND%',
+ '%NIK%',
+ '%SCORE%',
+ '%TIME%',
+ '%MUTE%'
+ ], [
+ $team,
+ preg_replace("~$forbidden~", $replacement['replace_to'], $player['name']),
+ sprintf('%d/%d', $player['kills'], $player['deaths']),
+ (new Carbon($player['time']))->format('H:i:s'),
+ (isset($player['mute']) && $player['mute'] != 0 ? '| 🔇' : '')
+ ], $row)
+ ]);
+ }
+
+ sort($scoreTable);
+ foreach ($scoreTable as $index => $item) {
+ if (preg_match('~(^.*)(3S|4N)~', $item)) {
+ $scoreTable = array_merge(array_slice($scoreTable, 0, $index), [
+ $footer
+ ], array_slice($scoreTable, $index, count($scoreTable)));
+ break;
+ }
+ }
+ $scoreTable = array_map(function ($item) {
+ return preg_replace('~(^.*)(\d)(C|T|S|N)~', '$1$3', $item);
+ }, $scoreTable);
+ $scoreTable = str_replace(
+ ['%MAP%', '%PLAYERS%'],
+ [$event['map'], (count($event['players']) ? count($event['bots']) : count($event['players']))],
+ implode('', $scoreTable)
+ );
+ }
+
+ VkApi::message($groupToken)
+ ->send((new MessageRequestFields())
+ ->setPeerId($groupServerPeerId)
+ ->setDisableMentions(true)
+ ->setDontParseLinks(true)
+ ->setMessage($scoreTable)
+ );
+ }
+}
diff --git a/src/Providers/ServiceProvider.php b/src/Providers/ServiceProvider.php
index c77b411..da4a2f5 100644
--- a/src/Providers/ServiceProvider.php
+++ b/src/Providers/ServiceProvider.php
@@ -6,7 +6,11 @@
use Hopex\VkSdk\Foundation\Core\Entities\RequestFields;
use Hopex\VkSdk\Foundation\Format;
use Hopex\VkSdk\Foundation\SdkConfig;
-use Hopex\VkSdk\Services\CallbackEventService;
+use Hopex\VkSdk\Foundation\Core\Sources\Keyboard;
+use Hopex\VkSdk\Foundation\Core\Sources\Note;
+use Hopex\VkSdk\Foundation\Server;
+use Hopex\VkSdk\Services\CallbackEventsService;
+use Hopex\VkSdk\Services\ServerEventsService;
use Illuminate\Support\ServiceProvider as BaseServiceProvider;
class ServiceProvider extends BaseServiceProvider
@@ -18,12 +22,16 @@ class ServiceProvider extends BaseServiceProvider
*/
public function register(): void
{
- $this->app->bind(CallbackEventService::class);
+ $this->app->bind(CallbackEventsService::class);
+ $this->app->bind(ServerEventsService::class);
$this->app->bind('sdkconfig', SdkConfig::class);
$this->app->bind('format', Format::class);
$this->app->bind('vkapi', Client::class);
$this->app->bind('requestfields', RequestFields::class);
+ $this->app->bind('keyboard', Keyboard::class);
+ $this->app->bind('note', Note::class);
+ $this->app->bind('server', Server::class);
}
/**
@@ -41,8 +49,12 @@ public function boot(): void
__DIR__ . '/../.root/lang/ru.php' => $this->app->langPath('ru/vk-sdk.php'),
], 'vk-sdk-lang-ru');
- $this->loadMigrationsFrom(__DIR__ . '/../.root/database/migrations');
+ $this->publishes([
+ __DIR__ . '/../.root/storage/sdk/keyboards' => $this->app->storagePath('app/vk-sdk/keyboards'),
+ __DIR__ . '/../.root/storage/sdk/notes' => $this->app->storagePath('app/vk-sdk/notes'),
+ ], 'vk-sdk-sources');
- $this->loadRoutesFrom(__DIR__ . '/../.root/routes/callbacks.php');
+ $this->loadMigrationsFrom(__DIR__ . '/../.root/database/migrations');
+ $this->loadRoutesFrom(__DIR__ . '/../.root/routes/api.php');
}
}
diff --git a/src/Services/CallbackEventService.php b/src/Services/CallbackEventsService.php
similarity index 79%
rename from src/Services/CallbackEventService.php
rename to src/Services/CallbackEventsService.php
index 0f3bfce..84cb1c3 100644
--- a/src/Services/CallbackEventService.php
+++ b/src/Services/CallbackEventsService.php
@@ -3,7 +3,6 @@
namespace Hopex\VkSdk\Services;
use Hopex\VkSdk\Contracts\CallbackEventsContract;
-use Hopex\VkSdk\Contracts\EventEntityContract;
use Hopex\VkSdk\Exceptions\Callback\SecretException;
use Hopex\VkSdk\Exceptions\Callback\UnknownEntityException;
use Hopex\VkSdk\Exceptions\Callback\UnknownEventException;
@@ -15,19 +14,22 @@
use Illuminate\Database\QueryException;
use Illuminate\Http\Request;
use Illuminate\Support\Collection;
+use Illuminate\Support\Facades\Session;
use Throwable;
-class CallbackEventService
+class CallbackEventsService
{
/** @var string */
- private const OK = 'ok';
+ private const SUCCESS = 'ok';
+
/** @var Request */
public Request $request;
+
/** @var Collection */
private Collection $entities;
/**
- * CallbackEventService constructor.
+ * CallbackEventsService constructor.
* @param Request $request
* @throws Throwable
*/
@@ -41,11 +43,12 @@ public function __construct(Request $request)
}
/**
- * @return string|array|null
+ * @return string
+ * @throws DatabaseOrTableNotFoundException
* @throws Throwable
- * @throws UnknownGroupIdException
+ * @throws UnknownEntityException
*/
- public function division(): string|array|null
+ public function divide(): string
{
$groupId = $this->request->json('group_id');
$eventId = $this->request->json('event_id');
@@ -59,7 +62,7 @@ public function division(): string|array|null
) {
Event::updateOrCreate($this->request->only('group_id', 'type', 'event_id'));
} else {
- return self::OK;
+ return self::SUCCESS;
}
} catch (QueryException) {
throw new DatabaseOrTableNotFoundException();
@@ -75,26 +78,39 @@ public function division(): string|array|null
!method_exists(CallbackEventsContract::class, $event),
UnknownEventException::class
);
+
throw_if(
SdkConfig::groups("$groupId.secret.verify") &&
SdkConfig::groups("$groupId.secret.code") != $this->request->json('secret'),
SecretException::class
);
+
+ $this->updateAccesses($groupId);
call_user_func(
[new (SdkConfig::groups("$groupId.events")), $event],
-// new BaseEvent(collect($this->request->only(['group_id', 'object'])))
$this->selectEntityByRequest()
);
- return self::OK;
+ return self::SUCCESS;
}
}
+ /**
+ * @param int $groupId
+ * @return void
+ */
+ private function updateAccesses(int $groupId): void
+ {
+ Session::put('service_token', SdkConfig::authApp('token'));
+ Session::put('group_token', SdkConfig::groups("$groupId.token"));
+ Session::put('group_id', $groupId);
+ }
+
/**
* @return mixed
* @throws UnknownEntityException
*/
- public function selectEntityByRequest(): mixed
+ private function selectEntityByRequest(): mixed
{
$object = collect($this->request->json('object'));
$entityType = $object->keys()->first();
diff --git a/src/Services/ServerEventsService.php b/src/Services/ServerEventsService.php
new file mode 100644
index 0000000..9e112ee
--- /dev/null
+++ b/src/Services/ServerEventsService.php
@@ -0,0 +1,61 @@
+request = $request;
+ }
+
+ /**
+ * @return string
+ */
+ public function divide(): string
+ {
+ $eventType = $this->request->json('type');
+ $eventObject = array_merge(
+ $this->request->get('object'),
+ $this->request->only(['server_ip', 'server_port'])
+ );
+
+ switch ($eventType)
+ {
+ case 'server_mute_new':
+ Server::reSendMute($eventObject);
+ break;
+ case 'server_ban_new':
+ Server::reSendBan($eventObject);
+ break;
+ case 'server_statistic':
+ Server::reSendStatistics($eventObject);
+ break;
+ case 'server_message_new':
+ Server::reSendMessage($eventObject);
+ break;
+ }
+
+ return self::SUCCESS;
+ }
+}
From d10c4063b21e3f4fe582293c6cb49c5d679f879d Mon Sep 17 00:00:00 2001
From: Schizo
Date: Sat, 7 Jan 2023 04:37:33 +0300
Subject: [PATCH 18/24] =?UTF-8?q?=D0=98=D1=81=D0=BF=D1=80=D0=B0=D0=B2?=
=?UTF-8?q?=D0=BB=D0=B5=D0=BD=20=D1=84=D0=BE=D1=80=D0=BC=D0=B0=D1=82=20?=
=?UTF-8?q?=D0=B2=D1=8B=D0=B2=D0=BE=D0=B4=D0=B0=20=D1=81=D1=82=D0=B0=D1=82?=
=?UTF-8?q?=D0=B8=D1=81=D1=82=D0=B8=D0=BA=D0=B8=20=D1=81=D0=B5=D1=80=D0=B2?=
=?UTF-8?q?=D0=B5=D1=80=D0=B0?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
src/Foundation/Server.php | 17 ++++++++++++-----
src/Services/ServerEventsService.php | 4 +---
2 files changed, 13 insertions(+), 8 deletions(-)
diff --git a/src/Foundation/Server.php b/src/Foundation/Server.php
index 9e3258a..ebd1287 100644
--- a/src/Foundation/Server.php
+++ b/src/Foundation/Server.php
@@ -139,13 +139,20 @@ public function reSendStatistics(array $event): void
$scoreTable = array_map(function ($item) {
return preg_replace('~(^.*)(\d)(C|T|S|N)~', '$1$3', $item);
}, $scoreTable);
- $scoreTable = str_replace(
- ['%MAP%', '%PLAYERS%'],
- [$event['map'], (count($event['players']) ? count($event['bots']) : count($event['players']))],
- implode('', $scoreTable)
- );
}
+ $scoreTable = str_replace([
+ '%MAP%',
+ '%TOTAL%',
+ '%ALIVE%'
+ ], [
+ $event['map'],
+ count($event['players']) + $event['bots'],
+ count($event['players'])
+ ],
+ implode('', $scoreTable)
+ );
+
VkApi::message($groupToken)
->send((new MessageRequestFields())
->setPeerId($groupServerPeerId)
diff --git a/src/Services/ServerEventsService.php b/src/Services/ServerEventsService.php
index 9e112ee..df2eab1 100644
--- a/src/Services/ServerEventsService.php
+++ b/src/Services/ServerEventsService.php
@@ -4,7 +4,6 @@
use Hopex\VkSdk\Facades\Server;
use Illuminate\Http\Request;
-use Illuminate\Support\Facades\Log;
use Throwable;
/**
@@ -40,8 +39,7 @@ public function divide(): string
$this->request->only(['server_ip', 'server_port'])
);
- switch ($eventType)
- {
+ switch ($eventType) {
case 'server_mute_new':
Server::reSendMute($eventObject);
break;
From 3e839c261db2eff9095dad8c77a583e21d7f8058 Mon Sep 17 00:00:00 2001
From: Schizo
Date: Sat, 7 Jan 2023 13:31:53 +0300
Subject: [PATCH 19/24] Added xpaw library to composer
---
composer.json | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
diff --git a/composer.json b/composer.json
index acf3d45..76332a0 100644
--- a/composer.json
+++ b/composer.json
@@ -21,7 +21,8 @@
"repository": "https://github.com/Hopex-Development/laravel-vk-sdk",
"require": {
"php": "^8",
- "ext-json": "*"
+ "ext-json": "*",
+ "xpaw/php-source-query-class": "^2.1"
},
"autoload": {
"psr-4": {
From db3dc5e8652757a3fd6064665ff38c3505e310a7 Mon Sep 17 00:00:00 2001
From: Schizo
Date: Sat, 7 Jan 2023 21:09:51 +0300
Subject: [PATCH 20/24] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB?=
=?UTF-8?q?=D0=B5=D0=BD=20=D0=B2=D1=8B=D0=B2=D0=BE=D0=B4=20=D0=BC=D1=83?=
=?UTF-8?q?=D1=82=D0=BE=D0=B2,=20=D0=B1=D0=B0=D0=BD=D0=BE=D0=B2,=20=D0=BD?=
=?UTF-8?q?=D0=B5=D0=B1=D0=BE=D0=BB=D1=8C=D1=88=D0=B0=D1=8F=20=D0=BE=D0=BF?=
=?UTF-8?q?=D1=82=D0=B8=D0=BC=D0=B8=D0=B7=D0=B0=D1=86=D0=B8=D1=8F=20=D0=BE?=
=?UTF-8?q?=D0=B1=D1=80=D0=B0=D1=89=D0=B5=D0=BD=D0=B8=D0=B9=20=D0=BA=20?=
=?UTF-8?q?=D1=81=D0=B5=D1=80=D0=B2=D0=B5=D1=80=D1=83?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
src/.root/config/vk-sdk.php | 14 +-
src/.root/lang/ru.php | 5 +-
.../storage/sdk/notes/server/blocks/ban.md | 6 +
.../storage/sdk/notes/server/blocks/mute.md | 6 +
.../sdk/notes/server/messages/from-server.md | 3 +
.../sdk/notes/server/messages/to-server.md | 3 +
.../storage/sdk/notes/server/scores/footer.md | 1 +
.../storage/sdk/notes/server/scores/header.md | 7 +
.../storage/sdk/notes/server/scores/row.md | 1 +
src/Contracts/ServerEventsContract.php | 69 ++++++
...ption.php => UnknownVkEntityException.php} | 6 +-
.../Server/UnknownServerEntityException.php | 14 ++
.../Server/UnknownServerException.php | 14 ++
src/Facades/Server.php | 20 --
src/Formatters/ClearInputMessageFormatter.php | 2 +-
.../ClearOutPutMessageFormatter.php | 24 ++
src/Formatters/ScoreTableFormatter.php | 79 +++++++
.../Core/Callback/EventsHandler.php | 2 +-
src/Foundation/Core/Entities/Server/Ban.php | 12 +
src/Foundation/Core/Entities/Server/Block.php | 106 +++++++++
.../Core/Entities/Server/Message.php | 60 +++++
src/Foundation/Core/Entities/Server/Mute.php | 12 +
.../Core/Entities/Server/Player.php | 162 ++++++++++++++
.../Core/Entities/Server/ServerEvent.php | 141 ++++++++++++
.../Core/Entities/Server/Statistics.php | 94 ++++++++
src/Foundation/Core/Server/EventsHandler.php | 205 ++++++++++++++++++
src/Foundation/Core/Sources/Keyboard.php | 3 +-
src/Foundation/Core/Sources/Note.php | 9 +-
src/Foundation/Core/Sources/Source.php | 19 ++
src/Foundation/SdkConfig.php | 14 +-
src/Foundation/Server.php | 164 --------------
src/Providers/ServiceProvider.php | 6 +-
src/Services/CallbackEventsService.php | 10 +-
src/Services/ServerEventsService.php | 68 ++++--
34 files changed, 1131 insertions(+), 230 deletions(-)
create mode 100644 src/.root/storage/sdk/notes/server/blocks/ban.md
create mode 100644 src/.root/storage/sdk/notes/server/blocks/mute.md
create mode 100644 src/.root/storage/sdk/notes/server/messages/from-server.md
create mode 100644 src/.root/storage/sdk/notes/server/messages/to-server.md
create mode 100644 src/.root/storage/sdk/notes/server/scores/footer.md
create mode 100644 src/.root/storage/sdk/notes/server/scores/header.md
create mode 100644 src/.root/storage/sdk/notes/server/scores/row.md
create mode 100644 src/Contracts/ServerEventsContract.php
rename src/Exceptions/Callback/{UnknownEntityException.php => UnknownVkEntityException.php} (51%)
create mode 100644 src/Exceptions/Server/UnknownServerEntityException.php
create mode 100644 src/Exceptions/Server/UnknownServerException.php
delete mode 100644 src/Facades/Server.php
create mode 100644 src/Formatters/ClearOutPutMessageFormatter.php
create mode 100644 src/Formatters/ScoreTableFormatter.php
create mode 100644 src/Foundation/Core/Entities/Server/Ban.php
create mode 100644 src/Foundation/Core/Entities/Server/Block.php
create mode 100644 src/Foundation/Core/Entities/Server/Message.php
create mode 100644 src/Foundation/Core/Entities/Server/Mute.php
create mode 100644 src/Foundation/Core/Entities/Server/Player.php
create mode 100644 src/Foundation/Core/Entities/Server/ServerEvent.php
create mode 100644 src/Foundation/Core/Entities/Server/Statistics.php
create mode 100644 src/Foundation/Core/Server/EventsHandler.php
delete mode 100644 src/Foundation/Server.php
diff --git a/src/.root/config/vk-sdk.php b/src/.root/config/vk-sdk.php
index bce27ab..52398aa 100644
--- a/src/.root/config/vk-sdk.php
+++ b/src/.root/config/vk-sdk.php
@@ -1,6 +1,7 @@
2000000002,
'target_server' => '46.3.223.76:27015',
- 'events' => EventsMapper::class,
+ 'events_handler' => EventsMapper::class,
'allow_retry_events' => true
],
],
@@ -122,6 +123,7 @@
'46-3-223-76-27015' => [
'target_group_id' => 205402271,
'rcon_password' => 'Nr8v6uxuCL8cA5NOx43cypz0DuaqCGP',
+ 'requests_handler' => RequestsMapper::class
],
],
@@ -168,6 +170,16 @@
'days' => 30,
'tap' => JsonLogFormatter::class,
],
+ 'source' => [
+ 'name' => 'vk-sdk-sources',
+ 'driver' => 'daily',
+ 'path' => storage_path('logs/vk-sdk/sources.log'),
+ 'level' => env('LOG_LEVEL', 'debug'),
+ 'permissions' => 0755,
+ 'locking' => true,
+ 'days' => 30,
+ 'tap' => JsonLogFormatter::class,
+ ],
'server' => [
'name' => 'vk-sdk-server',
'driver' => 'daily',
diff --git a/src/.root/lang/ru.php b/src/.root/lang/ru.php
index a0baa10..cb74929 100644
--- a/src/.root/lang/ru.php
+++ b/src/.root/lang/ru.php
@@ -166,7 +166,8 @@
'Unknown callback event' => 'Неизвестное событие',
'Invalid http status code' => 'Недопустимый код состояния http',
'Database or table not found' => 'База данных или таблица не найдены',
- 'Unknown or unsupported entity used' => 'Используется неизвестная или не поддерживаямая сущность',
+ 'Unknown vk entity used' => 'Используется неизвестная сущность ВК',
+ 'Unknown server entity used' => 'Используется неизвестная сущность сервера',
'Unknown api exception' => 'Неизвестное исключение API',
'Target keyboard source file not found' => 'Файл указанной клавиатуры не найден',
'Target note source file not found' => 'Файл указанного текста не найден',
@@ -175,4 +176,6 @@
'Failure socket connection' => 'Ошибка подключения к сокету',
'Failure SourceQuery authentication' => 'Ошибка аутентификации SourceQuery',
'Invalid SourceQuery packet' => 'Недопустимый пакет SourceQuery',
+ 'Unknown server' => 'Неизвестный сервер',
+ 'Undefined server response' => 'Неопределенный ответ сервера',
];
diff --git a/src/.root/storage/sdk/notes/server/blocks/ban.md b/src/.root/storage/sdk/notes/server/blocks/ban.md
new file mode 100644
index 0000000..b1fd414
--- /dev/null
+++ b/src/.root/storage/sdk/notes/server/blocks/ban.md
@@ -0,0 +1,6 @@
+⛔ Игрок получил блокировку на сервере
+================
+👤 Кто выдал: %ADMIN%
+🐩 Кому: %PLAYER%
+⚠ Причина: %REASON%
+⏱ Срок: %TIME%
diff --git a/src/.root/storage/sdk/notes/server/blocks/mute.md b/src/.root/storage/sdk/notes/server/blocks/mute.md
new file mode 100644
index 0000000..ad9bb00
--- /dev/null
+++ b/src/.root/storage/sdk/notes/server/blocks/mute.md
@@ -0,0 +1,6 @@
+🔇 Игрок получил блокировку чата на сервере
+================
+👤 Кто выдал: %ADMIN%
+🐩 Кому: %PLAYER%
+⚠ Причина: %REASON%
+⏱ Срок: %TIME%
diff --git a/src/.root/storage/sdk/notes/server/messages/from-server.md b/src/.root/storage/sdk/notes/server/messages/from-server.md
new file mode 100644
index 0000000..8dd355c
--- /dev/null
+++ b/src/.root/storage/sdk/notes/server/messages/from-server.md
@@ -0,0 +1,3 @@
+✏ Игрок %PLAYER% прислал сообщение с сервера
+================
+%MESSAGE%
diff --git a/src/.root/storage/sdk/notes/server/messages/to-server.md b/src/.root/storage/sdk/notes/server/messages/to-server.md
new file mode 100644
index 0000000..f254cae
--- /dev/null
+++ b/src/.root/storage/sdk/notes/server/messages/to-server.md
@@ -0,0 +1,3 @@
+✏ %PLAYER% написал(-а) сообщение на сервер
+================
+%MESSAGE%
diff --git a/src/.root/storage/sdk/notes/server/scores/footer.md b/src/.root/storage/sdk/notes/server/scores/footer.md
new file mode 100644
index 0000000..48ea612
--- /dev/null
+++ b/src/.root/storage/sdk/notes/server/scores/footer.md
@@ -0,0 +1 @@
+----------------
diff --git a/src/.root/storage/sdk/notes/server/scores/header.md b/src/.root/storage/sdk/notes/server/scores/header.md
new file mode 100644
index 0000000..dee4da4
--- /dev/null
+++ b/src/.root/storage/sdk/notes/server/scores/header.md
@@ -0,0 +1,7 @@
+================
+Карта: %MAP%
+Игроки: %TOTAL% (%ALIVE%)
+================
+[Team] Nik «K/D» (Time) | Mute
+================
+
diff --git a/src/.root/storage/sdk/notes/server/scores/row.md b/src/.root/storage/sdk/notes/server/scores/row.md
new file mode 100644
index 0000000..a1f39b4
--- /dev/null
+++ b/src/.root/storage/sdk/notes/server/scores/row.md
@@ -0,0 +1 @@
+[%COMMAND%] %NIK% «%SCORE%» (%TIME%) %MUTE%
diff --git a/src/Contracts/ServerEventsContract.php b/src/Contracts/ServerEventsContract.php
new file mode 100644
index 0000000..5ff407d
--- /dev/null
+++ b/src/Contracts/ServerEventsContract.php
@@ -0,0 +1,69 @@
+getPlayersCount() < 1) {
+ $scoreTable = array_merge($scoreTable, [
+ __('vk-sdk.There are no players on the server!')
+ ]);
+ } else {
+ /** @var Player $player */
+ foreach ($statistics->getPlayers() as $player) {
+ $scoreTable = array_merge($scoreTable, [
+ str_replace([
+ '%COMMAND%',
+ '%NIK%',
+ '%SCORE%',
+ '%TIME%',
+ '%MUTE%'
+ ], [
+ $player->getTeam(),
+ $player->getName(),
+ sprintf('%d/%d', $player->getKills(), $player->getDeaths()),
+ $player->getTime('H:i:s'),
+ ($player->isMute() ? '| 🔇' : '')
+ ], $row)
+ ]);
+ }
+
+ sort($scoreTable);
+ foreach ($scoreTable as $index => $item) {
+ if (preg_match('~(^.*)(3S|4N)~', $item)) {
+ $scoreTable = array_merge(array_slice($scoreTable, 0, $index), [
+ $footer
+ ], array_slice($scoreTable, $index, count($scoreTable)));
+ break;
+ }
+ }
+ $scoreTable = array_map(function ($item) {
+ return preg_replace('~(^.*)(\d)(C|T|S|N)~', '$1$3', $item);
+ }, $scoreTable);
+ }
+
+ return str_replace([
+ '%MAP%',
+ '%TOTAL%',
+ '%ALIVE%'
+ ], [
+ $statistics->getMap(),
+ $statistics->getPlayersCount() + $statistics->getBots(),
+ $statistics->getPlayersCount()
+ ],
+ implode('', $scoreTable)
+ );
+ }
+}
diff --git a/src/Foundation/Core/Callback/EventsHandler.php b/src/Foundation/Core/Callback/EventsHandler.php
index ef42cb0..420bdc9 100644
--- a/src/Foundation/Core/Callback/EventsHandler.php
+++ b/src/Foundation/Core/Callback/EventsHandler.php
@@ -26,8 +26,8 @@ abstract class EventsHandler implements CallbackEventsContract
public function __construct()
{
- $this->sessionsConstruct();
$this->logger = Log::build((array)SdkConfig::logging('channels.info'));
+ $this->sessionsConstruct();
}
/**
diff --git a/src/Foundation/Core/Entities/Server/Ban.php b/src/Foundation/Core/Entities/Server/Ban.php
new file mode 100644
index 0000000..ddf8e57
--- /dev/null
+++ b/src/Foundation/Core/Entities/Server/Ban.php
@@ -0,0 +1,12 @@
+setAdminName($event['admin_name']);
+ $this->setPlayerName($event['target_name']);
+ $this->setReason($event['reason']);
+ $this->setTime($event['duration']);
+
+ parent::__construct($event);
+ }
+
+ /**
+ * @return string
+ */
+ public function getAdminName(): string
+ {
+ return $this->adminName;
+ }
+
+ /**
+ * @return string
+ */
+ public function getPlayerName(): string
+ {
+ return $this->playerName;
+ }
+
+ /**
+ * @return string
+ */
+ public function getReason(): string
+ {
+ return $this->reason;
+ }
+
+ /**
+ * @return Carbon
+ */
+ public function getTime(): Carbon
+ {
+ return $this->time;
+ }
+
+ /**
+ * @param string $adminName
+ */
+ private function setAdminName(string $adminName): void
+ {
+ $this->adminName = $adminName;
+ }
+
+ /**
+ * @param string $playerName
+ */
+ private function setPlayerName(string $playerName): void
+ {
+ $this->playerName = $playerName;
+ }
+
+ /**
+ * @param string $reason
+ */
+ private function setReason(string $reason): void
+ {
+ $this->reason = $reason;
+ }
+
+ /**
+ * @param int $time
+ */
+ private function setTime(int $time): void
+ {
+ $this->time = new Carbon($time);
+ }
+}
diff --git a/src/Foundation/Core/Entities/Server/Message.php b/src/Foundation/Core/Entities/Server/Message.php
new file mode 100644
index 0000000..d810fea
--- /dev/null
+++ b/src/Foundation/Core/Entities/Server/Message.php
@@ -0,0 +1,60 @@
+setPlayer($event['name']);
+ $this->setText($event['message']);
+
+ parent::__construct($event);
+ }
+
+ /**
+ * @return string
+ */
+ public function getPlayer(): string
+ {
+ return $this->player;
+ }
+
+ /**
+ * @return string
+ */
+ public function getText(): string
+ {
+ return $this->text;
+ }
+
+ /**
+ * @param string $player
+ */
+ private function setPlayer(string $player): void
+ {
+ $this->player = $player;
+ }
+
+ /**
+ * @param string $text
+ */
+ private function setText(string $text): void
+ {
+ $this->text = $text;
+ }
+}
diff --git a/src/Foundation/Core/Entities/Server/Mute.php b/src/Foundation/Core/Entities/Server/Mute.php
new file mode 100644
index 0000000..ffa1647
--- /dev/null
+++ b/src/Foundation/Core/Entities/Server/Mute.php
@@ -0,0 +1,12 @@
+setTeam($team);
+ $this->setName($player['name']);
+ $this->setKills($player['kills']);
+ $this->setDeaths($player['deaths']);
+ $this->setMute($player['mute']);
+ $this->setTime($player['time']);
+ }
+
+ /**
+ * @return string
+ */
+ public function getTeam(): string
+ {
+ return $this->team;
+ }
+
+ /**
+ * @return string
+ */
+ public function getName(): string
+ {
+ return $this->name;
+ }
+
+ /**
+ * @return int
+ */
+ public function getKills(): int
+ {
+ return $this->kills;
+ }
+
+ /**
+ * @return int
+ */
+ public function getDeaths(): int
+ {
+ return $this->deaths;
+ }
+
+ /**
+ * @return bool
+ */
+ public function isMute(): bool
+ {
+ return $this->mute;
+ }
+
+ /**
+ * @param string|null $format
+ * @return Carbon|string
+ */
+ public function getTime(string $format = null): Carbon|string
+ {
+ return $format ? $this->time->format($format) : $this->time;
+ }
+
+ /**
+ * @param string $team
+ */
+ private function setTeam(string $team): void
+ {
+ $this->team = $team;
+ }
+
+ /**
+ * @param string $name
+ */
+ private function setName(string $name): void
+ {
+ $this->name = $name;
+ }
+
+ /**
+ * @param int $kills
+ */
+ private function setKills(int $kills): void
+ {
+ $this->kills = $kills;
+ }
+
+ /**
+ * @param int $deaths
+ */
+ private function setDeaths(int $deaths): void
+ {
+ $this->deaths = $deaths;
+ }
+
+ /**
+ * @param bool $mute
+ */
+ private function setMute(bool $mute): void
+ {
+ $this->mute = $mute;
+ }
+
+ /**
+ * @param int $time
+ */
+ private function setTime(int $time): void
+ {
+ $this->time = new Carbon($time);
+ }
+}
diff --git a/src/Foundation/Core/Entities/Server/ServerEvent.php b/src/Foundation/Core/Entities/Server/ServerEvent.php
new file mode 100644
index 0000000..a6fe5ce
--- /dev/null
+++ b/src/Foundation/Core/Entities/Server/ServerEvent.php
@@ -0,0 +1,141 @@
+setIp($event['server_ip']);
+ $this->setPort($event['server_port']);
+ $this->setGroupId(SdkConfig::servers($this->getIp(), $this->getPort(), 'target_group_id'));
+ $this->setPeerId(SdkConfig::groups("{$this->getGroupId()}.server_peer_id"));
+ $this->setGroupToken(SdkConfig::groups("{$this->getGroupId()}.token"));
+ }
+
+ /**
+ * @return string
+ */
+ public function __toString(): string
+ {
+ return json_encode(get_object_vars($this));
+ }
+
+ /**
+ * @return int
+ */
+ public function getGroupId(): int
+ {
+ return $this->groupId;
+ }
+
+ /**
+ * @return int
+ */
+ public function getPeerId(): int
+ {
+ return $this->peerId;
+ }
+
+ /**
+ * @return string
+ */
+ public function getGroupToken(): string
+ {
+ return $this->groupToken;
+ }
+
+ /**
+ * @return string
+ */
+ public function getIp(): string
+ {
+ return $this->ip;
+ }
+
+ /**
+ * @return int
+ */
+ public function getPort(): int
+ {
+ return $this->port;
+ }
+
+ /**
+ * @param string $ip
+ */
+ private function setIp(string $ip): void
+ {
+ $this->ip = $ip;
+ }
+
+ /**
+ * @param int $port
+ */
+ private function setPort(int $port): void
+ {
+ $this->port = $port;
+ }
+
+ /**
+ * @param int $groupId
+ */
+ private function setGroupId(int $groupId): void
+ {
+ $this->groupId = $groupId;
+ }
+
+ /**
+ * @param int $peerId
+ */
+ private function setPeerId(int $peerId): void
+ {
+ $this->peerId = $peerId;
+ }
+
+ /**
+ * @param string $groupToken
+ */
+ private function setGroupToken(string $groupToken): void
+ {
+ $this->groupToken = $groupToken;
+ }
+}
diff --git a/src/Foundation/Core/Entities/Server/Statistics.php b/src/Foundation/Core/Entities/Server/Statistics.php
new file mode 100644
index 0000000..67b5415
--- /dev/null
+++ b/src/Foundation/Core/Entities/Server/Statistics.php
@@ -0,0 +1,94 @@
+setMap($event['map']);
+ $this->setPlayers($event['players']);
+ $this->setBots($event['bots']);
+
+ parent::__construct($event);
+ }
+
+ /**
+ * @return string
+ */
+ public function getMap(): string
+ {
+ return $this->map;
+ }
+
+ /**
+ * @return Collection
+ */
+ public function getPlayers(): Collection
+ {
+ return $this->players;
+ }
+
+ /**
+ * @return int
+ */
+ public function getPlayersCount(): int
+ {
+ return count($this->players);
+ }
+
+ /**
+ * @return int
+ */
+ public function getBots(): int
+ {
+ return $this->bots;
+ }
+
+ /**
+ * @param string $map
+ */
+ private function setMap(string $map): void
+ {
+ $this->map = $map;
+ }
+
+ /**
+ * @param array $players
+ */
+ private function setPlayers(array $players): void
+ {
+ $this->players = collect($players)->map(function ($player) {
+ return new Player($player);
+ });
+ }
+
+ /**
+ * @param int $bots
+ */
+ private function setBots(int $bots): void
+ {
+ $this->bots = $bots;
+ }
+}
diff --git a/src/Foundation/Core/Server/EventsHandler.php b/src/Foundation/Core/Server/EventsHandler.php
new file mode 100644
index 0000000..0d03080
--- /dev/null
+++ b/src/Foundation/Core/Server/EventsHandler.php
@@ -0,0 +1,205 @@
+logger = Log::build((array)SdkConfig::logging('channels.server'));
+ }
+
+ /**
+ * @inheritDoc
+ */
+ public function server_message_new(Message $message): void
+ {
+ $this->messageSendToVk($message, str_replace([
+ '%PLAYER%',
+ '%MESSAGE%'
+ ], [
+ $message->getPlayer(),
+ $message->getText()
+ ], Note::get('server.messages.from-server')));
+ }
+
+ /**
+ * @inheritDoc
+ */
+ public function server_mute_new(Mute $mute): void
+ {
+ $this->messageSendToVk($mute, str_replace([
+ '%ADMIN%',
+ '%PLAYER%',
+ '%REASON%',
+ '%TIME%'
+ ], [
+ $mute->getAdminName(),
+ $mute->getPlayerName(),
+ $mute->getReason(),
+ $mute->getTime()->format('H:i:s'),
+ ], Note::get('server.blocks.mute')));
+ }
+
+ /**
+ * @inheritDoc
+ */
+ public function server_ban_new(Ban $ban): void
+ {
+ $this->messageSendToVk($ban, str_replace([
+ '%ADMIN%',
+ '%PLAYER%',
+ '%REASON%',
+ '%TIME%'
+ ], [
+ $ban->getAdminName(),
+ $ban->getPlayerName(),
+ $ban->getReason(),
+ $ban->getTime()->format('H:i:s'),
+ ], Note::get('server.blocks.ban')));
+ }
+
+ /**
+ * @inheritDoc
+ * @throws Throwable
+ */
+ public function server_statistic(Statistics $statistics): void
+ {
+ $scoreTable[] = Note::get('server.scores.header');
+ $row = Note::get('server.scores.row');
+ $footer = Note::get('server.scores.footer');
+ $this->messageSendToVk($statistics, (new ScoreTableFormatter())->format([
+ 'stats' => $statistics,
+ 'score_table' => $scoreTable,
+ 'row' => $row,
+ 'footer' => $footer,
+ ]));
+ }
+
+ /**
+ * @param int $groupId
+ * @return void
+ * @throws AuthenticationSourceQueryException
+ * @throws InvalidArgumentSourceQueryException
+ * @throws InvalidPacketSourceQueryException
+ * @throws SocketSourceQueryException
+ */
+ public function requestStatistics(int $groupId): void
+ {
+ $this->logger->info("Statistic requested from group $groupId");
+ $this->sourceQueryCall($groupId, 'sm_chat_stats');
+ }
+
+ /**
+ * @param int $groupId
+ * @param int $peerId
+ * @param string $name
+ * @param string $text
+ * @return void
+ * @throws AuthenticationSourceQueryException
+ * @throws InvalidArgumentSourceQueryException
+ * @throws InvalidPacketSourceQueryException
+ * @throws SocketSourceQueryException
+ */
+ public function messageSendToServer(int $groupId, int $peerId, string $name, string $text): void
+ {
+ $this->logger->info("Message \"$text\" from \"$name\" has been send to server by group $groupId");
+// $this->sourceQueryCall($groupId, 'sm_chat_say "' . $name . '" "' . $text . '"');
+ $this->sourceQueryCall($groupId, "sm_chat_say \"$name\" \"$text\"");
+
+ VkApi::message(Session::get('group_token'))
+ ->send((new MessageRequestFields())
+ ->setPeerId($peerId)
+ ->setDisableMentions(true)
+ ->setDontParseLinks(true)
+ ->setMessage(str_replace([
+ '%PLAYER%',
+ '%MESSAGE%'
+ ], [
+ $name,
+ $text
+ ], Note::get('server.messages.to-server')))
+ );
+ }
+
+ /**
+ * @inheritDoc
+ */
+ public function messageSendToVk(ServerEvent $event, string $message): void
+ {
+ VkApi::message($event->getGroupToken())
+ ->send((new MessageRequestFields())
+ ->setPeerId($event->getPeerId())
+ ->setDisableMentions(true)
+ ->setDontParseLinks(true)
+ ->setMessage((new ClearOutPutMessageFormatter())->format($message))
+ );
+ }
+
+ /**
+ * @throws InvalidArgumentSourceQueryException
+ * @throws SocketSourceQueryException
+ * @throws AuthenticationSourceQueryException
+ * @throws InvalidPacketSourceQueryException
+ */
+ public function sourceQueryCall(int $groupId, string $command): void
+ {
+ $serverConfig = SdkConfig::groups("$groupId.target_server");
+ $ip = preg_replace('~(.*):(\d+)$~', '$1', $serverConfig);
+ $port = preg_replace('~(.*):(\d+)$~', '$2', $serverConfig);
+ $password = SdkConfig::servers($ip, $port, 'rcon_password');
+ $sourceQuery = new SourceQuery();
+
+ try {
+ $sourceQuery->Connect($ip, $port);
+ $sourceQuery->SetRconPassword($password);
+ $this->logger->info($sourceQuery->Rcon($command));
+ } catch (InvalidArgumentException) {
+ throw new InvalidArgumentSourceQueryException();
+ } catch (SocketException) {
+ throw new SocketSourceQueryException();
+ } catch (AuthenticationException) {
+ throw new AuthenticationSourceQueryException();
+ } catch (InvalidPacketException) {
+ throw new InvalidPacketSourceQueryException();
+ } finally {
+ $sourceQuery->Disconnect();
+ }
+ }
+}
diff --git a/src/Foundation/Core/Sources/Keyboard.php b/src/Foundation/Core/Sources/Keyboard.php
index da2ff97..346f7fa 100644
--- a/src/Foundation/Core/Sources/Keyboard.php
+++ b/src/Foundation/Core/Sources/Keyboard.php
@@ -21,9 +21,10 @@ class Keyboard extends Source
*/
public function get(string $key): string
{
- $keyboard = Storage::path(sprintf($this->path, $key));
+ $keyboard = Storage::path(sprintf($this->path, $this->makePath($key)));
if (!file_exists($keyboard)) {
+ $this->logger->emergency("Keyboard not found: $keyboard");
throw new KeyboardException();
}
diff --git a/src/Foundation/Core/Sources/Note.php b/src/Foundation/Core/Sources/Note.php
index 7208b56..935cc45 100644
--- a/src/Foundation/Core/Sources/Note.php
+++ b/src/Foundation/Core/Sources/Note.php
@@ -11,7 +11,7 @@
*/
class Note extends Source
{
- /** @var string */
+ /** @var string */
protected string $path = 'vk-sdk/notes/%s.md';
/**
@@ -21,12 +21,13 @@ class Note extends Source
*/
public function get(string $key): string
{
- $keyboard = Storage::path(sprintf($this->path, $key));
+ $note = Storage::path(sprintf($this->path, $this->makePath($key)));
- if (!file_exists($keyboard)) {
+ if (!file_exists($note)) {
+ $this->logger->emergency("Note not found: $note");
throw new NoteException();
}
- return file_get_contents($keyboard);
+ return file_get_contents($note);
}
}
diff --git a/src/Foundation/Core/Sources/Source.php b/src/Foundation/Core/Sources/Source.php
index cda6257..8d7505c 100644
--- a/src/Foundation/Core/Sources/Source.php
+++ b/src/Foundation/Core/Sources/Source.php
@@ -2,6 +2,10 @@
namespace Hopex\VkSdk\Foundation\Core\Sources;
+use Hopex\VkSdk\Facades\SdkConfig;
+use Illuminate\Support\Facades\Log;
+use Psr\Log\LoggerInterface;
+
/**
* Class Source
* @package Hopex\VkSdk\Foundation\Core\Sources
@@ -11,6 +15,21 @@ abstract class Source
/** @var string */
protected string $path;
+ /**
+ * @var LoggerInterface
+ */
+ protected LoggerInterface $logger;
+
+ /**
+ * @param string $path
+ * @return string
+ */
+ protected function makePath(string $path): string
+ {
+ $this->logger = Log::build((array)SdkConfig::logging('channels.source'));
+ return str_replace('.', DIRECTORY_SEPARATOR, $path);
+ }
+
/**
* @param string $key
* @return string
diff --git a/src/Foundation/SdkConfig.php b/src/Foundation/SdkConfig.php
index bfd0e6c..cad879b 100644
--- a/src/Foundation/SdkConfig.php
+++ b/src/Foundation/SdkConfig.php
@@ -8,28 +8,28 @@
*/
class SdkConfig
{
- /** @var string */
+ /** @var string */
private const CONFIG_PREFIX = 'vk-sdk';
- /** @var string */
+ /** @var string */
private const CONFIG_ROUTES = 'routes';
- /** @var string */
+ /** @var string */
private const CONFIG_API = 'api';
- /** @var string */
+ /** @var string */
private const CONFIG_GROUPS = 'groups';
- /** @var string */
+ /** @var string */
private const CONFIG_SERVERS = 'servers';
- /** @var string */
+ /** @var string */
private const CONFIG_LOGGING = 'logging';
- /** @var string */
+ /** @var string */
private const CONFIG_AUTH_APP = 'auth_app';
diff --git a/src/Foundation/Server.php b/src/Foundation/Server.php
deleted file mode 100644
index ebd1287..0000000
--- a/src/Foundation/Server.php
+++ /dev/null
@@ -1,164 +0,0 @@
-Connect($ip, $port);
- $sourceQuery->SetRconPassword($password);
- $response = $sourceQuery->Rcon('sm_chat_stats');
-
- if ($response && $response != 'ok') {
- Log::build((array)SdkConfig::logging('channels.server'))->notice($response);
- }
- } catch (InvalidArgumentException) {
- throw new InvalidArgumentSourceQueryException();
- } catch (SocketException) {
- throw new SocketSourceQueryException();
- } catch (AuthenticationException) {
- throw new AuthenticationSourceQueryException();
- } catch (InvalidPacketException) {
- throw new InvalidPacketSourceQueryException();
- } finally {
- $sourceQuery->Disconnect();
- }
- }
-
- /**
- * @param array $event
- * @return void
- * @throws ApiException
- * @throws Throwable
- */
- public function reSendStatistics(array $event): void
- {
- Log::build((array)SdkConfig::logging('channels.server'))->notice($event);
-
- $ip = $event['server_ip'];
- $port = $event['server_port'];
- $scoreTable[] = Note::get('score-table-header');
- $row = Note::get('score-table-row');
- $footer = Note::get('score-table-footer');
-
- $groupId = SdkConfig::servers($ip, $port, 'target_group_id');
- $groupServerPeerId = SdkConfig::groups("$groupId.server_peer_id");
- $groupToken = SdkConfig::groups("$groupId.token");
-
- if (count($event['players']) < 1) {
- $scoreTable = array_merge($scoreTable, [
- __('vk-sdk.There are no players on the server!')
- ]);
- } else {
- foreach ($event['players'] as $player) {
- $team = '4NO TEAM';
- switch ($player['team']) {
- case '1':
- $team = '3SPEC';
- break;
- case '2':
- $team = '2T';
- break;
- case '3':
- $team = '1CT';
- break;
- }
-
- $replacement = SdkConfig::query('replacement');
- $forbidden = implode('|', $replacement['forbidden']);
- $scoreTable = array_merge($scoreTable, [
- str_replace([
- '%COMMAND%',
- '%NIK%',
- '%SCORE%',
- '%TIME%',
- '%MUTE%'
- ], [
- $team,
- preg_replace("~$forbidden~", $replacement['replace_to'], $player['name']),
- sprintf('%d/%d', $player['kills'], $player['deaths']),
- (new Carbon($player['time']))->format('H:i:s'),
- (isset($player['mute']) && $player['mute'] != 0 ? '| 🔇' : '')
- ], $row)
- ]);
- }
-
- sort($scoreTable);
- foreach ($scoreTable as $index => $item) {
- if (preg_match('~(^.*)(3S|4N)~', $item)) {
- $scoreTable = array_merge(array_slice($scoreTable, 0, $index), [
- $footer
- ], array_slice($scoreTable, $index, count($scoreTable)));
- break;
- }
- }
- $scoreTable = array_map(function ($item) {
- return preg_replace('~(^.*)(\d)(C|T|S|N)~', '$1$3', $item);
- }, $scoreTable);
- }
-
- $scoreTable = str_replace([
- '%MAP%',
- '%TOTAL%',
- '%ALIVE%'
- ], [
- $event['map'],
- count($event['players']) + $event['bots'],
- count($event['players'])
- ],
- implode('', $scoreTable)
- );
-
- VkApi::message($groupToken)
- ->send((new MessageRequestFields())
- ->setPeerId($groupServerPeerId)
- ->setDisableMentions(true)
- ->setDontParseLinks(true)
- ->setMessage($scoreTable)
- );
- }
-}
diff --git a/src/Providers/ServiceProvider.php b/src/Providers/ServiceProvider.php
index da4a2f5..bee9695 100644
--- a/src/Providers/ServiceProvider.php
+++ b/src/Providers/ServiceProvider.php
@@ -4,11 +4,10 @@
use Hopex\VkSdk\Foundation\Core\Api\Client;
use Hopex\VkSdk\Foundation\Core\Entities\RequestFields;
-use Hopex\VkSdk\Foundation\Format;
-use Hopex\VkSdk\Foundation\SdkConfig;
use Hopex\VkSdk\Foundation\Core\Sources\Keyboard;
use Hopex\VkSdk\Foundation\Core\Sources\Note;
-use Hopex\VkSdk\Foundation\Server;
+use Hopex\VkSdk\Foundation\Format;
+use Hopex\VkSdk\Foundation\SdkConfig;
use Hopex\VkSdk\Services\CallbackEventsService;
use Hopex\VkSdk\Services\ServerEventsService;
use Illuminate\Support\ServiceProvider as BaseServiceProvider;
@@ -31,7 +30,6 @@ public function register(): void
$this->app->bind('requestfields', RequestFields::class);
$this->app->bind('keyboard', Keyboard::class);
$this->app->bind('note', Note::class);
- $this->app->bind('server', Server::class);
}
/**
diff --git a/src/Services/CallbackEventsService.php b/src/Services/CallbackEventsService.php
index 84cb1c3..260b3af 100644
--- a/src/Services/CallbackEventsService.php
+++ b/src/Services/CallbackEventsService.php
@@ -4,9 +4,9 @@
use Hopex\VkSdk\Contracts\CallbackEventsContract;
use Hopex\VkSdk\Exceptions\Callback\SecretException;
-use Hopex\VkSdk\Exceptions\Callback\UnknownEntityException;
use Hopex\VkSdk\Exceptions\Callback\UnknownEventException;
use Hopex\VkSdk\Exceptions\Callback\UnknownGroupIdException;
+use Hopex\VkSdk\Exceptions\Callback\UnknownVkEntityException;
use Hopex\VkSdk\Exceptions\Database\DatabaseOrTableNotFoundException;
use Hopex\VkSdk\Facades\SdkConfig;
use Hopex\VkSdk\Foundation\Core\Entities\Messages\MessageFields;
@@ -46,7 +46,7 @@ public function __construct(Request $request)
* @return string
* @throws DatabaseOrTableNotFoundException
* @throws Throwable
- * @throws UnknownEntityException
+ * @throws UnknownVkEntityException
*/
public function divide(): string
{
@@ -87,7 +87,7 @@ public function divide(): string
$this->updateAccesses($groupId);
call_user_func(
- [new (SdkConfig::groups("$groupId.events")), $event],
+ [new (SdkConfig::groups("$groupId.events_handler")), $event],
$this->selectEntityByRequest()
);
@@ -108,7 +108,7 @@ private function updateAccesses(int $groupId): void
/**
* @return mixed
- * @throws UnknownEntityException
+ * @throws UnknownVkEntityException
*/
private function selectEntityByRequest(): mixed
{
@@ -117,7 +117,7 @@ private function selectEntityByRequest(): mixed
$entityItems = collect($object->get($entityType));
if (!$this->entities->has($entityType)) {
- throw new UnknownEntityException();
+ throw new UnknownVkEntityException();
}
return new ($this->entities->get($entityType))($entityItems);
diff --git a/src/Services/ServerEventsService.php b/src/Services/ServerEventsService.php
index df2eab1..f534d3a 100644
--- a/src/Services/ServerEventsService.php
+++ b/src/Services/ServerEventsService.php
@@ -2,8 +2,15 @@
namespace Hopex\VkSdk\Services;
-use Hopex\VkSdk\Facades\Server;
+use Hopex\VkSdk\Exceptions\Server\UnknownServerEntityException;
+use Hopex\VkSdk\Exceptions\Server\UnknownServerException;
+use Hopex\VkSdk\Facades\SdkConfig;
+use Hopex\VkSdk\Foundation\Core\Entities\Server\Ban;
+use Hopex\VkSdk\Foundation\Core\Entities\Server\Message;
+use Hopex\VkSdk\Foundation\Core\Entities\Server\Mute;
+use Hopex\VkSdk\Foundation\Core\Entities\Server\Statistics;
use Illuminate\Http\Request;
+use Illuminate\Support\Collection;
use Throwable;
/**
@@ -18,6 +25,9 @@ class ServerEventsService
/** @var Request */
public Request $request;
+ /** @var Collection */
+ private Collection $entities;
+
/**
* CallbackEventsService constructor.
* @param Request $request
@@ -25,35 +35,57 @@ class ServerEventsService
*/
public function __construct(Request $request)
{
+ $this->entities = new Collection([
+ 'server_mute_new' => Mute::class,
+ 'server_ban_new' => Ban::class,
+ 'server_statistic' => Statistics::class,
+ 'server_message_new' => Message::class,
+ ]);
+
$this->request = $request;
}
/**
* @return string
+ * @throws UnknownServerEntityException
+ * @throws Throwable
*/
public function divide(): string
{
- $eventType = $this->request->json('type');
- $eventObject = array_merge(
+ $handler = SdkConfig::servers(
+ $this->request->json('server_ip'),
+ $this->request->json('server_port'),
+ 'requests_handler'
+ );
+ throw_if(!$handler, UnknownServerException::class);
+ call_user_func(
+ [new ($handler), $this->request->json('type')],
+ $this->selectEntityByRequest()
+ );
+
+ return self::SUCCESS;
+ }
+
+ /**
+ * @return mixed
+ * @throws UnknownServerEntityException
+ */
+ private function selectEntityByRequest(): mixed
+ {
+ $entityType = $this->request->json('type');
+ $entityItems = array_merge(
$this->request->get('object'),
- $this->request->only(['server_ip', 'server_port'])
+ $this->request->only([
+ 'server_ip',
+ 'server_port',
+ 'type'
+ ])
);
- switch ($eventType) {
- case 'server_mute_new':
- Server::reSendMute($eventObject);
- break;
- case 'server_ban_new':
- Server::reSendBan($eventObject);
- break;
- case 'server_statistic':
- Server::reSendStatistics($eventObject);
- break;
- case 'server_message_new':
- Server::reSendMessage($eventObject);
- break;
+ if (!$this->entities->has($entityType)) {
+ throw new UnknownServerEntityException();
}
- return self::SUCCESS;
+ return new ($this->entities->get($entityType))($entityItems);
}
}
From f984fab7c743f307911c8a5ea41c1b3d6a7668c1 Mon Sep 17 00:00:00 2001
From: Schizo
Date: Sat, 7 Jan 2023 23:04:32 +0300
Subject: [PATCH 21/24] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB?=
=?UTF-8?q?=D0=B5=D0=BD=D1=8B=20=D1=82=D0=B0=D0=B1=D0=BB=D0=B8=D1=86=D1=8B?=
=?UTF-8?q?=20=D0=B4=D0=BB=D1=8F=20=D0=B4=D0=B0=D0=BB=D1=8C=D0=BD=D0=B5?=
=?UTF-8?q?=D0=B9=D1=88=D0=B5=D0=B3=D0=BE=20=D0=BF=D0=B5=D1=80=D0=B5=D1=85?=
=?UTF-8?q?=D0=BE=D0=B4=D0=B0=20=D0=BD=D0=B0=20=D0=91=D0=94?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
README.md | 45 +++++++++++++++++
README_RU.md | 50 -------------------
...3_01_07_000000_create_vk_events_table.php} | 4 +-
...2023_01_07_000001_create_servers_table.php | 30 +++++++++++
...1_07_000002_create_server_blocks_table.php | 30 +++++++++++
...07_000003_create_server_messages_table.php | 30 +++++++++++
..._01_07_000004_create_application_table.php | 27 ++++++++++
src/.root/lang/{ru.php => ru/vk-sdk.php} | 6 +--
.../Core/Entities/Messages/Message.php | 2 +-
src/Foundation/Core/Entities/Server/Block.php | 2 +-
.../Core/Entities/Server/Message.php | 2 +-
src/Foundation/Core/Server/EventsHandler.php | 2 +-
src/Models/Server.php | 22 ++++++++
src/Models/ServerBlock.php | 22 ++++++++
src/Models/ServerMessage.php | 22 ++++++++
src/Models/{Event.php => VkEvent.php} | 9 ++--
src/Providers/ServiceProvider.php | 4 +-
src/Services/CallbackEventsService.php | 6 +--
18 files changed, 247 insertions(+), 68 deletions(-)
create mode 100644 README.md
delete mode 100644 README_RU.md
rename src/.root/database/migrations/{create_events_table.php => 2023_01_07_000000_create_vk_events_table.php} (83%)
create mode 100644 src/.root/database/migrations/2023_01_07_000001_create_servers_table.php
create mode 100644 src/.root/database/migrations/2023_01_07_000002_create_server_blocks_table.php
create mode 100644 src/.root/database/migrations/2023_01_07_000003_create_server_messages_table.php
create mode 100644 src/.root/database/migrations/2023_01_07_000004_create_application_table.php
rename src/.root/lang/{ru.php => ru/vk-sdk.php} (98%)
create mode 100644 src/Models/Server.php
create mode 100644 src/Models/ServerBlock.php
create mode 100644 src/Models/ServerMessage.php
rename src/Models/{Event.php => VkEvent.php} (75%)
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..7985c51
--- /dev/null
+++ b/README.md
@@ -0,0 +1,45 @@
+
+
+
+
+
+
+
+
+
+
+
+# About
+Библиотека VK API SDK разработана для фреймворка Laravel, она позволит просто использовать большинство модулей социальной сети ВКонтакте.
+Мы связали сущности ВКонтакте между собой таким образом, чтобы Вы смогли быстро строить вложенные запросы.
+Библиотека служит хорошим фундаментом для развертывания сложных ботов и включает в себя следующий функционал:
+- Простое и быстрое подтверждение Callback сервера: маршруты уже созданы
+- Обработка событий сообщества (новое сообщение, пост на стене и пр.)
+- Отправка сообщений различных типов в личные чаты и беседы
+- Интеграция с игровыми серверами (SourceQuery)
+- Использование неограниченного количества сообществ и игровых серверов
+
+
+# Installing
+
+1. Запустите команду, используя [composer](https://getcomposer.org/):
+
+```
+composer req hopex/vk-api-sdk
+```
+
+2. Опубликуйте ресурсы:
+
+```
+php artisan vendor:publish --tag=vk-sdk-config --tag=vk-sdk-lang --tag=vk-sdk-sources
+```
+
+3. Выполните миграцию необходимых таблиц:
+
+```
+php artisan migrate
+```
+
+## License
+
+The VK API SDK for Laravel framework is open-sourced software licensed under the [MIT license](https://opensource.org/licenses/MIT).
diff --git a/README_RU.md b/README_RU.md
deleted file mode 100644
index ffc1744..0000000
--- a/README_RU.md
+++ /dev/null
@@ -1,50 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-> #### You can read the [English version](https://github.com/H0pex/laravel-vk-sdk/README_EN)
-
-[Laravel](https://github.com/laravel/laravel) библиотека для упрощенного использования API модулей социальной сети
-ВКонтакте.
-Предназначена для быстрого развертывания приложений-ботов, а также использования VK API в одностороннем порядке.
-
-# Установка
-
-Осуществить установку можно используя [composer](https://getcomposer.org/):
-
-```
-composer require hopex/vk-api-sdk
-```
-
-Публикация необходимых ресурсов:
-
-```
-php artisan vendor:publish --tag=vk-sdk-config --tag=vk-sdk-lang
-```
-
-Провайдер и фасады будут автоматически зарегистрированы, однако вы можете вручную добавить их в `config/app.php`.
-
-```php
-'providers' => [
- // ...
- Hopex\VkApiSdk\Providers\ServiceProvider::class,
-],
-'aliases' => Facade::defaultAliases()->merge([
- // ...
- 'VkApi' => \Hopex\VkSdk\Foundation\Core\Api\Client::class,
- 'Format' => \Hopex\VkSdk\Foundation\Format::class,
- 'SdkConfig' => \Hopex\VkSdk\Foundation\SdkConfig::class,
-])->toArray(),
-```
-
-# Лицензия
-
-[MIT License](https://github.com/H0pex/vk-api-sdk/LICENSE)
diff --git a/src/.root/database/migrations/create_events_table.php b/src/.root/database/migrations/2023_01_07_000000_create_vk_events_table.php
similarity index 83%
rename from src/.root/database/migrations/create_events_table.php
rename to src/.root/database/migrations/2023_01_07_000000_create_vk_events_table.php
index 2b93944..5c1c651 100644
--- a/src/.root/database/migrations/create_events_table.php
+++ b/src/.root/database/migrations/2023_01_07_000000_create_vk_events_table.php
@@ -10,7 +10,7 @@
*/
public function up(): void
{
- Schema::create('vk__events', function (Blueprint $table) {
+ Schema::create('vk_events', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('group_id');
$table->string('type');
@@ -24,6 +24,6 @@ public function up(): void
*/
public function down(): void
{
- Schema::dropIfExists('vk__events');
+ Schema::dropIfExists('vk_events');
}
};
diff --git a/src/.root/database/migrations/2023_01_07_000001_create_servers_table.php b/src/.root/database/migrations/2023_01_07_000001_create_servers_table.php
new file mode 100644
index 0000000..b8ea512
--- /dev/null
+++ b/src/.root/database/migrations/2023_01_07_000001_create_servers_table.php
@@ -0,0 +1,30 @@
+id();
+ $table->string('ip');
+ $table->unsignedInteger('port');
+ $table->string('rcon_password');
+ $table->timestamps();
+ });
+ }
+
+ /**
+ * @return void
+ */
+ public function down(): void
+ {
+ Schema::dropIfExists('servers');
+ }
+};
diff --git a/src/.root/database/migrations/2023_01_07_000002_create_server_blocks_table.php b/src/.root/database/migrations/2023_01_07_000002_create_server_blocks_table.php
new file mode 100644
index 0000000..b08bf9d
--- /dev/null
+++ b/src/.root/database/migrations/2023_01_07_000002_create_server_blocks_table.php
@@ -0,0 +1,30 @@
+id();
+ $table->foreignIdFor(Server::class, 'server_id');
+ $table->string('type');
+ $table->string('player');
+ $table->timestamps();
+ });
+ }
+
+ /**
+ * @return void
+ */
+ public function down(): void
+ {
+ Schema::dropIfExists('server_blocks');
+ }
+};
diff --git a/src/.root/database/migrations/2023_01_07_000003_create_server_messages_table.php b/src/.root/database/migrations/2023_01_07_000003_create_server_messages_table.php
new file mode 100644
index 0000000..8dabb71
--- /dev/null
+++ b/src/.root/database/migrations/2023_01_07_000003_create_server_messages_table.php
@@ -0,0 +1,30 @@
+id();
+ $table->foreignIdFor(Server::class, 'server_id');
+ $table->string('player');
+ $table->string('text');
+ $table->timestamps();
+ });
+ }
+
+ /**
+ * @return void
+ */
+ public function down(): void
+ {
+ Schema::dropIfExists('server_messages');
+ }
+};
diff --git a/src/.root/database/migrations/2023_01_07_000004_create_application_table.php b/src/.root/database/migrations/2023_01_07_000004_create_application_table.php
new file mode 100644
index 0000000..b804b35
--- /dev/null
+++ b/src/.root/database/migrations/2023_01_07_000004_create_application_table.php
@@ -0,0 +1,27 @@
+id();
+ $table->boolean('production')->default(false);
+ });
+ }
+
+ /**
+ * @return void
+ */
+ public function down(): void
+ {
+ Schema::dropIfExists('application');
+ }
+};
diff --git a/src/.root/lang/ru.php b/src/.root/lang/ru/vk-sdk.php
similarity index 98%
rename from src/.root/lang/ru.php
rename to src/.root/lang/ru/vk-sdk.php
index cb74929..d2e5893 100644
--- a/src/.root/lang/ru.php
+++ b/src/.root/lang/ru/vk-sdk.php
@@ -119,12 +119,12 @@
'Can\'t edit this kind of message' => 'Невозможно отредактировать сообщение такого типа',
'Your community can\'t interact with this peer' => 'Ваше сообщество не может взаимодействовать с этим диалогом',
'Keyboard format is invalid' => 'Недопустимый формат клавиатуры',
- 'Message request already send' => 'Запрос на сообщение уже отправлен',
- 'Message request already sent' => 'Запрос на сообщение уже отправлен',
+ 'ServerMessage request already send' => 'Запрос на сообщение уже отправлен',
+ 'ServerMessage request already sent' => 'Запрос на сообщение уже отправлен',
'Can\'t send messages to this user due to their privacy settings' => 'Невозможно отправить сообщение этому пользователю из-за его настроек конфиденциальности',
'Can\'t sent this message, because it\'s too big' => 'Невозможно отправить это сообщение, потому что оно слишком большое',
'Too many forwarded messages' => 'Слишком много пересылаемых сообщений',
- 'Message is too long' => 'Сообщение слишком длинное',
+ 'ServerMessage is too long' => 'Сообщение слишком длинное',
'Too many posts in messages' => 'Слишком много постов в сообщениях',
'Value of ts or pts is too new' => 'Значение ts или pts слишком новое',
'Value of ts or pts is too old' => 'Значение ts или pts слишком старое',
diff --git a/src/Foundation/Core/Entities/Messages/Message.php b/src/Foundation/Core/Entities/Messages/Message.php
index 7efb3a5..4602831 100644
--- a/src/Foundation/Core/Entities/Messages/Message.php
+++ b/src/Foundation/Core/Entities/Messages/Message.php
@@ -8,7 +8,7 @@
use Throwable;
/**
- * Class Message
+ * Class ServerMessage
* @package Hopex\VkSdk\Foundation\Core\Entities\Messages
*/
class Message extends Request
diff --git a/src/Foundation/Core/Entities/Server/Block.php b/src/Foundation/Core/Entities/Server/Block.php
index 9b77345..784aced 100644
--- a/src/Foundation/Core/Entities/Server/Block.php
+++ b/src/Foundation/Core/Entities/Server/Block.php
@@ -5,7 +5,7 @@
use Carbon\Carbon;
/**
- * Class Block
+ * Class ServerBlock
* @package Hopex\VkSdk\Foundation\Core\Entities\Server
*/
abstract class Block extends ServerEvent
diff --git a/src/Foundation/Core/Entities/Server/Message.php b/src/Foundation/Core/Entities/Server/Message.php
index d810fea..c049db8 100644
--- a/src/Foundation/Core/Entities/Server/Message.php
+++ b/src/Foundation/Core/Entities/Server/Message.php
@@ -3,7 +3,7 @@
namespace Hopex\VkSdk\Foundation\Core\Entities\Server;
/**
- * Class Message
+ * Class ServerMessage
* @package Hopex\VkSdk\Foundation\Core\Entities\Server
*/
class Message extends ServerEvent
diff --git a/src/Foundation/Core/Server/EventsHandler.php b/src/Foundation/Core/Server/EventsHandler.php
index 0d03080..5771161 100644
--- a/src/Foundation/Core/Server/EventsHandler.php
+++ b/src/Foundation/Core/Server/EventsHandler.php
@@ -139,7 +139,7 @@ public function requestStatistics(int $groupId): void
*/
public function messageSendToServer(int $groupId, int $peerId, string $name, string $text): void
{
- $this->logger->info("Message \"$text\" from \"$name\" has been send to server by group $groupId");
+ $this->logger->info("ServerMessage \"$text\" from \"$name\" has been send to server by group $groupId");
// $this->sourceQueryCall($groupId, 'sm_chat_say "' . $name . '" "' . $text . '"');
$this->sourceQueryCall($groupId, "sm_chat_say \"$name\" \"$text\"");
diff --git a/src/Models/Server.php b/src/Models/Server.php
new file mode 100644
index 0000000..9aad459
--- /dev/null
+++ b/src/Models/Server.php
@@ -0,0 +1,22 @@
+publishes([
- __DIR__ . '/../.root/lang/ru.php' => $this->app->langPath('ru/vk-sdk.php'),
- ], 'vk-sdk-lang-ru');
+ __DIR__ . '/../.root/lang/' => $this->app->langPath('/'),
+ ], 'vk-sdk-lang');
$this->publishes([
__DIR__ . '/../.root/storage/sdk/keyboards' => $this->app->storagePath('app/vk-sdk/keyboards'),
diff --git a/src/Services/CallbackEventsService.php b/src/Services/CallbackEventsService.php
index 260b3af..1834e0e 100644
--- a/src/Services/CallbackEventsService.php
+++ b/src/Services/CallbackEventsService.php
@@ -10,7 +10,7 @@
use Hopex\VkSdk\Exceptions\Database\DatabaseOrTableNotFoundException;
use Hopex\VkSdk\Facades\SdkConfig;
use Hopex\VkSdk\Foundation\Core\Entities\Messages\MessageFields;
-use Hopex\VkSdk\Models\Event;
+use Hopex\VkSdk\Models\VkEvent;
use Illuminate\Database\QueryException;
use Illuminate\Http\Request;
use Illuminate\Support\Collection;
@@ -57,10 +57,10 @@ public function divide(): string
try {
if (
SdkConfig::groups("$groupId.allow_retry_events") ||
- !Event::where('event_id', $eventId)->first() ||
+ !VkEvent::where('event_id', $eventId)->first() ||
!$eventId
) {
- Event::updateOrCreate($this->request->only('group_id', 'type', 'event_id'));
+ VkEvent::updateOrCreate($this->request->only('group_id', 'type', 'event_id'));
} else {
return self::SUCCESS;
}
From f9e2ac678ce7cdd5c9bb3665606d0f1715bb282c Mon Sep 17 00:00:00 2001
From: Schizo
Date: Sun, 8 Jan 2023 17:20:30 +0300
Subject: [PATCH 22/24] Readme file has been updated (badges and description)
---
README.md | 32 ++++++++++++++++----------------
1 file changed, 16 insertions(+), 16 deletions(-)
diff --git a/README.md b/README.md
index 7985c51..f874373 100644
--- a/README.md
+++ b/README.md
@@ -1,40 +1,40 @@
-
+
-
-
-
-
+
+
+
+
# About
-Библиотека VK API SDK разработана для фреймворка Laravel, она позволит просто использовать большинство модулей социальной сети ВКонтакте.
-Мы связали сущности ВКонтакте между собой таким образом, чтобы Вы смогли быстро строить вложенные запросы.
-Библиотека служит хорошим фундаментом для развертывания сложных ботов и включает в себя следующий функционал:
-- Простое и быстрое подтверждение Callback сервера: маршруты уже созданы
-- Обработка событий сообщества (новое сообщение, пост на стене и пр.)
-- Отправка сообщений различных типов в личные чаты и беседы
-- Интеграция с игровыми серверами (SourceQuery)
-- Использование неограниченного количества сообществ и игровых серверов
+The VK API SDK library is developed for the Laravel framework, it will allow you to use most of the modules of the VKontakte social network simply.
+We have linked VKontakte entities to each other in such a way that you can quickly build the subqueries.
+The library provides a good foundation for deploying complex bots and includes the following functionality:
+- Simple and quick confirmation of the Callback server: routes have already been created
+- Processing community events (new message, wall post, etc.)
+- Sending messages of various types to personal and group chats
+- Integration with game servers (SourceQuery)
+- The use of an unlimited number of communities and game servers
# Installing
-1. Запустите команду, используя [composer](https://getcomposer.org/):
+1. Run the command using [composer](https://getcomposer.org/):
```
composer req hopex/vk-api-sdk
```
-2. Опубликуйте ресурсы:
+2. Publish resources:
```
php artisan vendor:publish --tag=vk-sdk-config --tag=vk-sdk-lang --tag=vk-sdk-sources
```
-3. Выполните миграцию необходимых таблиц:
+3. Migrate the necessary tables:
```
php artisan migrate
From 722b1c7eb060da7335ddab6456a03e95bc15d703 Mon Sep 17 00:00:00 2001
From: Schizo
Date: Sun, 8 Jan 2023 17:27:28 +0300
Subject: [PATCH 23/24] Added laravel version to readme
---
README.md | 7 ++++---
1 file changed, 4 insertions(+), 3 deletions(-)
diff --git a/README.md b/README.md
index f874373..2df79f5 100644
--- a/README.md
+++ b/README.md
@@ -3,9 +3,10 @@
-
-
-
+
+
+
+
From 75a3f6212c21a32ea257523a90c0aed460bbc2fc Mon Sep 17 00:00:00 2001
From: Schizo
Date: Sun, 8 Jan 2023 17:30:30 +0300
Subject: [PATCH 24/24] Description updated
---
README.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/README.md b/README.md
index 2df79f5..557691d 100644
--- a/README.md
+++ b/README.md
@@ -17,6 +17,7 @@ The library provides a good foundation for deploying complex bots and includes t
- Simple and quick confirmation of the Callback server: routes have already been created
- Processing community events (new message, wall post, etc.)
- Sending messages of various types to personal and group chats
+- Adding censorship to messages and player names sent from the game server
- Integration with game servers (SourceQuery)
- The use of an unlimited number of communities and game servers