From 8c81adc8e83969e90b4c54daf4a396b1094134ff Mon Sep 17 00:00:00 2001 From: Igor Scheller Date: Thu, 31 Aug 2017 17:30:54 +0200 Subject: Implemented container --- src/Config/Config.php | 28 ---------- src/Container/Container.php | 105 +++++++++++++++++++++++++++++++++++ src/Container/ContainerException.php | 11 ++++ src/Container/NotFoundException.php | 10 ++++ src/Http/Request.php | 25 --------- src/Renderer/Renderer.php | 24 +------- src/Routing/UrlGenerator.php | 4 +- src/helpers.php | 29 ++++++++-- 8 files changed, 152 insertions(+), 84 deletions(-) create mode 100644 src/Container/Container.php create mode 100644 src/Container/ContainerException.php create mode 100644 src/Container/NotFoundException.php (limited to 'src') diff --git a/src/Config/Config.php b/src/Config/Config.php index 02080de4..34c21a78 100644 --- a/src/Config/Config.php +++ b/src/Config/Config.php @@ -2,15 +2,8 @@ namespace Engelsystem\Config; -use ErrorException; - class Config { - /** - * @var self - */ - protected static $instance; - /** * The config values * @@ -104,25 +97,4 @@ class Config { $this->remove($key); } - - /** - * @return Config - * @throws ErrorException - */ - public static function getInstance() - { - if (!self::$instance instanceof self) { - throw new ErrorException('Config not initialized'); - } - - return self::$instance; - } - - /** - * @param self $instance - */ - public static function setInstance($instance) - { - self::$instance = $instance; - } } diff --git a/src/Container/Container.php b/src/Container/Container.php new file mode 100644 index 00000000..df2f92fe --- /dev/null +++ b/src/Container/Container.php @@ -0,0 +1,105 @@ +has($id)) { + return $this->resolve($id); + } + + throw new NotFoundException(sprintf('The entry with the id "%s" could not be found')); + } + + /** + * Register a shared entry in the container + * + * @param string $abstract Identifier of the entry to set + * @param mixed $instance Entry + */ + public function instance($abstract, $instance) + { + $this->instances[$abstract] = $instance; + } + + /** + * Returns true if the container can return an entry for the given identifier + * Returns false otherwise + * + * `has($id)` returning true does not mean that `get($id)` will not throw an exception + * It does however mean that `get($id)` will not throw a `NotFoundExceptionInterface` + * + * @param string $id Identifier of the entry to look for + * + * @return bool + */ + public function has($id) + { + return isset($this->instances[$id]); + } + + /** + * Get the globally available instance of the container + * + * @return Container + */ + public static function getInstance() + { + if (is_null(static::$instance)) { + static::$instance = new static; + } + + return static::$instance; + } + + /** + * Set the globally available instance of the container + * + * @param Container $container + */ + public static function setInstance(Container $container) + { + static::$instance = $container; + } + + /** + * Resolve the requested object + * + * @param string $abstract + * @return mixed + */ + protected function resolve($abstract) + { + return $this->instances[$abstract]; + } +} diff --git a/src/Container/ContainerException.php b/src/Container/ContainerException.php new file mode 100644 index 00000000..3cdde506 --- /dev/null +++ b/src/Container/ContainerException.php @@ -0,0 +1,11 @@ +getUri()), '/'); } - - /** - * @return self - * @throws ErrorException - */ - public static function getInstance() - { - if (!self::$instance instanceof self) { - throw new ErrorException('Request not initialized'); - } - - return self::$instance; - } - - /** - * @param self $instance - */ - public static function setInstance($instance) - { - self::$instance = $instance; - } } diff --git a/src/Renderer/Renderer.php b/src/Renderer/Renderer.php index bf3d5609..5ed7cf31 100644 --- a/src/Renderer/Renderer.php +++ b/src/Renderer/Renderer.php @@ -2,13 +2,8 @@ namespace Engelsystem\Renderer; -use ErrorException; - class Renderer { - /** @var self */ - protected static $instance; - /** @var EngineInterface[] */ protected $renderer = []; @@ -29,7 +24,7 @@ class Renderer return $renderer->get($template, $data); } - engelsystem_error('Unable to find a renderer for template file «' . $template . '».'); + engelsystem_error('Unable to find a renderer for template file "' . $template . '".'); return ''; } @@ -42,21 +37,4 @@ class Renderer { $this->renderer[] = $renderer; } - - /** - * @return self - * @throws ErrorException - */ - public static function getInstance() - { - return self::$instance; - } - - /** - * @param self $instance - */ - public static function setInstance($instance) - { - self::$instance = $instance; - } } diff --git a/src/Routing/UrlGenerator.php b/src/Routing/UrlGenerator.php index 8dc464c6..33eef7b0 100644 --- a/src/Routing/UrlGenerator.php +++ b/src/Routing/UrlGenerator.php @@ -2,8 +2,6 @@ namespace Engelsystem\Routing; -use Engelsystem\Http\Request; - class UrlGenerator { /** @@ -14,7 +12,7 @@ class UrlGenerator public static function to($path, $parameters = []) { $path = '/' . ltrim($path, '/'); - $request = Request::getInstance(); + $request = app('request'); $uri = $request->getUriForPath($path); if (!empty($parameters) && is_array($parameters)) { diff --git a/src/helpers.php b/src/helpers.php index 24f93f2c..733b902d 100644 --- a/src/helpers.php +++ b/src/helpers.php @@ -2,11 +2,27 @@ // Some useful functions use Engelsystem\Config\Config; +use Engelsystem\Container\Container; use Engelsystem\Http\Request; use Engelsystem\Renderer\Renderer; use Engelsystem\Routing\UrlGenerator; use Symfony\Component\HttpFoundation\Session\SessionInterface; +/** + * Get the global container instance + * + * @param string $id + * @return mixed + */ +function app($id = null) +{ + if (is_null($id)) { + return Container::getInstance(); + } + + return Container::getInstance()->get($id); +} + /** * Get or set config values * @@ -16,15 +32,18 @@ use Symfony\Component\HttpFoundation\Session\SessionInterface; */ function config($key = null, $default = null) { + $config = app('config'); + if (empty($key)) { - return Config::getInstance(); + return $config; } if (is_array($key)) { - Config::getInstance()->set($key); + $config->set($key); + return true; } - return Config::getInstance()->get($key, $default); + return $config->get($key, $default); } /** @@ -34,7 +53,7 @@ function config($key = null, $default = null) */ function request($key = null, $default = null) { - $request = Request::getInstance(); + $request = app('request'); if (is_null($key)) { return $request; @@ -66,7 +85,7 @@ function session($key = null, $default = null) */ function view($template = null, $data = null) { - $renderer = Renderer::getInstance(); + $renderer = app('renderer'); if (is_null($template)) { return $renderer; -- cgit v1.2.3-70-g09d2 From 0ac981876432ff8f7f76ffee8c5102b633d760d4 Mon Sep 17 00:00:00 2001 From: Igor Scheller Date: Tue, 19 Sep 2017 14:50:20 +0200 Subject: Added Application --- includes/engelsystem_provider.php | 19 ++++++++----------- src/Application.php | 25 +++++++++++++++++++++++++ src/Container/Container.php | 35 +++++++++++++++++++++++------------ src/helpers.php | 8 ++++---- 4 files changed, 60 insertions(+), 27 deletions(-) create mode 100644 src/Application.php (limited to 'src') diff --git a/includes/engelsystem_provider.php b/includes/engelsystem_provider.php index f3c161a6..e10fdba0 100644 --- a/includes/engelsystem_provider.php +++ b/includes/engelsystem_provider.php @@ -1,13 +1,12 @@ instance('container', $container); -$container->instance(ContainerInterface::class, $container); +$app = Application::getInstance(); /** * Load configuration */ $config = new Config(); -$container->instance('config', $config); +$app->instance('config', $config); $config->set(require __DIR__ . '/../config/config.default.php'); if (file_exists(__DIR__ . '/../config/config.php')) { @@ -48,7 +45,7 @@ date_default_timezone_set($config->get('timezone')); * @var Request $request */ $request = Request::createFromGlobals(); -$container->instance('request', $request); +$app->instance('request', $request); /** @@ -64,7 +61,7 @@ if ($config->get('maintenance')) { * Initialize renderer */ $renderer = new Renderer(); -$container->instance('renderer', $renderer); +$app->instance('renderer', $renderer); $renderer->addRenderer(new HtmlEngine()); @@ -72,7 +69,7 @@ $renderer->addRenderer(new HtmlEngine()); * Register error handler */ $errorHandler = new ExceptionHandler(); -$container->instance('error.handler', $errorHandler); +$app->instance('error.handler', $errorHandler); if (config('environment') == 'development') { $errorHandler->setEnvironment(ExceptionHandler::ENV_DEVELOPMENT); ini_set('display_errors', true); @@ -184,7 +181,7 @@ foreach ($includeFiles as $file) { * Init application */ $session = new Session(); -$container->instance('session', $session); +$app->instance('session', $session); $session->start(); $request->setSession($session); diff --git a/src/Application.php b/src/Application.php new file mode 100644 index 00000000..674b3869 --- /dev/null +++ b/src/Application.php @@ -0,0 +1,25 @@ +registerBaseBindings(); + } + + protected function registerBaseBindings() + { + self::setInstance($this); + Container::setInstance($this); + $this->instance('app', $this); + $this->instance('container', $this); + $this->instance(Container::class, $this); + $this->instance(Application::class, $this); + $this->instance(ContainerInterface::class, $this); + } +} diff --git a/src/Container/Container.php b/src/Container/Container.php index df2f92fe..9af5c1e6 100644 --- a/src/Container/Container.php +++ b/src/Container/Container.php @@ -48,6 +48,17 @@ class Container implements ContainerInterface * @param mixed $instance Entry */ public function instance($abstract, $instance) + { + $this->singleton($abstract, $instance); + } + + /** + * Register a shared entry as singleton in the container + * + * @param string $abstract + * @param mixed $instance + */ + public function singleton($abstract, $instance) { $this->instances[$abstract] = $instance; } @@ -68,10 +79,21 @@ class Container implements ContainerInterface return isset($this->instances[$id]); } + /** + * Resolve the requested object + * + * @param string $abstract + * @return mixed + */ + protected function resolve($abstract) + { + return $this->instances[$abstract]; + } + /** * Get the globally available instance of the container * - * @return Container + * @return self */ public static function getInstance() { @@ -91,15 +113,4 @@ class Container implements ContainerInterface { static::$instance = $container; } - - /** - * Resolve the requested object - * - * @param string $abstract - * @return mixed - */ - protected function resolve($abstract) - { - return $this->instances[$abstract]; - } } diff --git a/src/helpers.php b/src/helpers.php index 733b902d..b942068f 100644 --- a/src/helpers.php +++ b/src/helpers.php @@ -1,15 +1,15 @@ get($id); + return Application::getInstance()->get($id); } /** -- cgit v1.2.3-70-g09d2 From b3b65743cdc534f7632c8e04e80d3489eec9677c Mon Sep 17 00:00:00 2001 From: Igor Scheller Date: Tue, 19 Sep 2017 18:30:42 +0200 Subject: Added Logger --- composer.json | 3 +- includes/engelsystem_provider.php | 14 ++++ src/Logger/EngelsystemLogger.php | 74 ++++++++++++++++++++ test/Logger/EngelsystemLoggerTest.php | 126 ++++++++++++++++++++++++++++++++++ 4 files changed, 216 insertions(+), 1 deletion(-) create mode 100644 src/Logger/EngelsystemLogger.php create mode 100644 test/Logger/EngelsystemLoggerTest.php (limited to 'src') diff --git a/composer.json b/composer.json index 0769a6b6..35956e20 100644 --- a/composer.json +++ b/composer.json @@ -18,7 +18,8 @@ "erusev/parsedown": "1.6.*", "twbs/bootstrap": "^3.3", "symfony/http-foundation": "^3.3", - "psr/container": "^1.0" + "psr/container": "^1.0", + "psr/log": "^1.0" }, "require-dev": { "phpunit/phpunit": "^6.3" diff --git a/includes/engelsystem_provider.php b/includes/engelsystem_provider.php index c7734a7c..a9305df5 100644 --- a/includes/engelsystem_provider.php +++ b/includes/engelsystem_provider.php @@ -5,9 +5,12 @@ use Engelsystem\Config\Config; use Engelsystem\Database\Db; use Engelsystem\Exceptions\Handler as ExceptionHandler; use Engelsystem\Http\Request; +use Engelsystem\Logger\EngelsystemLogger; use Engelsystem\Renderer\HtmlEngine; use Engelsystem\Renderer\Renderer; +use Psr\Log\LoggerInterface; use Symfony\Component\HttpFoundation\Session\Session; +use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage; /** * This file includes all needed functions, connects to the db etc. @@ -89,6 +92,14 @@ Db::connect( Db::getPdo()->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); Db::getPdo()->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); +/** + * Init logger + */ +$logger = new EngelsystemLogger(); +$app->instance('logger', $logger); +$app->instance(LoggerInterface::class, $logger); +$app->instance(EngelsystemLogger::class, $logger); + /** * Include legacy code @@ -180,6 +191,9 @@ foreach ($includeFiles as $file) { * Init application */ $session = new Session(); +if (PHP_SAPI == 'cli') { + $session = new Session(new MockArraySessionStorage()); +} $app->instance('session', $session); $session->start(); $request->setSession($session); diff --git a/src/Logger/EngelsystemLogger.php b/src/Logger/EngelsystemLogger.php new file mode 100644 index 00000000..db46215c --- /dev/null +++ b/src/Logger/EngelsystemLogger.php @@ -0,0 +1,74 @@ +checkLevel($level)) { + throw new InvalidArgumentException(); + } + + $message = $this->interpolate($message, $context); + + LogEntry_create('Logger: ' . $level, $message); + } + + /** + * Interpolates context values into the message placeholders. + * + * @param string $message + * @param array $context + * @return string + */ + protected function interpolate($message, array $context = []) + { + foreach ($context as $key => $val) { + // check that the value can be casted to string + if (is_array($val) || (is_object($val) && !method_exists($val, '__toString'))) { + continue; + } + + // replace the values of the message + $message = str_replace('{' . $key . '}', $val, $message); + } + + return $message; + } + + /** + * @param string $level + * @return bool + */ + protected function checkLevel($level) + { + return in_array($level, $this->allowedLevels); + } +} diff --git a/test/Logger/EngelsystemLoggerTest.php b/test/Logger/EngelsystemLoggerTest.php new file mode 100644 index 00000000..da10800d --- /dev/null +++ b/test/Logger/EngelsystemLoggerTest.php @@ -0,0 +1,126 @@ +assertInstanceOf('Psr\Log\LoggerInterface', $this->getLogger()); + } + + /** + * @dataProvider provideLogLevels + * @param string $level + */ + public function testAllLevels($level) + { + $logger = $this->getLogger(); + + LogEntries_clear_all(); + + $logger->log($level, 'First log message'); + $logger->{$level}('Second log message'); + + $entries = LogEntries(); + $this->assertCount(2, $entries); + } + + /** + * @return string[] + */ + public function provideLogLevels() + { + return [ + [LogLevel::ALERT], + [LogLevel::CRITICAL], + [LogLevel::DEBUG], + [LogLevel::EMERGENCY], + [LogLevel::ERROR], + [LogLevel::INFO], + [LogLevel::NOTICE], + [LogLevel::WARNING], + ]; + } + + public function testContextReplacement() + { + $logger = $this->getLogger(); + LogEntries_clear_all(); + + $logger->log(LogLevel::INFO, 'My username is {username}', ['username' => 'Foo']); + + $entry = $this->getLastEntry(); + $this->assertEquals('My username is Foo', $entry['message']); + $this->assertContains(LogLevel::INFO, $entry['nick'], '', true); + + foreach ( + [ + ['Data and {context}', []], + ['Data and ', ['context' => null]], + ['Data and {context}', ['context' => new \stdClass()]], + ] as $data + ) { + list($result, $context) = $data; + + $logger->log(LogLevel::INFO, 'Data and {context}', $context); + + $entry = $this->getLastEntry(); + $this->assertEquals($result, $entry['message']); + } + } + + public function testContextToString() + { + $logger = $this->getLogger(); + LogEntries_clear_all(); + + $mock = $this->getMockBuilder('someDataProvider') + ->setMethods(['__toString']) + ->getMock(); + + $mock->expects($this->atLeastOnce()) + ->method('__toString') + ->will($this->returnValue('FooBar')); + + $logger->log(LogLevel::INFO, 'Some data and {context}', ['context' => $mock]); + + $entry = $this->getLastEntry(); + $this->assertEquals('Some data and FooBar', $entry['message']); + } + + /** + * @expectedException InvalidArgumentException + */ + public function testThrowExceptionOnInvalidLevel() + { + $logger = $this->getLogger(); + + $logger->log('This log level should never be defined', 'Some message'); + } + + /** + * @return array + */ + public function getLastEntry() + { + $entries = LogEntries(); + $entry = array_pop($entries); + + return $entry; + } +} -- cgit v1.2.3-70-g09d2 From e6ed8a30171b86b452cec21a283373fc14dd5330 Mon Sep 17 00:00:00 2001 From: Igor Scheller Date: Tue, 19 Sep 2017 19:33:24 +0200 Subject: Changed LogEntries table: Use log level instead of nick name --- db/update.sql | 3 +++ includes/model/LogEntries_model.php | 12 ++++++------ includes/pages/admin_log.php | 8 +++----- includes/sys_log.php | 6 ++++-- phpunit.xml | 3 +++ src/Logger/EngelsystemLogger.php | 2 +- test/Logger/EngelsystemLoggerTest.php | 7 ++++++- test/model/LogEntriesModelTest.php | 29 ++++++++++++----------------- test/model/RoomModelTest.php | 17 +++++++---------- 9 files changed, 45 insertions(+), 42 deletions(-) (limited to 'src') diff --git a/db/update.sql b/db/update.sql index 5d93e230..3ed37ceb 100644 --- a/db/update.sql +++ b/db/update.sql @@ -28,3 +28,6 @@ UPDATE `Groups` SET UID = UID * 10; INSERT INTO `Groups` (Name, UID) VALUES ('News Admin', -65); INSERT INTO `Privileges` (id, name, `desc`) VALUES (42, 'admin_news_html', 'Use HTML in news'); INSERT INTO `GroupPrivileges` (group_id, privilege_id) VALUES (-65, 14), (-65, 42); + +-- Add log level to LogEntries +ALTER TABLE `LogEntries` CHANGE COLUMN `nick` `level` VARCHAR(20) NOT NULL; diff --git a/includes/model/LogEntries_model.php b/includes/model/LogEntries_model.php index 0e11bf8e..f0ee6673 100644 --- a/includes/model/LogEntries_model.php +++ b/includes/model/LogEntries_model.php @@ -5,16 +5,16 @@ use Engelsystem\Database\DB; /** * Creates a log entry. * - * @param string $nick Username - * @param string $message Log Message + * @param string $logLevel Log level + * @param string $message Log Message * @return bool */ -function LogEntry_create($nick, $message) +function LogEntry_create($logLevel, $message) { return DB::insert(' - INSERT INTO `LogEntries` (`timestamp`, `nick`, `message`) + INSERT INTO `LogEntries` (`timestamp`, `level`, `message`) VALUES(?, ?, ?) - ', [time(), $nick, $message]); + ', [time(), $logLevel, $message]); } /** @@ -43,7 +43,7 @@ function LogEntries_filter($keyword) return DB::select(' SELECT * FROM `LogEntries` - WHERE `nick` LIKE ? + WHERE `level` LIKE ? OR `message` LIKE ? ORDER BY `timestamp` DESC ', diff --git a/includes/pages/admin_log.php b/includes/pages/admin_log.php index 03c9abb0..694b1d5a 100644 --- a/includes/pages/admin_log.php +++ b/includes/pages/admin_log.php @@ -17,12 +17,10 @@ function admin_log() if (request()->has('keyword')) { $filter = strip_request_item('keyword'); } - $log_entries_source = LogEntries_filter($filter); + $log_entries = LogEntries_filter($filter); - $log_entries = []; - foreach ($log_entries_source as $log_entry) { + foreach ($log_entries as &$log_entry) { $log_entry['date'] = date('d.m.Y H:i', $log_entry['timestamp']); - $log_entries[] = $log_entry; } return page_with_title(admin_log_title(), [ @@ -33,7 +31,7 @@ function admin_log() ]), table([ 'date' => 'Time', - 'nick' => 'Angel', + 'level' => 'Type', 'message' => 'Log Entry' ], $log_entries) ]); diff --git a/includes/sys_log.php b/includes/sys_log.php index c4ef890e..513586e6 100644 --- a/includes/sys_log.php +++ b/includes/sys_log.php @@ -9,10 +9,12 @@ function engelsystem_log($message) { global $user; - $nick = "Guest"; + $logger = app('logger'); + if (isset($user)) { $nick = User_Nick_render($user); } - LogEntry_create($nick, $message); + + $logger->info('{nick}: {message}', ['nick' => $nick, 'message' => $message]); } diff --git a/phpunit.xml b/phpunit.xml index ff6eb120..ee5ae3e8 100644 --- a/phpunit.xml +++ b/phpunit.xml @@ -7,6 +7,9 @@ ./test/model/ + + ./test/Logger/ + diff --git a/src/Logger/EngelsystemLogger.php b/src/Logger/EngelsystemLogger.php index db46215c..1f255b69 100644 --- a/src/Logger/EngelsystemLogger.php +++ b/src/Logger/EngelsystemLogger.php @@ -38,7 +38,7 @@ class EngelsystemLogger extends AbstractLogger $message = $this->interpolate($message, $context); - LogEntry_create('Logger: ' . $level, $message); + LogEntry_create($level, $message); } /** diff --git a/test/Logger/EngelsystemLoggerTest.php b/test/Logger/EngelsystemLoggerTest.php index da10800d..2219cdb2 100644 --- a/test/Logger/EngelsystemLoggerTest.php +++ b/test/Logger/EngelsystemLoggerTest.php @@ -66,7 +66,7 @@ class EngelsystemLoggerTest extends TestCase $entry = $this->getLastEntry(); $this->assertEquals('My username is Foo', $entry['message']); - $this->assertContains(LogLevel::INFO, $entry['nick'], '', true); + $this->assertEquals(LogLevel::INFO, $entry['level']); foreach ( [ @@ -123,4 +123,9 @@ class EngelsystemLoggerTest extends TestCase return $entry; } + + public function tearDown() + { + LogEntries_clear_all(); + } } diff --git a/test/model/LogEntriesModelTest.php b/test/model/LogEntriesModelTest.php index 25d46fc4..761725c4 100644 --- a/test/model/LogEntriesModelTest.php +++ b/test/model/LogEntriesModelTest.php @@ -1,37 +1,32 @@ assertNotFalse(LogEntry_create('test', 'test_LogEntry_create')); - + $this->assertNotFalse(LogEntry_create(LogLevel::WARNING, 'test_LogEntry_create')); + // There should be one more log entry now $this->assertEquals(count(LogEntries()), $count + 1); } - public function test_LogEntries_clear_all() + public function testClearAllLogEntries() { - $this->create_LogEntry(); + LogEntry_create(LogLevel::WARNING, 'test'); $this->assertTrue(count(LogEntries()) > 0); + $this->assertNotFalse(LogEntries_clear_all()); - $this->assertEquals(count(LogEntries()), 0); + $this->assertCount(0, LogEntries()); } - /** - * @after - */ - public function teardown() + public function tearDown() { LogEntries_clear_all(); } diff --git a/test/model/RoomModelTest.php b/test/model/RoomModelTest.php index 135a6108..4205845b 100644 --- a/test/model/RoomModelTest.php +++ b/test/model/RoomModelTest.php @@ -1,11 +1,11 @@ create_Room(); - + $room = Room($this->room_id); - + $this->assertNotFalse($room); $this->assertNotNull($room); $this->assertEquals($room['Name'], 'test'); - - $this->assertNull(Room(- 1)); + + $this->assertNull(Room(-1)); } - /** - * @after - */ - public function teardown() + public function tearDown() { if ($this->room_id != null) { Room_delete($this->room_id); -- cgit v1.2.3-70-g09d2 From 2cb636b651c889243919d99eda8fa724d5c08392 Mon Sep 17 00:00:00 2001 From: Igor Scheller Date: Tue, 19 Sep 2017 21:50:22 +0200 Subject: Added Container unit test --- src/Container/Container.php | 2 +- tests/Unit/Container/ContainerTest.php | 98 ++++++++++++++++++++++++++++++++++ 2 files changed, 99 insertions(+), 1 deletion(-) create mode 100644 tests/Unit/Container/ContainerTest.php (limited to 'src') diff --git a/src/Container/Container.php b/src/Container/Container.php index 9af5c1e6..59a17a04 100644 --- a/src/Container/Container.php +++ b/src/Container/Container.php @@ -38,7 +38,7 @@ class Container implements ContainerInterface return $this->resolve($id); } - throw new NotFoundException(sprintf('The entry with the id "%s" could not be found')); + throw new NotFoundException(sprintf('The entry with the id "%s" could not be found', $id)); } /** diff --git a/tests/Unit/Container/ContainerTest.php b/tests/Unit/Container/ContainerTest.php new file mode 100644 index 00000000..f0ba24e7 --- /dev/null +++ b/tests/Unit/Container/ContainerTest.php @@ -0,0 +1,98 @@ +instance('foo', $class); + $this->assertSame($class, $container->get('foo')); + } + + /** + * @covers \Engelsystem\Container\Container::get + * @expectedException \Engelsystem\Container\NotFoundException + */ + public function testGetException() + { + $container = new Container(); + + $container->get('not.registered.service'); + } + + /** + * @covers \Engelsystem\Container\Container::instance + * @covers \Engelsystem\Container\Container::resolve + */ + public function testInstance() + { + $container = new Container(); + $class = new class + { + }; + + $container->instance('foo', $class); + $this->assertSame($class, $container->get('foo')); + } + + /** + * @covers \Engelsystem\Container\Container::has + */ + public function testHas() + { + $container = new Container(); + + $this->assertFalse($container->has('test')); + + $class = new class + { + }; + + $container->instance('test', $class); + $this->assertTrue($container->has('test')); + } + + /** + * @covers \Engelsystem\Container\Container::singleton + */ + public function testSingleton() + { + $container = new Container(); + $class = new class + { + }; + + $container->singleton('foo', $class); + $this->assertSame($class, $container->get('foo')); + $this->assertSame($class, $container->get('foo')); + } + + /** + * @covers \Engelsystem\Container\Container::setInstance + * @covers \Engelsystem\Container\Container::getInstance + */ + public function testContainerSingleton() + { + $container0 = new Container(); + $container = Container::getInstance(); + + $this->assertNotSame($container0, $container); + + $container1 = new Container; + Container::setInstance($container1); + + $this->assertSame($container1, Container::getInstance()); + } +} -- cgit v1.2.3-70-g09d2 From 1e267ce3b133299f82661a37d82c0f50e8575e1e Mon Sep 17 00:00:00 2001 From: Igor Scheller Date: Tue, 19 Sep 2017 23:55:24 +0200 Subject: Added Renderer unit test --- src/Renderer/HtmlEngine.php | 2 +- src/Renderer/Renderer.php | 9 ++++- tests/Unit/Renderer/HtmlEngineTest.php | 67 ++++++++++++++++++++++++++++++++++ tests/Unit/Renderer/RendererTest.php | 55 ++++++++++++++++++++++++++++ 4 files changed, 131 insertions(+), 2 deletions(-) create mode 100644 tests/Unit/Renderer/HtmlEngineTest.php create mode 100644 tests/Unit/Renderer/RendererTest.php (limited to 'src') diff --git a/src/Renderer/HtmlEngine.php b/src/Renderer/HtmlEngine.php index 4a48e1f0..75343bbd 100644 --- a/src/Renderer/HtmlEngine.php +++ b/src/Renderer/HtmlEngine.php @@ -29,6 +29,6 @@ class HtmlEngine implements EngineInterface */ public function canRender($path) { - return strpos($path, '.html') && file_exists($path); + return strpos($path, '.htm') && file_exists($path); } } diff --git a/src/Renderer/Renderer.php b/src/Renderer/Renderer.php index 5ed7cf31..de31ca74 100644 --- a/src/Renderer/Renderer.php +++ b/src/Renderer/Renderer.php @@ -2,8 +2,12 @@ namespace Engelsystem\Renderer; +use Psr\Log\LoggerAwareTrait; + class Renderer { + use LoggerAwareTrait; + /** @var EngineInterface[] */ protected $renderer = []; @@ -24,7 +28,10 @@ class Renderer return $renderer->get($template, $data); } - engelsystem_error('Unable to find a renderer for template file "' . $template . '".'); + if ($this->logger) { + $this->logger->error('Unable to find a renderer for template file "{file}"', ['file' => $template]); + } + return ''; } diff --git a/tests/Unit/Renderer/HtmlEngineTest.php b/tests/Unit/Renderer/HtmlEngineTest.php new file mode 100644 index 00000000..0b317b72 --- /dev/null +++ b/tests/Unit/Renderer/HtmlEngineTest.php @@ -0,0 +1,67 @@ +createTempFile('
%main_content%
'); + + $data = $engine->get($file, ['main_content' => 'Lorem ipsum dolor sit']); + $this->assertEquals('
Lorem ipsum dolor sit
', $data); + } + + /** + * @covers \Engelsystem\Renderer\HtmlEngine::canRender + */ + public function testCanRender() + { + $engine = new HtmlEngine(); + + $this->assertFalse($engine->canRender('/dev/null')); + + $file = $this->createTempFile(); + $this->assertTrue($engine->canRender($file)); + + $htmFile = $this->createTempFile('', '.htm'); + $this->assertTrue($engine->canRender($htmFile)); + } + + /** + * @param string $content + * @param string $extension + * @return string + */ + protected function createTempFile($content = '', $extension = '.html') + { + $tmpFileName = tempnam(sys_get_temp_dir(), 'EngelsystemUnitTest'); + + $fileName = $tmpFileName . $extension; + rename($tmpFileName, $fileName); + + file_put_contents($fileName, $content); + + $this->tmpFileNames[] = $fileName; + + return $fileName; + } + + public function tearDown() + { + foreach ($this->tmpFileNames as $fileName) { + unlink($fileName); + } + } +} diff --git a/tests/Unit/Renderer/RendererTest.php b/tests/Unit/Renderer/RendererTest.php new file mode 100644 index 00000000..b0238078 --- /dev/null +++ b/tests/Unit/Renderer/RendererTest.php @@ -0,0 +1,55 @@ +getMockForAbstractClass(EngineInterface::class); + + $nullRenderer->expects($this->atLeastOnce()) + ->method('canRender') + ->willReturn(false); + $renderer->addRenderer($nullRenderer); + + $mockRenderer = $this->getMockForAbstractClass(EngineInterface::class); + + $mockRenderer->expects($this->atLeastOnce()) + ->method('canRender') + ->with('foo.template') + ->willReturn(true); + + $mockRenderer->expects($this->atLeastOnce()) + ->method('get') + ->with('foo.template', ['lorem' => 'ipsum']) + ->willReturn('Rendered content'); + + $renderer->addRenderer($mockRenderer); + $data = $renderer->render('foo.template', ['lorem' => 'ipsum']); + + $this->assertEquals('Rendered content', $data); + } + + public function testError() + { + $renderer = new Renderer(); + + $loggerMock = $this->getMockForAbstractClass(LoggerInterface::class); + $loggerMock + ->expects($this->once()) + ->method('error'); + + $renderer->setLogger($loggerMock); + + $data = $renderer->render('testing.template'); + $this->assertEquals('', $data); + } +} -- cgit v1.2.3-70-g09d2 From 86c0713baa2f616bf1dff6d9dbe0ea68b1c00e91 Mon Sep 17 00:00:00 2001 From: Igor Scheller Date: Wed, 20 Sep 2017 01:09:11 +0200 Subject: Added helpers unit test --- includes/engelsystem_provider.php | 8 ++ src/Routing/UrlGenerator.php | 2 +- src/helpers.php | 14 ++- tests/Unit/HelpersTest.php | 152 ++++++++++++++++++++++++++++++++ tests/Unit/Routing/UrlGeneratorTest.php | 3 +- 5 files changed, 173 insertions(+), 6 deletions(-) create mode 100644 tests/Unit/HelpersTest.php (limited to 'src') diff --git a/includes/engelsystem_provider.php b/includes/engelsystem_provider.php index a9305df5..cd22f6a7 100644 --- a/includes/engelsystem_provider.php +++ b/includes/engelsystem_provider.php @@ -8,6 +8,7 @@ use Engelsystem\Http\Request; use Engelsystem\Logger\EngelsystemLogger; use Engelsystem\Renderer\HtmlEngine; use Engelsystem\Renderer\Renderer; +use Engelsystem\Routing\UrlGenerator; use Psr\Log\LoggerInterface; use Symfony\Component\HttpFoundation\Session\Session; use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage; @@ -59,6 +60,13 @@ if ($config->get('maintenance')) { } +/** + * Register UrlGenerator + */ +$urlGenerator = new UrlGenerator(); +$app->instance('routing.urlGenerator', $urlGenerator); + + /** * Initialize renderer */ diff --git a/src/Routing/UrlGenerator.php b/src/Routing/UrlGenerator.php index 33eef7b0..6df52425 100644 --- a/src/Routing/UrlGenerator.php +++ b/src/Routing/UrlGenerator.php @@ -9,7 +9,7 @@ class UrlGenerator * @param array $parameters * @return string */ - public static function to($path, $parameters = []) + public function to($path, $parameters = []) { $path = '/' . ltrim($path, '/'); $request = app('request'); diff --git a/src/helpers.php b/src/helpers.php index b942068f..de303963 100644 --- a/src/helpers.php +++ b/src/helpers.php @@ -69,7 +69,7 @@ function request($key = null, $default = null) */ function session($key = null, $default = null) { - $session = request()->getSession(); + $session = app('session'); if (is_null($key)) { return $session; @@ -97,9 +97,15 @@ function view($template = null, $data = null) /** * @param string $path * @param array $parameters - * @return string + * @return UrlGenerator|string */ -function url($path, $parameters = []) +function url($path = null, $parameters = []) { - return UrlGenerator::to($path, $parameters); + $urlGenerator = app('routing.urlGenerator'); + + if (is_null($path)) { + return $urlGenerator; + } + + return $urlGenerator->to($path, $parameters); } diff --git a/tests/Unit/HelpersTest.php b/tests/Unit/HelpersTest.php new file mode 100644 index 00000000..d9782888 --- /dev/null +++ b/tests/Unit/HelpersTest.php @@ -0,0 +1,152 @@ +getAppMock('some.name', $class); + + $this->assertEquals($appMock, app()); + $this->assertEquals($class, app('some.name')); + } + + /** + * @covers \config + */ + public function testConfig() + { + $configMock = $this->getMockBuilder(Config::class) + ->getMock(); + + $this->getAppMock('config', $configMock); + $this->assertEquals($configMock, config()); + + $configMock->expects($this->once()) + ->method('set') + ->with(['foo' => 'bar']); + + $this->assertTrue(config(['foo' => 'bar'])); + + $configMock->expects($this->once()) + ->method('get') + ->with('mail') + ->willReturn(['user' => 'FooBar']); + + $this->assertEquals(['user' => 'FooBar'], config('mail')); + } + + /** + * @covers \request + */ + public function testRequest() + { + $requestMock = $this->getMockBuilder(Request::class) + ->getMock(); + + $this->getAppMock('request', $requestMock); + $this->assertEquals($requestMock, request()); + + $requestMock->expects($this->once()) + ->method('input') + ->with('requestKey') + ->willReturn('requestValue'); + + $this->assertEquals('requestValue', request('requestKey')); + } + + /** + * @covers \session + */ + public function testSession() + { + $sessionMock = $this->getMockBuilder(Session::class) + ->getMock(); + + $this->getAppMock('session', $sessionMock); + $this->assertEquals($sessionMock, session()); + + $sessionMock->expects($this->once()) + ->method('get') + ->with('someKey') + ->willReturn('someValue'); + + $this->assertEquals('someValue', session('someKey')); + } + + /** + * @covers \view + */ + public function testView() + { + $rendererMock = $this->getMockBuilder(Renderer::class) + ->getMock(); + + $this->getAppMock('renderer', $rendererMock); + $this->assertEquals($rendererMock, view()); + + $rendererMock->expects($this->once()) + ->method('render') + ->with('template.name', ['template' => 'data']) + ->willReturn('rendered template'); + + $this->assertEquals('rendered template', view('template.name', ['template' => 'data'])); + } + + /** + * @covers \url + */ + public function testUrl() + { + $urlGeneratorMock = $this->getMockBuilder(UrlGenerator::class) + ->getMock(); + + $this->getAppMock('routing.urlGenerator', $urlGeneratorMock); + $this->assertEquals($urlGeneratorMock, url()); + + $urlGeneratorMock->expects($this->once()) + ->method('to') + ->with('foo/bar', ['param' => 'value']) + ->willReturn('http://lorem.ipsum/foo/bar?param=value'); + + $this->assertEquals('http://lorem.ipsum/foo/bar?param=value', url('foo/bar', ['param' => 'value'])); + } + + /** + * @param string $alias + * @param object $object + * @return Application|\PHPUnit_Framework_MockObject_MockObject + */ + protected function getAppMock($alias, $object) + { + $appMock = $this->getMockBuilder(Container::class) + ->getMock(); + + $appMock->expects($this->atLeastOnce()) + ->method('get') + ->with($alias) + ->willReturn($object); + + /** @var $appMock Application */ + Application::setInstance($appMock); + + return $appMock; + } +} diff --git a/tests/Unit/Routing/UrlGeneratorTest.php b/tests/Unit/Routing/UrlGeneratorTest.php index 5b53a04e..fc23520a 100644 --- a/tests/Unit/Routing/UrlGeneratorTest.php +++ b/tests/Unit/Routing/UrlGeneratorTest.php @@ -32,6 +32,7 @@ class UrlGeneratorTest extends TestCase public function testTo($urlToPath, $path, $willReturn, $arguments, $expectedUrl) { $app = new Container(); + $urlGenerator = new UrlGenerator(); Application::setInstance($app); $request = $this->getMockBuilder(Request::class) @@ -44,7 +45,7 @@ class UrlGeneratorTest extends TestCase $app->instance('request', $request); - $url = UrlGenerator::to($urlToPath, $arguments); + $url = $urlGenerator->to($urlToPath, $arguments); $this->assertEquals($expectedUrl, $url); } } -- cgit v1.2.3-70-g09d2 From 31414905d710ed53796d67759dec24baf2eeefc7 Mon Sep 17 00:00:00 2001 From: Igor Scheller Date: Wed, 20 Sep 2017 01:29:04 +0200 Subject: Fixed exceptionHandler to catch PdoExceptions, formatting --- .gitignore | 1 + public/.htaccess | 1 + src/Exceptions/Handler.php | 2 +- 3 files changed, 3 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/.gitignore b/.gitignore index eb3f8939..eb12eae7 100644 --- a/.gitignore +++ b/.gitignore @@ -21,6 +21,7 @@ _vimrc_local.vim # Project files /config/config.php /test/coverage +/public/coverage # Composer files /vendor/ diff --git a/public/.htaccess b/public/.htaccess index c9d40187..2b1d3a7a 100644 --- a/public/.htaccess +++ b/public/.htaccess @@ -1,3 +1,4 @@ + RewriteEngine on diff --git a/src/Exceptions/Handler.php b/src/Exceptions/Handler.php index c4fb639c..95bcd132 100644 --- a/src/Exceptions/Handler.php +++ b/src/Exceptions/Handler.php @@ -42,7 +42,7 @@ class Handler /** * @param Throwable $e */ - public function exceptionHandler(Throwable $e) + public function exceptionHandler($e) { $this->handle( 'exception', -- cgit v1.2.3-70-g09d2