Skip to content

Instantly share code, notes, and snippets.

Created February 18, 2013 16:03
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/4978441 to your computer and use it in GitHub Desktop.
Save anonymous/4978441 to your computer and use it in GitHub Desktop.
<?php
/***************************************************************
* Copyright notice
*
* (c) 2013 Jan Kiesewetter <janYYYY@t3easy.de>, t3easy
*
* All rights reserved
*
* This script is part of the TYPO3 project. The TYPO3 project is
* free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* The GNU General Public License can be found at
* http://www.gnu.org/copyleft/gpl.html.
*
* This script is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* This copyright notice MUST APPEAR in all copies of the script!
***************************************************************/
/**
* @package flextend
*
*/
class Tx_Flextend_Domain_Repository_SessionRepository implements t3lib_Singleton {
/**
* The session key
*
* @var string
*/
protected $sessionKey;
/**
* The session type 'user' or 'ses'
*
* @var string session type
*/
protected $sessionType = 'ses';
/**
* The configuration manager
*
* @var Tx_Extbase_Configuration_ConfigurationManagerInterface
*/
protected $configurationManager;
/**
* The framework configuration
*
* @var array
*/
protected $configuration;
/**
* Inject configuration manager
*
* @param Tx_Extbase_Configuration_ConfigurationManagerInterface $configurationManager
* @return void
*/
public function injectConfigurationManager(Tx_Extbase_Configuration_ConfigurationManagerInterface $configurationManager) {
$this->configurationManager = $configurationManager;
$this->configuration = $this->configurationManager->getConfiguration(
Tx_Extbase_Configuration_ConfigurationManagerInterface::CONFIGURATION_TYPE_FRAMEWORK
);
$this->injectSessionType();
$this->injectSessionKey();
}
/**
* Inject the default session key
*
* @return void
*/
public function injectSessionKey() {
$this->sessionKey = strtolower($this->configuration['extensionName'] . '_' . $this->configuration['pluginName']);
}
/**
* Inject session type
*
* @return void
*/
public function injectSessionType() {
if ($GLOBALS['TSFE']->loginUser) {
$this->sessionType = 'user';
} else {
$this->sessionType = 'ses';
}
}
/**
* Sets the session key
*
* @param string|null $sessionKey
* @return boolean
*/
public function setSessionKey($sessionKey = NULL) {
if ($sessionKey !== NULL) {
$this->sessionKey = $this->getSessionKey($sessionKey);
return TRUE;
}
return FALSE;
}
/**
* Returns the session key
*
* @param string|null $sessionKey
* @return string session key
*/
public function getSessionKey($sessionKey = NULL) {
if (is_string($sessionKey)) {
$sessionKey = preg_replace('/\\s/', '_', (string) $sessionKey);
return preg_replace('/[^a-zA-Z0-9_\\-]/', '', $sessionKey);
}
return $this->sessionKey;
}
/**
* Sets the session type
*
* @param string|null $sessionType
* @return boolean
*/
public function setSessionType($sessionType = NULL) {
if ($sessionType === 'user' || $sessionType === 'ses') {
$this->sessionType = $sessionType;
return TRUE;
}
return FALSE;
}
/**
* Returns the session type
*
* @return string $sessionType
*/
public function getSessionType() {
return $this->sessionType;
}
/**
* Sets session type and key
*
* @param string|null $sessionType
* @param string|null $sessionKey
* @return void
*/
public function setSessionTypeAndKey($sessionType = NULL, $sessionKey = NULL) {
if (is_string($sessionType)) {
$this->setSessionType($sessionType);
}
if (is_string($sessionKey)) {
$this->setSessionKey($sessionKey);
}
}
/**
* Return the session
*
* @param string|null $sessionKey
* @return mixed
*/
public function findOneBySessionKey($sessionKey = NULL) {
$sessionData = $GLOBALS['TSFE']->fe_user->getKey($this->sessionType, $this->getSessionKey($sessionKey));
if ($sessionData) {
return unserialize($sessionData);
}
return NULL;
}
/**
* Set the session
*
* @param array $sessionData
* @param string|null $sessionKey
* @return boolean
*/
public function setSession($sessionData, $sessionKey = NULL) {
if ($sessionData !== NULL) {
$GLOBALS['TSFE']->fe_user->setKey($this->sessionType, $this->getSessionKey($sessionKey), serialize($sessionData));
$GLOBALS['TSFE']->fe_user->storeSessionData();
return TRUE;
}
return FALSE;
}
/**
* Add or update the session
*
* @param array $sessionData A session array
* @param string|null $sessionKey the session key, optional
* @return boolean
*/
public function addOrUpdateSession($sessionData, $sessionKey = NULL) {
if ($sessionData !== NULL) {
$sessionData = array_merge((array)$this->findOneBySessionKey($sessionKey), (array)$sessionData);
return $this->setSession($sessionData, $sessionKey);
}
return FALSE;
}
/**
* Destroy the session data for the form
*
* @param string|null $sessionKey
* @return boolean Did the session exists
*/
public function destroySession($sessionKey = NULL) {
if ($this->_sessionExists()) {
$GLOBALS['TSFE']->fe_user->setKey($this->sessionType, $this->getSessionKey($sessionKey), NULL);
$GLOBALS['TSFE']->storeSessionData();
return TRUE;
}
return FALSE;
}
/**
* Check if session exists after session type and key is set
*
* @param string|null $sessionKey
* @return boolean
*/
public function _sessionExists($sessionKey = NULL) {
return (boolean)$GLOBALS['TSFE']->fe_user->getKey($this->sessionType, $this->getSessionKey($sessionKey));
}
/*******************************************************************************
* @TODO Use a model for properties
*******************************************************************************/
/**
* Return session property
*
* @param string $propertyName
* @param string|null $sessionKey
* @return mixed
*/
public function getSessionProperty($propertyName, $sessionKey = NULL) {
$sessionData = $this->findOneBySessionKey($sessionKey);
return $sessionData[$propertyName];
}
/**
* Set session property
*
* @param string $propertyName
* @param mixed $propertyValue
* @param null $sessionKey
* @return void
*/
public function setSessionProperty($propertyName, $propertyValue, $sessionKey = NULL) {
/** @var array $sessionData */
$sessionData = $this->findOneBySessionKey($sessionKey);
$sessionData[$propertyName] = $propertyValue;
$this->setSession($sessionData, $sessionKey);
}
/**
* update session property if it exists
*
* @param string $propertyName
* @param mixed $propertyValue
* @param null $sessionKey
* @return boolean
*/
public function updateSessionProperty($propertyName, $propertyValue, $sessionKey = NULL) {
$sessionData = $this->findOneBySessionKey($sessionKey);
if ($this->_hasProperty($propertyName, $sessionData)) {
$sessionData[$propertyName] = $propertyValue;
$this->setSession($sessionData, $sessionKey);
return TRUE;
}
return FALSE;
}
/**
* Add or update a session property
*
* @param string $propertyName
* @param mixed $propertyValue
* @param string|null $sessionKey
* @return void
*/
public function addOrUpdateSessionProperty($propertyName, $propertyValue, $sessionKey = NULL) {
$sessionData = $this->findOneBySessionKey($sessionKey);
if (is_array($propertyValue) && is_array($sessionData[$propertyName])) {
$sessionData[$propertyName] = array_merge($sessionData[$propertyName], $propertyValue);
} else {
$sessionData[$propertyName] = $propertyValue;
}
$this->setSession($sessionData, $sessionKey);
}
/**
* Destroy session property
*
* @param string $propertyName
* @param string|null $sessionKey
* @return bool
*/
public function destroySessionProperty($propertyName, $sessionKey = NULL) {
$sessionData = $this->findOneBySessionKey($sessionKey);
if ($this->_hasProperty($propertyName, $sessionData)) {
unset($sessionData[$propertyName]);
$this->setSession($sessionData, $sessionKey);
return TRUE;
}
return FALSE;
}
/**
* Checks if the given property exists
*
* @param string $propertyName
* @param $sessionData
* @return boolean TRUE bool true if the property exists, FALSE if it doesn't exist.
*/
public function _hasProperty($propertyName, $sessionData) {
return array_key_exists($propertyName, $sessionData);
}
}
?>
<?php
/***************************************************************
* Copyright notice
*
* (c) 2013 Jan Kiesewetter <janYYYY@t3easy.de>, t3easy
*
* All rights reserved
*
* This script is part of the TYPO3 project. The TYPO3 project is
* free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* The GNU General Public License can be found at
* http://www.gnu.org/copyleft/gpl.html.
*
* This script is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* This copyright notice MUST APPEAR in all copies of the script!
***************************************************************/
/**
* @package flextend
*
*/
class Tx_Flextend_Tests_Unit_Domain_Repository_SessionRepositoryTest extends Tx_Extbase_Tests_Unit_BaseTestCase {
/**
* @var tslib_fe
*/
protected $tsfeBackup;
/**
* A sample session
*
* @var array
*/
protected $sampleSession = array(
'array' => array(
0,
1,
2,
3,
'four',
'five'
),
'property2' => array(
5,
9,
52,
31
),
'key1' => 'value1',
'key2' => 'value2',
'value',
'value2'
);
/**
* A sample configuration
*
* @var array
*/
protected $configuration;
/**
* The fixture
*
* @var PHPUnit_Framework_MockObject_MockObject|Tx_Flextend_Domain_Repository_SessionRepository
*/
private $fixture;
/**
* Setup
*
* @return void
*/
protected function setUp() {
$this->tsfeBackup = $GLOBALS['TSFE'];
$GLOBALS['TSFE'] = $this->getMock('tslib_fe', array('dummy'), array(), '', FALSE);
$GLOBALS['TSFE']->initFEuser();
$this->fixture = $this->getAccessibleMock('Tx_Flextend_Domain_Repository_SessionRepository', array('dummy'), array(), '', TRUE);
$this->fixture->_set('configuration', array(
'extensionName' => 'flextend',
'pluginName' => 'UnitTestSetup'
));
$this->fixture->injectSessionKey();
}
/**
* tear down
*
* @return void
*/
public function tearDown() {
$this->fixture->destroySession();
$GLOBALS['TSFE'] = $this->tsfeBackup;
unset($this->fixture);
unset($this->tsfeBackup);
}
/**
* TEST
*
* @test
* @return void
*/
public function isFixtureInstanceOfTx_Flextend_Domain_Repository_SessionRepository() {
$this->assertInstanceOf(
'Tx_Flextend_Domain_Repository_SessionRepository',
$this->fixture
);
}
/**
* TEST
*
* @test
* @return void
*/
public function isTsfeInstanceOfTslib_fe() {
$this->assertInstanceOf(
'tslib_fe',
$GLOBALS['TSFE']
);
}
/**
* TEST
*
* @test
* @return void
*/
public function doesSetSessionKeyFromStringSetsSessionKey() {
$this->fixture->setSessionKey('my_session_key');
$this->assertSame(
'my_session_key',
$this->fixture->getSessionKey()
);
}
/**
* TEST
*
* @test
* @return void
*/
public function doesInjectSessionKeyWithoutParameterSetsSessionKeyFromConfiguration() {
$configuration = array(
'extensionName' => 'flextend',
'pluginName' => 'UnitTest'
);
$this->fixture->_set('configuration', $configuration);
$this->fixture->injectSessionKey();
$this->assertSame(
'flextend_unittest',
$this->fixture->getSessionKey()
);
}
/**
* TEST
*
* @test
* @return void
*/
public function doesSetSessionTypeSetsSessionType() {
$this->fixture->setSessionType('user');
$this->assertSame(
'user',
$this->fixture->getSessionType()
);
$this->fixture->setSessionType('ses');
$this->assertSame(
'ses',
$this->fixture->getSessionType()
);
$this->fixture->setSessionType('unknown');
$this->assertSame(
'ses',
$this->fixture->getSessionType()
);
}
/*****************************************************
* Session tests
*****************************************************/
/**
* TEST
*
* @test
* @return void
*/
public function doesFindOneBySessionKeyReturnsNullIfNoSession() {
$this->assertNull(
$this->fixture->findOneBySessionKey()
);
}
/**
* TEST
*
* @test
* @return void
*/
public function doesGetSessionTypeReturnsInitialValue() {
$this->assertSame(
'ses',
$this->fixture->getSessionType()
);
}
/**
* TEST
*
* @test
* @return void
*/
public function doesSetSessionFromArraySetsSession() {
$this->assertTrue(
$this->fixture->setSession($this->sampleSession)
);
$this->assertSame(
$this->sampleSession,
$this->fixture->findOneBySessionKey()
);
}
/**
* TEST
*
* @test
* @return void
*/
public function doesSetSessionFromNullDoNotSetsSession() {
$this->assertFalse(
$this->fixture->setSession(NULL)
);
}
/**
* TEST
*
* @test
* @return void
*/
public function doesDestroySessionDestroysSession() {
$this->fixture->setSession($this->sampleSession);
$this->assertTrue(
$this->fixture->destroySession()
);
$this->assertNull(
$this->fixture->findOneBySessionKey()
);
$this->assertFalse(
$this->fixture->destroySession()
);
}
/**
* TEST
*
* @test
* @return void
*/
public function doesAddOrUpdateSessionAddsOrUpdatesSession() {
$expected = $this->sampleSession;
$expected['key2'] = 'value2';
$this->fixture->setSession($this->sampleSession);
$this->fixture->addOrUpdateSession(
array('key2' => 'value2')
);
$this->assertSame(
$expected,
$this->fixture->findOneBySessionKey()
);
}
/**
*
* @test
* @return void
*/
public function doesSetSessionMultipleTimesSetsMultipleSessions() {
$expected = $this->sampleSession;
$expected['foo'] = 'bar';
$expected2 = $this->sampleSession;
$expected2['foobar'] = 4711;
$this->fixture->setSession($expected);
$this->fixture->setSession($expected2, 'second_session_key');
$this->assertSame(
$expected,
$this->fixture->findOneBySessionKey()
);
$this->assertSame(
$expected2,
$this->fixture->findOneBySessionKey('second_session_key')
);
}
/*****************************************************
* session property tests
*****************************************************/
/**
* doesSetSessionPropertyJustSetsSessionPropertyIfSessionPropertyExists
*
* @test
* @return void
*/
public function doesUpdateSessionPropertyJustSetsSessionPropertyIfSessionPropertyExists() {
$this->fixture->setSession($this->sampleSession);
$this->assertTrue(
$this->fixture->updateSessionProperty('key2', 'exists')
);
$this->assertSame(
'exists',
$this->fixture->getSessionProperty('key2')
);
$this->assertFalse(
$this->fixture->updateSessionProperty('key3', 'not exists')
);
$this->assertNull(
$this->fixture->getSessionProperty('key3')
);
}
/**
* TEST
*
* @test
* @return void
*/
public function doesAddOrUpdateSessionPropertyAddsOrUpdatesSessionProperty() {
$expected = $this->sampleSession;
$expected['key2'] = 'differentValue';
$expected['array']['testKey'] = 'testValue';
$expected['property2'][] = 4711;
$expected['property3'][] = 790;
$this->fixture->setSession($this->sampleSession);
$this->fixture->addOrUpdateSessionProperty(
'key2',
'differentValue'
);
$this->fixture->addOrUpdateSessionProperty(
'array',
array('testKey' => 'testValue')
);
$this->fixture->addOrUpdateSessionProperty(
'property2',
array(4711)
);
$this->fixture->addOrUpdateSessionProperty(
'property3',
array(790)
);
$this->assertSame(
$expected,
$this->fixture->findOneBySessionKey()
);
}
/**
* TEST
*
* @test
* @return void
*/
public function doesAddOrUpdateSessionPropertyFromNullKeepsSessionProperty() {
$this->fixture->setSession($this->sampleSession);
$this->fixture->addOrUpdateSessionProperty(
'key1',
NULL
);
$this->assertTrue(
$this->fixture->_hasProperty('key1', $this->sampleSession)
);
}
/**
* TEST
*
* @test
* @return void
*/
public function doesGetSessionPropertyReturnsPropertyValue() {
$this->fixture->setSession($this->sampleSession);
$this->assertSame(
$this->sampleSession['key2'],
$this->fixture->getSessionProperty('key2')
);
$this->assertSame(
$this->sampleSession['array'],
$this->fixture->getSessionProperty('array')
);
$this->assertNull(
$this->fixture->getSessionProperty('notExistingProperty')
);
}
/**
* TEST
*
* @test
* @return void
*/
public function doesHasPropertyReturnsTrueOrFalse() {
$this->fixture->setSession($this->sampleSession);
$this->assertTrue(
$this->fixture->_hasProperty('key1', $this->fixture->findOneBySessionKey())
);
$this->assertFalse(
$this->fixture->_hasProperty('keyXY', $this->fixture->findOneBySessionKey())
);
}
/**
* @test
* @return void
*/
public function doesDestroySessionPropertyDestroysSessionProperty() {
$this->fixture->setSession($this->sampleSession);
$this->assertTrue(
$this->fixture->destroySessionProperty('property2')
);
$this->assertFalse(
$this->fixture->_hasProperty('property2', $this->fixture->findOneBySessionKey())
);
$this->assertNull(
$this->fixture->getSessionProperty('property2')
);
}
}
?>
@t3easy
Copy link

t3easy commented Feb 19, 2013

Sample Usage

Inject the session repository

/**
 * Session Repository
 *
 * @var Tx_Flextend_Domain_Repository_SessionRepository
 */
protected $sessionRepository;

/**
 * Inject session repository
 *
 * @return void
 */
public function injectSessionRepository(Tx_Flextend_Domain_Repository_SessionRepository $sessionRepository) {
    $this->sessionRepository = $sessionRepository;
}

Use in your actions

/**
 * Foo Action
 *
 * @return void
 */
public function fooAction() {
    $lastAccess = $this->sessionRepository->getSessionProperty('lastAccess');
    if ($lastAccess + 604800 > time()) {
        $this->flashMessageContainer->add("Long time no see, long time no say!");
    }
    $this->sessionRepository->addOrUpdateSessionProperty('lastAccess', time());
}

/**
 * Add to basket
 *
 * @param Tx_FooBar_Domain_Model_BasketEntry $basketEntry
 * @return void
 */
public function addToBasketAction($basketEntry) {
    $basket = array(
        array(
            "quantity" => $basketEntry->getQuantity(),
            "product" => $basketEntry->getProduct()
        ),
    );
    $this->sessionRepository->addOrUpdateSessionProperty('basket', $basket);
}

/**
 * Clear basket
 *
 * @return void
 */
public function clearBasketAction() {
    $this->sessionRepository->destroySessionProperty('basket');
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment