Source of file SessionManagement.php
Size: 3,129 Bytes - Last Modified: 2020-07-03T12:08:09+00:00
/var/www/docs.ssmods.com/process/src/src/Api/SessionManagement.php
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107 | <?php namespace Sunnysideup\UpgradeToSilverstripe4\Api; use Sunnysideup\UpgradeToSilverstripe4\Interfaces\SessionManagementInterface; use Sunnysideup\UpgradeToSilverstripe4\Traits\Creator; class SessionManagement implements SessionManagementInterface { use Creator; protected $sessionFileLocation = ''; /** * @param string $sessionFileLocation * @return SessionManagementInterface */ public static function initSession(string $sessionFileLocation): SessionManagementInterface { $obj = self::create(); $obj->setSessionFileLocation($sessionFileLocation); return $obj; } public function setSessionFileLocation($sessionFileLocation): SessionManagementInterface { $this->sessionFileLocation = $sessionFileLocation; return $this; } public function getSessionFileLocation(): string { return $this->sessionFileLocation; } public function deleteSession() { unlink($this->getSessionFileLocation()); } public function getSessionValue(string $key): string { $session = $this->getSessionData(); if (isset($session[$key])) { return $session[$key]; } return ''; } public function getSessionData(): array { if (file_exists($this->getSessionFileLocation())) { $data = file_get_contents($this->getSessionFileLocation()) ?? '{}'; if (! $data) { user_error('Could not read from: ' . $this->getSessionFileLocation()); } return json_decode($data, true); } $this->setSessionData([]); return $this->getSessionData(); } /** * @param array $session */ public function setSessionData(array $session): SessionManagementInterface { if (! file_exists($this->getSessionFileLocation())) { $session['Started'] = date('Y-m-d h:i '); } $data = json_encode($session, JSON_PRETTY_PRINT); try { $file = fopen($this->getSessionFileLocation(), 'w'); if ($file === false) { throw new \RuntimeException('Failed to open file: ' . $this->getSessionFileLocation()); } $writeOutcome = fwrite($file, (string) $data); if ($writeOutcome === false) { throw new \RuntimeException('Failed to write file: ' . $this->getSessionFileLocation()); } $closeOutcome = fclose($file); if ($closeOutcome === false) { throw new \RuntimeException('Failed to close file: ' . $this->getSessionFileLocation()); } } catch (\Exception $e) { // send error message if you can echo 'Caught exception: ' . $e->getMessage(); } return $this; } public function setSessionValue(string $key, string $value): SessionManagementInterface { $session = $this->getSessionData(); $session[$key] = trim($value); $this->setSessionData($session); return $this; } } |