Skip to content

Commit

Permalink
refactor ini settings
Browse files Browse the repository at this point in the history
allow auto-import of db
  • Loading branch information
vijinho committed Aug 20, 2016
1 parent 9558b45 commit 96b404f
Show file tree
Hide file tree
Showing 11 changed files with 211 additions and 6 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Expand Up @@ -3,6 +3,8 @@
# Version 2.5.0

- Refactored .ini settings and defaults into different hive sections
- Option to auto-insert database dump added
- Initial test script added to setup f3 tests and environment

# Version 2.4.1

Expand Down
4 changes: 4 additions & 0 deletions README.md
Expand Up @@ -46,6 +46,9 @@ I wrote this project for myself, but if you are thinking to use it, thinking on
- Edit `app/config/config.ini `and add anything extra from `default.ini` for overrides
- In the top level folder `run composer install`

### Database
- Create a database dumpfile to auto-import in `data/db/sql/create.sql` (set ini option for db.create=true)

### Folders & Permissions
Setup empty website folders as follows:

Expand Down Expand Up @@ -83,6 +86,7 @@ They can then be included in your own project by adding the same lines in your `
* `app/en/templates/error/debug.phtml` - debug error page (if DEBUG=3)
* `app/en/templates/error/404.phtml` - 'friendly' file not found page
* `app/en/templates/error/error.phtml` - 'friendly' error page
* `tests` - unit tests see [docs/TESTING.md](docs/TESTING.md])

## Supplemental Files/Paths

Expand Down
2 changes: 2 additions & 0 deletions app/config/config.example.ini
Expand Up @@ -7,7 +7,9 @@ TZ=Europe/London
env=dev

[db]
create=false
dsn_http=mysql://root:root@127.0.0.1:3306/development_db
dsn_test=mysql://root:root@127.0.0.1:3306/development_db

[security]
salt=MY_SALT
Expand Down
2 changes: 2 additions & 0 deletions app/config/default.ini
Expand Up @@ -61,6 +61,8 @@ date=Y-m-d H:i:s
; database settings
; @see http://fatfreeframework.com/databases
[db]
; auto-create db - create a db dump in data/db/sql/create.sql and it will auto-insert on first request
create=true
; a DSN like this
;dsn_http=mysql://user:pass@host:port/table
;dsn_http=mysql://root:root@127.0.0.1:3306/development_db
Expand Down
9 changes: 6 additions & 3 deletions app/lib/App/CLI.php
Expand Up @@ -30,6 +30,10 @@ function boot()
// load dependency injection container
$dice = new \Dice\Dice;

// logging for application
$logfile = $f3->get('log.file');
$dice->addRule('Log', ['shared' => true, 'constructParams' => [$logfile]]);

// database connection used by app
$dbConfig = $f3->get('db');
$dice->addRule('DB\\SQL', ['shared' => true, 'constructParams' => [
Expand All @@ -39,9 +43,8 @@ function boot()
[\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION]
]]);

// logging for application
$logfile = $f3->get('log.file');
$dice->addRule('Log', ['shared' => true, 'constructParams' => [$logfile]]);
// auto-create database if options set
\App\Setup::database($dice);

// run the main application
require_once 'lib/App/App.php';
Expand Down
37 changes: 37 additions & 0 deletions app/lib/App/Setup.php
@@ -0,0 +1,37 @@
<?php

namespace App;

/**
* Setup Class.
*
* @author Vijay Mahrra <vijay@yoyo.org>
* @copyright (c) Copyright 2016 Vijay Mahrra
* @license GPLv3 (http://www.gnu.org/licenses/gpl-3.0.html)
*/
class Setup
{

/**
* setup database
*
* @param \Dice\Dice dependency injector
* @return void
*/
public static function database(&$dice)
{
$f3 = \Base::instance();
$cache = \Cache::instance();
// cli mode will not use cache on cli and will check db every time if in dev mode
if ($f3->get('db.create') && (!$cache->exists('tables', $tables) || PHP_SAPI == 'cli' || 'dev' == $f3->get('app.env'))) {
$db = $dice->create('DB\\SQL');
$tables = $db->exec('SHOW TABLES');
if (empty($tables)) {
$sql = $f3->get('HOMEDIR') . '/data/db/sql/create.sql';
$db->exec(file_get_contents($sql));
$tables = $db->exec('SHOW TABLES');
}
$cache->set('tables', $tables, 600);
}
}
}
Empty file added data/db/sql/create.sql
Empty file.
20 changes: 20 additions & 0 deletions docs/TESTING.md
@@ -0,0 +1,20 @@
# Test Environment

## F3 Unit Tests

Require the file `tests/setup.php` which contains the function `setup()` which will do the following:

- Setup the base application environment
- Read the `dsn_test` database DSN value from the config.ini
- Delete all existing tables in the test database
- Execute Setup::database from `app/lib/App/Setup.php` which will import the sql dump from `data/db/sql/create.sql` and create a new root user and api app for that user.
- It then returns an instance of $f3 which can be used by the test suite

This environment can then be used for safe testing which doesn't interfere with the running website.

### Run the test database setup and checks

```
cd tests
php setuptest.php
```
90 changes: 90 additions & 0 deletions tests/setup.php
@@ -0,0 +1,90 @@
<?php
namespace App;

/**
* Load, configure, test environment, return database handle to it
*
* @return \Base $f3 instance
*/
function &setup()
{
if (session_status() == PHP_SESSION_NONE) {
ini_set('session.auto_start', 'Off');
} else {
ini_set('session.lazy_write', 'On');
}

chdir(__DIR__ . '/../app');
require_once '../lib/autoload.php'; // composer autoloader

// bootstrap initial environment
$f3 = \Base::instance();

\FFMVC\App::start();

// override db params for test
// setup database connection params
// @see http://fatfreeframework.com/databases
$httpDSN = $f3->get('db.dsn_test');
if (!empty($httpDSN)) {
$dbParams = $f3->get('db');
$params = \FFMVC\Helpers\DB::instance()->parseHttpDsn($httpDSN);
$params['dsn'] = \FFMVC\Helpers\DB::instance()->createDbDsn($params);
$dbParams = array_merge($dbParams, $params);
$f3->set('db', $dbParams);
}

// load dependency injection container
$dice = new \Dice\Dice;

// logging for application
$logfile = $f3->get('log.file');
$dice->addRule('Log', ['shared' => true, 'constructParams' => [$logfile]]);

// database connection used by app
$dbConfig = $f3->get('db');

$dice->addRule('DB\\SQL', ['shared' => true, 'constructParams' => [
\FFMVC\Helpers\DB::createDbDsn($dbConfig),
$dbConfig['user'],
$dbConfig['pass'],
[\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION]
]]);

// auto-create database if options set
try {
$db = $dice->create('DB\\SQL');
\Registry::set('db', $db);
} catch (\PDOException $e) {
switch ($e->getCode()) {
case 1049: // db doesn't exist
die($e->getMessage());
break;
default:
throw($e);
return;
}
}

// drop existing tables, re-create db
try {
$results = $db->exec('SHOW TABLES');
$queries = [];
if (!empty($results)) {
$queries[] = 'SET FOREIGN_KEY_CHECKS = 0';
foreach ($results as $result) {
foreach ($result as $table) {
$queries[] = sprintf('DROP TABLE IF EXISTS %s', $db->quotekey($table));
}
}
$queries[] = 'SET FOREIGN_KEY_CHECKS = 1';
$db->exec($queries);
}
\App\Setup::database($dice);
\Registry::set('db', $db);
} catch (\PDOException $e) {
throw($e);
}

return $f3;
}
42 changes: 42 additions & 0 deletions tests/setuptest.php
@@ -0,0 +1,42 @@
<?php
declare (strict_types=1);

namespace App;

if (PHP_SAPI !== 'cli') {
die("This can only be executed in CLI mode.");
}

require_once 'setup.php';

// initialise test database
try {
$f3 = setup();
$db = \Registry::get('db');
} catch (\Exception $e) {
// fatal, can't continue
throw($e);
}

$test = new \Test;

// insert tests here from f3
// https://fatfreeframework.com/test
// https://fatfreeframework.com/unit-testing

// This is where the tests begin
$test->expect(
count($db->exec('SHOW TABLES')),
'Tables exist?''
);

// Display the results; not MVC but let's keep it simple
foreach ($test->results() as $result) {
echo $result['text'].'<br>';
if ($result['status']) {
echo 'Pass';
} else {
echo 'Fail ('.$result['source'].')';
}
echo '<br>';
}
9 changes: 6 additions & 3 deletions www/index.php
Expand Up @@ -28,6 +28,10 @@ function boot()
// load dependency injection container
$dice = new \Dice\Dice;

// logging for application
$logfile = $f3->get('log.file');
$dice->addRule('Log', ['shared' => true, 'constructParams' => [$logfile]]);

// database connection used by app
$dbConfig = $f3->get('db');
$dice->addRule('DB\\SQL', ['shared' => true, 'constructParams' => [
Expand All @@ -37,9 +41,8 @@ function boot()
[\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION]
]]);

// logging for application
$logfile = $f3->get('log.file');
$dice->addRule('Log', ['shared' => true, 'constructParams' => [$logfile]]);
// auto-create database if options set
\App\Setup::database($dice);

// run the main application
require_once 'lib/App/App.php';
Expand Down

0 comments on commit 96b404f

Please sign in to comment.