dflydev / dflydev-fig-cookies

Cookies for PSR-7 HTTP Message Interface.
MIT License
224 stars 29 forks source link

Fig Cookies - Modifying cookie value (JSON array) #13

Open JamesTheHacker opened 8 years ago

JamesTheHacker commented 8 years ago

I want to be able to store an array of ID's to their cookies. I figured the easiest way is to json_encode the array of save IDs. Code below:

$app->get('/save/{id: [0-9]+}', function($request, $response, $args) {

  // Check if cookie exists
  $cookie = FigRequestCookies::get($request, 'saves');

  if($cookie->getValue() !== "null") {

    // Convert old cookie JSON array to PHP array
    $saves = json_decode($cookie->getValue(), true);

    // Push new save ID onto array
    array_push($saves, $args['id']);

    // Modify cookie
    $response = FigResponseCookies::modify($response, 'saves', function(SetCookie $setCookie) use ($saves)  {
      return $setCookie->withValue(json_encode($saves));
    });
  }
  else {

    // No cookie found set one
    $setCookie = SetCookie::create('saves')
      ->withValue(json_encode([ $args['id'] ]))
      ->rememberForever()
      ->withPath('/')
      ->withDomain('.localhost');

    $response = FigResponseCookies::set($response, $setCookie);
  }

  // Return user to save area
  return $this->view->render($response, 'saves.php');
});

My problem is the array only ever gets two values regardless of how many times I save a page. If I visit the following pages ...

http://example.com/save/22
http://example.com/save/32
http://example.com/save/18

... the array of $saves is only ever set to:

[22, 18]

If I save another page:

http://example.com/save/9

... the array is:

[22, 9]

Not sure what's going on here.

simensen commented 8 years ago

@JamesTheHacker That seems very strange to me. I'll have to carve out some time to try this example code you've shared. I can't see any glaring logic errors that might explain what might be going on here. Have you done more debugging on this and found a reason yet?