Symfony 3.4 не регистрирует какие-либо куки? - PullRequest
0 голосов
/ 05 апреля 2019

Я пытаюсь сохранить куки, но они не работают. В чем проблема?

Класс обслуживания:

<?php

namespace AppBundle\Service;

use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Response;

class MyUser
{
    private $requestStack;

    public function __construct(RequestStack $requestStack)
    {
        $this->requestStack = $requestStack->getCurrentRequest();
    }

    // Adds a location to the user's wishlist
    public function addToWishlist($locationId)
    {
        $cookies = $this->requestStack->cookies;
        error_log(print_r($cookies, true));
        $wishlist = $cookies->get('myWishlist', array());
        if (!in_array($locationId, $wishlist))
        {
            $wishlist[] = $locationId;
        }
        $wishlistCookie = new Cookie('myWishlist', $wishlist, strtotime("+1 year"));
        $response = new Response();
        $response->headers->setCookie($wishlistCookie);
    }
    /**
     * Returns an array of the user's wishlist IDs
     *
     * @return array
     */
    public function getWishlistIDs()
    {
        $cookies = $this->requestStack->cookies;
        return $cookies->get('myWishlist', array());
    }
    /**
     * Returns a count of the number of items in the wishlist
     *
     * @return int
     */
    public function getWishlistCount()
    {
        return count($this->getWishlistIDs());
    }
    /**
     * Checks if a location is in this user's wishlist.
     *
     * @param  $id A location ID
     * @return boolean
     */
    public function locationInWishlist($id)
    {
        $cookies = $this->requestStack->cookies;
        $wishlist = $cookies->get('myWishlist', array());
        return (in_array($id, $wishlist));
    }
    /**
     * Removes a location from the user's wishlist,
     * by location ID
     *
     * @param  $id
     * @return void
     */
    public function removeFromWishlistById($id)
    {
        $cookies = $this->requestStack->cookies;
        $id = abs(intval($id));
        $wishlist = $cookies->get('myWishlist', array());
        if (in_array($id, $wishlist))
        {
            $vals = array_flip($wishlist);
            unset($vals[$id]);
            $wishlist = array_flip($vals);
        }
        $wishlistCookie = new Cookie('myWishlist', $wishlist, strtotime("+1 year"));
        $response = new Response();
        $response->headers->setCookie($wishlistCookie);    }
    /**
     * Removes all venues from the user's wishlist
     *
     * @return void
     */
    public function removeAllFromWishlist()
    {
        $wishlistCookie = new Cookie('myWishlist', array(), strtotime("+1 year"));
        $response = new Response();
        $response->headers->setCookie($wishlistCookie);
    }

}

Класс контроллера:

<?php

namespace AppBundle\Controller\Frontend;

use AppBundle\Entity\LocationStat;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use AppBundle\Entity\Enquiry;
use AppBundle\Entity\EventType;
use AppBundle\Entity\PcawCodes;
use AppBundle\Entity\Setting;
use AppBundle\Entity\Thumbnail;
use AppBundle\Entity\WishlistCount;
use AppBundle\Form\Frontend\EnquiryForm;
use AppBundle\Service\MyUser;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use AppBundle\Entity\Location;
use AppBundle\Entity\Wishlist;
use AppBundle\Service\UniqueValues;
use AppBundle\Form\Frontend\WishlistSaveEmailForm;
use Symfony\Component\Validator\Validator\ValidatorInterface;


class WishlistsController extends Controller
{
    /**
     * @Route("wishlists/addVenueAjax/id/{id}", name="add_venue_ajax")
     */
    public function addVenueAjaxAction(Request $request)
    {
        $doctrine = $this->getDoctrine();

        if (!$request->isXmlHttpRequest())
            return $this->redirectToRoute('homepage');

        $id = $request->get("id", false);
        $id = abs(intval($id));

        if (!$id)
            return new JsonResponse(array("error" => true, "render" => ""));

        // Look up location.  We can only add it if it's published etc.
        $loc = $doctrine->getRepository(Location::class)->find($id);

        if (!$loc || !$loc->getPublishedStatus())
            return new JsonResponse(array("error" => true, "render" => ""));

        // Add location to wishlist
        $user = $this->get(MyUser::class);
        $user->addToWishlist($id);

        return new JsonResponse(array("error" => false, "newCount" => $user->getWishlistCount(), 'render' => $this->renderView('frontend/wishlists/partials/_itemwishlistaction.html.twig', array('locationid' => $loc->getId(),'user' => $user))));
    }

}

Но я не вижу файлов cookie в разделе ответов профилировщика:

enter image description here

1 Ответ

0 голосов
/ 05 апреля 2019

Вообще-то, теперь я все заработал.

1) Я не отправлял заголовки после установки cookie через $response->send()

2) Существует проблема с установкой массива в качестве cookie, поэтому вместо этого я зашифровал массив в json, а затем расшифровал после прочтения, так что я сохранил массив в cookie.

ОБНОВЛЕННЫЙ КОД:

namespace AppBundle\Service;

use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Response;

class MyUser
{
    private $requestStack;

    public function __construct(RequestStack $requestStack)
    {
        $this->requestStack = $requestStack->getCurrentRequest();
    }

    // Adds a location to the user's wishlist
    public function addToWishlist($locationId)
    {
        $cookies = $this->requestStack->cookies;
        $wishlist = json_decode($cookies->get('myWishlist', "[]"));
        if (!in_array($locationId, $wishlist))
        {
            $wishlist[] = $locationId;
        }
        $wishlistCookie = new Cookie('myWishlist', json_encode($wishlist), strtotime("+1 year"));
        $response = new Response();
        $response->headers->setCookie($wishlistCookie);
        $response->send();
    }
    /**
     * Returns an array of the user's wishlist IDs
     *
     * @return array
     */
    public function getWishlistIDs()
    {
        $cookies = $this->requestStack->cookies;
        return json_decode($cookies->get('myWishlist', "[]"));
    }
    /**
     * Returns a count of the number of items in the wishlist
     *
     * @return int
     */
    public function getWishlistCount()
    {
        return count($this->getWishlistIDs());
    }
    /**
     * Checks if a location is in this user's wishlist.
     *
     * @param  $id A location ID
     * @return boolean
     */
    public function locationInWishlist($id)
    {
        $cookies = $this->requestStack->cookies;
        $wishlist = json_decode($cookies->get('myWishlist', "[]"));
        return (in_array($id, $wishlist));
    }
    /**
     * Removes a location from the user's wishlist,
     * by location ID
     *
     * @param  $id
     * @return void
     */
    public function removeFromWishlistById($id)
    {
        $cookies = $this->requestStack->cookies;
        $id = abs(intval($id));
        $wishlist = json_decode($cookies->get('myWishlist', "[]"));
        if (in_array($id, $wishlist))
        {
            $vals = array_flip($wishlist);
            unset($vals[$id]);
            $wishlist = array_flip($vals);
        }
        $wishlistCookie = new Cookie('myWishlist', json_encode($wishlist), strtotime("+1 year"));
        $response = new Response();
        $response->headers->setCookie($wishlistCookie);
        $response->send();
    }

    /**
     * Removes all venues from the user's wishlist
     *
     * @return void
     */
    public function removeAllFromWishlist()
    {
        $wishlistCookie = new Cookie('myWishlist', "[]", strtotime("+1 year"));
        $response = new Response();
        $response->headers->setCookie($wishlistCookie);
        $response->send();
    }

}

?>

enter image description here

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...