PHP code example of yakoffka / laravel-notification-channels-ru-store

1. Go to this page and download the library: Download yakoffka/laravel-notification-channels-ru-store library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

yakoffka / laravel-notification-channels-ru-store example snippets



    /**
     * Получение массива ru-store push-токенов пользователя.
     * Используется пакетом yakoffka/laravel-notification-channels-ru-store (laravel-notification-channels/rustore)
     *
     * @return array<int|string, mixed>
     */
    public function routeNotificationForRuStore(): array
    {
        return $this->rustore_push_tokens;
    }


declare(strict_types=1);

namespace App\Notifications\Development;

use App\Models\User;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Notification;
use NotificationChannels\RuStore\Resources\MessageAndroid;
use NotificationChannels\RuStore\Resources\MessageAndroidNotification;
use NotificationChannels\RuStore\Resources\MessageNotification;
use NotificationChannels\RuStore\RuStoreChannel;
use NotificationChannels\RuStore\RuStoreMessage;

/**
 * Уведомление пользователя, отправляемое через консоль для проверки работы канала RuStore
 */
class RuStoreTestNotification extends Notification implements ShouldQueue
{
    use Queueable;

    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct(public readonly string $title, public readonly string $body)
    {
    }

    /**
     * Get the notification's delivery channels.
     *
     * @param User $notifiable
     * @return array
     */
    public function via(User $notifiable): array
    {
        return [
            RuStoreChannel::class, // указать канал отправки RuStoreChannel
        ];
    }

    /**
     * Формирование сообщения, отправляемого через RuStoreChannel
     *
     * @param User $notifiable
     * @return RuStoreMessage
     */
    public function toRuStore(User $notifiable): RuStoreMessage
    {
        return (new RuStoreMessage(
            notification: new MessageNotification(
                title: 'Test Push by RuStore',
                body: 'Hello! Test body from RuStoreTestingNotification',
            ),
            android: new MessageAndroid(
                notification: new MessageAndroidNotification(
                    title: 'Android test Push by RuStore',
                    body: 'Hello! Android test body from RuStoreTestingNotification',
                )
            )
        ));
    }
}


    // class SentListener

    /**
     * Обработка успешно отправленных сообщений
     */
    public function handle(NotificationSent $event): void
    {
        match ($event->channel) {
            RuStoreChannel::class => $this->handleRuStoreSuccess($event),
            default => null
        };
    }

    /**
     * Логирование успешно отправленных ru-store-уведомлений
     */
    public function handleRuStoreSuccess(NotificationSent $event): void
    {
        /** @var Collection<string, RuStoreReport> $reports */
        $reports = $event->response;

        $tokens = $reports->map(fn(RuStoreReport $singleReport) => $singleReport->target());
        if ($tokens->isNotEmpty()) {
            /** @var NotifiableUser $notifiable */
            $notifiable = $event->notifiable;

            Log::channel('notifications_ru_store')->info("Успешно отправлены уведомления {$notifiable->short_info}", [
                'tokens' =>  $tokens->toArray(),
            ]);
        }
    }


    // class FailedSendingListener

    public function handle(NotificationFailed $event): void
    {
        match ($event->channel) {
            RuStoreChannel::class => $this->handleRuStoreFailed($event),
            default => null
        };
    }

    /**
     * Обработка неудачной отправки ru-store-уведомлений
     *
     * @param NotificationFailed $event
     * @return void
     */
    private function handleRuStoreFailed(NotificationFailed $event): void
    {
        /** @var RuStoreReport $report */
        $report = Arr::get($event->data, 'report'); // @todo $report может быть null: падение до отправки!
        /** @var Throwable $e */
        $e = $report->error();
        /** @var NotifiableUser $notifiable */
        $notifiable = $event->notifiable;

        Log::channel('notifications_ru_store')
            ->error("Ошибка отправки уведомления {$notifiable->short_info} " . $e::class, compact('event'));

        if ($e::class === NotFoundException::class || $e::class === InvalidPushTokenException::class) {
            resolve(RuStorePushService::class)->deleteRuStoreToken($notifiable, $report->target(), $e);
        }
    }

bash
  php artisan vendor:publish --provider="NotificationChannels\RuStore\RuStoreServiceProvider"