/** * Runs the error controller action for the specified HTTP error code. * * @param int $errorCode The error code * * @return void */ protected function runErrorAction($errorCode) { $controllerName = $this->config->get('system.errorController', self::DEFAULT_ERROR_CONTROLLER_NAME); try { try { $controller = $this->diContainer->getController($controllerName, $this->request, $this->response); } catch (ControllerException $exception) { // No such controller, fall back to built in default $controller = $this->diContainer->getDefaultErrorController($this->request, $this->response); $controllerName = self::DEFAULT_ERROR_CONTROLLER_NAME; } } catch (\Exception $e) { $this->dispatchedController = $controllerName; $this->dispatchedAction = 500; throw $e; } $this->dispatchedController = $controllerName; $this->dispatchedAction = $errorCode; $this->raiseEventIfNotRaisedYet(Event::TYPE_APPLICATION_BEFORE_CONTROLLER_RUN); $controller->run($errorCode); $this->raiseEventIfNotRaisedYet(Event::TYPE_APPLICATION_AFTER_CONTROLLER_RUN); $this->response->render(); $this->raiseEventIfNotRaisedYet(Event::TYPE_APPLICATION_BEFORE_OUTPUT_SEND); $this->response->send(); $this->raiseEventIfNotRaisedYet(Event::TYPE_APPLICATION_AFTER_OUTPUT_SEND); }
/** * Constructor. * * @param string $keyPrefix The prefix for the cache keys of the bo instance. If not set, one will be generated * based on the configuration and the class-name. */ public function __construct($keyPrefix = null) { if (empty($keyPrefix)) { $keyPrefix = Config::getInstance()->get('system.project.name') . '.' . get_class($this); } $this->keyPrefix = $keyPrefix; }
/** * Sets up the fixture, for example, open a network connection. * This method is called before a test is executed. * * @return void */ protected function setUp() { parent::setUp(); Config::getInstance()->set(array('resource.log.' . self::SYSLOG_CONNECTION_CONFIG_NAME . '.facility' => LOG_LOCAL5, 'resource.log.' . self::SYSLOG_CONNECTION_CONFIG_NAME . '.applicationIdent' => self::SYSLOG_CONNECTION_APPLICATION_INDENT, 'resource.log.' . self::SYSLOG_CONNECTION_CONFIG_NAME . '.includeSapiName' => false, 'resource.log.' . self::SYSLOG_CONNECTION_CONFIG_NAME . '.addPid' => false)); $this->syslogConnectionMock = new SyslogConnectionMock(); $this->syslogLogger = new SyslogLoggerMock(self::SYSLOG_CONNECTION_CONFIG_NAME, $this->syslogConnectionMock); }
/** * Creates a syslog connection. * * @param string $configName The name of the configuration to use. * @param \YapepBase\Syslog\ISyslogConnection $connection The Syslog connection to use. * * @todo Remove the possibility to set config options. Use only the set connection [emul] */ public function __construct($configName, \YapepBase\Syslog\ISyslogConnection $connection = null) { $config = Config::getInstance(); $properties = array('applicationIdent', 'facility', 'includeSapiName', 'addPid'); foreach ($properties as $property) { try { $this->configOptions[$property] = $config->get('resource.log.' . $configName . '.' . $property, false); } catch (ConfigException $e) { // We just swallow this because we don't know what properties do we need in advance } } $this->verifyConfig($configName); if ($connection) { $this->connection = $connection; //@codeCoverageIgnoreStart } elseif (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { $this->connection = new \YapepBase\Syslog\LegacySyslogConnection(); } else { $this->connection = new \YapepBase\Syslog\NativeSyslogConnection(); } //@codeCoverageIgnoreEnd $ident = $this->configOptions['applicationIdent']; if (isset($this->configOptions['includeSapiName']) && $this->configOptions['includeSapiName']) { $ident .= '-' . PHP_SAPI; } // TODO: Can be dangerous as it can override an already set value [emul] $this->connection->setIdent($ident); $this->connection->setFacility($this->configOptions['facility']); $options = 0; if (isset($this->configOptions['addPid']) && $this->configOptions['addPid']) { $options += \YapepBase\Syslog\ISyslogConnection::LOG_PID; } $this->connection->setOptions($options); $this->connection->open(); }
protected function setUp() { parent::setUp(); // TODO Make this setting global. For this, there should be a base class for all tests [szeber] Config::getInstance()->set('system.project.name', 'test'); $this->originalObLevel = ob_get_level(); }
/** * Constructor. * * @param \YapepBase\Request\IRequest $request The request instance * @param string $configName The name of the configuration where the routes are * stored. * @param \YapepBase\Router\IReverseRouter $reverseRouter The reverse router to use. If not set, it will use * an ArrayReverseRouter. * * @throws RouterException On error */ public function __construct(IRequest $request, $configName, IReverseRouter $reverseRouter = null) { $routes = Config::getInstance()->get('resource.routing.' . $configName, false); if (!is_array($routes)) { throw new RouterException('No route config found for name: ' . $configName, RouterException::ERR_ROUTE_CONFIG); } parent::__construct($request, $routes, $reverseRouter); }
/** * Returns the requested storage. * * @param string $configName The name of the config. * * @throws \YapepBase\Exception\StorageException If the given storage type is invalid. * @throws \YapepBase\Exception\ConfigException On configuration errors. * * @return \YapepBase\Storage\StorageAbstract */ public static function get($configName) { if (!isset(static::$storages[$configName])) { $config = Config::getInstance(); $storageType = $config->get('resource.storage.' . $configName . '.storageType'); if (empty($storageType)) { throw new StorageException('No storageType configured in the config: ' . $configName); } static::$storages[$configName] = static::getStorage($configName, $storageType); } return static::$storages[$configName]; }
/** * Runs the action and returns the result as an ViewAbstract instance. * * @param string $methodName The name of the method that contains the action. * * @return string|\YapepBase\View\RestTemplate The result view or the rendered output. * * @throws \YapepBase\Exception\ControllerException On controller specific error. (eg. action not found) * @throws \YapepBase\Exception\Exception On framework related errors. * @throws \Exception On non-framework related errors. */ protected function runAction($methodName) { $result = $this->{$methodName}(); if (is_array($result)) { $view = new RestTemplate(); $view->setRootNode(Config::getInstance()->get('system.rest.xmlRootNode', 'rest')); $view->setContent($result); return $view; } elseif (!is_string($result) && !$result instanceof RestTemplate) { throw new ControllerException('The received result is not a RestTemplate or an array or string', ControllerException::ERR_INVALID_ACTION_RETURN_VALUE); } return $result; }
/** * Constructor. * * @param string $configName The name of the configuration to use. * * @throws \YapepBase\Exception\ConfigException On configuration errors. * @throws \YapepBase\Exception\StorageException On storage errors. */ public function __construct($configName) { $this->currentConfigurationName = $configName; $properties = $this->getConfigProperties(); $configData = array(); foreach ($properties as $property) { try { $configData[$property] = Config::getInstance()->get('resource.storage.' . $configName . '.' . $property); } catch (ConfigException $e) { // We just swallow this because we don't know what properties do we need in advance } } $this->setupConfig($configData); }
/** * Test configuration section handling */ public function testSections() { $testData = array('test.first' => 1, 'test.second' => 2, 'test.secondLevel.first' => 'first', 'test.secondLevel.second' => 'second', 'test2' => 'test'); $this->config->set($testData); $this->assertSame(false, $this->config->get('test*', false), 'Returning invalid wildcard returns the default'); $result = $this->config->get('test.*'); $this->assertInternalType('array', $result); $this->assertEquals(4, count($result)); $this->assertArrayHasKey('first', $result); $this->assertSame(1, $result['first']); $result = $this->config->get('test.*', null, true); $this->assertInternalType('array', $result); $this->assertEquals(4, count($result)); $this->assertArrayHasKey('test.first', $result); $this->assertSame(1, $result['test.first']); }
/** * Runs the command and returns the command output and the separated STDERR in the outgoing parameter. * * Uses the "system.commandOutputHelper.work.path" config, what is describes the directory where the temporary * file pointer will be added. (default => /tmp) * * @param CommandExecutor $command The command executor object. * @param string $stdErr The error messages [Outgoing] * * @return \YapepBase\Shell\CommandOutput The output of the command. * @throws \Exception */ public function runCommandWithStdErr(CommandExecutor $command, &$stdErr) { $dir = Config::getInstance()->get('system.commandOutputHelper.work.path', '/tmp'); $pipePath = tempnam($dir, 'stderr-'); $fileHandler = Application::getInstance()->getDiContainer()->getFileHandler(); try { posix_mkfifo($pipePath, 0755); $command->setOutputRedirection(CommandExecutor::OUTPUT_REDIRECT_STDERR, $pipePath); $result = $command->run(); $stdErr = $fileHandler->getAsString($pipePath); $fileHandler->remove($pipePath); } catch (\Exception $e) { if ($fileHandler->checkIsPathExists($pipePath)) { $fileHandler->remove($pipePath); } throw $e; } return $result; }
/** * Tests the runCommandWithStdErr() method. * * @return void */ public function testRunCommandWithStdErr() { $testPath = getenv('YAPEPBASE_TEST_TEMPPATH'); $this->testFilePath = null; $testInstance = $this; $expectedError = 'error message'; $commandExecutorMock = \Mockery::mock('\\YapepBase\\Shell\\CommandExecutor')->shouldReceive('setOutputRedirection')->with(CommandExecutor::OUTPUT_REDIRECT_STDERR, \Mockery::on(function ($param) use($testInstance) { $testInstance->testFilePath = $param; return true; }))->getMock()->shouldReceive('run')->andReturnUsing(function () use($testInstance, $expectedError) { file_put_contents($testInstance->testFilePath, $expectedError); return new CommandOutput('test', '', 0, 'test 2> ' . $testInstance->testFilePath); })->getMock(); if (empty($testPath)) { $this->markTestSkipped('Test cannot be done without a test directory'); } if (!file_exists($testPath) && !mkdir($testPath, 0755, true)) { $this->fail('The test path does not exist, and cannot be created: ' . $testPath); } Config::getInstance()->set('system.commandOutputHelper.work.path', $testPath); $this->commandOutputHelper->runCommandWithStdErr($commandExecutorMock, $errorMessage); $this->assertEquals($expectedError, $errorMessage); $this->assertFileNotExists($this->testFilePath); }
public function create($username, $password, $email) { $passwordHash = password_hash($password, PASSWORD_DEFAULT, ['cost' => Config::getInstance()->get('application.passwordHash.cost')]); return $this->getUserDao()->create($username, $passwordHash, $email); }
/** * Outputs (echoes) all parameters. * * @return void */ public function out() { if (Config::getInstance()->get('system.output.gzip', false)) { ob_start('ob_gzhandler'); } else { ob_start(); } foreach (func_get_args() as $string) { echo $string; } ob_end_flush(); }
/** * Tests if the factory produces an error on trying to create a connection to an invalid backend. */ public function testBadConnectionBackendType() { $this->setExpectedException('\\YapepBase\\Exception\\DatabaseException', 'Invalid database config'); $this->config->set(array('resource.database.test2.rw.backendType' => 'invalid')); DbFactory::getConnection('test2', DbFactory::TYPE_READ_WRITE); }
protected function setUp() { parent::setUp(); $this->originalObLevel = ob_get_level(); Config::getInstance()->set(array('resource.missingCookieName.namespace' => 'test2')); }
/** * Returns a new OAuth helper instance. * * @return OAuth */ public function getOAuth() { $config = Config::getInstance(); return new OAuth($config->get('resource.vend.oauth.clientId'), $config->get('resource.vend.oauth.clientSecret'), $config->get('resource.vend.oauth.redirectUri')); }
/** * Returns a database connection of the specified name and type * * @param string $connectionName The name of the database connection. * @param string $connectionType The type of the database connection. {@uses self::TYPE_*} * * @return DbConnectionAbstract The requested connection. * * @throws DatabaseException On configuration or connection errors. */ public static function getConnection($connectionName, $connectionType = self::TYPE_READ_WRITE) { if (!isset(static::$connections[$connectionName][$connectionType])) { $config = Config::getInstance(); if (is_null(static::$paramPrefix)) { static::$paramPrefix = (string) $config->get('system.database.paramPrefix', ''); } $properties = array('backendType', 'charset', 'database', 'host', 'isPersistent', 'password', 'path', 'user', 'useTraditionalStrictMode', 'timezone'); $configData = array(); foreach ($properties as $property) { try { $configData[$property] = $config->get('resource.database.' . $connectionName . '.' . $connectionType . '.' . $property); } catch (ConfigException $e) { // We just swallow this because we don't know what properties do we need in advance } } if (empty($configData)) { throw new DatabaseException('Database connection configuration "' . $connectionName . '" not found'); } if (!static::validateConnectionConfig($configData)) { throw new DatabaseException('Invalid database config: ' . $connectionName); } static::$connections[$connectionName][$connectionType] = static::makeConnection($configData, $connectionName); if (self::TYPE_READ_WRITE == $connectionType || isset(static::$connections[$connectionName][self::TYPE_READ_ONLY])) { static::$connections[$connectionName][self::TYPE_READ_ONLY] = static::$connections[$connectionName][$connectionType]; } } return static::$connections[$connectionName][$connectionType]; }
protected function setUp() { parent::setUp(); Config::getInstance()->set(['resource.vend.oauth.clientId' => 'clientId', 'resource.vend.oauth.clientSecret' => 'clientSecret', 'resource.vend.oauth.redirectUri' => 'redirectUri']); }
/** * Tears down the fixture, for example, close a network connection. * This method is called after a test is executed. * * @return void */ protected function tearDown() { Config::getInstance()->clear(); Application::getInstance()->getDiContainer()->getEventHandlerRegistry()->clearAll(); parent::tearDown(); }
/** * Constructor. */ public function __construct() { $this->timeout = Config::getInstance()->get('system.shell.executedCommandTimeout', 0); }
/** * Runs the specified action * * @param string $action The name of the action (without the controller specific prefix) * * @return void * * @throws \YapepBase\Exception\ControllerException On controller specific error. (eg. action not found) * @throws \YapepBase\Exception\Exception On framework related errors. * @throws \YapepBase\Exception\RedirectException On redirections. * @throws \Exception On non-framework related errors. */ public function run($action) { $methodName = $this->getActionPrefix() . $action; if (!method_exists($this, $methodName)) { throw new ControllerException('Action ' . $methodName . ' does not exist in ' . get_class($this), ControllerException::ERR_ACTION_NOT_FOUND); } if (Config::getInstance()->get('system.performStrictControllerActionNameValidation', false)) { $reflection = new \ReflectionClass($this); $method = $reflection->getMethod($methodName); if ($method->name != $methodName) { throw new ControllerException('Invalid case when running action ' . $methodName . ' in ' . get_class($this) . '. The valid case is: ' . $method->name, ControllerException::ERR_ACTION_NOT_FOUND); } } $this->before(); $result = $this->runAction($methodName); if (!empty($result) && !is_string($result) && !$result instanceof ViewAbstract) { throw new ControllerException('Result of the action (' . get_class($this) . '/' . $action . ') is not an instance of ViewAbstract or string', ControllerException::ERR_INVALID_ACTION_RESULT); } // We called the run method, but we did not rendered the output yet $this->runBeforeRender(); $this->runBeforeResponseSet($result); if (!empty($result)) { if (is_string($result)) { $this->response->setRenderedBody($result); } else { $this->response->setBody($result); } } $this->after(); }
/** * Sets a cookie with the response. The params are same as for the php setCookie() function. * {@link http://php.net/setCookie} * * @param string $name Cookie name. * @param string $value The cookie value. * @param int $expiration The expiration timestamp. * @param string $path Path. * @param string $domain Cookie domain. * @param bool $secure Is the cookie HTTPS only. * @param bool $httpOnly Is the cookie HTTP only. * * @return void */ public function setCookie($name, $value, $expiration = 0, $path = '/', $domain = null, $secure = false, $httpOnly = false) { if (is_null($domain)) { $domain = Config::getInstance()->get('system.response.defaultCookieDomain', false); if (false === $domain) { $domain = null; } } if ($this->isBufferingEnabled) { $this->cookies[$name] = array('name' => $name, 'value' => $value, 'expiration' => $expiration, 'path' => $path, 'domain' => $domain, 'secure' => $secure, 'httpOnly' => $httpOnly); } else { $this->output->setCookie($name, $value, $expiration, $path, $domain, $secure, $httpOnly); } }
/** * Tears down the fixture, for example, closes a network connection. * This method is called after a test is executed. */ protected function tearDown() { Config::getInstance()->clear(); Application::getInstance()->setDiContainer(new SystemContainer()); }
function setupMySqlDbConfig($varName, $dbName) { $parsed = parse_url(getenv($varName)); $config = Config::getInstance(); $config->set(['resource.database.' . $dbName . '.rw.backendType' => 'mysql', 'resource.database.' . $dbName . '.rw.host' => $parsed['host'], 'resource.database.' . $dbName . '.rw.user' => $parsed['user'], 'resource.database.' . $dbName . '.rw.password' => $parsed['pass'], 'resource.database.' . $dbName . '.rw.database' => ltrim($parsed['path'], '/'), 'resource.database.' . $dbName . '.rw.port' => $parsed['port'], 'resource.database.' . $dbName . '.rw.charset' => 'utf8', 'resource.database.' . $dbName . '.ro.backendType' => 'mysql', 'resource.database.' . $dbName . '.ro.host' => $parsed['host'], 'resource.database.' . $dbName . '.ro.user' => $parsed['user'], 'resource.database.' . $dbName . '.ro.password' => $parsed['pass'], 'resource.database.' . $dbName . '.ro.database' => ltrim($parsed['path'], '/'), 'resource.database.' . $dbName . '.ro.port' => $parsed['port'], 'resource.database.' . $dbName . '.ro.charset' => 'utf8']); }
/** * Constructor * * @param string $configName Name of the session config. * @param \YapepBase\Storage\IStorage $storage The storage object. * @param bool $autoRegister If TRUE, it will automatically register as an event handler. * * @throws \YapepBase\Exception\ConfigException On configuration problems * @throws \YapepBase\Exception\Exception On other problems */ public function __construct($configName, IStorage $storage, $autoRegister = true) { if (!$storage->isTtlSupported()) { throw new Exception('Storage without TTL support passed to session handler.'); } $this->storage = $storage; $properties = array('namespace', 'lifetime'); $properties = array_merge($properties, $this->getConfigProperties()); $configData = array(); foreach ($properties as $property) { try { $configData[$property] = Config::getInstance()->get('resource.session.' . $configName . '.' . $property); } catch (ConfigException $e) { // We just swallow this because we don't know what properties do we need in advance } } if (empty($configData)) { throw new ConfigException('Configuration not found for session handler: ' . $configName); } if (!isset($configData['namespace'])) { throw new ConfigException('No namespace has been set for the session handler: ' . $configName); } $this->validateConfig($configData); $this->namespace = $configData['namespace']; $this->lifetime = empty($configData['lifetime']) ? self::DEFAULT_LIFETIME : (int) $configData['lifetime']; if ($autoRegister) { $this->registerEventHandler(); } $this->id = $this->getSessionId(); }
public function testRun() { $response = null; $controller = $this->getController($response); $controller->setAction(function () { }); $this->assertFalse($controller->ran); $controller->run('Test'); $this->assertTrue($controller->ran); try { $controller->run('nonExistent'); $this->fail('Running a non-existent action should result in a ControllerException'); } catch (\YapepBase\Exception\ControllerException $e) { $this->assertEquals(\YapepBase\Exception\ControllerException::ERR_ACTION_NOT_FOUND, $e->getCode()); } $controller->setAction(function () { return 3.14; }); try { $controller->run('Test'); $this->fail('Running an action with an invalid result in a ControllerException'); } catch (\YapepBase\Exception\ControllerException $e) { $this->assertEquals(\YapepBase\Exception\ControllerException::ERR_INVALID_ACTION_RESULT, $e->getCode()); } $controller->setAction(function () { return 'test string'; }); $controller->run('Test'); $this->assertEquals('test string', $response->getRenderedBody()); $controller->setAction(function () { $view = new ViewMock(); $view->set('view test string'); return $view; }); $controller->run('Test'); $this->assertEquals('view test string', $response->getRenderedBody()); $controller->setAction(function (MockController $controller) { $controller->internalRedirect('Mock', 'RedirectTarget'); }); try { $controller->run('Test'); $this->fail('No redirectException is thrown'); } catch (RedirectException $exception) { } $this->assertEquals('redirect test', $response->getRenderedBody()); // Test if the action is run with an invalid case with no strict checking $controller->setAction(function (MockController $controller) { return 'test'; }); $controller->run('test'); $this->assertTrue($controller->ran, 'The action should have been run with an invalid case in the action and no strict checking enabled'); // Test if the action is run with an invalid case with strict checking enabled Config::getInstance()->set('system.performStrictControllerActionNameValidation', true); $controller->setAction(function (MockController $controller) { return 'test'; }); try { $controller->run('test'); $this->fail('There should be a ControllerException thrown when running an action with an invalid case' . ' and strict checking is enabled'); } catch (ControllerException $e) { $this->assertEquals(ControllerException::ERR_ACTION_NOT_FOUND, $e->getCode(), 'The exception should have a code for action not found'); $this->assertContains('Invalid case', $e->getMessage(), 'The error message should contain invalid case'); } $this->assertFalse($controller->ran, 'The action should not have been run with an invalid case in the action and strict checking enabled'); // Test that strict checking doesn't affect running a correctly named action $controller->setAction(function (MockController $controller) { return 'test'; }); $controller->run('Test'); $this->assertTrue($controller->ran, 'The action should have been run with a valid case in the action and strict checking enabled'); }
/** * Runs after each test * * @return void */ protected function tearDown() { parent::tearDown(); Application::getInstance()->setDiContainer($this->originalDiContainer); Config::getInstance()->clear(); }
<?php /** * Configurations of the application. */ use YapepBase\Config; Config::getInstance()->set(array('application.name' => 'Www'));
/** * Returns the debug data URL for the specified error ID or an empty string, if the debug data url is not * configured properly. * * @param string $errorId The error ID. * * @return string */ protected function getDebugDataUrl($errorId) { $config = Config::getInstance(); $urlTemplate = $config->get('system.debugger.errorDebugUrlTemplate', ''); $paramName = $config->get('system.debugger.errorDebugUrlParamName', ''); if (empty($urlTemplate) || empty($paramName)) { return ''; } return str_replace($paramName, $errorId, $urlTemplate); }