Merge pull request #145 from php-flasher/stateless-routes

fix: fallback to array storage if session is not started
This commit is contained in:
Younes KHOUBZA
2023-06-04 22:19:17 +02:00
committed by GitHub
3 changed files with 62 additions and 4 deletions
+9
View File
@@ -52,6 +52,15 @@ final class Request implements RequestInterface
*/
public function hasType($type)
{
if (!$this->hasSession()) {
return false;
}
$session = $this->request->getSession();
if (!$session->isStarted()) {
return false;
}
/** @var Session $session */
$session = $this->request->getSession();
$flashBag = $session->getFlashBag();
+32
View File
@@ -0,0 +1,32 @@
<?php
namespace Flasher\Symfony\Storage;
class FallbackSession
{
private static $storage = array();
/**
* @param string $name
* @param mixed $default
*
* @return mixed
*/
public function get($name, $default = null)
{
return array_key_exists($name, self::$storage)
? self::$storage[$name]
: $default;
}
/**
* @param string $name
* @param mixed $value
*
* @return void
*/
public function set($name, $value)
{
self::$storage[$name] = $value;
}
}
+21 -4
View File
@@ -8,6 +8,7 @@
namespace Flasher\Symfony\Storage;
use Flasher\Prime\Storage\Bag\BagInterface;
use Symfony\Component\HttpFoundation\Exception\SessionNotFoundException;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Session as LegacySession;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
@@ -21,12 +22,18 @@ final class SessionBag implements BagInterface
*/
private $session;
/**
* @var FallbackSession
*/
private $fallbackSession;
/**
* @param RequestStack|SessionInterface $session
*/
public function __construct($session)
{
$this->session = $session;
$this->fallbackSession = new FallbackSession();
}
/**
@@ -54,10 +61,20 @@ final class SessionBag implements BagInterface
return $this->session; // @phpstan-ignore-line
}
if (method_exists($this->session, 'getSession')) {
return $this->session = $this->session->getSession();
}
try {
if (method_exists($this->session, 'getSession')) {
$session = $this->session->getSession();
} else {
$session = $this->session->getCurrentRequest()->getSession();
}
return $this->session = $this->session->getCurrentRequest()->getSession(); // @phpstan-ignore-line
if (null !== $session && $session->isStarted()) {
return $this->session = $session;
}
return $this->fallbackSession;
} catch (SessionNotFoundException $e) {
return $this->fallbackSession;
}
}
}