norkunas / onesignal-php-api

OneSignal API for PHP
MIT License
233 stars 82 forks source link

Integrate with symfony 2 #62

Closed tjaoc closed 6 years ago

tjaoc commented 7 years ago

Hello,

How integrate with symfony 2?

The bundle dizda/OnesignalApiBundle work with version 0.1.0 and i´m version 1 with Guzzle 6.

Thanks

norkunas commented 7 years ago

Hey @tiacruz,

You could use http://docs.php-http.org/en/latest/integrations/symfony-bundle.html and then register this library as a service and pass the httplug client.

httplug:
    clients:
        acme:
            factory: 'httplug.factory.guzzle6'

services:
    app.onesignal_config:
        class: OneSignal\Config
        calls:
            - ["setApplicationId", ["your_app_id"]]
            - ["setApplicationAuthKey", ["your_app_auth_key"]]
            - ["setUserAuthKey", ["your_auth_key"]]
    app.onesignal:
        class: OneSignal\OneSignal
        arguments:
            - "@app.onesignal_config"
            - "@httplug.client.acme"
tjaoc commented 7 years ago

Very Thanks, but i´m please other help.

This is my 3 files on my config. Before i´m ionic push service, and i´m interesed in change to OneSginal, it´s posible verify my files and help me the changes to integrate OneSignal Pease?

I´m sorry for my bad English.

OneSginalPushService.php

`<?php

namespace AppBundle\Services;

use GuzzleHttp\Client; use Monolog\Logger; use Http\Adapter\Guzzle6\Client as GuzzleAdapter; use Http\Client\Common\HttpMethodsClient as HttpClient; use Http\Message\MessageFactory\GuzzleMessageFactory; use OneSignal\Config; use OneSignal\Devices; use OneSignal\OneSignal;

class OneSignalPushService {

protected $client;
protected $logger;

public function __construct(Client $client, Logger $logger)
{

    $this->client = $client;
    $this->logger = $logger;

}

/**
 * Get the list of push sent so far
 */
public function getPushList()
{

    $response = $this->client->get("/push/notifications");

}

/**
 * @param string $message
 * Send push to all registered devices
 */
public function sendPushToAll($message)
{

    $this->logger->info("sending push to all users");

    $json = [
        "notification" => ["message" => $message],
        "profile" => "prod",
        "send_to_all" => true,
        "tokens" => []
    ];

    $this->client->post("/push/notifications", ["json" => $json]);
}

public function sendPushToUsers($message, $tokens)
{

    $this->logger->info("sending push to selected users");
    $this->logger->critical("Sending push");

    $json = [
        "notification" => ["message" => $message],
        "profile" => "prod",
        "tokens" => $tokens
    ];

    $this->client->post("/push/notifications", ["json" => $json]);
}

}`

ComunicationsManager.php

`<?php

namespace AppBundle\Comunications;

use AppBundle\Entity\Comunication; use AppBundle\Entity\User; use AppBundle\Entity\View; use AppBundle\Services\WNSPushService; use Doctrine\ORM\EntityManager; use Knp\Component\Pager\Paginator; use AppBundle\Services\OneSignalPushService;

class ComunicationsManager {

protected $em;

private $logger;
private $pusher;
private $paginator;
private $windowsPusher;

public function __construct(EntityManager $em, OneSignalPushService $pusher, Paginator $paginator, WNSPushService $windowsPusher)
{

    $this->em = $em;
    $this->pusher = $pusher;
    $this->paginator = $paginator;
    $this->windowsPusher = $windowsPusher;

}

public function getGroupComunicates($group)
{

    if ($this->em) {
        $comunicationsRepository = $this->em->getRepository(Comunication::class);

        $qb = $comunicationsRepository->createQueryBuilder("com");
        $qb->where("com.type = 2")
            ->andWhere("com.workgroup = :group")
            ->orderBy("com.date", "DESC")
            ->setParameter("group", $group);

        return $qb->getQuery()->getResult();
    } else {
        return null;
    }

}

public function getGeneralComunicatesPaginator($page = 1, $limit = 10)
{

    $comunicationsRepository = $this->em->getRepository(Comunication::class);
    $qb = $comunicationsRepository->createQueryBuilder("com");
    $qb = $qb->where("com.type = 1")->orderBy("com.date", "DESC");;

    return $this->paginator->paginate($qb->getQuery(), $page, $limit, array('pageParameterName' => 'general_com_page'));

}

public function getGroupComunicatesPaginator($user, $group, $page = 1, $limit = 10)
{

    $comunicationsRepository = $this->em->getRepository(Comunication::class);
    $qb = $comunicationsRepository->createQueryBuilder("com");
    $qb->where("com.type = 2")->andWhere("com.workgroup = :group OR com.author = :user")->setParameters(["group" => $group, "user" => $user])->orderBy("com.date", "DESC");

    return $this->paginator->paginate($qb->getQuery(), $page, $limit, array('pageParameterName' => 'group_com_page'));

}

/**
 * @param User $user
 * @param int $page
 * @param int $limit
 * @return \Knp\Component\Pager\Pagination\PaginationInterface
 */
public function getDirectComunicatesPaginator(User $user, $page = 1, $limit = 10)
{

    $comunicationsRepository = $this->em->getRepository(Comunication::class);
    $qb = $comunicationsRepository->createQueryBuilder("com")->where("com.type = 3")->andWhere(":u MEMBER OF com.users OR com.author = :u")->setParameter("u", $user)->orderBy("com.date", "DESC");
    return $this->paginator->paginate($qb->getQuery(), $page, $limit, array('pageParameterName' => 'direct_com_page'));

}

public function getGeneralComunicates()
{

    if ($this->em) {
        $comunicationsRepository = $this->em->getRepository(Comunication::class);

        $qb = $comunicationsRepository->createQueryBuilder("com")->orderBy("com.date", "DESC");
        $qb->where("com.type = 1");

        return $qb->getQuery()->getResult();

    } else {
        return null;
    }

}

public function getUnreadGeneralComunicates(User $user)
{
    $dql = "SELECT com from AppBundle:Comunication  com WHERE com.type = 1 AND  com.id NOT IN ( SELECT IDENTITY(view.message) FROM AppBundle:View view WHERE view.user = :user) ORDER BY com.date DESC";
    $query = $this->em->createQuery($dql);
    $query->setParameter("user", $user);
    $messages = $query->getResult();
    return $messages;

}

public function getUnreadGroupComunicates(User $user, $group)
{

    $dql = "SELECT com from AppBundle:Comunication  com WHERE com.type = 2 AND com.workgroup = :group AND  com.id NOT IN ( SELECT IDENTITY(view.message) FROM AppBundle:View view WHERE view.user = :user) ORDER BY com.date DESC";
    $query = $this->em->createQuery($dql);
    $query->setParameters(["group" => $group, 'user' => $user]);

    $messages = $query->getResult();
    return $messages;

}

public function getUnreadDirectComunicates(User $user)
{

    $dql = "SELECT com from AppBundle:Comunication  com WHERE com.type = 3 AND :user MEMBER OF com.users AND  com.id NOT IN ( SELECT IDENTITY(view.message) FROM AppBundle:View view WHERE view.user = :user) ORDER BY com.date DESC";
    $query = $this->em->createQuery($dql);
    $query->setParameter("user", $user);
    $messages = $query->getResult();
    return $messages;
}

public function save($comunicate)
{

    $this->em->persist($comunicate);
    $this->em->flush();
    $this->notifyUsers($comunicate);

}

/**
 * @param Comunication $comunicate
 */
protected function notifyUsers($comunicate)
{

    switch ($comunicate->getType()) {
        case Comunication::TYPE_GENERAL: {
            $users = $this->em->getRepository(User::class)->findBy(["device_type" => [User::DEVICE_WP, User::DEVICE_WEB]]);
            $this->pusher->sendPushToAll($comunicate->getTitle());
            $this->windowsPusher->sendPushToUsers($comunicate, $users);
            break;
        }
        case Comunication::TYPE_GROUP: {

            $group = $comunicate->getWorkgroup();
            $users = $group->getMembers();
            $tokens = $this->tokenFromUsers($users);
            $this->pusher->sendPushToUsers($comunicate->getTitle(), $tokens);
            $this->windowsPusher->sendPushToUsers($comunicate, $users);
            break;
        }
        case Comunication::TYPE_DIRECT: {
            $tokens = $this->tokenFromUsers($comunicate->getUsers());
            $this->pusher->sendPushToUsers($comunicate->getTitle(), $tokens);
            $this->windowsPusher->sendPushToUsers($comunicate, $comunicate->getUsers());

        }

    }

}

/**
 * @param $users
 * @return array $tokens
 */
protected function tokenFromUsers($users)
{
    $tokens = [];
    foreach ($users as $user) {
        if ($user->getDeviceToken() != null) {
            $tokens[] = $user->getDeviceToken();
        }
    }
    return $tokens;
}

/**
 * @param User $user
 * @brief Get the comunicates the user is into
 *         and the user, if it was the only user, the comunicate gets deleted as well
 *
 */
public function removeUserFromComunicates(User $user)
{

    $user_comunicates = $this->getDirectComunicates($user);
    //remove the user for all the comunicates
    foreach ($user_comunicates as $comunicate) {
        $comunicate->removeUser($user);
        if (count($comunicate->getUsers()) == 0) {
            //this was the only user, delete as well the comunicate
            $this->em->remove($comunicate);
        } else {
            //save it with less users
            $this->em->persist($comunicate);
        }

    }
    $comunicates = $this->getUserComunicates($user);
    if (count($comunicates) > 0) {
        foreach ($comunicates as $comunicate) {
            $this->em->remove($comunicate);
        }
    }
    $this->em->flush();

}

public function getDirectComunicates(User $user)
{

    $comunicationsRepository = $this->em->getRepository(Comunication::class);
    $qb = $comunicationsRepository->createQueryBuilder("com")
        ->where("com.type = 3")
        ->andWhere(":u MEMBER OF com.users")
        ->orderBy("com.date", "DESC")
        ->setParameter("u", $user);
    $messages = $qb->getQuery()->getResult();

    return $messages;

}

public function getUserComunicates(User $user)
{

    $comunicationsRepository = $this->em->getRepository(Comunication::class);
    $comunications = $comunicationsRepository->findBy(["author" => $user]);
    return $comunications;

}

/**
 * Register the user in the list of persons that saw the comunicate
 * @param Comunication $comunication
 * @param User $user
 */
public function addView(Comunication $comunication, User $user)
{

// if ($comunication->getAuthor() == $user) return; $qb = $this->em->getRepository(View::class)->createQueryBuilder("view");

    $qb->where("view.user = :u")
        ->andWhere("view.message = :com")->setParameters(["u" => $user, "com" => $comunication]);
    $results = $qb->getQuery()->getResult();
    if (count($results) != 0) return;

    $view = new View();
    $view->setUser($user);
    $view->setMessage($comunication);
    $view->setViewAt(new \DateTime());
    $this->em->persist($view);
    $this->em->flush();
}

} `

ComunitacionsController.php

`<?php

namespace AppBundle\Controller;

use AppBundle\Comunications\ComunicationsManager; use AppBundle\Entity\Attachment; use AppBundle\Entity\Comunication; use AppBundle\Entity\ComunicationReply; use AppBundle\Entity\User; use AppBundle\Entity\Workgroup; use AppBundle\Form\ComunicationType;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Symfony\Bridge\Doctrine\Form\Type\EntityType; use Symfony\Bridge\Twig\Extension\RoutingExtension; use Symfony\Component\Form\Extension\Core\Type\CheckboxType; use Symfony\Component\Form\Extension\Core\Type\TextType; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\File\UploadedFile; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use Symfony\Component\Form\Extension\Core\Type\CollectionType;

use Symfony\Component\Form\Extension\Core\Type\ChoiceType;

class ComunicationsController extends Controller { /**

}`

norkunas commented 7 years ago

To make less changes as possible I think you'll need to pass the OneSignal library to your OneSignalPushService and then replace usage with it

tjaoc commented 7 years ago

Okay, thanks, I'll try. It's just that I'm new to this.