Skip to content

Commit

Permalink
Create Session class
Browse files Browse the repository at this point in the history
  • Loading branch information
gigili committed Oct 31, 2021
1 parent a0c0a45 commit b34743f
Show file tree
Hide file tree
Showing 8 changed files with 172 additions and 60 deletions.
64 changes: 32 additions & 32 deletions composer.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

13 changes: 11 additions & 2 deletions src/Core/App.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@

use Dotenv\Dotenv;
use Gac\GoodFoodTracker\Core\DB\Database;
use Gac\GoodFoodTracker\Core\Exceptions\AppNotInitializedException;
use Gac\GoodFoodTracker\Core\Session\Session;
use Gac\GoodFoodTracker\Core\Utility\Logger;
use Gac\Routing\Exceptions\CallbackNotFound;
use Gac\Routing\Exceptions\RouteNotFoundException;
Expand All @@ -17,6 +19,7 @@ class App
protected ?PredisClient $redis;
protected ?Routes $routes;
protected ?Database $db;
public Session $session;

public function __construct(string $envFile = "") {
$dotenv = Dotenv::createImmutable(BASE_PATH . "/../$envFile");
Expand All @@ -25,6 +28,7 @@ public function __construct(string $envFile = "") {
Logger::log("Instance of " . App::class . " created ");

self::$instance = $this;
$this->session = Session::getInstance();
}

/**
Expand All @@ -35,8 +39,13 @@ public function run() {
$this->routes->handle();
}

public static function get_instance() : ?App {
if ( is_null(self::$instance) ) Logger::error("App instance is null");
/**
* Gets the instance of the App class
*
* @throws AppNotInitializedException
*/
public static function get_instance() : App {
if ( is_null(self::$instance) ) throw new AppNotInitializedException;
return self::$instance;
}

Expand Down
7 changes: 3 additions & 4 deletions src/Core/Controllers/BaseController.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,18 +11,17 @@
use Exception;
use Gac\GoodFoodTracker\Core\App;
use Gac\GoodFoodTracker\Core\Utility\Logger;
use Predis\Client as RedisClient;

class BaseController implements ControllerInterface
{
/**
* @var RedisClient Instance of a redis cache
* @var App Instance of the app class
*/
protected RedisClient $redis;
protected App $app;

public function __construct() {
try {
$this->redis = ( App::get_instance() )->get_redis();
$this->app = App::get_instance();
} catch ( Exception $ex ) {
Logger::error("Redis error: {$ex->getMessage()}");
}
Expand Down
12 changes: 8 additions & 4 deletions src/Core/Entities/Entity.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

use Gac\GoodFoodTracker\Core\App;
use Gac\GoodFoodTracker\Core\DB\Database;
use Gac\GoodFoodTracker\Core\Exceptions\AppNotInitializedException;
use JetBrains\PhpStorm\ArrayShape;
use Ramsey\Uuid\Rfc4122\UuidV4;
use ReflectionClass;
Expand Down Expand Up @@ -43,11 +44,14 @@ abstract class Entity implements EntityInterface
*/
private array $annotations;

/**
* @throws AppNotInitializedException
*/
public function __construct(string $table, string $primaryKey = "id") {
$this->table = $table;
$this->primaryKey = $primaryKey;
$this->annotations = $this->get_annotations();
$this->db = (App::get_instance())->get_db();
$this->db = ( App::get_instance() )->get_db();
}

/**
Expand All @@ -57,7 +61,7 @@ public function __construct(string $table, string $primaryKey = "id") {
*
* @return Entity returns an instance of an Entity class with database columns converted into instance properties
*/
public function from_result(mixed $result) : Entity {
public function from_result(mixed $result) : self {
$t = new $this();
$reflection = new ReflectionClass($this);
$properties = $reflection->getProperties(ReflectionProperty::IS_PUBLIC);
Expand All @@ -79,7 +83,7 @@ public function from_result(mixed $result) : Entity {
*
* @throws ReflectionException Throws an exception if the class or property does not exist.
*/
public function save() : Entity {
public function save() : self {
$ref = new ReflectionClass($this);
$properties = $ref->getProperties();

Expand Down Expand Up @@ -164,7 +168,7 @@ public function save() : Entity {
*
* @return Entity Returns the instance of an entity class that was deleted
*/
public function delete() : Entity {
public function delete() : self {
$id = $this->{$this->primaryKey};
$query = "DELETE FROM " . $this->table . " WHERE " . $this->primaryKey . " = ?";
$this->db->get_result($query, [ $id ]);
Expand Down
2 changes: 2 additions & 0 deletions src/Core/Exceptions/AppNotInitializedException.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,6 @@

class AppNotInitializedException extends Exception
{
protected $message = "The app wasn't initialized properly";
protected $code = 500;
}
112 changes: 112 additions & 0 deletions src/Core/Session/Session.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
<?php
/**
* Author: Igor Ilić <[email protected]>
* Date: 2021-10-31
* Project: good-food-tracker-api
*/

namespace Gac\GoodFoodTracker\Core\Session;

class Session
{
/**
* @var Session The only instance of the class
*/
private static Session $instance;

/**
* @var bool State of the session class
*/
private bool $sessionState = false;

public function __construct() { }

/**
* Returns the instance of 'Session'.
* The session is automatically initialized if it wasn't.
*
* @return Session
**/
public static function getInstance() : self {
if ( !isset(self::$instance) ) {
self::$instance = new self;
}

self::$instance->start_session();

return self::$instance;
}

/**
* Starts a session if it wasn't already started
*
* @return bool Returns the status of the session
*/
public function start_session() : bool {
$status = session_status();
if ( $this->sessionState == false && $status == PHP_SESSION_NONE ) {
$this->sessionState = session_start();
}

return $this->sessionState;
}

/**
* Stops the session
*
* @return bool Returns the status of the session
*/
public function stop_session() : bool {
if ( $this->sessionState == true ) {
$this->sessionState = !session_destroy();
unset($_SESSION);
return !$this->sessionState;
}

return false;
}

/**
* Stores the key, value pair in the session
*
* @param string $key Key under which to be stored
* @param mixed $value Value to be stored
*/
public function set(string $key, mixed $value) {
$_SESSION[$key] = $value;
}

/**
* Gets value from the session
*
* @param string $key Key for which to return the value
* @param mixed|null $defaultValue Default value to be returned if the key doesn't exist in session
*
* @return mixed Returns value from the session or @see $defaultValue
*/
public function get(string $key, mixed $defaultValue = NULL) : mixed {
return $_SESSION[$key] ?? $defaultValue;
}

/**
* Check if the session has the value for specified key set
*
* @param string $key Key to be checked in the session
*
* @return bool Returns whether the key is present in session or not
*/
public function has(string $key) : bool {
return isset($_SESSION[$key]);
}

/**
* Removes the value from the session
*
* @param string $key Key for which to remove the value
*/
public function remove(string $key) {
if ( $this->has($key) ) {
unset($_SESSION[$key]);
}
}
}
7 changes: 4 additions & 3 deletions src/Modules/Auth/Models/AuthModel.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

namespace Gac\GoodFoodTracker\Modules\Auth\Models;

use Gac\GoodFoodTracker\Core\Exceptions\InvalidInstanceException;
use Gac\GoodFoodTracker\Entity\UserEntity;
use Gac\GoodFoodTracker\Modules\Auth\Exceptions\EmailNotSentException;
use Gac\GoodFoodTracker\Modules\Auth\Exceptions\EmailTakenException;
Expand Down Expand Up @@ -57,6 +58,7 @@ public static function login(
* @throws UsernameTakenException
* @throws EmailNotSentException
* @throws ReflectionException
* @throws InvalidInstanceException
*/
public static function register(string $name, string $email, string $username, string $password) : UserEntity {
$userEntity = new UserEntity();
Expand Down Expand Up @@ -106,10 +108,9 @@ public static function register(string $name, string $email, string $username, s
);

//TODO: Should this throw an exception or return success with warning?
if ( !$emailSent ) {
throw new EmailNotSentException();
}
if ( !$emailSent ) throw new EmailNotSentException();

if ( ( $user instanceof UserEntity ) == false ) throw new InvalidInstanceException("Not a valid instance of UserEntity in " . __FILE__ . ' @ ' . __LINE__);
return $user;
}

Expand Down
Loading

0 comments on commit b34743f

Please sign in to comment.