Updated entire project to PSR2 code standard. Some classes still need to be moved around.

This commit is contained in:
Abel Hoogeveen 2016-05-07 19:22:09 +02:00
parent edf1ce2fa3
commit 9f4742b063
73 changed files with 4633 additions and 4138 deletions

2
.gitignore vendored
View File

@ -21,3 +21,5 @@ build/
Modules/admin/themes/adminlte2.1/plugins/ Modules/admin/themes/adminlte2.1/plugins/
Modules/admin/themes/adminlte2.1/dist/ Modules/admin/themes/adminlte2.1/dist/
Modules/admin/themes/adminlte2.1/bootstrap/ Modules/admin/themes/adminlte2.1/bootstrap/
doc
nbproject

View File

@ -1,4 +1,6 @@
<?php return array ( <?php
return array(
'contact_email' => '', 'contact_email' => '',
'contact_name' => '', 'contact_name' => '',
'contact_adress' => '', 'contact_adress' => '',
@ -6,5 +8,5 @@
'contact_postal_code' => '', 'contact_postal_code' => '',
'contact_region' => '', 'contact_region' => '',
'contact_country' => '', 'contact_country' => '',
'contact_city' => '' 'contact_city' => '',
) ; );

View File

@ -1,4 +1,6 @@
<?php return array ( <?php
return array(
'enable_composer' => true, 'enable_composer' => true,
'composer_autoloader' => '' 'composer_autoloader' => '',
) ; );

View File

@ -1,4 +1,6 @@
<?php return array ( <?php
return array(
'type' => '', 'type' => '',
'host' => '', 'host' => '',
'database' => '', 'database' => '',
@ -6,4 +8,4 @@
'password' => '', 'password' => '',
'prefix' => '', 'prefix' => '',
'debug' => false, 'debug' => false,
) ; );

View File

@ -1,4 +1,6 @@
<?php return array ( <?php
return array(
'debug' => false, 'debug' => false,
'error_reporting' => true, 'error_reporting' => true,
) ; );

View File

@ -1,4 +1,6 @@
<?php return array ( <?php
return array(
'SITE_URL' => '', 'SITE_URL' => '',
'SITE_DOMAIN' => '', 'SITE_DOMAIN' => '',
'SERVER_NAME' => '', 'SERVER_NAME' => '',
@ -6,4 +8,4 @@
'administrator_mail' => '', 'administrator_mail' => '',
'default_controller' => 'standard', 'default_controller' => 'standard',
'default_function' => 'index', 'default_function' => 'index',
) ; );

View File

@ -1,8 +1,9 @@
<?php <?php
return array( return array(
// '/^alias(|\-(?P<function>.*?))$/' => array( // '/^alias(|\-(?P<function>.*?))$/' => array(
// 'controller' => 'home' // 'controller' => 'home'
// ), // ),
'/^(?P<controller>.*?)(|\/(?P<function>.*?)(|\/(?P<parameters>.*?)))$/', '/^(?P<controller>.*?)(|\/(?P<function>.*?)(|\/(?P<parameters>.*?)))$/',
); );

View File

@ -1,6 +1,6 @@
<?php <?php
/** /**
* FuzeWorks * FuzeWorks.
* *
* The FuzeWorks MVC PHP FrameWork * The FuzeWorks MVC PHP FrameWork
* *
@ -19,18 +19,21 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
* *
* @author TechFuze * @author TechFuze
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
* @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/) * @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/)
* @license http://opensource.org/licenses/GPL-3.0 GPLv3 License * @license http://opensource.org/licenses/GPL-3.0 GPLv3 License
* @link http://fuzeworks.techfuze.net *
* @since Version 0.0.1 * @link http://fuzeworks.techfuze.net
* @version Version 0.0.1 * @since Version 0.0.1
*
* @version Version 0.0.1
*/ */
namespace Application\Controller; namespace Application\Controller;
use \FuzeWorks\ControllerAbstract;
use \FuzeWorks\Layout; use FuzeWorks\ControllerAbstract;
use FuzeWorks\Layout;
/** /**
* The default controller of FuzeWorks. * The default controller of FuzeWorks.
@ -38,23 +41,20 @@ use \FuzeWorks\Layout;
* This controller gets loaded when the '/' path is provided, eg. the home page. * This controller gets loaded when the '/' path is provided, eg. the home page.
* By default, the index function gets loaded. * By default, the index function gets loaded.
* *
* @package net.techfuze.fuzeworks.core * @author Abel Hoogeveen <abel@techfuze.net>
* @author Abel Hoogeveen <abel@techfuze.net> * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net)
*/ */
class Standard extends ControllerAbstract { class Standard extends ControllerAbstract
{
/** /**
* The default function of FuzeWorks. * The default function of FuzeWorks.
* *
* This code gets loaded for the Home page * This code gets loaded for the Home page
* @param array $path The path provided by the HTTP Server *
* @return void * @param array $path The path provided by the HTTP Server
*/ */
public function index($path = null) { public function index($path = null)
Layout::view('home'); {
} Layout::view('home');
}
} }
?>

View File

@ -1,6 +1,6 @@
<?php <?php
/** /**
* FuzeWorks * FuzeWorks.
* *
* The FuzeWorks MVC PHP FrameWork * The FuzeWorks MVC PHP FrameWork
* *
@ -19,34 +19,36 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
* *
* @author TechFuze * @author TechFuze
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
* @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/) * @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/)
* @license http://opensource.org/licenses/GPL-3.0 GPLv3 License * @license http://opensource.org/licenses/GPL-3.0 GPLv3 License
* @link http://fuzeworks.techfuze.net *
* @since Version 0.0.1 * @link http://fuzeworks.techfuze.net
* @version Version 0.0.1 * @since Version 0.0.1
*
* @version Version 0.0.1
*/ */
namespace Application\Model; namespace Application\Model;
use \FuzeWorks\Model;
use FuzeWorks\Model;
/** /**
* Example model to show how to use models * Example model to show how to use models.
* *
* This model connects to an example table if present in the database * This model connects to an example table if present in the database
* @package net.techfuze.fuzeworks.application.model *
* @author Abel Hoogeveen <abel@techfuze.net> * @author Abel Hoogeveen <abel@techfuze.net>
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
*/ */
class Example extends Model{ class Example extends Model
{
public function __construct(&$core){ public function __construct(&$core)
{
parent::__construct($core); parent::__construct($core);
$this->setType('core/databaseutils', 'Model'); $this->setType('core/databaseutils', 'Model');
$this->table = 'example'; $this->table = 'example';
} }
} }
?>

View File

@ -1,6 +1,6 @@
<?php <?php
/** /**
* FuzeWorks * FuzeWorks.
* *
* The FuzeWorks MVC PHP FrameWork * The FuzeWorks MVC PHP FrameWork
* *
@ -19,34 +19,37 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
* *
* @author TechFuze * @author TechFuze
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
* @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/) * @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/)
* @license http://opensource.org/licenses/GPL-3.0 GPLv3 License * @license http://opensource.org/licenses/GPL-3.0 GPLv3 License
* @link http://fuzeworks.techfuze.net *
* @since Version 0.0.1 * @link http://fuzeworks.techfuze.net
* @version Version 0.0.1 * @since Version 0.0.1
*
* @version Version 0.0.1
*/ */
namespace Application\Model; namespace Application\Model;
use \FuzeWorks\Model;
use FuzeWorks\Model;
/** /**
* SQLTable model * SQLTable model.
* *
* This model connects to the querybuilder and is used to quickly interact with SQL tables. * This model connects to the querybuilder and is used to quickly interact with SQL tables.
* *
* Start building a query AND DON'T FORGET TO USE setTable() before executing the query * Start building a query AND DON'T FORGET TO USE setTable() before executing the query
* @package net.techfuze.fuzeworks.application.model *
* @author Abel Hoogeveen <abel@techfuze.net> * @author Abel Hoogeveen <abel@techfuze.net>
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
*/ */
class Sqltable extends Model{ class Sqltable extends Model
{
public function __construct(){ public function __construct()
{
$this->setType('core/databaseutils', 'Model'); $this->setType('core/databaseutils', 'Model');
$this->fields = '*'; $this->fields = '*';
$this->table = 'table'; $this->table = 'table';
} }
} }

View File

@ -1,6 +1,6 @@
<?php <?php
/** /**
* FuzeWorks * FuzeWorks.
* *
* The FuzeWorks MVC PHP FrameWork * The FuzeWorks MVC PHP FrameWork
* *
@ -19,75 +19,77 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
* *
* @author TechFuze * @author TechFuze
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
* @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/) * @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/)
* @license http://opensource.org/licenses/GPL-3.0 GPLv3 License * @license http://opensource.org/licenses/GPL-3.0 GPLv3 License
* @link http://fuzeworks.techfuze.net *
* @since Version 0.0.1 * @link http://fuzeworks.techfuze.net
* @version Version 0.0.1 * @since Version 0.0.1
*
* @version Version 0.0.1
*/ */
?> ?>
<html> <html>
<head> <head>
<title>Page not found</title> <title>Page not found</title>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet"> <link href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet">
<style> <style>
body { body {
background: #ecf0f1; background: #ecf0f1;
border-bottom: 1px solid #DDD; border-bottom: 1px solid #DDD;
padding: 100px 0 100px; padding: 100px 0 100px;
font-size: 16px; font-size: 16px;
} }
#setupcontainer { #setupcontainer {
max-width: 950px; max-width: 950px;
margin-left: auto; margin-left: auto;
margin-right: auto; margin-right: auto;
} }
.col-centered{ .col-centered{
float: none; float: none;
margin: 0 auto; margin: 0 auto;
} }
</style> </style>
</head> </head>
<body> <body>
<div id='setupcontainer'> <div id='setupcontainer'>
<div class='row'> <div class='row'>
<div class='col-lg-12 col-md-4 col-sm-12'> <div class='col-lg-12 col-md-4 col-sm-12'>
<div id='contentPanel' class="panel panel-default" style='display:none'> <div id='contentPanel' class="panel panel-default" style='display:none'>
<div id='1' class="panel-body" style='display:none'> <div id='1' class="panel-body" style='display:none'>
<p class="lead">Page not found</p> <p class="lead">Page not found</p>
<p> <p>
The requested page could not be found. The requested page could not be found.
</p> </p>
<p> <p>
Our apologies for the inconvenience. Our apologies for the inconvenience.
</p> </p>
</div> </div>
</div> </div>
</div> </div>
</div> </div>
</div> </div>
<footer> <footer>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script> <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script> <script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<script> <script>
var currentPage = 0; var currentPage = 0;
var currentProgress = 0; var currentProgress = 0;
start(); start();
function start() { function start() {
$("#contentPanel").fadeIn(500); $("#contentPanel").fadeIn(500);
$("#1").fadeIn(500); $("#1").fadeIn(500);
} }
</script> </script>
</footer> </footer>
</body> </body>
</html> </html>

View File

@ -1,6 +1,6 @@
<?php <?php
/** /**
* FuzeWorks * FuzeWorks.
* *
* The FuzeWorks MVC PHP FrameWork * The FuzeWorks MVC PHP FrameWork
* *
@ -20,79 +20,87 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
* *
* @author TechFuze * @author TechFuze
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
* @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/) * @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/)
* @license http://opensource.org/licenses/GPL-3.0 GPLv3 License * @license http://opensource.org/licenses/GPL-3.0 GPLv3 License
*
* @link http://fuzeworks.techfuze.net * @link http://fuzeworks.techfuze.net
* @since Version 0.0.1 * @since Version 0.0.1
*
* @version Version 0.0.1 * @version Version 0.0.1
*/ */
?> ?>
<html> <html>
<head> <head>
<title>FuzeWorks - Home</title> <title>FuzeWorks - Home</title>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet"> <link href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet">
<style> <style>
body { body {
background: #ecf0f1; background: #ecf0f1;
border-bottom: 1px solid #DDD; border-bottom: 1px solid #DDD;
padding: 100px 0 100px; padding: 100px 0 100px;
font-size: 16px; font-size: 16px;
} }
#setupcontainer { #setupcontainer {
max-width: 950px; max-width: 950px;
margin-left: auto; margin-left: auto;
margin-right: auto; margin-right: auto;
} }
.col-centered{ .col-centered{
float: none; float: none;
margin: 0 auto; margin: 0 auto;
} }
</style> </style>
</head> </head>
<body> <body>
<div id='setupcontainer'> <div id='setupcontainer'>
<div class='row'> <div class='row'>
<div class='col-lg-12 col-md-4 col-sm-12'> <div class='col-lg-12 col-md-4 col-sm-12'>
<div id='contentPanel' class="panel panel-default" style='display:none'> <div id='contentPanel' class="panel panel-default" style='display:none'>
<div id='1' class="panel-body" style='display:none'> <div id='1' class="panel-body" style='display:none'>
<p class="lead">Welcome to FuzeWorks</p> <p class="lead">Welcome to FuzeWorks</p>
<p> <p>
This website is currently under development. This website is currently under development.
</p> </p>
<p> <p>
<?php if ($vars['adminMail'] == '') { ?> <?php if ($vars['adminMail'] == '') {
For further information, please contact the website administrator</a> ?>
<?php } else { ?> For further information, please contact the website administrator</a>
For further information, please contact <a href='mailto:<?php echo($vars['adminMail']); ?>'><?php echo($vars['adminMail']); ?></a> <?php
<?php } ?> } else {
?>
For further information, please contact <a href='mailto:<?php echo $vars['adminMail'];
?>'><?php echo $vars['adminMail'];
?></a>
<?php
} ?>
</p> </p>
</div> </div>
</div> </div>
</div> </div>
</div> </div>
</div> </div>
<footer> <footer>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script> <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script> <script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<script> <script>
var currentPage = 0; var currentPage = 0;
var currentProgress = 0; var currentProgress = 0;
start(); start();
function start() { function start() {
$("#contentPanel").fadeIn(500); $("#contentPanel").fadeIn(500);
$("#1").fadeIn(500); $("#1").fadeIn(500);
} }
</script> </script>
</footer> </footer>
</body> </body>
</html> </html>

View File

@ -1,6 +1,6 @@
<?php <?php
/** /**
* FuzeWorks * FuzeWorks.
* *
* The FuzeWorks MVC PHP FrameWork * The FuzeWorks MVC PHP FrameWork
* *
@ -19,38 +19,40 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
* *
* @author TechFuze * @author TechFuze
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
* @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/) * @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/)
* @license http://opensource.org/licenses/GPL-3.0 GPLv3 License * @license http://opensource.org/licenses/GPL-3.0 GPLv3 License
* @link http://fuzeworks.techfuze.net *
* @since Version 0.0.1 * @link http://fuzeworks.techfuze.net
* @version Version 0.0.1 * @since Version 0.0.1
*
* @version Version 0.0.1
*/ */
namespace Application; namespace Application;
use \FuzeWorks\Bus;
use FuzeWorks\Bus;
/** /**
* Class init * Class init.
* *
* This class will be loaded before the a controller is loaded. Handy to do some we-need-to-do-this-all-the-time-things like setting locales or importing functions. * This class will be loaded before the a controller is loaded. Handy to do some we-need-to-do-this-all-the-time-things like setting locales or importing functions.
* Can also be used to authenticate users and provide all views with sessionData. * Can also be used to authenticate users and provide all views with sessionData.
* Will only be loaded if the default callable is used. * Will only be loaded if the default callable is used.
* @package net.techfuze.fuzeworks.application *
* @author Abel Hoogeveen <abel@techfuze.net> * @author Abel Hoogeveen <abel@techfuze.net>
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
*/ */
class Init extends Bus { class Init extends Bus
{
/** /**
* Constructor * Constructor.
* *
* @param \FuzeWorks\Core $core Pointer to core class * @param \FuzeWorks\Core $core Pointer to core class
*/ */
public function __construct(&$core){ public function __construct(&$core)
{
parent::__construct($core); parent::__construct($core);
} }
} }
?>

View File

@ -1,6 +1,6 @@
<?php <?php
/** /**
* FuzeWorks * FuzeWorks.
* *
* The FuzeWorks MVC PHP FrameWork * The FuzeWorks MVC PHP FrameWork
* *
@ -19,59 +19,64 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
* *
* @author TechFuze * @author TechFuze
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
* @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/) * @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/)
* @license http://opensource.org/licenses/GPL-3.0 GPLv3 License * @license http://opensource.org/licenses/GPL-3.0 GPLv3 License
* @link http://fuzeworks.techfuze.net *
* @since Version 0.0.1 * @link http://fuzeworks.techfuze.net
* @version Version 0.0.1 * @since Version 0.0.1
*
* @version Version 0.0.1
*/ */
namespace FuzeWorks\Event; namespace FuzeWorks\Event;
use \FuzeWorks\Event;
use FuzeWorks\Event;
/** /**
* Event that gets loaded when a view is loaded. * Event that gets loaded when a view is loaded.
* *
* Use this to cancel the loading of a view, or change the file or engine of a view * Use this to cancel the loading of a view, or change the file or engine of a view
* *
* @package net.techfuze.fuzeworks.core.event * @author Abel Hoogeveen <abel@techfuze.net>
* @author Abel Hoogeveen <abel@techfuze.net> * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net)
*/ */
class LayoutLoadViewEvent extends Event { class LayoutLoadViewEvent extends Event
{
/** /**
* The directory of the view to be loaded * The directory of the view to be loaded.
* @var string *
*/ * @var string
*/
public $directory; public $directory;
/** /**
* The file of the view to be loaded * The file of the view to be loaded.
*
* @var string * @var string
*/ */
public $file; public $file;
/** /**
* The engine the file will be loaded with * The engine the file will be loaded with.
*
* @var object * @var object
*/ */
public $engine; public $engine;
/** /**
* The assigned variables to the template * The assigned variables to the template.
*
* @var array * @var array
*/ */
public $assigned_variables; public $assigned_variables;
public function init($file, $directory, $engine, $assigned_variables){ public function init($file, $directory, $engine, $assigned_variables)
{
$this->file = $file; $this->file = $file;
$this->directory = $directory; $this->directory = $directory;
$this->engine = $engine; $this->engine = $engine;
$this->assigned_variables = $assigned_variables; $this->assigned_variables = $assigned_variables;
} }
} }
?>

View File

@ -1,6 +1,6 @@
<?php <?php
/** /**
* FuzeWorks * FuzeWorks.
* *
* The FuzeWorks MVC PHP FrameWork * The FuzeWorks MVC PHP FrameWork
* *
@ -19,45 +19,48 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
* *
* @author TechFuze * @author TechFuze
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
* @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/) * @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/)
* @license http://opensource.org/licenses/GPL-3.0 GPLv3 License * @license http://opensource.org/licenses/GPL-3.0 GPLv3 License
* @link http://fuzeworks.techfuze.net *
* @since Version 0.0.1 * @link http://fuzeworks.techfuze.net
* @version Version 0.0.1 * @since Version 0.0.1
*
* @version Version 0.0.1
*/ */
namespace FuzeWorks\Event; namespace FuzeWorks\Event;
use \FuzeWorks\Event;
use FuzeWorks\Event;
/** /**
* Event that gets loaded when a model is loaded. * Event that gets loaded when a model is loaded.
* *
* Use this to cancel the loading of a model, or change the model to be loaded * Use this to cancel the loading of a model, or change the model to be loaded
* *
* @package net.techfuze.fuzeworks.core.event * @author Abel Hoogeveen <abel@techfuze.net>
* @author Abel Hoogeveen <abel@techfuze.net> * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net)
*/ */
class ModelLoadEvent extends Event { class ModelLoadEvent extends Event
{
/** /**
* The directory the model gets loaded from * The directory the model gets loaded from.
* @var string|null *
*/ * @var string|null
*/
public $directory = null; public $directory = null;
/** /**
* The name of the model to be loaded * The name of the model to be loaded.
*
* @var string|null * @var string|null
*/ */
public $model = null; public $model = null;
public function init($model, $directory){ public function init($model, $directory)
{
$this->model = $model; $this->model = $model;
$this->directory = $directory; $this->directory = $directory;
} }
} }
?>

View File

@ -1,6 +1,6 @@
<?php <?php
/** /**
* FuzeWorks * FuzeWorks.
* *
* The FuzeWorks MVC PHP FrameWork * The FuzeWorks MVC PHP FrameWork
* *
@ -19,29 +19,31 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
* *
* @author TechFuze * @author TechFuze
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
* @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/) * @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/)
* @license http://opensource.org/licenses/GPL-3.0 GPLv3 License * @license http://opensource.org/licenses/GPL-3.0 GPLv3 License
* @link http://fuzeworks.techfuze.net *
* @since Version 0.0.1 * @link http://fuzeworks.techfuze.net
* @version Version 0.0.1 * @since Version 0.0.1
*
* @version Version 0.0.1
*/ */
namespace FuzeWorks\Event; namespace FuzeWorks\Event;
use \FuzeWorks\Event;
use FuzeWorks\Event;
/** /**
* Class routerLoadCallableEvent * Class routerLoadCallableEvent.
* *
* Called when a callable is about to be loaded * Called when a callable is about to be loaded
* *
* @package net.techfuze.fuzeworks.core.event * @author Abel Hoogeveen <abel@techfuze.net>
* @author Abel Hoogeveen <abel@techfuze.net> * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net)
*/ */
class routerLoadCallableEvent extends Event{ class routerLoadCallableEvent extends Event
{
/** /**
* @var callable The callable * @var callable The callable
*/ */
@ -53,15 +55,16 @@ class routerLoadCallableEvent extends Event{
public $matches = array(); public $matches = array();
/** /**
* The route which was matched * The route which was matched.
*
* @var null|string * @var null|string
*/ */
public $route = null; public $route = null;
public function init($callable, $matches, $route){ public function init($callable, $matches, $route)
{
$this->callable = $callable; $this->callable = $callable;
$this->matches = $matches; $this->matches = $matches;
$this->route = $route; $this->route = $route;
} }
} }

View File

@ -1,6 +1,6 @@
<?php <?php
/** /**
* FuzeWorks * FuzeWorks.
* *
* The FuzeWorks MVC PHP FrameWork * The FuzeWorks MVC PHP FrameWork
* *
@ -19,51 +19,54 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
* *
* @author TechFuze * @author TechFuze
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
* @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/) * @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/)
* @license http://opensource.org/licenses/GPL-3.0 GPLv3 License * @license http://opensource.org/licenses/GPL-3.0 GPLv3 License
* @link http://fuzeworks.techfuze.net *
* @since Version 0.0.1 * @link http://fuzeworks.techfuze.net
* @version Version 0.0.1 * @since Version 0.0.1
*
* @version Version 0.0.1
*/ */
namespace FuzeWorks\Event; namespace FuzeWorks\Event;
use \FuzeWorks\Event;
use FuzeWorks\Event;
/** /**
* Class routerRouteEvent * Class routerRouteEvent.
* *
* Fired after the router has extracted the path, and is about to find out what route matches the path. * Fired after the router has extracted the path, and is about to find out what route matches the path.
* *
* This Event is usefull for adding routes. * This Event is usefull for adding routes.
* *
* @package net.techfuze.fuzeworks.core.event * @author Abel Hoogeveen <abel@techfuze.net>
* @author Abel Hoogeveen <abel@techfuze.net> * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net)
*/ */
class routerRouteEvent extends Event{ class routerRouteEvent extends Event
{
/** /**
* @var array The routing table * @var array The routing table
*/ */
public $routes; public $routes;
/** /**
* @var boolean Whether the callable will be loaded directly after or not * @var bool Whether the callable will be loaded directly after or not
*/ */
public $loadCallable; public $loadCallable;
/** /**
* The current path input to FuzeWorks * The current path input to FuzeWorks.
*
* @var null|string * @var null|string
*/ */
public $path; public $path;
public function init($routes, $loadCallable, $path){ public function init($routes, $loadCallable, $path)
{
$this->routes = $routes; $this->routes = $routes;
$this->loadCallable = $loadCallable; $this->loadCallable = $loadCallable;
$this->path = $path; $this->path = $path;
} }
} }

View File

@ -1,6 +1,6 @@
<?php <?php
/** /**
* FuzeWorks * FuzeWorks.
* *
* The FuzeWorks MVC PHP FrameWork * The FuzeWorks MVC PHP FrameWork
* *
@ -19,39 +19,40 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
* *
* @author TechFuze * @author TechFuze
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
* @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/) * @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/)
* @license http://opensource.org/licenses/GPL-3.0 GPLv3 License * @license http://opensource.org/licenses/GPL-3.0 GPLv3 License
* @link http://fuzeworks.techfuze.net *
* @since Version 0.0.1 * @link http://fuzeworks.techfuze.net
* @version Version 0.0.1 * @since Version 0.0.1
*
* @version Version 0.0.1
*/ */
namespace FuzeWorks\Event; namespace FuzeWorks\Event;
use \FuzeWorks\Event;
use FuzeWorks\Event;
/** /**
* Class routerSetPathEvent * Class routerSetPathEvent.
* *
* Fired when the router's path is changing * Fired when the router's path is changing
* *
* @package net.techfuze.fuzeworks.core.event * @author Abel Hoogeveen <abel@techfuze.net>
* @author Abel Hoogeveen <abel@techfuze.net> * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net)
*/ */
class routerSetPathEvent extends Event{ class routerSetPathEvent extends Event
{
/** /**
* The path to be set to the router * The path to be set to the router.
* @var string The new path *
*/ * @var string The new path
public $path; */
public $path;
public function init($path){
public function init($path)
{
$this->path = $path; $this->path = $path;
} }
} }
?>

View File

@ -1,6 +1,6 @@
<?php <?php
/** /**
* FuzeWorks * FuzeWorks.
* *
* The FuzeWorks MVC PHP FrameWork * The FuzeWorks MVC PHP FrameWork
* *
@ -19,23 +19,27 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
* *
* @author TechFuze * @author TechFuze
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
* @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/) * @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/)
* @license http://opensource.org/licenses/GPL-3.0 GPLv3 License * @license http://opensource.org/licenses/GPL-3.0 GPLv3 License
* @link http://fuzeworks.techfuze.net *
* @since Version 0.0.1 * @link http://fuzeworks.techfuze.net
* @version Version 0.0.1 * @since Version 0.0.1
*
* @version Version 0.0.1
*/ */
namespace FuzeWorks; namespace FuzeWorks;
/** /**
* Abstract class ControllerAbstract * Abstract class ControllerAbstract.
* *
* At this point does nothing, can be extended in the future to allow special controller functions * At this point does nothing, can be extended in the future to allow special controller functions
* @package net.techfuze.fuzeworks.core *
* @author Abel Hoogeveen <abel@techfuze.net> * @author Abel Hoogeveen <abel@techfuze.net>
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
*/ */
abstract class ControllerAbstract {} abstract class ControllerAbstract
{
}

View File

@ -1,6 +1,6 @@
<?php <?php
/** /**
* FuzeWorks * FuzeWorks.
* *
* The FuzeWorks MVC PHP FrameWork * The FuzeWorks MVC PHP FrameWork
* *
@ -19,43 +19,47 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
* *
* @author TechFuze * @author TechFuze
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
* @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/) * @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/)
* @license http://opensource.org/licenses/GPL-3.0 GPLv3 License * @license http://opensource.org/licenses/GPL-3.0 GPLv3 License
* @link http://fuzeworks.techfuze.net *
* @since Version 0.0.1 * @link http://fuzeworks.techfuze.net
* @version Version 0.0.1 * @since Version 0.0.1
*
* @version Version 0.0.1
*/ */
namespace FuzeWorks; namespace FuzeWorks;
/** /**
* Class Event * Class Event.
* *
* A simple class for events. The only current purpose is to be able to cancel events, but it can be easily extended. * A simple class for events. The only current purpose is to be able to cancel events, but it can be easily extended.
* @package net.techfuze.fuzeworks.core *
* @author Abel Hoogeveen <abel@techfuze.net> * @author Abel Hoogeveen <abel@techfuze.net>
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
*/ */
class Event { class Event
{
private $cancelled = false; private $cancelled = false;
/** /**
* @return boolean True if the event is cancelled, false if the event is not cancelled * @return bool True if the event is cancelled, false if the event is not cancelled
*/ */
public function isCancelled() { public function isCancelled()
return $this->cancelled; {
} return $this->cancelled;
}
/** /**
* @param boolean $cancelled True if the event is cancelled, false if the event is not cancelled * @param bool $cancelled True if the event is cancelled, false if the event is not cancelled
*/ */
public function setCancelled($cancelled) { public function setCancelled($cancelled)
if ($cancelled == true){ {
if ($cancelled == true) {
$this->cancelled = true; $this->cancelled = true;
} else{ } else {
$this->cancelled = false; $this->cancelled = false;
} }
} }
@ -64,11 +68,11 @@ class Event {
namespace FuzeWorks\Event; namespace FuzeWorks\Event;
/** /**
* Simple event which will notify components of an event, but does not contain any data * Simple event which will notify components of an event, but does not contain any data.
* @package net.techfuze.fuzeworks.core *
* @author Abel Hoogeveen <abel@techfuze.net> * @author Abel Hoogeveen <abel@techfuze.net>
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
*/ */
class NotifierEvent extends \FuzeWorks\Event {} class NotifierEvent extends \FuzeWorks\Event
{
?> }

View File

@ -1,6 +1,6 @@
<?php <?php
/** /**
* FuzeWorks * FuzeWorks.
* *
* The FuzeWorks MVC PHP FrameWork * The FuzeWorks MVC PHP FrameWork
* *
@ -19,19 +19,21 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
* *
* @author TechFuze * @author TechFuze
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
* @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/) * @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/)
* @license http://opensource.org/licenses/GPL-3.0 GPLv3 License * @license http://opensource.org/licenses/GPL-3.0 GPLv3 License
* @link http://fuzeworks.techfuze.net *
* @since Version 0.0.1 * @link http://fuzeworks.techfuze.net
* @version Version 0.0.1 * @since Version 0.0.1
*
* @version Version 0.0.1
*/ */
namespace FuzeWorks; namespace FuzeWorks;
/** /**
* Class EventPriority * Class EventPriority.
* *
* The EventPriority is an "enum" which gives priorities an integer value, the higher the integer value, the lower the * The EventPriority is an "enum" which gives priorities an integer value, the higher the integer value, the lower the
* priority. The available priorities are, from highest to lowest: * priority. The available priorities are, from highest to lowest:
@ -42,42 +44,41 @@ namespace FuzeWorks;
* EventPriority::NORMAL * EventPriority::NORMAL
* EventPriority::LOW * EventPriority::LOW
* EventPriority::LOWEST * EventPriority::LOWEST
* @package net.techfuze.fuzeworks.core *
* @author Abel Hoogeveen <abel@techfuze.net> * @author Abel Hoogeveen <abel@techfuze.net>
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
*/ */
abstract class EventPriority abstract class EventPriority
{ {
const LOWEST = 5;
const LOWEST = 5; const LOW = 4;
const LOW = 4; const NORMAL = 3;
const NORMAL = 3; const HIGH = 2;
const HIGH = 2; const HIGHEST = 1;
const HIGHEST = 1; const MONITOR = 0;
const MONITOR = 0;
/** /**
* Returns the string of the priority based on the integer * Returns the string of the priority based on the integer.
*
* @param $intPriorty * @param $intPriorty
*
* @return bool|string A bool when the integer isn't a priority. If the integer is a priority, the name is returned * @return bool|string A bool when the integer isn't a priority. If the integer is a priority, the name is returned
*/ */
static function getPriority($intPriorty){ public static function getPriority($intPriorty)
{
switch($intPriorty){ switch ($intPriorty) {
case 5: case 5:
return "EventPriority::LOWEST"; return 'EventPriority::LOWEST';
case 4: case 4:
return "EventPriority::LOW"; return 'EventPriority::LOW';
case 3: case 3:
return "EventPriority::NORMAL"; return 'EventPriority::NORMAL';
case 2: case 2:
return "EventPriority::HIGH"; return 'EventPriority::HIGH';
case 1: case 1:
return "EventPriority::HIGHEST"; return 'EventPriority::HIGHEST';
case 0: case 0:
return "EventPriority::MONITOR"; return 'EventPriority::MONITOR';
default: default:
return false; return false;
} }
@ -85,21 +86,23 @@ abstract class EventPriority
/** /**
* Returns the highest priority * Returns the highest priority
* This function is needed for the firing of events in the right order, * This function is needed for the firing of events in the right order,.
*
* @return int * @return int
*/ */
static function getHighestPriority(){ public static function getHighestPriority()
{
return EventPriority::MONITOR; return self::MONITOR;
} }
/** /**
* Returns the lowest priority * Returns the lowest priority
* This function is needed for the firing of events in the right order, * This function is needed for the firing of events in the right order,.
*
* @return int * @return int
*/ */
static function getLowestPriority(){ public static function getLowestPriority()
{
return EventPriority::LOWEST; return self::LOWEST;
} }
} }

View File

@ -1,6 +1,6 @@
<?php <?php
/** /**
* FuzeWorks * FuzeWorks.
* *
* The FuzeWorks MVC PHP FrameWork * The FuzeWorks MVC PHP FrameWork
* *
@ -19,85 +19,94 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
* *
* @author TechFuze * @author TechFuze
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
* @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/) * @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/)
* @license http://opensource.org/licenses/GPL-3.0 GPLv3 License * @license http://opensource.org/licenses/GPL-3.0 GPLv3 License
* @link http://fuzeworks.techfuze.net *
* @since Version 0.0.1 * @link http://fuzeworks.techfuze.net
* @version Version 0.0.1 * @since Version 0.0.1
*
* @version Version 0.0.1
*/ */
namespace FuzeWorks; namespace FuzeWorks;
/** /**
* Interface for a Module that gives abstract model types * Interface for a Module that gives abstract model types
* A model server must contain the methods from this interface in order to correctly serve models * A model server must contain the methods from this interface in order to correctly serve models.
* @package net.techfuze.fuzeworks.core *
* @author Abel Hoogeveen <abel@techfuze.net> * @author Abel Hoogeveen <abel@techfuze.net>
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
*/ */
interface ModelServer { interface ModelServer
public function giveModel($type); {
public function giveModel($type);
} }
/** /**
* Abstract class Model * Abstract class Model.
* *
* Abstract for a model data representation, loads the correct parent type * Abstract for a model data representation, loads the correct parent type
* @package net.techfuze.fuzeworks.core *
* @author Abel Hoogeveen <abel@techfuze.net> * @author Abel Hoogeveen <abel@techfuze.net>
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
*/ */
abstract class Model { abstract class Model
{
/**
* The parent class holder object
* Requests get redirected to this class.
*
* @var Parent Object
*/
private $parentClass;
/** /**
* The parent class holder object * Set the type of this model. Eg, use techfuze/databasemodel and Databasemodel to get a SQL connected model.
* Requests get redirected to this class *
* @access private * @param string Module_name, the name of the module where the model can be found
* @var Parent Object * @param string Model_type, model type to return
*/ */
private $parentClass; protected function setType($module_name, $model_type)
{
$mod = Modules::get($module_name);
$this->parentClass = $mod->giveModel($model_type);
}
/** /**
* Set the type of this model. Eg, use techfuze/databasemodel and Databasemodel to get a SQL connected model * Retrieves a value from the model class.
* @access protected *
* @param String Module_name, the name of the module where the model can be found * @param Any key
* @param String Model_type, model type to return *
*/ * @return Any value from the model class
protected function setType($module_name, $model_type) { */
$mod = Modules::get($module_name); public function __get($name)
$this->parentClass = $mod->giveModel($model_type); {
} return $this->parentClass->$name;
}
/** /**
* Retrieves a value from the model class * Sets a value in the model class.
* @access public *
* @param Any key * @param Any key
* @return Any value from the model class * @param Any value
*/ */
public function __get($name) { public function __set($name, $value)
return $this->parentClass->$name; {
} $this->parentClass->$name = $value;
}
/** /**
* Sets a value in the model class * Calls a function in the model class.
* @access public *
* @param Any key * @param string function_name
* @param Any value * @param array values
*/ *
public function __set($name, $value) { * @return Function return
$this->parentClass->$name = $value; */
} public function __call($name, $params)
{
/** return call_user_func_array(array($this->parentClass, $name), $params);
* Calls a function in the model class }
* @access public }
* @param String function_name
* @param Array values
* @return Function return
*/
public function __call($name, $params) {
return call_user_func_array(array($this->parentClass, $name), $params);
}
}

View File

@ -1,6 +1,6 @@
<?php <?php
/** /**
* FuzeWorks * FuzeWorks.
* *
* The FuzeWorks MVC PHP FrameWork * The FuzeWorks MVC PHP FrameWork
* *
@ -19,167 +19,185 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
* *
* @author TechFuze * @author TechFuze
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
* @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/) * @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/)
* @license http://opensource.org/licenses/GPL-3.0 GPLv3 License * @license http://opensource.org/licenses/GPL-3.0 GPLv3 License
* @link http://fuzeworks.techfuze.net *
* @since Version 0.0.1 * @link http://fuzeworks.techfuze.net
* @version Version 0.0.1 * @since Version 0.0.1
*
* @version Version 0.0.1
*/ */
namespace FuzeWorks; namespace FuzeWorks;
/** /**
* Trait Module * Trait Module.
* *
* Contains all the methods modules should have * Contains all the methods modules should have
* @package net.techfuze.fuzeworks.core *
* @author Abel Hoogeveen <abel@techfuze.net> * @author Abel Hoogeveen <abel@techfuze.net>
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
*/ */
trait Module { trait Module
{
/**
* @var null|string Relative path to the module
*/
protected static $modulePath = null;
/** /**
* @var null|string Relative path to the module * @var string Internal name of the module
*/ */
protected static $modulePath = null; protected static $moduleName = 'placeholder';
/** /**
* @var string Internal name of the module * @var string name used in the mod array
*/ */
protected static $moduleName = 'placeholder'; protected static $linkName = 'placeholder';
/** /**
* @var String name used in the mod array * @var moduleInfo object of the module
*/ */
protected static $linkName = 'placeholder'; protected static $cfg;
/** /**
* @var moduleInfo object of the module * @var array Advertisements send from other modules
*/ */
protected static $cfg; protected static $advertisements = array();
/**
* @var array Advertisements send from other modules
*/
protected static $advertisements = array();
/**
* Returns the name of the module
*
* @return string Returns the name of the module
*/
public static function getModuleName(){
/**
* Returns the name of the module.
*
* @return string Returns the name of the module
*/
public static function getModuleName()
{
return self::$moduleName; return self::$moduleName;
} }
/** /**
* Returns the path to the module * Returns the path to the module.
* @return null|string *
*/ * @return null|string
public static function getModulePath(){ */
public static function getModulePath()
{
return self::$modulePath; return self::$modulePath;
} }
/** /**
* Returns the config of the module (moduleInfo.php) * Returns the config of the module (moduleInfo.php).
* @access public *
* @return stdClass module config * @return stdClass module config
*/ */
public static function getModuleConfig() { public static function getModuleConfig()
return self::$cfg; {
return self::$cfg;
} }
/** /**
* Changes the path to the location of the module * Changes the path to the location of the module.
* *
* This function can only be executed once, because when the path has been set this function won't save changes anymore. * This function can only be executed once, because when the path has been set this function won't save changes anymore.
* This prevents modules or other systems to mess with modules and their stability. * This prevents modules or other systems to mess with modules and their stability.
* *
* @param string $modulePath * @param string $modulePath
*/ */
public static function setModulePath($modulePath = null){ public static function setModulePath($modulePath = null)
{
// Only allow one change of this variable from outside // Only allow one change of this variable from outside
if(self::$modulePath === null) if (self::$modulePath === null) {
self::$modulePath = $modulePath; self::$modulePath = $modulePath;
}
} }
/** /**
* Set the link name of the module. The link name is the address in the module array so that the module can self reference. * Set the link name of the module. The link name is the address in the module array so that the module can self reference.
* @access public *
* @param String link name * @param string link name
*/ */
public static function setModuleLinkName($linkName) { public static function setModuleLinkName($linkName)
self::$linkName = $linkName; {
self::$linkName = $linkName;
} }
/** /**
* The name that is required to load itself, eg 'exampleauthor/examplemodulename' or 'techfuze/cms' * The name that is required to load itself, eg 'exampleauthor/examplemodulename' or 'techfuze/cms'.
* @access public *
* @param String module name * @param string module name
*/ */
public static function setModuleName($modName) { public static function setModuleName($modName)
self::$moduleName = $modName; {
self::$moduleName = $modName;
} }
/** /**
* Add the moduleInfo.php to the module for direct interaction * Add the moduleInfo.php to the module for direct interaction.
* @access public *
* @param stdClass module config * @param stdClass module config
*/ */
public static function setModuleConfig($config) { public static function setModuleConfig($config)
self::$cfg = $config; {
self::$cfg = $config;
} }
/** /**
* Set a value in the modules moduleInfo.php * Set a value in the modules moduleInfo.php.
* @access protected *
* @param Mixed config Key * @param mixed config Key
* @param Mixed config value * @param mixed config value
*/ */
public static function setConfigValue($key, $value) { public static function setConfigValue($key, $value)
$file = self::getModulePath() . "moduleInfo.php"; {
self::$cfg->$key = $value; $file = self::getModulePath().'moduleInfo.php';
self::$cfg->$key = $value;
// Check if the module path is set yet // Check if the module path is set yet
if (self::getModulePath() == null) { if (self::getModulePath() == null) {
Logger::logWarning("Could not write module config. ModulePath is not set", get_class($this)); Logger::logWarning('Could not write module config. ModulePath is not set', get_class($this));
return false;
}
if (file_exists($file) && is_writable($file)) { return false;
$config = var_export($this->cfg, true); }
file_put_contents($file, "<?php return $config ;");
}
}
/** if (file_exists($file) && is_writable($file)) {
* Set the advertisements send by other modules $config = var_export($this->cfg, true);
* @param array $advertisements Advertisement data file_put_contents($file, "<?php return $config ;");
*/ }
public static function setAdvertisements($advertiseName, $advertiseData) { }
self::$advertisements[$advertiseName] = $advertiseData;
}
/** /**
* Get the advertisements with a specific name * Set the advertisements send by other modules.
* @param String $advertiseName AdvertisementName *
* @return array AdvertisementData * @param array $advertisements Advertisement data
*/ */
public static function getAdvertisements($advertiseName) { public static function setAdvertisements($advertiseName, $advertiseData)
return self::$advertisements[$advertiseName]; {
} self::$advertisements[$advertiseName] = $advertiseData;
}
/** /**
* Return a value from the module configuration * Get the advertisements with a specific name.
* @access public *
* @param Mixed config Key * @param string $advertiseName AdvertisementName
* @return Mixed config value *
*/ * @return array AdvertisementData
public static function getConfigValue($key) { */
return self::$cfg->$key; public static function getAdvertisements($advertiseName)
} {
} return self::$advertisements[$advertiseName];
}
/**
* Return a value from the module configuration.
*
* @param mixed config Key
*
* @return mixed config value
*/
public static function getConfigValue($key)
{
return self::$cfg->$key;
}
}

View File

@ -1,6 +1,6 @@
<?php <?php
/** /**
* FuzeWorks * FuzeWorks.
* *
* The FuzeWorks MVC PHP FrameWork * The FuzeWorks MVC PHP FrameWork
* *
@ -19,416 +19,467 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
* *
* @author TechFuze * @author TechFuze
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
* @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/) * @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/)
* @license http://opensource.org/licenses/GPL-3.0 GPLv3 License * @license http://opensource.org/licenses/GPL-3.0 GPLv3 License
* @link http://fuzeworks.techfuze.net *
* @since Version 0.0.1 * @link http://fuzeworks.techfuze.net
* @version Version 0.0.1 * @since Version 0.0.1
*
* @version Version 0.0.1
*/ */
namespace FuzeWorks; namespace FuzeWorks;
use \PDOException;
use \FuzeWorks\ORM\ConfigFileORM;
use \FuzeWorks\ORM\ConfigDatabaseORM;
use PDOException;
use FuzeWorks\ORM\ConfigFileORM;
use FuzeWorks\ORM\ConfigDatabaseORM;
/** /**
* Config Class * Config Class.
* *
* This class gives access to the config files. It allows you to open configurations and edit them. * This class gives access to the config files. It allows you to open configurations and edit them.
* This class is extensible, but not yet from the outside * This class is extensible, but not yet from the outside
* @package net.techfuze.fuzeworks.core *
* @author Abel Hoogeveen <abel@techfuze.net> * @author Abel Hoogeveen <abel@techfuze.net>
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
*/ */
class Config { class Config
{
/**
* whether or not the database is active at the moment.
*
* @var bool true on active database
*/
public static $dbActive = false;
/** /**
* whether or not the database is active at the moment * All loaded Config files.
* @access public *
* @var Boolean true on active database * @var array of ConfigORM
*/ */
public static $dbActive = false; private static $cfg = array();
/** /**
* All loaded Config files * Loads a config file and returns it as an object.
* @var Array of ConfigORM *
*/ * @param string config file name
private static $cfg = array(); * @param string directory, default is Application/Config
*
* @throws \Exception on file not found
*
* @return \FuzeWorks\ORM\ConfigORM of config
*/
public static function loadConfigFile($name, $directory = null)
{
$dir = (isset($directory) ? $directory : 'Application/Config/');
$file = $dir.'config.'.strtolower($name).'.php';
/** // If already loaded, return a reference to the ORM
* Loads a config file and returns it as an object if (isset(self::$cfg[$name])) {
* @access public return $cfg = self::$cfg[$name];
* @param String config file name }
* @param String directory, default is Application/Config
* @throws \Exception on file not found
* @return \FuzeWorks\ORM\ConfigORM of config
*/
public static function loadConfigFile($name, $directory = null) {
$dir = (isset($directory) ? $directory : "Application/Config/");
$file = $dir . 'config.' . strtolower($name).".php";
// If already loaded, return a reference to the ORM // Is this the real file?
if (isset(self::$cfg[$name])) { if (file_exists($file)) {
return $cfg = self::$cfg[$name]; // Is it just reference?
} return $cfg = self::$cfg[$name] = new ConfigFileORM($file);
} else {
// Caught in a datastream
$module = Modules::get('core/database');
// No escape from dbactive
if (self::$dbActive) {
// Open your stream
$dborm = new ConfigDatabaseORM($module, $name);
// Lookup for success
if ($dborm->success) {
// And see
return $cfg = self::$cfg[$name] = $dborm;
}
}
// Is this the real file? // I'm just a poor exception
if (file_exists($file)) { throw new ConfigException("Config file '".strtolower($name)."' was not found", 1);
// Is it just reference?
return $cfg = self::$cfg[$name] = new ConfigFileORM($file);
} else {
// Caught in a datastream
$module = Modules::get('core/database');
// No escape from dbactive
if (self::$dbActive) {
// Open your stream
$dborm = new ConfigDatabaseORM($module, $name);
// Lookup for the success
if ($dborm->success) {
// And see
return $cfg = self::$cfg[$name] = $dborm;
}
}
// I'm just a poor exception // I need no returnee
throw new ConfigException("Config file '".strtolower($name)."' was not found", 1); return false;
}
}
// I need no returnee /**
return false; * Magic config getter.
} *
} * @param string config file name
*
/** * @return \FuzeWorks\ORM\ConfigORM of config
* Magic config getter */
* @access public public static function get($name)
* @param String config file name {
* @return \FuzeWorks\ORM\ConfigORM of config return self::loadConfigFile($name);
*/ }
public static function get($name) {
return self::loadConfigFile($name);
}
} }
namespace FuzeWorks\ORM; namespace FuzeWorks\ORM;
use \Iterator;
use Iterator;
/** /**
* Abstract ConfigORM class. * Abstract ConfigORM class.
* *
* This class implements the iterator, so a config file can be accessed using foreach. * This class implements the iterator, so a config file can be accessed using foreach.
* A file can also be returned using toArray(), so it will be converted to an array * A file can also be returned using toArray(), so it will be converted to an array
* @package net.techfuze.fuzeworks.core *
* @author Abel Hoogeveen <abel@techfuze.net> * @author Abel Hoogeveen <abel@techfuze.net>
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
*/ */
abstract class ConfigORM implements Iterator { abstract class ConfigORM implements Iterator
{
/**
* The original state of a config file. Can be reverted to using revert().
*
* @var StdObject Config file
*/
protected $originalCfg;
/** /**
* The original state of a config file. Can be reverted to using revert() * The current state of a config file.
* @var StdObject Config file *
*/ * @var StdObject Config file
protected $originalCfg; */
protected $cfg;
/** /**
* The current state of a config file. * Revert to the original conditions of the config file.
* @var StdObject Config file */
*/ public function revert()
protected $cfg; {
$this->cfg = $this->originalCfg;
}
/** /**
* Revert to the original conditions of the config file. * Checks if a requested key is set in the config file.
*/ *
public function revert() { * @param string $name Parameter name
$this->cfg = $this->originalCfg; *
} * @return bool true on isset, false on not
*/
public function __isset($name)
{
return isset($this->cfg[$name]);
}
/** /**
* Checks if a requested key is set in the config file * Return a value from a config file.
* @param String $name Parameter name *
* @return boolean true on isset, false on not * @param string $name Key of the requested entry
*/ *
public function __isset($name) { * @return mixed Value of the requested entry
return isset($this->cfg[$name]); */
} public function __get($name)
{
return $this->cfg[$name];
}
/** /**
* Return a value from a config file * Sets an entry in the config file.
* @param String $name Key of the requested entry *
* @return Mixed Value of the requested entry * @param string $name Key of the entry
*/ * @param mixed $value Value of the entry
public function __get($name) { */
return $this->cfg[$name]; public function __set($name, $value)
} {
$this->cfg[$name] = $value;
}
/** /**
* Sets an entry in the config file * Unset a value in a config file.
* @param String $name Key of the entry *
* @param Mixed $value Value of the entry * @param string Key of the entry
*/ */
public function __set($name, $value) { public function __unset($name)
$this->cfg[$name] = $value; {
} unset($this->cfg[$name]);
}
/** /**
* Unset a value in a config file * Iterator method.
* @param String Key of the entry */
*/ public function rewind()
public function __unset($name) { {
unset($this->cfg[$name]); return reset($this->cfg);
} }
/** /**
* Iterator method * Iterator method.
*/ */
public function rewind() { public function current()
return reset($this->cfg); {
} return current($this->cfg);
}
/** /**
* Iterator method * Iterator method.
*/ */
public function current() { public function key()
return current($this->cfg); {
} return key($this->cfg);
}
/** /**
* Iterator method * Iterator method.
*/ */
public function key() { public function next()
return key($this->cfg); {
} return next($this->cfg);
}
/** /**
* Iterator method * Iterator method.
*/ */
public function next() { public function valid()
return next($this->cfg); {
} return key($this->cfg) !== null;
}
/** /**
* Iterator method * Returns the config file as an array.
*/ *
public function valid() { * @return array Config file
return key($this->cfg) !== null; */
} public function toArray()
{
/** return $this->cfg;
* Returns the config file as an array }
* @return Array Config file
*/
public function toArray() {
return $this->cfg;
}
} }
/** /**
* ORM class for config files in a database * ORM class for config files in a database.
* *
* Handles entries in the database of FuzeWorks and is able to dynamically update them when requested * Handles entries in the database of FuzeWorks and is able to dynamically update them when requested
* @package net.techfuze.fuzeworks.core *
* @author Abel Hoogeveen <abel@techfuze.net> * @author Abel Hoogeveen <abel@techfuze.net>
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
*/ */
class ConfigDatabaseORM extends ConfigORM { class ConfigDatabaseORM extends ConfigORM
{
/**
* The current connection to the database.
*
* @var \FuzeWorks\Database Database Connection
*/
private $dbh;
/** /**
* The current connection to the database * whether the database connection has been successfully established.
* @var \FuzeWorks\Database Database Connection *
*/ * @var bool true on success
private $dbh; */
public $success = false;
/** /**
* whether the database connection has been successfully established * The current filename.
* @var boolean true on success *
*/ * @var string filename
public $success = false; */
private $file;
/** /**
* The current filename * Sets up the class and the connection to the database.
* @var String filename *
*/ * @param \FuzeWorks\Database $db The Database connection
private $file; * @param string $filename The current filename
*
* @throws ConfigException on fatal error
*/
public function __construct($db, $filename)
{
$this->dbh = $db;
$this->cfg = $this->openDb($filename);
$this->originalCfg = $this->cfg;
$this->file = $filename;
}
/** /**
* Sets up the class and the connection to the database * Opens up a database connection with the requested filename.
* @param \FuzeWorks\Database $db The Database connection *
* @param String $filename The current filename * @param string $name Name of the file
* @throws ConfigException on fatal error *
*/ * @return array Content of the file
public function __construct($db, $filename) { *
$this->dbh = $db; * @throws ConfigException on fatal error
$this->cfg = $this->openDb($filename); */
$this->originalCfg = $this->cfg; private function openDb($name)
$this->file = $filename; {
} $prefix = $this->dbh->getPrefix();
try {
/** $stmnt = $this->dbh->prepare('SELECT * FROM '.$prefix.'config WHERE `file` = ?');
* Opens up a database connection with the requested filename
* @param String $name Name of the file
* @return Array Content of the file
* @throws ConfigException on fatal error
*/
private function openDb($name) {
$prefix = $this->dbh->getPrefix();
try{
$stmnt = $this->dbh->prepare("SELECT * FROM ".$prefix."config WHERE `file` = ?");
$stmnt->execute(array($name)); $stmnt->execute(array($name));
} catch (PDOException $e){ } catch (PDOException $e) {
throw new ConfigException('Could not execute SQL-query due PDO-exception '.$e->getMessage()); throw new ConfigException('Could not execute SQL-query due PDO-exception '.$e->getMessage());
} }
// Fetch results // Fetch results
$result = $stmnt->fetchAll(\PDO::FETCH_ASSOC); $result = $stmnt->fetchAll(\PDO::FETCH_ASSOC);
$return = array(); $return = array();
for ($i=0; $i < count($result); $i++) { for ($i = 0; $i < count($result); ++$i) {
$return[ $result[$i]['key'] ] = $result[$i]['value']; $return[ $result[$i]['key'] ] = $result[$i]['value'];
} }
// Return if found in DB // Return if found in DB
if (!empty($return)) { if (!empty($return)) {
$this->success = true; $this->success = true;
return (array) $return;
return (array) $return;
} }
} }
/** /**
* Write config updates to the database * Write config updates to the database.
* @throws ConfigException on fatal error *
*/ * @throws ConfigException on fatal error
private function writeDb() { */
// First arrays of all the fields that need to change private function writeDb()
$changed_fields = array(); {
$removed_fields = array(); // First arrays of all the fields that need to change
$new_fields = array(); $changed_fields = array();
$removed_fields = array();
$new_fields = array();
// First check for changed and new feeds // First check for changed and new feeds
foreach ($this->cfg as $key => $value) { foreach ($this->cfg as $key => $value) {
if (isset($this->originalCfg[$key])) { if (isset($this->originalCfg[$key])) {
if ($this->originalCfg[$key] != $value) { if ($this->originalCfg[$key] != $value) {
// Changed field // Changed field
$changed_fields[$key] = $value; $changed_fields[$key] = $value;
} }
} else { } else {
// New field // New field
$new_fields[$key] = $value; $new_fields[$key] = $value;
} }
} }
// Then check for removed fields // Then check for removed fields
foreach ($this->originalCfg as $key => $value) { foreach ($this->originalCfg as $key => $value) {
if (!isset($this->cfg[$key])) { if (!isset($this->cfg[$key])) {
$removed_fields[$key] = $value; $removed_fields[$key] = $value;
} }
} }
// First for the removed values // First for the removed values
$prefix = $this->dbh->getPrefix(); $prefix = $this->dbh->getPrefix();
try { try {
$stmnt = $this->dbh->prepare("DELETE FROM ".$prefix."config WHERE `file` = :file AND `key` = :key"); $stmnt = $this->dbh->prepare('DELETE FROM '.$prefix.'config WHERE `file` = :file AND `key` = :key');
foreach ($removed_fields as $key => $value) { foreach ($removed_fields as $key => $value) {
$stmnt->execute(array('file' => $this->file, 'key' => $key)); $stmnt->execute(array('file' => $this->file, 'key' => $key));
} }
} catch (PDOException $e) { } catch (PDOException $e) {
throw new ConfigException("Could not change config due to PDOException: " . $e->getMessage(), 1); throw new ConfigException('Could not change config due to PDOException: '.$e->getMessage(), 1);
} }
// Then for the changed values // Then for the changed values
try { try {
$stmnt = $this->dbh->prepare("UPDATE ".$prefix."config SET `value` = :value WHERE `file` = :file AND `key` = :key"); $stmnt = $this->dbh->prepare('UPDATE '.$prefix.'config SET `value` = :value WHERE `file` = :file AND `key` = :key');
foreach ($changed_fields as $key => $value) { foreach ($changed_fields as $key => $value) {
$stmnt->execute(array('file' => $this->file, 'key' => $key, 'value' => $value)); $stmnt->execute(array('file' => $this->file, 'key' => $key, 'value' => $value));
} }
} catch (PDOException $e) { } catch (PDOException $e) {
throw new ConfigException("Could not change config due to PDOException: " . $e->getMessage(), 1); throw new ConfigException('Could not change config due to PDOException: '.$e->getMessage(), 1);
} }
// And finally for the new values
try {
$stmnt = $this->dbh->prepare("INSERT INTO ".$prefix."config (`file`,`key`,`value`) VALUES (:file,:key,:value)");
foreach ($new_fields as $key => $value) {
$stmnt->execute(array('file' => $this->file, 'key' => $key, 'value' => $value));
}
} catch (PDOException $e) {
throw new ConfigException("Could not change config due to PDOException: " . $e->getMessage(), 1);
}
}
/**
* Write updates of the config file to the database
* @throws ConfigException on fatal error
*/
public function commit() {
$this->writeDb();
}
// And finally for the new values
try {
$stmnt = $this->dbh->prepare('INSERT INTO '.$prefix.'config (`file`,`key`,`value`) VALUES (:file,:key,:value)');
foreach ($new_fields as $key => $value) {
$stmnt->execute(array('file' => $this->file, 'key' => $key, 'value' => $value));
}
} catch (PDOException $e) {
throw new ConfigException('Could not change config due to PDOException: '.$e->getMessage(), 1);
}
}
/**
* Write updates of the config file to the database.
*
* @throws ConfigException on fatal error
*/
public function commit()
{
$this->writeDb();
}
} }
/** /**
* ORM class for config files in PHP files * ORM class for config files in PHP files.
* *
* Handles entries in the config directory of FuzeWorks and is able to dynamically update them when requested * Handles entries in the config directory of FuzeWorks and is able to dynamically update them when requested
* @package net.techfuze.fuzeworks.core *
* @author Abel Hoogeveen <abel@techfuze.net> * @author Abel Hoogeveen <abel@techfuze.net>
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
*/ */
class ConfigFileORM extends ConfigORM { class ConfigFileORM extends ConfigORM
{
/**
* The current filename.
*
* @var string filename
*/
private $file;
/** /**
* The current filename * Sets up the class and the connection to the PHP file.
* @var String filename *
*/ * @param string $filename The current filename
private $file; *
* @throws ConfigException on fatal error
*/
public function __construct($file)
{
if (file_exists($file)) {
$this->file = $file;
$this->openFile($file);
$this->originalCfg = $this->cfg;
} else {
throw new ConfigException('Could not load config file. Config file does not exist', 1);
}
}
/** /**
* Sets up the class and the connection to the PHP file * Opens the file and returns the data.
* @param String $filename The current filename *
* @throws ConfigException on fatal error * @param string $file Name of the config file
*/ *
public function __construct($file) { * @return array Content of the file
if (file_exists($file)) { */
$this->file = $file; private function openFile($file)
$this->openFile($file); {
$this->originalCfg = $this->cfg; $this->cfg = (array) include $file;
} else { }
throw new ConfigException("Could not load config file. Config file does not exist", 1);
}
}
/** /**
* Opens the file and returns the data * Updates the config file and writes it to the database.
* @param String $file Name of the config file *
* @return Array Content of the file * @throws ConfigException on fatal error
*/ */
private function openFile($file) { private function writeFile()
$this->cfg = (array) require($file); {
} // Implement writing here
if (is_writable($this->file)) {
$config = var_export($this->cfg, true);
file_put_contents($this->file, "<?php return $config ;");
/** return true;
* Updates the config file and writes it to the database }
* @throws ConfigException on fatal error throw new ConfigException("Could not write config file. $file is not writable", 1);
*/ }
private function writeFile() {
// Implement writing here
if (is_writable($this->file)) {
$config = var_export($this->cfg, true);
file_put_contents($this->file, "<?php return $config ;");
return true;
}
throw new ConfigException("Could not write config file. $file is not writable", 1);
}
/** /**
* Updates the config file and writes it * Updates the config file and writes it.
* @throws ConfigException on fatal error *
*/ * @throws ConfigException on fatal error
public function commit() { */
$this->writeFile(); public function commit()
} {
$this->writeFile();
}
} }
?>

View File

@ -1,6 +1,6 @@
<?php <?php
/** /**
* FuzeWorks * FuzeWorks.
* *
* The FuzeWorks MVC PHP FrameWork * The FuzeWorks MVC PHP FrameWork
* *
@ -19,34 +19,35 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
* *
* @author TechFuze * @author TechFuze
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
* @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/) * @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/)
* @license http://opensource.org/licenses/GPL-3.0 GPLv3 License * @license http://opensource.org/licenses/GPL-3.0 GPLv3 License
* @link http://fuzeworks.techfuze.net *
* @since Version 0.0.1 * @link http://fuzeworks.techfuze.net
* @version Version 0.0.1 * @since Version 0.0.1
*
* @version Version 0.0.1
*/ */
namespace FuzeWorks; namespace FuzeWorks;
use \stdClass;
/** /**
* FuzeWorks Core * FuzeWorks Core.
* *
* Holds all the modules and starts the framework. Allows for starting and managing modules * Holds all the modules and starts the framework. Allows for starting and managing modules
* @package net.techfuze.fuzeworks.core *
* @author Abel Hoogeveen <abel@techfuze.net> * @author Abel Hoogeveen <abel@techfuze.net>
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
*/ */
class Core { class Core
{
/** /**
* The current version of the framework * The current version of the framework.
* @access public *
* @var String Framework version * @var string Framework version
*/ */
public static $version = "0.0.1"; public static $version = '0.0.1';
/** /**
* @var bool Whether the files has been loaded * @var bool Whether the files has been loaded
@ -54,131 +55,133 @@ class Core {
private static $loaded = false; private static $loaded = false;
/** /**
* Working directory of the Framework * Working directory of the Framework.
* *
* This is required to make the shutdown function working under Apache webservers * This is required to make the shutdown function working under Apache webservers
* @var String $cwd *
* @var string
*/ */
public static $cwd; public static $cwd;
/** /**
* Initializes the core * Initializes the core.
* *
* @throws \Exception * @throws \Exception
*/ */
public static function init() { public static function init()
// Defines the time the framework starts. Used for timing functions in the framework {
if (!defined('STARTTIME')) { // Defines the time the framework starts. Used for timing functions in the framework
define('STARTTIME', microtime(true)); if (!defined('STARTTIME')) {
} define('STARTTIME', microtime(true));
}
// Load basics // Load basics
ignore_user_abort(true); ignore_user_abort(true);
register_shutdown_function(array('\FuzeWorks\Core', "shutdown")); register_shutdown_function(array('\FuzeWorks\Core', 'shutdown'));
// Load core functionality // Load core functionality
self::loadStartupFiles(); self::loadStartupFiles();
// Load the config file of the FuzeWorks core // Load the config file of the FuzeWorks core
$config = Config::get('core'); $config = Config::get('core');
// Load the logger // Load the logger
Logger::init(); Logger::init();
// And initialize the router paths // And initialize the router paths
Router::init(); Router::init();
// Build all the registers for correct operation // Build all the registers for correct operation
Modules::buildRegister(); Modules::buildRegister();
// Load Composer // Load Composer
if ($config->enable_composer) { if ($config->enable_composer) {
$file = ($config->composer_autoloader != '' ? $config->composer_autoloader : 'vendor/autoload.php'); $file = ($config->composer_autoloader != '' ? $config->composer_autoloader : 'vendor/autoload.php');
self::loadComposer($file); self::loadComposer($file);
} }
// And fire the coreStartEvent // And fire the coreStartEvent
$event = Events::fireEvent('coreStartEvent'); $event = Events::fireEvent('coreStartEvent');
if ($event->isCancelled()) { if ($event->isCancelled()) {
return true; return true;
} }
// Set the CWD for usage in the shutdown function+ // Set the CWD for usage in the shutdown function+
self::$cwd = getcwd(); self::$cwd = getcwd();
} }
/** /**
* Load all the files of the FuzeWorks Framework. * Load all the files of the FuzeWorks Framework.
*/ */
private static function loadStartupFiles() { private static function loadStartupFiles()
if (self::$loaded) {
return; if (self::$loaded) {
return;
}
// Load core abstracts // Load core abstracts
require_once("Core/System/class.exceptions.php"); include_once 'Core/System/class.exceptions.php';
require_once("Core/System/class.abstract.event.php"); include_once 'Core/System/class.abstract.event.php';
// Load the core classes // Load the core classes
require_once("Core/System/class.config.php"); include_once 'Core/System/class.config.php';
require_once("Core/System/class.abstract.eventPriority.php"); include_once 'Core/System/class.abstract.eventPriority.php';
require_once("Core/System/class.events.php"); include_once 'Core/System/class.events.php';
require_once("Core/System/class.logger.php"); include_once 'Core/System/class.logger.php';
require_once("Core/System/class.abstract.model.php"); include_once 'Core/System/class.abstract.model.php';
require_once("Core/System/class.models.php"); include_once 'Core/System/class.models.php';
require_once("Core/System/class.layout.php"); include_once 'Core/System/class.layout.php';
require_once("Core/System/class.abstract.controllerabstract.php"); include_once 'Core/System/class.abstract.controllerabstract.php';
require_once("Core/System/class.router.php"); include_once 'Core/System/class.router.php';
require_once("Core/System/class.abstract.module.php"); include_once 'Core/System/class.abstract.module.php';
require_once("Core/System/class.modules.php"); include_once 'Core/System/class.modules.php';
// Create the module holder // Create the module holder
new Config(); new Config();
new Logger(); new Logger();
new Events(); new Events();
new Models(); new Models();
new Layout(); new Layout();
new Router(); new Router();
new Modules(); new Modules();
self::$loaded = true; self::$loaded = true;
} }
/** /**
* Stop FuzeWorks and run all shutdown functions. * Stop FuzeWorks and run all shutdown functions.
* *
* Afterwards run the Logger shutdown function in order to possibly display the log * Afterwards run the Logger shutdown function in order to possibly display the log
* @access public */
* @return void public static function shutdown()
*/ {
public static function shutdown() { // Fix Apache bug where CWD is changed upon shutdown
// Fix Apache bug where CWD is changed upon shutdown chdir(self::$cwd);
chdir(self::$cwd);
// Fire the Shutdown event // Fire the Shutdown event
Events::fireEvent('coreShutdownEvent'); Events::fireEvent('coreShutdownEvent');
// And end the logger // And end the logger
Logger::shutdown(); Logger::shutdown();
} }
/** /**
* Load composer if it is present * Load composer if it is present.
* @access private *
* @param String directory of composer autoload file (optional) * @param string directory of composer autoload file (optional)
* @return boolean true on success, false on failure *
*/ * @return bool true on success, false on failure
private static function loadComposer($file = "vendor/autoload.php") { */
if (file_exists($file)) { private static function loadComposer($file = 'vendor/autoload.php')
require($file); {
Logger::log('Loaded Composer'); if (file_exists($file)) {
return true; include $file;
} Logger::log('Loaded Composer');
Logger::log('Failed to load Composer. File \''.$file.'\' not found');
return false;
}
return true;
}
Logger::log('Failed to load Composer. File \''.$file.'\' not found');
return false;
}
} }
?>

View File

@ -1,6 +1,6 @@
<?php <?php
/** /**
* FuzeWorks * FuzeWorks.
* *
* The FuzeWorks MVC PHP FrameWork * The FuzeWorks MVC PHP FrameWork
* *
@ -19,19 +19,21 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
* *
* @author TechFuze * @author TechFuze
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
* @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/) * @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/)
* @license http://opensource.org/licenses/GPL-3.0 GPLv3 License * @license http://opensource.org/licenses/GPL-3.0 GPLv3 License
* @link http://fuzeworks.techfuze.net *
* @since Version 0.0.1 * @link http://fuzeworks.techfuze.net
* @version Version 0.0.1 * @since Version 0.0.1
*
* @version Version 0.0.1
*/ */
namespace FuzeWorks; namespace FuzeWorks;
/** /**
* Class Events * Class Events.
* *
* FuzeWorks is built in a way that almost every core-event can be manipulated by modules. This class provides various ways to hook into the core (or other modules) * FuzeWorks is built in a way that almost every core-event can be manipulated by modules. This class provides various ways to hook into the core (or other modules)
* and manipulate the outcome of the functions. Modules and core actions can 'fire' an event and modules can 'hook' into that event. Let's take a look at the example below: * and manipulate the outcome of the functions. Modules and core actions can 'fire' an event and modules can 'hook' into that event. Let's take a look at the example below:
@ -48,163 +50,181 @@ namespace FuzeWorks;
* *
* $event->title = date('H:i:s ').$event->title; * $event->title = date('H:i:s ').$event->title;
* *
* @package net.techfuze.fuzeworks.core * @author Abel Hoogeveen <abel@techfuze.net>
* @author Abel Hoogeveen <abel@techfuze.net> * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net)
*/ */
class Events { class Events
{
/** /**
* Array of classes that can handle events * Array of classes that can handle events.
*
* @var array * @var array
*/ */
public static $listeners = array(); public static $listeners = array();
/** /**
* Whether the event system is enabled or not * Whether the event system is enabled or not.
*
* @var array * @var array
*/ */
private static $enabled = true; private static $enabled = true;
/** /**
* A register with all the events and associated modules which should be loaded upon eventFire * A register with all the events and associated modules which should be loaded upon eventFire.
*
* @var array * @var array
*/ */
public static $register; public static $register;
/** /**
* Adds a function as listener * Adds a function as listener.
* *
* @param mixed callback The callback when the events get fired, see {@link http://php.net/manual/en/language.types.callable.php PHP.net} * @param mixed callback The callback when the events get fired, see {@link http://php.net/manual/en/language.types.callable.php PHP.net}
* @param String $eventName The name of the event * @param string $eventName The name of the event
* @param int $priority The priority, even though integers are valid, please use EventPriority (for example EventPriority::Lowest) * @param int $priority The priority, even though integers are valid, please use EventPriority (for example EventPriority::Lowest)
*
* @see EventPriority * @see EventPriority
* *
* @throws EventException * @throws EventException
*/ */
public static function addListener($callback, $eventName, $priority = EventPriority::NORMAL){ public static function addListener($callback, $eventName, $priority = EventPriority::NORMAL)
if(EventPriority::getPriority($priority) == false) {
throw new Exception("Unknown priority " . $priority); if (EventPriority::getPriority($priority) == false) {
throw new Exception('Unknown priority '.$priority);
}
if(!isset(self::$listeners[$eventName])) if (!isset(self::$listeners[$eventName])) {
self::$listeners[$eventName] = array(); self::$listeners[$eventName] = array();
}
if(!isset(self::$listeners[$eventName][$priority])) if (!isset(self::$listeners[$eventName][$priority])) {
self::$listeners[$eventName][$priority] = array(); self::$listeners[$eventName][$priority] = array();
}
self::$listeners[$eventName][$priority][] = $callback; self::$listeners[$eventName][$priority][] = $callback;
} }
/** /**
* Removes a function as listener * Removes a function as listener.
* *
* @param mixed callback The callback when the events get fired, see {@link http://php.net/manual/en/language.types.callable.php PHP.net} * @param mixed callback The callback when the events get fired, see {@link http://php.net/manual/en/language.types.callable.php PHP.net}
* @param String $eventName The name of the event * @param string $eventName The name of the event
* @param int $priority The priority, even though integers are valid, please use EventPriority (for example EventPriority::Lowest) * @param int $priority The priority, even though integers are valid, please use EventPriority (for example EventPriority::Lowest)
*
* @see EventPriority * @see EventPriority
* *
* @throws EventException * @throws EventException
*/ */
public static function removeListener($callback, $eventName, $priority = EventPriority::NORMAL){ public static function removeListener($callback, $eventName, $priority = EventPriority::NORMAL)
if(EventPriority::getPriority($priority) == false) {
throw new Exception("Unknown priority " . $priority); if (EventPriority::getPriority($priority) == false) {
throw new Exception('Unknown priority '.$priority);
}
if(!isset(self::$listeners[$eventName])) if (!isset(self::$listeners[$eventName])) {
return; return;
}
if(!isset(self::$listeners[$eventName][$priority])) if (!isset(self::$listeners[$eventName][$priority])) {
return; return;
}
foreach(self::$listeners[$eventName][$priority] as $i => $_callback){ foreach (self::$listeners[$eventName][$priority] as $i => $_callback) {
if ($_callback == $callback) {
if($_callback == $callback) {
unset(self::$listeners[$eventName][$priority][$i]); unset(self::$listeners[$eventName][$priority][$i]);
return; return;
} }
} }
} }
/** /**
* Fires an Event * Fires an Event.
* *
* The Event gets created, passed around and then returned to the issuer. * The Event gets created, passed around and then returned to the issuer.
* @param Mixed $input Object for direct event, string for system event or notifierEvent *
* @return \FuzeWorks\Event The Event * @param mixed $input Object for direct event, string for system event or notifierEvent
*
* @return \FuzeWorks\Event The Event
*/ */
public static function fireEvent($input) { public static function fireEvent($input)
if (is_string($input)) { {
// If the input is a string if (is_string($input)) {
$eventClass = $input; // If the input is a string
$eventName = $input; $eventClass = $input;
if(!class_exists($eventClass)){ $eventName = $input;
// Check if the file even exists if (!class_exists($eventClass)) {
$file = "Core/Events/event.".$eventName.".php"; // Check if the file even exists
if(file_exists($file)){ $file = 'Core/Events/event.'.$eventName.'.php';
// Load the file if (file_exists($file)) {
$eventClass = "\FuzeWorks\Event\\" . $eventClass; // Load the file
require_once($file); $eventClass = "\FuzeWorks\Event\\".$eventClass;
}else{ include_once $file;
// No event arguments? Looks like a notify-event } else {
if(func_num_args() == 1){ // No event arguments? Looks like a notify-event
// Load notify-event-class if (func_num_args() == 1) {
$eventClass = '\FuzeWorks\Event\NotifierEvent'; // Load notify-event-class
}else{ $eventClass = '\FuzeWorks\Event\NotifierEvent';
// No notify-event: we tried all we could } else {
throw new Exception("Event ".$eventName." could not be found!"); // No notify-event: we tried all we could
} throw new Exception('Event '.$eventName.' could not be found!');
} }
} }
}
$event = new $eventClass($this); $event = new $eventClass($this);
} elseif (is_object($input)) { } elseif (is_object($input)) {
$eventName = get_class($input); $eventName = get_class($input);
$eventName = explode('\\', $eventName); $eventName = explode('\\', $eventName);
$eventName = end($eventName); $eventName = end($eventName);
$event = $input; $event = $input;
} else { } else {
// INVALID EVENT // INVALID EVENT
return false; return false;
} }
Logger::newLevel("Firing Event: '".$eventName."'"); Logger::newLevel("Firing Event: '".$eventName."'");
Logger::log('Initializing Event'); Logger::log('Initializing Event');
if (func_num_args() > 1) if (func_num_args() > 1) {
call_user_func_array(array($event, 'init'), array_slice(func_get_args(), 1)); call_user_func_array(array($event, 'init'), array_slice(func_get_args(), 1));
}
// Do not run if the event system is disabled // Do not run if the event system is disabled
if (!self::$enabled) { if (!self::$enabled) {
Logger::log("Event system is disabled"); Logger::log('Event system is disabled');
Logger::stopLevel(); Logger::stopLevel();
return $event; return $event;
} }
Logger::log("Checking for Listeners"); Logger::log('Checking for Listeners');
// Read the event register for listeners // Read the event register for listeners
$register = self::$register; $register = self::$register;
if (isset($register[$eventName])) { if (isset($register[$eventName])) {
for ($i=0; $i < count($register[$eventName]); $i++) { for ($i = 0; $i < count($register[$eventName]); ++$i) {
Modules::get($register[$eventName][$i]); Modules::get($register[$eventName][$i]);
} }
} }
//There are listeners for this event //There are listeners for this event
if(isset(self::$listeners[$eventName])) { if (isset(self::$listeners[$eventName])) {
//Loop from the highest priority to the lowest //Loop from the highest priority to the lowest
for ($priority = EventPriority::getHighestPriority(); $priority <= EventPriority::getLowestPriority(); $priority++) { for ($priority = EventPriority::getHighestPriority(); $priority <= EventPriority::getLowestPriority(); ++$priority) {
//Check for listeners in this priority //Check for listeners in this priority
if (isset(self::$listeners[$eventName][$priority])) { if (isset(self::$listeners[$eventName][$priority])) {
$listeners = self::$listeners[$eventName][$priority]; $listeners = self::$listeners[$eventName][$priority];
Logger::newLevel('Found listeners with priority ' . EventPriority::getPriority($priority)); Logger::newLevel('Found listeners with priority '.EventPriority::getPriority($priority));
//Fire the event to each listener //Fire the event to each listener
foreach ($listeners as $callback) { foreach ($listeners as $callback) {
if (is_callable($callback)) { if (is_callable($callback)) {
Logger::newLevel('Firing function'); Logger::newLevel('Firing function');
} elseif(!is_string($callback[0])) } elseif (!is_string($callback[0])) {
Logger::newLevel('Firing ' . get_class($callback[0]) . '->' . $callback[1]); Logger::newLevel('Firing '.get_class($callback[0]).'->'.$callback[1]);
else } else {
Logger::newLevel('Firing ' . join('->', $callback)); Logger::newLevel('Firing '.implode('->', $callback));
}
try { try {
call_user_func($callback, $event); call_user_func($callback, $event);
} catch (ModuleException $e) { } catch (ModuleException $e) {
@ -218,26 +238,26 @@ class Events {
} }
} }
Logger::stopLevel(); Logger::stopLevel();
return $event;
} return $event;
}
/** /**
* Enables the event system * Enables the event system.
*/ */
public static function enable() { public static function enable()
Logger::log("Enabled the Event system"); {
Logger::log('Enabled the Event system');
self::$enabled = true; self::$enabled = true;
} }
/** /**
* Disables the event system * Disables the event system.
*/ */
public static function disable() { public static function disable()
Logger::log("Disabled the Event system"); {
Logger::log('Disabled the Event system');
self::$enabled = false; self::$enabled = false;
} }
} }
?>

View File

@ -1,6 +1,6 @@
<?php <?php
/** /**
* FuzeWorks * FuzeWorks.
* *
* The FuzeWorks MVC PHP FrameWork * The FuzeWorks MVC PHP FrameWork
* *
@ -19,93 +19,115 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
* *
* @author TechFuze * @author TechFuze
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
* @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/) * @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/)
* @license http://opensource.org/licenses/GPL-3.0 GPLv3 License * @license http://opensource.org/licenses/GPL-3.0 GPLv3 License
* @link http://fuzeworks.techfuze.net *
* @since Version 0.0.1 * @link http://fuzeworks.techfuze.net
* @version Version 0.0.1 * @since Version 0.0.1
*
* @version Version 0.0.1
*/ */
namespace FuzeWorks; namespace FuzeWorks;
/** /**
* Class Exception * Class Exception.
* @package net.techfuze.fuzeworks.core *
* @author Abel Hoogeveen <abel@techfuze.net> * @author Abel Hoogeveen <abel@techfuze.net>
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
*/ */
class Exception extends \Exception{} class Exception extends \Exception
{
}
/** /**
* Class LayoutException * Class LayoutException.
* @package net.techfuze.fuzeworks.core *
* @author Abel Hoogeveen <abel@techfuze.net> * @author Abel Hoogeveen <abel@techfuze.net>
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
*/ */
class LayoutException extends Exception{} class LayoutException extends Exception
{
}
/** /**
* Class ConfigException * Class ConfigException.
* @package net.techfuze.fuzeworks.core *
* @author Abel Hoogeveen <abel@techfuze.net> * @author Abel Hoogeveen <abel@techfuze.net>
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
*/ */
class ConfigException extends Exception{} class ConfigException extends Exception
{
}
/** /**
* Class ModelException * Class ModelException.
* @package net.techfuze.fuzeworks.core *
* @author Abel Hoogeveen <abel@techfuze.net> * @author Abel Hoogeveen <abel@techfuze.net>
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
*/ */
class ModelException extends Exception{} class ModelException extends Exception
{
}
/** /**
* Class LoggerException * Class LoggerException.
* @package net.techfuze.fuzeworks.core *
* @author Abel Hoogeveen <abel@techfuze.net> * @author Abel Hoogeveen <abel@techfuze.net>
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
*/ */
class LoggerException extends Exception{} class LoggerException extends Exception
{
}
/** /**
* Class RouterException * Class RouterException.
* @package net.techfuze.fuzeworks.core *
* @author Abel Hoogeveen <abel@techfuze.net> * @author Abel Hoogeveen <abel@techfuze.net>
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
*/ */
class RouterException extends Exception{} class RouterException extends Exception
{
}
/** /**
* Class CoreException * Class CoreException.
* @package net.techfuze.fuzeworks.core *
* @author Abel Hoogeveen <abel@techfuze.net> * @author Abel Hoogeveen <abel@techfuze.net>
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
*/ */
class CoreException extends Exception{} class CoreException extends Exception
{
}
/** /**
* Class EventException * Class EventException.
* @package net.techfuze.fuzeworks.core *
* @author Abel Hoogeveen <abel@techfuze.net> * @author Abel Hoogeveen <abel@techfuze.net>
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
*/ */
class EventException extends Exception{} class EventException extends Exception
{
}
/** /**
* Class DatabaseException * Class DatabaseException.
* @package net.techfuze.fuzeworks.core *
* @author Abel Hoogeveen <abel@techfuze.net> * @author Abel Hoogeveen <abel@techfuze.net>
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
*/ */
class DatabaseException extends Exception{} class DatabaseException extends Exception
{
}
/** /**
* Class ModuleException * Class ModuleException.
* @package net.techfuze.fuzeworks.core *
* @author Abel Hoogeveen <abel@techfuze.net> * @author Abel Hoogeveen <abel@techfuze.net>
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
*/ */
class ModuleException extends Exception{} class ModuleException extends Exception
{
}

File diff suppressed because it is too large Load Diff

View File

@ -1,6 +1,6 @@
<?php <?php
/** /**
* FuzeWorks * FuzeWorks.
* *
* The FuzeWorks MVC PHP FrameWork * The FuzeWorks MVC PHP FrameWork
* *
@ -19,385 +19,400 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
* *
* @author TechFuze * @author TechFuze
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
* @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/) * @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/)
* @license http://opensource.org/licenses/GPL-3.0 GPLv3 License * @license http://opensource.org/licenses/GPL-3.0 GPLv3 License
* @link http://fuzeworks.techfuze.net *
* @since Version 0.0.1 * @link http://fuzeworks.techfuze.net
* @version Version 0.0.1 * @since Version 0.0.1
*
* @version Version 0.0.1
*/ */
namespace FuzeWorks; namespace FuzeWorks;
/** /**
* Logger Class * Logger Class.
* *
* The main tool to handle errors and exceptions. Provides some tools for debugging and tracking where errors take place * The main tool to handle errors and exceptions. Provides some tools for debugging and tracking where errors take place
* All fatal errors get catched by this class and get displayed if configured to do so. * All fatal errors get catched by this class and get displayed if configured to do so.
* @package net.techfuze.fuzeworks.core *
* @author Abel Hoogeveen <abel@techfuze.net> * @author Abel Hoogeveen <abel@techfuze.net>
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
*/ */
class Logger { class Logger
{
/**
* Log entries which display information entries.
*
* @var array
*/
public static $infoErrors = array();
/** /**
* Log entries which display information entries * Log entries which display critical error entries.
* @var array *
*/ * @var array
public static $infoErrors = array(); */
public static $criticalErrors = array();
/** /**
* Log entries which display critical error entries * Log entries which display warning entries.
* @var array *
*/ * @var array
public static $criticalErrors = array(); */
public static $warningErrors = array();
/** /**
* Log entries which display warning entries * All log entries, unsorted.
* @var array *
*/ * @var array
public static $warningErrors = array(); */
public static $Logs = array();
/** /**
* All log entries, unsorted * whether to output the log after FuzeWorks has run.
* @var array *
*/ * @var bool
public static $Logs = array(); */
private static $print_to_screen = false;
/** /**
* whether to output the log after FuzeWorks has run * whether to output the log after FuzeWorks has run, regardless of conditions.
* @var boolean *
*/ * @var bool
private static $print_to_screen = false; */
public static $debug = false;
/** /**
* whether to output the log after FuzeWorks has run, regardless of conditions * Initiates the Logger.
* @var boolean *
*/ * Registers the error and exception handler, when required to do so by configuration
public static $debug = false; */
public static function init()
{
// Register the error handler
if (Config::get('error')->error_reporting == true) {
set_error_handler(array('\FuzeWorks\Logger', 'errorHandler'), E_ALL);
set_Exception_handler(array('\FuzeWorks\Logger', 'exceptionHandler'));
error_reporting(false);
}
self::$debug = Config::get('error')->debug;
self::newLevel('Logger Initiated');
}
/** /**
* Initiates the Logger. * Function to be run upon FuzeWorks shutdown.
* *
* Registers the error and exception handler, when required to do so by configuration * Logs a fatal error and outputs the log when configured or requested to do so
*/ */
public static function init() { public static function shutdown()
// Register the error handler {
if (Config::get('error')->error_reporting == true) { // Load last error if thrown
set_error_handler(array('\FuzeWorks\Logger', "errorHandler"), E_ALL); $errfile = 'Unknown file';
set_Exception_handler(array('\FuzeWorks\Logger', "exceptionHandler")); $errstr = 'shutdown';
error_reporting(false); $errno = E_CORE_ERROR;
} $errline = 0;
self::$debug = Config::get('error')->debug;
self::newLevel("Logger Initiated");
}
/** $error = error_get_last();
* Function to be run upon FuzeWorks shutdown. if ($error !== null) {
* $errno = $error['type'];
* Logs a fatal error and outputs the log when configured or requested to do so $errfile = $error['file'];
*/ $errline = $error['line'];
public static function shutdown() { $errstr = $error['message'];
// Load last error if thrown
$errfile = "Unknown file";
$errstr = "shutdown";
$errno = E_CORE_ERROR;
$errline = 0;
$error = error_get_last(); // Log it!
if ($error !== NULL) { self::errorHandler($errno, $errstr, $errfile, $errline);
$errno = $error['type']; self::logInfo(self::backtrace());
$errfile = $error['file']; }
$errline = $error['line'];
$errstr = $error['message'];
// Log it! // And finally stop the Logging
self::errorHandler($errno, $errstr, $errfile, $errline); self::stopLevel();
self::logInfo(self::backtrace());
}
// And finally stop the Logging if (self::$debug == true || self::$print_to_screen) {
self::stopLevel(); self::log('Parsing debug log');
echo self::logToScreen();
}
}
if (self::$debug == true || self::$print_to_screen) { /**
self::log("Parsing debug log"); * System that redirects the errors to the appropriate logging method.
echo self::logToScreen(); *
} * @param int $type Error-type, Pre defined PHP Constant
} * @param string error. The error itself
* @param string File. The absolute path of the file
* @param int Line. The line on which the error occured.
* @param array context. Some of the error's relevant variables
*/
public static function errorHandler($type = E_USER_NOTICE, $error = 'Undefined Error', $errFile = null, $errLine = null, $context = null)
{
// Check type
$thisType = self::getType($type);
$LOG = array('type' => (!is_null($thisType) ? $thisType : 'ERROR'),
'message' => (!is_null($error) ? $error : ''),
'logFile' => (!is_null($errFile) ? $errFile : ''),
'logLine' => (!is_null($errLine) ? $errLine : ''),
'context' => (!is_null($context) ? $context : ''),
'runtime' => round(self::getRelativeTime(), 4), );
self::$Logs[] = $LOG;
}
/** /**
* System that redirects the errors to the appropriate logging method * Exception handler
* @access public * Will be triggered when an uncaught exception occures. This function shows the error-message, and shuts down the script.
* @param int $type Error-type, Pre defined PHP Constant * Please note that most of the user-defined exceptions will be caught in the router, and handled with the error-controller.
* @param string error. The error itself *
* @param string File. The absolute path of the file * @param Exception $exception The occured exception.
* @param int Line. The line on which the error occured. */
* @param array context. Some of the error's relevant variables public static function exceptionHandler($exception)
* @return void {
*/ $message = $exception->getMessage();
public static function errorHandler($type = E_USER_NOTICE, $error = "Undefined Error", $errFile = null, $errLine = null, $context = null) { $code = $exception->getCode();
// Check type $file = $exception->getFile();
$thisType = self::getType($type); $line = $exception->getLine();
$LOG = array('type' => (!is_null($thisType) ? $thisType : "ERROR"), $context = $exception->getTraceAsString();
'message' => (!is_null($error) ? $error : ""),
'logFile' => (!is_null($errFile) ? $errFile : ""),
'logLine' => (!is_null($errLine) ? $errLine : ""),
'context' => (!is_null($context) ? $context : ""),
'runtime' => round(self::getRelativeTime(), 4));
self::$Logs[] = $LOG;
}
/** self::logError('Exception thrown: '.$message.' | '.$code, null, $file, $line);
* Exception handler }
* Will be triggered when an uncaught exception occures. This function shows the error-message, and shuts down the script.
* Please note that most of the user-defined exceptions will be caught in the router, and handled with the error-controller.
*
* @access public
* @param Exception $exception The occured exception.
* @return void
*/
public static function exceptionHandler($exception)
{
$message = $exception->getMessage();
$code = $exception->getCode();
$file = $exception->getFile();
$line = $exception->getLine();
$context = $exception->getTraceAsString();
self::logError("Exception thrown: " . $message . " | " . $code, null, $file, $line); /**
} * Output the entire log to the screen. Used for debugging problems with your code.
*
* @return string Output of the log
*/
public static function logToScreen()
{
// Send a screenLogEvent, allows for new screen log designs
$event = Events::fireEvent('screenLogEvent');
if ($event->isCancelled()) {
return false;
}
/** // Otherwise just load it
* Output the entire log to the screen. Used for debugging problems with your code.
* @return String Output of the log
*/
public static function logToScreen() {
// Send a screenLogEvent, allows for new screen log designs
$event = Events::fireEvent('screenLogEvent');
if ($event->isCancelled()) {
return false;
}
// Otherwise just load it
$string = '<h3>FuzeWorks debug log</h3>'; $string = '<h3>FuzeWorks debug log</h3>';
$layer = 0; $layer = 0;
for($i = 0; $i < count(self::$Logs); $i++){ for ($i = 0; $i < count(self::$Logs); ++$i) {
$log = self::$Logs[$i];
$log = self::$Logs[$i]; if ($log['type'] == 'LEVEL_START') {
if($log['type'] == 'LEVEL_START'){ ++$layer;
$layer++; $color = 255 - ($layer * 25);
$color = 255-($layer*25);
$string .= '<div style="background: rgb(188 , 232 ,'.$color.');border: 1px black solid;margin: 5px 0;padding: 5px 20px;">'; $string .= '<div style="background: rgb(188 , 232 ,'.$color.');border: 1px black solid;margin: 5px 0;padding: 5px 20px;">';
$string .= '<div style="font-weight: bold; font-size: 11pt;">'.$log['message'].'<span style="float: right">'.(!empty($log['runtime']) ? "(".round($log['runtime']*1000, 4).'ms)' : "").'</span></div>'; $string .= '<div style="font-weight: bold; font-size: 11pt;">'.$log['message'].'<span style="float: right">'.(!empty($log['runtime']) ? '('.round($log['runtime'] * 1000, 4).'ms)' : '').'</span></div>';
} elseif ($log['type'] == "LEVEL_STOP") { } elseif ($log['type'] == 'LEVEL_STOP') {
$layer--; --$layer;
$string .= "</div>"; $string .= '</div>';
} elseif ($log['type'] == "ERROR") { } elseif ($log['type'] == 'ERROR') {
$string .= '<div style="'.($layer == 0 ? 'padding-left: 21px;' : "").'font-size: 11pt; background-color:#f56954;">['.$log['type'].']'.(!empty($log['context']) && is_string($log['context']) ? '<u>['.$log['context'].']</u>' : "").' '.$log["message"].' $string .= '<div style="'.($layer == 0 ? 'padding-left: 21px;' : '').'font-size: 11pt; background-color:#f56954;">['.$log['type'].']'.(!empty($log['context']) && is_string($log['context']) ? '<u>['.$log['context'].']</u>' : '').' '.$log['message'].'
<span style="float: right">'.(!empty($log['logFile']) ? $log['logFile'] : "")." : ".(!empty($log['logLine']) ? $log['logLine'] : "").'('.round($log['runtime']*1000, 4).' ms)</span></div>'; <span style="float: right">'.(!empty($log['logFile']) ? $log['logFile'] : '').' : '.(!empty($log['logLine']) ? $log['logLine'] : '').'('.round($log['runtime'] * 1000, 4).' ms)</span></div>';
} elseif ($log['type'] == "WARNING") { } elseif ($log['type'] == 'WARNING') {
$string .= '<div style="'.($layer == 0 ? 'padding-left: 21px;' : "").'font-size: 11pt; background-color:#f39c12;">['.$log['type'].']'.(!empty($log['context']) && is_string($log['context']) ? '<u>['.$log['context'].']</u>' : "").' '.$log["message"].' $string .= '<div style="'.($layer == 0 ? 'padding-left: 21px;' : '').'font-size: 11pt; background-color:#f39c12;">['.$log['type'].']'.(!empty($log['context']) && is_string($log['context']) ? '<u>['.$log['context'].']</u>' : '').' '.$log['message'].'
<span style="float: right">'.(!empty($log['logFile']) ? $log['logFile'] : "")." : ".(!empty($log['logLine']) ? $log['logLine'] : "").'('.round($log['runtime']*1000, 4).' ms)</span></div>'; <span style="float: right">'.(!empty($log['logFile']) ? $log['logFile'] : '').' : '.(!empty($log['logLine']) ? $log['logLine'] : '').'('.round($log['runtime'] * 1000, 4).' ms)</span></div>';
} elseif ($log['type'] == "INFO") { } elseif ($log['type'] == 'INFO') {
$string .= '<div style="'.($layer == 0 ? 'padding-left: 21px;' : "").'font-size: 11pt;">'.(!empty($log['context']) ? '<u>['.$log['context'].']</u>' : "").' '.$log["message"].'<span style="float: right">('.round($log['runtime']*1000, 4).' ms)</span></div>'; $string .= '<div style="'.($layer == 0 ? 'padding-left: 21px;' : '').'font-size: 11pt;">'.(!empty($log['context']) ? '<u>['.$log['context'].']</u>' : '').' '.$log['message'].'<span style="float: right">('.round($log['runtime'] * 1000, 4).' ms)</span></div>';
} }
} }
return $string; return $string;
} }
/** /**
* Backtrace a problem to the source using the trace of an Exception * Backtrace a problem to the source using the trace of an Exception.
* @return string HTML backtrace *
*/ * @return string HTML backtrace
public static function backtrace() { */
$e = new Exception(); public static function backtrace()
$trace = explode("\n", $e->getTraceAsString()); {
// reverse array to make steps line up chronologically $e = new Exception();
$trace = array_reverse($trace); $trace = explode("\n", $e->getTraceAsString());
array_shift($trace); // remove {main} // reverse array to make steps line up chronologically
array_pop($trace); // remove call to this method $trace = array_reverse($trace);
$length = count($trace); array_shift($trace); // remove {main}
$result = array(); array_pop($trace); // remove call to this method
$length = count($trace);
$result = array();
for ($i = 0; $i < $length; $i++) for ($i = 0; $i < $length; ++$i) {
{ $result[] = ($i + 1).')'.substr($trace[$i], strpos($trace[$i], ' ')); // replace '#someNum' with '$i)', set the right ordering
$result[] = ($i + 1) . ')' . substr($trace[$i], strpos($trace[$i], ' ')); // replace '#someNum' with '$i)', set the right ordering }
}
return "<b>BACKTRACE: <br/>\t" . implode("<br/>", $result)."</b>"; return "<b>BACKTRACE: <br/>\t".implode('<br/>', $result).'</b>';
} }
/* =========================================LOGGING METHODS==============================================================*/ /* =========================================LOGGING METHODS==============================================================*/
/** /**
* Create a information log entry * Create a information log entry.
* @param String $msg The information to be logged *
* @param String $mod The name of the module * @param string $msg The information to be logged
* @param String $file The file where the log occured * @param string $mod The name of the module
* @param integer $line The line where the log occured * @param string $file The file where the log occured
* @return void * @param int $line The line where the log occured
*/ */
public static function log($msg, $mod = null, $file = 0, $line = 0) { public static function log($msg, $mod = null, $file = 0, $line = 0)
self::logInfo($msg, $mod, $file, $line); {
} self::logInfo($msg, $mod, $file, $line);
}
/** /**
* Create a information log entry * Create a information log entry.
* @param String $msg The information to be logged *
* @param String $mod The name of the module * @param string $msg The information to be logged
* @param String $file The file where the log occured * @param string $mod The name of the module
* @param integer $line The line where the log occured * @param string $file The file where the log occured
* @return void * @param int $line The line where the log occured
*/ */
public static function logInfo($msg, $mod = null, $file = 0, $line = 0) { public static function logInfo($msg, $mod = null, $file = 0, $line = 0)
$LOG = array('type' => 'INFO', {
'message' => (!is_null($msg) ? $msg : ""), $LOG = array('type' => 'INFO',
'logFile' => (!is_null($file) ? $file : ""), 'message' => (!is_null($msg) ? $msg : ''),
'logLine' => (!is_null($line) ? $line : ""), 'logFile' => (!is_null($file) ? $file : ''),
'context' => (!is_null($mod) ? $mod : ""), 'logLine' => (!is_null($line) ? $line : ''),
'runtime' => round(self::getRelativeTime(), 4)); 'context' => (!is_null($mod) ? $mod : ''),
'runtime' => round(self::getRelativeTime(), 4), );
self::$infoErrors[] = $LOG; self::$infoErrors[] = $LOG;
self::$Logs[] = $LOG; self::$Logs[] = $LOG;
} }
/** /**
* Create a error log entry * Create a error log entry.
* @param String $msg The information to be logged *
* @param String $mod The name of the module * @param string $msg The information to be logged
* @param String $file The file where the log occured * @param string $mod The name of the module
* @param integer $line The line where the log occured * @param string $file The file where the log occured
* @return void * @param int $line The line where the log occured
*/ */
public static function logError($msg, $mod = null, $file = 0, $line = 0) { public static function logError($msg, $mod = null, $file = 0, $line = 0)
$LOG = array('type' => 'ERROR', {
'message' => (!is_null($msg) ? $msg : ""), $LOG = array('type' => 'ERROR',
'logFile' => (!is_null($file) ? $file : ""), 'message' => (!is_null($msg) ? $msg : ''),
'logLine' => (!is_null($line) ? $line : ""), 'logFile' => (!is_null($file) ? $file : ''),
'context' => (!is_null($mod) ? $mod : ""), 'logLine' => (!is_null($line) ? $line : ''),
'runtime' => round(self::getRelativeTime(), 4)); 'context' => (!is_null($mod) ? $mod : ''),
'runtime' => round(self::getRelativeTime(), 4), );
self::$criticalErrors[] = $LOG; self::$criticalErrors[] = $LOG;
self::$Logs[] = $LOG; self::$Logs[] = $LOG;
} }
/** /**
* Create a warning log entry * Create a warning log entry.
* @param String $msg The information to be logged *
* @param String $mod The name of the module * @param string $msg The information to be logged
* @param String $file The file where the log occured * @param string $mod The name of the module
* @param integer $line The line where the log occured * @param string $file The file where the log occured
* @return void * @param int $line The line where the log occured
*/ */
public static function logWarning($msg, $mod = null, $file = 0, $line = 0) { public static function logWarning($msg, $mod = null, $file = 0, $line = 0)
$LOG = array('type' => 'WARNING', {
'message' => (!is_null($msg) ? $msg : ""), $LOG = array('type' => 'WARNING',
'logFile' => (!is_null($file) ? $file : ""), 'message' => (!is_null($msg) ? $msg : ''),
'logLine' => (!is_null($line) ? $line : ""), 'logFile' => (!is_null($file) ? $file : ''),
'context' => (!is_null($mod) ? $mod : ""), 'logLine' => (!is_null($line) ? $line : ''),
'runtime' => round(self::getRelativeTime(), 4)); 'context' => (!is_null($mod) ? $mod : ''),
'runtime' => round(self::getRelativeTime(), 4), );
self::$warningErrors[] = $LOG; self::$warningErrors[] = $LOG;
self::$Logs[] = $LOG; self::$Logs[] = $LOG;
} }
/** /**
* Create a new Level log entry. Used to categorise logs * Create a new Level log entry. Used to categorise logs.
* @param String $msg The name of the new level *
* @param String $mod The name of the module * @param string $msg The name of the new level
* @param String $file The file where the log occured * @param string $mod The name of the module
* @param integer $line The line where the log occured * @param string $file The file where the log occured
* @return void * @param int $line The line where the log occured
*/ */
public static function newLevel($msg, $mod = null, $file = null, $line = null) { public static function newLevel($msg, $mod = null, $file = null, $line = null)
$LOG = array('type' => 'LEVEL_START', {
'message' => (!is_null($msg) ? $msg : ""), $LOG = array('type' => 'LEVEL_START',
'logFile' => (!is_null($file) ? $file : ""), 'message' => (!is_null($msg) ? $msg : ''),
'logLine' => (!is_null($line) ? $line : ""), 'logFile' => (!is_null($file) ? $file : ''),
'context' => (!is_null($mod) ? $mod : ""), 'logLine' => (!is_null($line) ? $line : ''),
'runtime' => round(self::getRelativeTime(), 4)); 'context' => (!is_null($mod) ? $mod : ''),
'runtime' => round(self::getRelativeTime(), 4), );
self::$Logs[] = $LOG; self::$Logs[] = $LOG;
} }
/** /**
* Create a stop Level log entry. Used to close log categories * Create a stop Level log entry. Used to close log categories.
* @param String $msg The name of the new level *
* @param String $mod The name of the module * @param string $msg The name of the new level
* @param String $file The file where the log occured * @param string $mod The name of the module
* @param integer $line The line where the log occured * @param string $file The file where the log occured
* @return void * @param int $line The line where the log occured
*/ */
public static function stopLevel($msg = null, $mod = null, $file = null, $line = null) { public static function stopLevel($msg = null, $mod = null, $file = null, $line = null)
$LOG = array('type' => 'LEVEL_STOP', {
'message' => (!is_null($msg) ? $msg : ""), $LOG = array('type' => 'LEVEL_STOP',
'logFile' => (!is_null($file) ? $file : ""), 'message' => (!is_null($msg) ? $msg : ''),
'logLine' => (!is_null($line) ? $line : ""), 'logFile' => (!is_null($file) ? $file : ''),
'context' => (!is_null($mod) ? $mod : ""), 'logLine' => (!is_null($line) ? $line : ''),
'runtime' => round(self::getRelativeTime(), 4)); 'context' => (!is_null($mod) ? $mod : ''),
'runtime' => round(self::getRelativeTime(), 4), );
self::$Logs[] = $LOG; self::$Logs[] = $LOG;
} }
/* =========================================OTHER METHODS==============================================================*/ /* =========================================OTHER METHODS==============================================================*/
/** /**
* Returns a string representation of an error * Returns a string representation of an error
* Turns a PHP error-constant (or integer) into a string representation. * Turns a PHP error-constant (or integer) into a string representation.
* *
* @access public * @param int $type PHP-constant errortype (e.g. E_NOTICE).
* @param int $type PHP-constant errortype (e.g. E_NOTICE). *
* @return string String representation * @return string String representation
*/ */
public static function getType($type) { public static function getType($type)
{
switch ($type) {
case E_ERROR:
return 'ERROR';
case E_WARNING:
return 'WARNING';
case E_PARSE:
return 'ERROR';
case E_NOTICE:
return 'WARNING';
case E_CORE_ERROR:
return 'ERROR';
case E_CORE_WARNING:
return 'WARNING';
case E_COMPILE_ERROR:
return 'ERROR';
case E_COMPILE_WARNING:
return 'WARNING';
case E_USER_ERROR:
return 'ERROR';
case E_USER_WARNING:
return 'WARNING';
case E_USER_NOTICE:
return 'WARNING';
case E_USER_DEPRECATED:
return 'WARNING';
case E_STRICT:
return 'ERROR';
case E_RECOVERABLE_ERROR:
return 'ERROR';
case E_DEPRECATED:
return 'WARNING';
}
switch ($type) return $type = 'Unknown error: '.$type;
{ }
case E_ERROR:
return "ERROR";
case E_WARNING:
return "WARNING";
case E_PARSE:
return "ERROR";
case E_NOTICE:
return "WARNING";
case E_CORE_ERROR:
return "ERROR";
case E_CORE_WARNING:
return "WARNING";
case E_COMPILE_ERROR:
return "ERROR";
case E_COMPILE_WARNING:
return "WARNING";
case E_USER_ERROR:
return "ERROR";
case E_USER_WARNING:
return "WARNING";
case E_USER_NOTICE:
return "WARNING";
case E_USER_DEPRECATED:
return "WARNING";
case E_STRICT:
return "ERROR";
case E_RECOVERABLE_ERROR:
return "ERROR";
case E_DEPRECATED:
return "WARNING";
}
return $type = 'Unknown error: '.$type;
}
/**
* Calls an HTTP error, sends it as a header, and loads a template if required to do so.
* @param integer $errno HTTP error code
* @param boolean $view true to view error on website
*/
public static function http_error($errno = 500, $view = true){
/**
* Calls an HTTP error, sends it as a header, and loads a template if required to do so.
*
* @param int $errno HTTP error code
* @param bool $view true to view error on website
*/
public static function http_error($errno = 500, $view = true)
{
$http_codes = array( $http_codes = array(
400 => 'Bad Request', 400 => 'Bad Request',
@ -432,58 +447,59 @@ class Logger {
506 => 'Variant Also Negotiates', 506 => 'Variant Also Negotiates',
509 => 'Bandwidth Limit Exceeded', 509 => 'Bandwidth Limit Exceeded',
510 => 'Not Extended', 510 => 'Not Extended',
511 => 'Network Authentication Required' 511 => 'Network Authentication Required',
); );
self::logError('HTTP-error '.$errno.' called'); self::logError('HTTP-error '.$errno.' called');
self::log('Sending header HTTP/1.1 '.$errno.' '.$http_codes[$errno]); self::log('Sending header HTTP/1.1 '.$errno.' '.$http_codes[$errno]);
header('HTTP/1.1 '.$errno.' '.$http_codes[$errno]); header('HTTP/1.1 '.$errno.' '.$http_codes[$errno]);
// Do we want the error-view with it? // Do we want the error-view with it?
if($view == false) if ($view == false) {
return; return;
}
// Load the view // Load the view
$view = 'errors/'.$errno; $view = 'errors/'.$errno;
self::log('Loading view '.$view); self::log('Loading view '.$view);
// Try and load the view, if impossible, load HTTP code instead. // Try and load the view, if impossible, load HTTP code instead.
try{ try {
Layout::view($view); Layout::view($view);
} catch(LayoutException $exception){ } catch (LayoutException $exception) {
// No error page could be found, just echo the result // No error page could be found, just echo the result
echo "<h1>$errno</h1><h3>".$http_codes[$errno]."</h3>"; echo "<h1>$errno</h1><h3>".$http_codes[$errno].'</h3>';
} }
} }
/** /**
* Enable error to screen logging * Enable error to screen logging.
* @access public */
*/ public static function enable()
public static function enable() { {
self::$print_to_screen = true; self::$print_to_screen = true;
} }
/** /**
* Disable error to screen logging * Disable error to screen logging.
* @access public */
*/ public static function disable()
public static function disable() { {
self::$print_to_screen = false; self::$print_to_screen = false;
} }
/** /**
* Get the relative time since the framework started. * Get the relative time since the framework started.
* *
* Used for debugging timings in FuzeWorks * Used for debugging timings in FuzeWorks
* @return int Time passed since FuzeWorks init *
*/ * @return int Time passed since FuzeWorks init
private static function getRelativeTime() { */
$startTime = STARTTIME; private static function getRelativeTime()
$time = microtime(true) - $startTime; {
return $time; $startTime = STARTTIME;
} $time = microtime(true) - $startTime;
return $time;
}
} }
?>

View File

@ -1,6 +1,6 @@
<?php <?php
/** /**
* FuzeWorks * FuzeWorks.
* *
* The FuzeWorks MVC PHP FrameWork * The FuzeWorks MVC PHP FrameWork
* *
@ -19,84 +19,93 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
* *
* @author TechFuze * @author TechFuze
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
* @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/) * @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/)
* @license http://opensource.org/licenses/GPL-3.0 GPLv3 License * @license http://opensource.org/licenses/GPL-3.0 GPLv3 License
* @link http://fuzeworks.techfuze.net *
* @since Version 0.0.1 * @link http://fuzeworks.techfuze.net
* @version Version 0.0.1 * @since Version 0.0.1
*
* @version Version 0.0.1
*/ */
namespace FuzeWorks; namespace FuzeWorks;
/** /**
* Models Class * Models Class.
* *
* Simple loader class for MVC Models. Typically loads models from Application/Models unless otherwise specified. * Simple loader class for MVC Models. Typically loads models from Application/Models unless otherwise specified.
* If a model is not found, it will load a DatabaseModel type which will analyze the database and can directly be used. * If a model is not found, it will load a DatabaseModel type which will analyze the database and can directly be used.
* @package net.techfuze.fuzeworks.core *
* @author Abel Hoogeveen <abel@techfuze.net> * @author Abel Hoogeveen <abel@techfuze.net>
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
*/ */
class Models { class Models
{
/** /**
* Array of all the loaded models * Array of all the loaded models.
*
* @var array * @var array
*/ */
private static $models_array = array(); private static $models_array = array();
/** /**
* Array of all the existing model types (classes) * Array of all the existing model types (classes).
*
* @var array * @var array
*/ */
private static $model_types = array(); private static $model_types = array();
/** /**
* Load a model. * Load a model.
* @param String $name Name of the model *
* @param String $directory Optional directory of the model * @param string $name Name of the model
* @return Object The Model object. * @param string $directory Optional directory of the model
*
* @return object The Model object.
*/ */
public static function loadModel($name, $directory = null){ public static function loadModel($name, $directory = null)
{
// Model load event // Model load event
$event = Events::fireEvent('modelLoadEvent', $name, $directory); $event = Events::fireEvent('modelLoadEvent', $name, $directory);
$directory = ($event->directory === null ? "Application/Models" : $event->directory); $directory = ($event->directory === null ? 'Application/Models' : $event->directory);
$name = ($event->model === null ? $name : $event->model); $name = ($event->model === null ? $name : $event->model);
$file = $directory.'/model.'.$name.'.php'; $file = $directory.'/model.'.$name.'.php';
if (isset(self::$model_types[$name])) { if (isset(self::$model_types[$name])) {
Logger::log('Loading Model: '.get_class(self::$model_types[$name]), get_class(self::$model_types[$name])); Logger::log('Loading Model: '.get_class(self::$model_types[$name]), get_class(self::$model_types[$name]));
self::$models_array[$name] = self::$model_types[$name]; self::$models_array[$name] = self::$model_types[$name];
} elseif (file_exists($file)){ } elseif (file_exists($file)) {
require_once($file); include_once $file;
$model = "\Application\Model\\" . ucfirst($name); $model = "\Application\Model\\".ucfirst($name);
Logger::log('Loading Model: '.$model, $model); Logger::log('Loading Model: '.$model, $model);
return self::$models_array[$name] = new $model(); return self::$models_array[$name] = new $model();
} else{ } else {
throw new ModelException("The requested model: \''.$name.'\' could not be found", 1); throw new ModelException("The requested model: \''.$name.'\' could not be found", 1);
} }
} }
/** /**
* Retrieve a model * Retrieve a model.
* @param String $name Name of the model *
* @return Object The Model object * @param string $name Name of the model
*
* @return object The Model object
*/ */
public static function get($name){ public static function get($name)
{
// Get the name // Get the name
$name = strtolower($name); $name = strtolower($name);
// Check if it already exists // Check if it already exists
if (isset(self::$models_array[$name])) { if (isset(self::$models_array[$name])) {
// Return if it does // Return if it does
return self::$models_array[$name]; return self::$models_array[$name];
} else { } else {
// If not, load and return afterwards // If not, load and return afterwards
return self::loadModel($name); return self::loadModel($name);
} }
} }
} }
?>

View File

@ -1,6 +1,6 @@
<?php <?php
/** /**
* FuzeWorks * FuzeWorks.
* *
* The FuzeWorks MVC PHP FrameWork * The FuzeWorks MVC PHP FrameWork
* *
@ -19,70 +19,80 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
* *
* @author TechFuze * @author TechFuze
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
* @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/) * @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/)
* @license http://opensource.org/licenses/GPL-3.0 GPLv3 License * @license http://opensource.org/licenses/GPL-3.0 GPLv3 License
* @link http://fuzeworks.techfuze.net *
* @since Version 0.0.1 * @link http://fuzeworks.techfuze.net
* @version Version 0.0.1 * @since Version 0.0.1
*
* @version Version 0.0.1
*/ */
namespace FuzeWorks; namespace FuzeWorks;
use \stdClass;
use stdClass;
/** /**
* Modules Class * Modules Class.
* @package net.techfuze.fuzeworks.core *
* @author Abel Hoogeveen <abel@techfuze.net> * @author Abel Hoogeveen <abel@techfuze.net>
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
*/ */
class Modules { class Modules
{
/** /**
* A register of all the existing module headers. * A register of all the existing module headers.
* *
* The module headers contain information required to loading the module * The module headers contain information required to loading the module
* @var Array *
* @var array
*/ */
private static $register; private static $register;
/** /**
* A register which holds all the module advertisements by key * A register which holds all the module advertisements by key.
*
* @var array * @var array
*/ */
private static $advertiseRegister = array(); private static $advertiseRegister = array();
/** /**
* An array of all the loaded modules * An array of all the loaded modules.
*
* @var array * @var array
*/ */
public static $modules = array(); public static $modules = array();
/** /**
* An array with the names of all modules that are loaded, and should not be loaded again * An array with the names of all modules that are loaded, and should not be loaded again.
* @access private *
* @var Array of module names * @var array of module names
*/ */
private static $loaded_modules = array(); private static $loaded_modules = array();
/** /**
* An array which holds the routes to module to load them quickly * An array which holds the routes to module to load them quickly.
* @access private *
* @var array * @var array
*/ */
private static $module_routes = array(); private static $module_routes = array();
/** /**
* Retrieves a module and returns it. * Retrieves a module and returns it.
* If a module is already loaded, it returns a reference to the loaded version * If a module is already loaded, it returns a reference to the loaded version.
* @param String $name Name of the module *
* @param string $name Name of the module
*
* @return \FuzeWorks\Module Module The module * @return \FuzeWorks\Module Module The module
*
* @throws \FuzeWorks\ModuleException * @throws \FuzeWorks\ModuleException
*/ */
public static function get($name) { public static function get($name)
{
// Where the modules are // Where the modules are
$path = "Modules/"; $path = 'Modules/';
// Check if the requested module is registered // Check if the requested module is registered
if (isset(self::$register[$name])) { if (isset(self::$register[$name])) {
@ -91,37 +101,40 @@ class Modules {
$cfg = (object) self::$register[$name]; $cfg = (object) self::$register[$name];
// Check if the module is disabled // Check if the module is disabled
if (isset($cfg->meta)) if (isset($cfg->meta)) {
throw new ModuleException("Could not load module. Module '".$name."' is not enabled", 1); throw new ModuleException("Could not load module. Module '".$name."' is not enabled", 1);
}
// Check if the module is already loaded. If so, only return a reference, if not, load the module // Check if the module is already loaded. If so, only return a reference, if not, load the module
if (in_array(strtolower($name), self::$loaded_modules)) { if (in_array(strtolower($name), self::$loaded_modules)) {
// return the link // return the link
$c = self::$modules[strtolower($cfg->module_name)]; $c = self::$modules[strtolower($cfg->module_name)];
return $c; return $c;
} else { } else {
// Load the module // Load the module
$file = $cfg->directory ."/". $cfg->module_file; $file = $cfg->directory.'/'.$cfg->module_file;
// Load the dependencies before the module loads // Load the dependencies before the module loads
$deps = (isset($cfg->dependencies) ? $cfg->dependencies : array()); $deps = (isset($cfg->dependencies) ? $cfg->dependencies : array());
for ($i=0; $i < count($deps); $i++) { for ($i = 0; $i < count($deps); ++$i) {
self::get($deps[$i]); self::get($deps[$i]);
} }
// Check if the file exists // Check if the file exists
if (file_exists($file)) { if (file_exists($file)) {
// And load it // And load it
require_once($file); include_once $file;
$class_name = $cfg->module_class; $class_name = $cfg->module_class;
$msg = "Loading Module '".ucfirst((isset($cfg->name) ? $cfg->name : $cfg->module_name)) . "'"; $msg = "Loading Module '".ucfirst((isset($cfg->name) ? $cfg->name : $cfg->module_name))."'";
$msg .= (isset($cfg->version) ? "; version: ".$cfg->version : ""); $msg .= (isset($cfg->version) ? '; version: '.$cfg->version : '');
$msg .= (isset($cfg->author) ? "; made by ".$cfg->author : ""); $msg .= (isset($cfg->author) ? '; made by '.$cfg->author : '');
$msg .= (isset($cfg->website) ? "; from ".$cfg->website: ""); $msg .= (isset($cfg->website) ? '; from '.$cfg->website : '');
Logger::log($msg); Logger::log($msg);
} else { } else {
// Throw Exception if the file does not exist // Throw Exception if the file does not exist
throw new ModuleException("Could not load module. Module '".$name."' class file was not found.", 1); throw new ModuleException("Could not load module. Module '".$name."' class file was not found.", 1);
return false; return false;
} }
@ -129,6 +142,7 @@ class Modules {
if (isset($cfg->abstract)) { if (isset($cfg->abstract)) {
if ($cfg->abstract) { if ($cfg->abstract) {
$CLASS = new stdClass(); $CLASS = new stdClass();
return self::$modules[strtolower($cfg->module_name)] = &$CLASS; return self::$modules[strtolower($cfg->module_name)] = &$CLASS;
} }
} }
@ -142,11 +156,13 @@ class Modules {
$CLASS::setModulePath($cfg->directory); $CLASS::setModulePath($cfg->directory);
} }
if (method_exists($CLASS, 'setModuleLinkName')) if (method_exists($CLASS, 'setModuleLinkName')) {
$CLASS::setModuleLinkName(strtolower($cfg->module_name)); $CLASS::setModuleLinkName(strtolower($cfg->module_name));
}
if (method_exists($CLASS, 'setModuleName')) if (method_exists($CLASS, 'setModuleName')) {
$CLASS::setModuleName($name); $CLASS::setModuleName($name);
}
// Send all advertisements // Send all advertisements
if (isset($cfg->listenFor)) { if (isset($cfg->listenFor)) {
@ -165,8 +181,8 @@ class Modules {
// Send the moduleConfig if possible // Send the moduleConfig if possible
if (method_exists($CLASS, 'setModuleConfig')) { if (method_exists($CLASS, 'setModuleConfig')) {
// Append the config file to the module CFG (accessable through $this->cfg) // Append the config file to the module CFG (accessable through $this->cfg)
if (file_exists($cfg->directory . "/" . "config.".strtolower($cfg->module_name).".php")) { if (file_exists($cfg->directory.'/'.'config.'.strtolower($cfg->module_name).'.php')) {
$data = (object) include($cfg->directory . "/" . "config.".strtolower($cfg->module_name).".php"); $data = (object) include $cfg->directory.'/'.'config.'.strtolower($cfg->module_name).'.php';
foreach ($data as $key => $value) { foreach ($data as $key => $value) {
$cfg->$key = $value; $cfg->$key = $value;
} }
@ -176,8 +192,9 @@ class Modules {
} }
// And finally check if it can be loaded // And finally check if it can be loaded
if (!method_exists($CLASS, 'onLoad')) if (!method_exists($CLASS, 'onLoad')) {
throw new ModuleException("Could not load module. Module '".$name."' does not have an onLoad() method", 1); throw new ModuleException("Could not load module. Module '".$name."' does not have an onLoad() method", 1);
}
// Prepare onLoad call // Prepare onLoad call
$args = func_get_args(); $args = func_get_args();
@ -201,14 +218,16 @@ class Modules {
} }
/** /**
* Set the value of a module config or moduleInfo.php * Set the value of a module config or moduleInfo.php.
* @param String $file File to edit *
* @param String $key Key to edit * @param string $file File to edit
* @param Mixed $value Value to set * @param string $key Key to edit
* @param mixed $value Value to set
*/ */
private static function setModuleValue($file, $key, $value) { private static function setModuleValue($file, $key, $value)
{
if (file_exists($file) && is_writable($file)) { if (file_exists($file) && is_writable($file)) {
$cfg = require($file); $cfg = include $file;
$cfg[$key] = $value; $cfg[$key] = $value;
$config = var_export($cfg, true); $config = var_export($cfg, true);
file_put_contents($file, "<?php return $config ;"); file_put_contents($file, "<?php return $config ;");
@ -216,26 +235,29 @@ class Modules {
} }
/** /**
* Add a module using a moduleInfo.php file * Add a module using a moduleInfo.php file.
*
* @param string Path to moduleInfo.php file
* *
* @param String Path to moduleInfo.php file
* @throws FuzeWorks\ModuleException * @throws FuzeWorks\ModuleException
*/ */
public static function addModule($moduleInfo_file) { public static function addModule($moduleInfo_file)
{
$file = $moduleInfo_file; $file = $moduleInfo_file;
$directory = dirname($file); $directory = dirname($file);
if (file_exists($file)) { if (file_exists($file)) {
$cfg = (object) require($file); $cfg = (object) include $file;
$cfg->directory = $directory; $cfg->directory = $directory;
// Define the module name // Define the module name
$name = ""; $name = '';
$name .= (!empty($cfg->author) ? strtolower($cfg->author)."/" : ""); $name .= (!empty($cfg->author) ? strtolower($cfg->author).'/' : '');
$name .= strtolower($cfg->module_name); $name .= strtolower($cfg->module_name);
Logger::log("Adding module: '".$name."'"); Logger::log("Adding module: '".$name."'");
if (isset(self::$register[$name])) { if (isset(self::$register[$name])) {
Logger::logError("Module '".$name."' can not be added. Module is already loaded"); Logger::logError("Module '".$name."' can not be added. Module is already loaded");
return false; return false;
} }
@ -251,7 +273,7 @@ class Modules {
$cfg2->module_name = $cfg->module_name; $cfg2->module_name = $cfg->module_name;
$cfg2->directory = $cfg->directory; $cfg2->directory = $cfg->directory;
$cfg2->meta = $cfg; $cfg2->meta = $cfg;
self::$register[$name] = (array)$cfg2; self::$register[$name] = (array) $cfg2;
Logger::log("[OFF] '".$name."'"); Logger::log("[OFF] '".$name."'");
} }
} else { } else {
@ -265,14 +287,15 @@ class Modules {
} }
/** /**
* Enables a module when it is disabled * Enables a module when it is disabled.
*
* @param string Module name
* @param bool true for permanent enable
* *
* @access public
* @param String Module name
* @param boolean true for permanent enable
* @throws FuzeWorks\ModuleException * @throws FuzeWorks\ModuleException
*/ */
public static function enableModule($name, $permanent = true) { public static function enableModule($name, $permanent = true)
{
if (isset(self::$register[$name])) { if (isset(self::$register[$name])) {
// Change the register // Change the register
$info = (object) self::$register[$name]; $info = (object) self::$register[$name];
@ -281,6 +304,7 @@ class Modules {
if (isset($info->enabled)) { if (isset($info->enabled)) {
if ($info->enabled) { if ($info->enabled) {
Logger::logWarning("Could not enable module '".$name."'. Module is already enabled."); Logger::logWarning("Could not enable module '".$name."'. Module is already enabled.");
return false; return false;
} }
} }
@ -288,13 +312,13 @@ class Modules {
// Otherwise move data from meta to the module config // Otherwise move data from meta to the module config
$info = $info->meta; $info = $info->meta;
$info->enabled = true; $info->enabled = true;
self::$register[$name] = (array)$info; self::$register[$name] = (array) $info;
Logger::log("Enabled module '".$name."'"); Logger::log("Enabled module '".$name."'");
// Enable it permanently if so desired // Enable it permanently if so desired
if ($permanent) { if ($permanent) {
$file = $info->directory . "/moduleInfo.php"; $file = $info->directory.'/moduleInfo.php';
self::setModuleValue($file, 'enabled', true); self::setModuleValue($file, 'enabled', true);
} }
@ -306,20 +330,22 @@ class Modules {
} }
/** /**
* Disableds a module when it is enabled * Disableds a module when it is enabled.
*
* @param string Module name
* @param bool true for permanent disable
* *
* @access public
* @param String Module name
* @param boolean true for permanent disable
* @throws FuzeWorks\ModuleException * @throws FuzeWorks\ModuleException
*/ */
public static function disableModule($name, $permanent = true) { public static function disableModule($name, $permanent = true)
{
if (isset(self::$register[$name])) { if (isset(self::$register[$name])) {
$info = (object) self::$register[$name]; $info = (object) self::$register[$name];
// Do nothing if it is already disabled // Do nothing if it is already disabled
if (isset($info->meta)) { if (isset($info->meta)) {
Logger::logWarning("Could not disable module '".$name."'. Module is already disabled."); Logger::logWarning("Could not disable module '".$name."'. Module is already disabled.");
return false; return false;
} }
@ -328,10 +354,10 @@ class Modules {
$disabled->directory = $info->directory; $disabled->directory = $info->directory;
$disabled->module_name = $info->module_name; $disabled->module_name = $info->module_name;
self::$register[$name] = (array)$disabled; self::$register[$name] = (array) $disabled;
Logger::log("Disabled module '".$name."'"); Logger::log("Disabled module '".$name."'");
if ($permanent) { if ($permanent) {
$file = $info->directory . "/moduleInfo.php"; $file = $info->directory.'/moduleInfo.php';
self::setModuleValue($file, 'enabled', false); self::setModuleValue($file, 'enabled', false);
} }
@ -343,20 +369,19 @@ class Modules {
} else { } else {
throw new ModuleException("Could not disable module '".$name."'. Module does not exist.", 1); throw new ModuleException("Could not disable module '".$name."'. Module does not exist.", 1);
} }
} }
/** /**
* Create a register with all the module headers from all the existing modules. * Create a register with all the module headers from all the existing modules.
* *
* Used to correctly load all modules * Used to correctly load all modules
* @return void
*/ */
public static function buildRegister() { public static function buildRegister()
Logger::newLevel("Loading Module Headers", 'Core'); {
Logger::newLevel('Loading Module Headers', 'Core');
// Get all the module directories // Get all the module directories
$dir = "Modules/"; $dir = 'Modules/';
$mod_dirs = array(); $mod_dirs = array();
$mod_dirs = array_values(array_diff(scandir($dir), array('..', '.'))); $mod_dirs = array_values(array_diff(scandir($dir), array('..', '.')));
@ -365,19 +390,19 @@ class Modules {
$event_register = array(); $event_register = array();
// Cycle through all module directories // Cycle through all module directories
for ($i=0; $i < count($mod_dirs); $i++) { for ($i = 0; $i < count($mod_dirs); ++$i) {
$mod_dir = $dir . $mod_dirs[$i] . "/"; $mod_dir = $dir.$mod_dirs[$i].'/';
// If a moduleInfo.php exists, load it // If a moduleInfo.php exists, load it
if (file_exists($mod_dir . "/moduleInfo.php")) { if (file_exists($mod_dir.'/moduleInfo.php')) {
// Load the configuration file // Load the configuration file
$cfg = (object) require($mod_dir . "/moduleInfo.php"); $cfg = (object) include $mod_dir.'/moduleInfo.php';
// Set enabled for now // Set enabled for now
$enabled = true; $enabled = true;
// Define the module name // Define the module name
$name = ""; $name = '';
$name .= (!empty($cfg->author) ? strtolower($cfg->author)."/" : ""); $name .= (!empty($cfg->author) ? strtolower($cfg->author).'/' : '');
$name .= strtolower($cfg->module_name); $name .= strtolower($cfg->module_name);
// Get the module directory // Get the module directory
@ -405,10 +430,11 @@ class Modules {
$register[$name] = (array) $cfg; $register[$name] = (array) $cfg;
// Log the name for enabled and disabled // Log the name for enabled and disabled
if (!$enabled) if (!$enabled) {
Logger::newLevel("[OFF] '".$name."'"); Logger::newLevel("[OFF] '".$name."'");
else } else {
Logger::newLevel("[ON] '".$name."'"); Logger::newLevel("[ON] '".$name."'");
}
// And possibly some aliases // And possibly some aliases
if (isset($cfg->aliases)) { if (isset($cfg->aliases)) {
@ -441,10 +467,11 @@ class Modules {
// Get the events and add them // Get the events and add them
foreach ($cfg->events as $event) { foreach ($cfg->events as $event) {
// First check if the event already exists, if so, append it // First check if the event already exists, if so, append it
if (isset($event_register[$event])) if (isset($event_register[$event])) {
$event_register[$event][] = $name; $event_register[$event][] = $name;
else } else {
$event_register[$event] = array($name); $event_register[$event] = array($name);
}
// Log the event // Log the event
Logger::Log('Event added: \''.$event.'\''); Logger::Log('Event added: \''.$event.'\'');
@ -456,7 +483,7 @@ class Modules {
// Cycle through advertisements // Cycle through advertisements
foreach ($cfg->advertise as $advertiseName => $advertiseData) { foreach ($cfg->advertise as $advertiseName => $advertiseData) {
// Log advertisement // Log advertisement
Logger::log('Advertisement added: \'' .$advertiseName. '\''); Logger::log('Advertisement added: \''.$advertiseName.'\'');
// Add to advertiseRegister // Add to advertiseRegister
self::$advertiseRegister[$advertiseName][$name] = $advertiseData; self::$advertiseRegister[$advertiseName][$name] = $advertiseData;
@ -464,7 +491,6 @@ class Modules {
} }
Logger::stopLevel(); Logger::stopLevel();
} else { } else {
// If no details are specified, create a basic mock module // If no details are specified, create a basic mock module
$name = $mod_dirs[$i]; $name = $mod_dirs[$i];
@ -472,14 +498,14 @@ class Modules {
// Build a default mock module config // Build a default mock module config
$mock = new stdClass(); $mock = new stdClass();
$mock->module_class = ucfirst($name); $mock->module_class = ucfirst($name);
$mock->module_file = 'class.'.strtolower($name).".php"; $mock->module_file = 'class.'.strtolower($name).'.php';
$mock->module_name = $name; $mock->module_name = $name;
$mock->dependencies = array(); $mock->dependencies = array();
$mock->versions = array(); $mock->versions = array();
$mock->directory = $mod_dir; $mock->directory = $mod_dir;
// Apply it // Apply it
$register[$name] = (array)$mock; $register[$name] = (array) $mock;
Logger::newLevel("[ON] '".$name."'"); Logger::newLevel("[ON] '".$name."'");
Logger::stopLevel(); Logger::stopLevel();
} }
@ -489,19 +515,18 @@ class Modules {
self::$register = $register; self::$register = $register;
Events::$register = $event_register; Events::$register = $event_register;
Logger::stopLevel(); Logger::stopLevel();
} }
/** /**
* The Module Callable * The Module Callable.
* *
* When a module listens for a specific routing path, this callable get's called. * When a module listens for a specific routing path, this callable get's called.
* After this the module can handle the request with the route() function in the module's root directory * After this the module can handle the request with the route() function in the module's root directory
* @access public *
* @param array Regex matches * @param array Regex matches
* @return void
*/ */
public static function moduleCallable($matches = array()){ public static function moduleCallable($matches = array())
{
// First detect what module is attached to this route // First detect what module is attached to this route
Logger::newLevel('Module callable called!'); Logger::newLevel('Module callable called!');
@ -517,13 +542,11 @@ class Modules {
unset($matches['route']); unset($matches['route']);
$mod->route($matches); $mod->route($matches);
} else { } else {
Logger::logError("Route did not match known module. Fatal error"); Logger::logError('Route did not match known module. Fatal error');
return Logger::http_error(500); return Logger::http_error(500);
} }
Logger::stopLevel(); Logger::stopLevel();
} }
} }
?>

View File

@ -1,6 +1,6 @@
<?php <?php
/** /**
* FuzeWorks * FuzeWorks.
* *
* The FuzeWorks MVC PHP FrameWork * The FuzeWorks MVC PHP FrameWork
* *
@ -19,20 +19,23 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
* *
* @author TechFuze * @author TechFuze
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
* @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/) * @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/)
* @license http://opensource.org/licenses/GPL-3.0 GPLv3 License * @license http://opensource.org/licenses/GPL-3.0 GPLv3 License
* @link http://fuzeworks.techfuze.net *
* @since Version 0.0.1 * @link http://fuzeworks.techfuze.net
* @version Version 0.0.1 * @since Version 0.0.1
*
* @version Version 0.0.1
*/ */
namespace FuzeWorks; namespace FuzeWorks;
use \Application\Init;
use Application\Init;
/** /**
* Class Router * Class Router.
* *
* This class handles the framework's routing. The router determines which system should be loaded and called. * This class handles the framework's routing. The router determines which system should be loaded and called.
* The overall structure of the routing is as follows: * The overall structure of the routing is as follows:
@ -75,42 +78,39 @@ use \Application\Init;
* @see Router::setPath * @see Router::setPath
* @see Router::route * @see Router::route
* *
* @package net.techfuze.fuzeworks.core * @author Abel Hoogeveen <abel@techfuze.net>
* @author Abel Hoogeveen <abel@techfuze.net> * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net)
*/ */
class Router { class Router
{
/** /**
* @var null|string The provided path * @var null|string The provided path
*/ */
private static $path = null; private static $path = null;
/** /**
* @var array Routes * @var array Routes
*/ */
private static $routes = array(); private static $routes = array();
/** /**
* @var null|mixed The callable * @var null|mixed The callable
*/ */
private static $callable = null; private static $callable = null;
/** /**
* @var null|array The extracted matches from the regex * @var null|array The extracted matches from the regex
*/ */
private static $matches = null; private static $matches = null;
/** /**
* The constructor adds the default route to the routing table * The constructor adds the default route to the routing table.
*/ */
public static function init(){ public static function init()
{
foreach(Config::get('routes') as $route => $callable){ foreach (Config::get('routes') as $route => $callable) {
if (is_int($route)) {
if(is_int($route)) { $route = $callable;
$route = $callable;
$callable = array('\FuzeWorks\Router', 'defaultCallable'); $callable = array('\FuzeWorks\Router', 'defaultCallable');
} }
@ -119,56 +119,60 @@ class Router {
} }
/** /**
* Returns the current routing path * Returns the current routing path.
* *
* @return bool|string * @return bool|string
*/ */
public static function getPath(){ public static function getPath()
{
return self::$path; return self::$path;
} }
/** /**
* Returns an array with all the routes * Returns an array with all the routes.
*
* @return array * @return array
*/ */
public static function getRoutes(){ public static function getRoutes()
{
return self::$routes; return self::$routes;
} }
/** /**
* Returns the currently loaded callable * Returns the currently loaded callable.
*
* @return null|callable * @return null|callable
*/ */
public static function getCallable(){ public static function getCallable()
{
return self::$callable; return self::$callable;
} }
/** /**
* Returns all the matches with the RegEx route * Returns all the matches with the RegEx route.
*
* @return null|array * @return null|array
*/ */
public static function getMatches() { public static function getMatches()
{
return self::$matches; return self::$matches;
} }
/** /**
* Set the current routing path * Set the current routing path.
* *
* @param string $path The routing path (e.g. a/b/c/d/e) * @param string $path The routing path (e.g. a/b/c/d/e)
*
* @return bool|string * @return bool|string
*/ */
public static function setPath($path){ public static function setPath($path)
{
// Fire the event to notify our modules // Fire the event to notify our modules
$event = Events::fireEvent('routerSetPathEvent', $path); $event = Events::fireEvent('routerSetPathEvent', $path);
// The event has been cancelled // The event has been cancelled
if($event->isCancelled()){ if ($event->isCancelled()) {
return false; return false;
} }
@ -176,18 +180,20 @@ class Router {
$path = preg_replace('@[/]+@', '/', $event->path); $path = preg_replace('@[/]+@', '/', $event->path);
// Remove first slash // Remove first slash
if(substr($path, 0, 1) == '/') if (substr($path, 0, 1) == '/') {
$path = substr($path, 1); $path = substr($path, 1);
}
// Remove trailing slash // Remove trailing slash
if(substr($path, -1, 1) == '/') if (substr($path, -1, 1) == '/') {
$path = substr($path, 0, strlen($path)-1); $path = substr($path, 0, strlen($path) - 1);
}
return self::$path = $path; return self::$path = $path;
} }
/** /**
* Add a route * Add a route.
* *
* The path will be checked before custom routes before the default route(/controller/function/param1/param2/etc) * The path will be checked before custom routes before the default route(/controller/function/param1/param2/etc)
* When the given RegEx matches the current routing-path, the callable will be called. * When the given RegEx matches the current routing-path, the callable will be called.
@ -227,27 +233,28 @@ class Router {
* You do not *have* to use named groups, but when you don't the arguments will be left NULL; and you will need to * You do not *have* to use named groups, but when you don't the arguments will be left NULL; and you will need to
* extract the information from the routing-path yourself. * extract the information from the routing-path yourself.
* *
* @param string $route This is a RegEx of the route, Every capture group will be a parameter * @param string $route This is a RegEx of the route, Every capture group will be a parameter
* @param callable $callable The callable to execute * @param callable $callable The callable to execute
* @param bool $prepend Whether or not to insert at the beginning of the routing table * @param bool $prepend Whether or not to insert at the beginning of the routing table
*/ */
public static function addRoute($route, $callable, $prepend = true){ public static function addRoute($route, $callable, $prepend = true)
{
if($prepend) if ($prepend) {
self::$routes = array($route => $callable) + self::$routes; self::$routes = array($route => $callable) + self::$routes;
else } else {
self::$routes[$route] = $callable; self::$routes[$route] = $callable;
}
Logger::log('Route added at '.($prepend ? 'top' : 'bottom').': "'.$route.'"'); Logger::log('Route added at '.($prepend ? 'top' : 'bottom').': "'.$route.'"');
} }
/** /**
* Removes a route from the array based on the given route * Removes a route from the array based on the given route.
* *
* @param $route string The route to remove * @param $route string The route to remove
*/ */
public static function removeRoute($route){ public static function removeRoute($route)
{
unset(self::$routes[$route]); unset(self::$routes[$route]);
Logger::log('Route removed: '.$route); Logger::log('Route removed: '.$route);
@ -258,7 +265,7 @@ class Router {
* *
* Determines what callable should be loaded and what data matches the route regex. * Determines what callable should be loaded and what data matches the route regex.
* *
* @param boolean $loadCallable Immediate load the callable when it's route matches * @param bool $loadCallable Immediate load the callable when it's route matches
*/ */
public static function route($loadCallable = true) public static function route($loadCallable = true)
{ {
@ -266,8 +273,7 @@ class Router {
$event = Events::fireEvent('routerRouteEvent', self::$routes, $loadCallable, self::$path); $event = Events::fireEvent('routerRouteEvent', self::$routes, $loadCallable, self::$path);
// The event has been cancelled // The event has been cancelled
if($event->isCancelled()){ if ($event->isCancelled()) {
return; return;
} }
@ -277,25 +283,25 @@ class Router {
//Check the custom routes //Check the custom routes
foreach ($routes as $r => $c) { foreach ($routes as $r => $c) {
//A custom route is found //A custom route is found
if(preg_match($r, $event->path, $matches)) { if (preg_match($r, $event->path, $matches)) {
Logger::log('Route matched: '.$r); Logger::log('Route matched: '.$r);
// Add the matches to the current class // Add the matches to the current class
self::$matches = $matches; self::$matches = $matches;
self::$callable = $c; self::$callable = $c;
if(!$loadCallable || !self::loadCallable($matches, $r)) if (!$loadCallable || !self::loadCallable($matches, $r)) {
break; break;
}
} }
} }
// Check if we found a callable anyway // Check if we found a callable anyway
if(self::$callable === null){ if (self::$callable === null) {
Logger::log('No routes found for given path: "'.$event->path.'"', E_WARNING); Logger::log('No routes found for given path: "'.$event->path.'"', E_WARNING);
Logger::http_error(404); Logger::http_error(404);
return; return;
} }
} }
@ -307,84 +313,88 @@ class Router {
* *
* Then the arguments get prepared and finally the callable is called. * Then the arguments get prepared and finally the callable is called.
* *
* @param array Preg matches with the routing path * @param array Preg matches with the routing path
* @param string The route that matched * @param string The route that matched
* @return boolean Whether or not the callable was satisfied *
* @return bool Whether or not the callable was satisfied
*/ */
public static function loadCallable($matches = array(), $route){ public static function loadCallable($matches = array(), $route)
{
Logger::newLevel('Loading callable'); Logger::newLevel('Loading callable');
// Fire the event to notify our modules // Fire the event to notify our modules
$event = Events::fireEvent('routerLoadCallableEvent', self::$callable, $matches, $route); $event = Events::fireEvent('routerLoadCallableEvent', self::$callable, $matches, $route);
// The event has been cancelled // The event has been cancelled
if($event->isCancelled()) if ($event->isCancelled()) {
return false; return false;
}
// Prepare the arguments and add the route // Prepare the arguments and add the route
$args = $event->matches; $args = $event->matches;
$args['route'] = $event->route; $args['route'] = $event->route;
if(!is_callable($event->callable)) if (!is_callable($event->callable)) {
if(isset(self::$callable['controller'])) { if (isset(self::$callable['controller'])) {
// Reset the arguments and fetch from custom callable
$args = array();
$args['controller'] = isset(self::$callable['controller']) ? self::$callable['controller'] : (isset($matches['controller']) ? $matches['controller'] : null);
$args['function'] = isset(self::$callable['function']) ? self::$callable['function'] : (isset($matches['function']) ? $matches['function'] : null);
$args['parameters'] = isset(self::$callable['parameters']) ? self::$callable['parameters'] : (isset($matches['parameters']) ? explode('/', $matches['parameters']) : null);
// Reset the arguments and fetch from custom callable self::$callable = array('\FuzeWorks\Router', 'defaultCallable');
$args = array(); } else {
$args['controller'] = isset(self::$callable['controller']) ? self::$callable['controller'] : (isset($matches['controller']) ? $matches['controller'] : null); Logger::log('The given callable is not callable!', E_ERROR);
$args['function'] = isset(self::$callable['function']) ? self::$callable['function'] : (isset($matches['function']) ? $matches['function'] : null); Logger::http_error(500);
$args['parameters'] = isset(self::$callable['parameters']) ? self::$callable['parameters'] : (isset($matches['parameters']) ? explode('/', $matches['parameters']) : null); Logger::stopLevel();
self::$callable = array('\FuzeWorks\Router', 'defaultCallable'); return true;
}else{ }
Logger::log('The given callable is not callable!', E_ERROR);
Logger::http_error(500);
Logger::stopLevel();
return true;
} }
// And log the input to the logger // And log the input to the logger
Logger::newLevel('Calling callable'); Logger::newLevel('Calling callable');
foreach ($args as $key => $value) { foreach ($args as $key => $value) {
Logger::log($key.": ".var_export($value,true).""); Logger::log($key.': '.var_export($value, true).'');
} }
Logger::stopLevel(); Logger::stopLevel();
$skip = call_user_func_array(self::$callable, array($args)) === false; $skip = call_user_func_array(self::$callable, array($args)) === false;
if($skip) if ($skip) {
Logger::log('Callable not satisfied, skipping to next callable'); Logger::log('Callable not satisfied, skipping to next callable');
}
Logger::stopLevel(); Logger::stopLevel();
return $skip; return $skip;
} }
/** /**
* The default callable * The default callable.
* *
* This callable will do the 'old skool' routing. It will load the controllers from the controller-directory * This callable will do the 'old skool' routing. It will load the controllers from the controller-directory
* in the application-directory. * in the application-directory.
*/ */
public static function defaultCallable($arguments = array()){ public static function defaultCallable($arguments = array())
{
Logger::log('Default callable called!'); Logger::log('Default callable called!');
$controller = empty($arguments['controller']) ? Config::get('main')->default_controller : $arguments['controller']; $controller = empty($arguments['controller']) ? Config::get('main')->default_controller : $arguments['controller'];
$function = empty($arguments['function']) ? Config::get('main')->default_function : $arguments['function']; $function = empty($arguments['function']) ? Config::get('main')->default_function : $arguments['function'];
$parameters = empty($arguments['parameters']) ? null : $arguments['parameters']; $parameters = empty($arguments['parameters']) ? null : $arguments['parameters'];
// Construct file paths and classes // Construct file paths and classes
$class = '\Application\Controller\\'.ucfirst($controller); $class = '\Application\Controller\\'.ucfirst($controller);
$file = 'Application/Controller/controller.'.$controller.'.php'; $file = 'Application/Controller/controller.'.$controller.'.php';
Logger::log('Loading controller '.$class.' from file: '.$file); Logger::log('Loading controller '.$class.' from file: '.$file);
// Check if the file exists // Check if the file exists
if(file_exists($file)){ if (file_exists($file)) {
if (!class_exists($class)) {
if(!class_exists($class)) include $file;
require $file; }
// Get the path the controller should know about // Get the path the controller should know about
$path = substr(self::getPath(), ($pos = strpos(self::getPath(), '/')) !== false ? $pos + 1 : 0); $path = substr(self::getPath(), ($pos = strpos(self::getPath(), '/')) !== false ? $pos + 1 : 0);
@ -398,22 +408,18 @@ class Router {
} }
// Check if method exists or if there is a caller function // Check if method exists or if there is a caller function
if(method_exists(self::$callable, $function) || method_exists(self::$callable, '__call')){ if (method_exists(self::$callable, $function) || method_exists(self::$callable, '__call')) {
// Execute the function on the controller // Execute the function on the controller
echo self::$callable->{$function}($parameters); echo self::$callable->{$function}($parameters);
}else{ } else {
// Function could not be found // Function could not be found
Logger::log('Could not find function '.$function.' on controller '.$class); Logger::log('Could not find function '.$function.' on controller '.$class);
Logger::http_error(404); Logger::http_error(404);
} }
}else{ } else {
// Controller could not be found // Controller could not be found
Logger::log('Could not find controller '.$class); Logger::log('Could not find controller '.$class);
Logger::http_error(404); Logger::http_error(404);
} }
} }
} }
?>

View File

@ -1,6 +1,6 @@
<?php <?php
/** /**
* FuzeWorks * FuzeWorks.
* *
* The FuzeWorks MVC PHP FrameWork * The FuzeWorks MVC PHP FrameWork
* *
@ -19,78 +19,80 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
* *
* @author TechFuze * @author TechFuze
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
* @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/) * @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/)
* @license http://opensource.org/licenses/GPL-3.0 GPLv3 License * @license http://opensource.org/licenses/GPL-3.0 GPLv3 License
* @link http://fuzeworks.techfuze.net *
* @since Version 0.0.1 * @link http://fuzeworks.techfuze.net
* @version Version 0.0.1 * @since Version 0.0.1
*
* @version Version 0.0.1
*/ */
namespace Module\Admin; namespace Module\Admin;
use \FuzeWorks\Module;
use FuzeWorks\Module;
/** /**
* Admin Module * Admin Module.
* *
* Admin panel module controller * Admin panel module controller
* @package net.techfuze.fuzeworks.admin *
* @author Abel Hoogeveen <abel@techfuze.net> * @author Abel Hoogeveen <abel@techfuze.net>
* @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
*/ */
class Main { class Main
use Module; {
use Module;
/** /**
* Loads the module and registers the events * Loads the module and registers the events.
* */
* @access public public function onLoad()
*/ {
public function onLoad() { include_once self::getModulePath().'/classes/class.layout_manager.php';
require_once(self::getModulePath() . "/classes/class.layout_manager.php"); include_once self::getModulePath().'/classes/class.admin_exception.php';
require_once(self::getModulePath() . "/classes/class.admin_exception.php"); include_once self::getModulePath().'/classes/class.theme_manager.php';
require_once(self::getModulePath() . "/classes/class.theme_manager.php"); include_once self::getModulePath().'/classes/class.advertise_fetcher.php';
require_once(self::getModulePath() . "/classes/class.advertise_fetcher.php"); include_once self::getModulePath().'/classes/class.page_loader.php';
require_once(self::getModulePath() . "/classes/class.page_loader.php"); include_once self::getModulePath().'/classes/class.page_data.php';
require_once(self::getModulePath() . "/classes/class.page_data.php"); include_once self::getModulePath().'/classes/class.page.php';
require_once(self::getModulePath() . "/classes/class.page.php"); include_once self::getModulePath().'/classes/class.page_list.php';
require_once(self::getModulePath() . "/classes/class.page_list.php"); include_once self::getModulePath().'/classes/class.page_router_interface.php';
require_once(self::getModulePath() . "/classes/class.page_router_interface.php"); include_once self::getModulePath().'/classes/class.page_interface.php';
require_once(self::getModulePath() . "/classes/class.page_interface.php"); include_once self::getModulePath().'/classes/class.admin_router.php';
require_once(self::getModulePath() . "/classes/class.admin_router.php"); }
}
/** /**
* Gets called when the path matches the regex of this module. * Gets called when the path matches the regex of this module.
* @access public *
* @param array Regex matches * @param array Regex matches
* @return void */
*/ public function route($matches = array())
public function route($matches = array()) { {
// First create a pageList based on the advertisements // First create a pageList based on the advertisements
$advertisements = self::getAdvertisements('admin'); $advertisements = self::getAdvertisements('admin');
if (!is_array($advertisements)) if (!is_array($advertisements)) {
throw new AdminException("Could not load advertised modules. Malformed object retrieved", 1); throw new AdminException('Could not load advertised modules. Malformed object retrieved', 1);
}
$pageList = AdvertiseFetcher::getPageList($advertisements); $pageList = AdvertiseFetcher::getPageList($advertisements);
// After that, load the authenticator and check if user is logged in // After that, load the authenticator and check if user is logged in
// @TODO IMPLEMENT // @TODO IMPLEMENT
// After that, load the theme that is set // After that, load the theme that is set
LayoutManager::setPageList($pageList); LayoutManager::setPageList($pageList);
LayoutManager::setMatches($matches); LayoutManager::setMatches($matches);
$html = LayoutManager::loadPanel(); $html = LayoutManager::loadPanel();
// And print it // And print it
echo $html; echo $html;
} }
public function getAdminRouter() {
return new AdminRouter();
}
public function getAdminRouter()
{
return new AdminRouter();
}
} }
?>

View File

@ -1,6 +1,6 @@
<?php <?php
/** /**
* FuzeWorks * FuzeWorks.
* *
* The FuzeWorks MVC PHP FrameWork * The FuzeWorks MVC PHP FrameWork
* *
@ -19,23 +19,25 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
* *
* @author TechFuze * @author TechFuze
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
* @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/) * @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/)
* @license http://opensource.org/licenses/GPL-3.0 GPLv3 License * @license http://opensource.org/licenses/GPL-3.0 GPLv3 License
* @link http://fuzeworks.techfuze.net *
* @since Version 0.0.1 * @link http://fuzeworks.techfuze.net
* @version Version 0.0.1 * @since Version 0.0.1
*
* @version Version 0.0.1
*/ */
namespace Module\Admin; namespace Module\Admin;
/** /**
* Class Exception * Class Exception.
* @package net.techfuze.fuzeworks.admin *
* @author Abel Hoogeveen <abel@techfuze.net> * @author Abel Hoogeveen <abel@techfuze.net>
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
*/ */
class AdminException extends \Exception{} class AdminException extends \Exception
{
?> }

View File

@ -1,6 +1,6 @@
<?php <?php
/** /**
* FuzeWorks * FuzeWorks.
* *
* The FuzeWorks MVC PHP FrameWork * The FuzeWorks MVC PHP FrameWork
* *
@ -19,38 +19,40 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
* *
* @author TechFuze * @author TechFuze
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
* @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/) * @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/)
* @license http://opensource.org/licenses/GPL-3.0 GPLv3 License * @license http://opensource.org/licenses/GPL-3.0 GPLv3 License
* @link http://fuzeworks.techfuze.net *
* @since Version 0.0.1 * @link http://fuzeworks.techfuze.net
* @version Version 0.0.1 * @since Version 0.0.1
*
* @version Version 0.0.1
*/ */
namespace Module\Admin; namespace Module\Admin;
class AdminRouter implements PageRouterInterface { class AdminRouter implements PageRouterInterface
{
private $pageObject;
private $pageObject; public function route()
{
//echo $pagePath;
}
public function route() { /**
//echo $pagePath; * Import the page object from the Admin Module.
} *
* @param Page $pageObject Page object
/** */
* Import the page object from the Admin Module public function importPage($pageObject)
* @param Page $pageObject Page object {
* @return void $this->pageObject = $pageObject;
*/ }
public function importPage($pageObject) {
$this->pageObject = $pageObject;
}
public function getPage() {
return $this->pageObject;
}
public function getPage()
{
return $this->pageObject;
}
} }
?>

View File

@ -1,6 +1,6 @@
<?php <?php
/** /**
* FuzeWorks * FuzeWorks.
* *
* The FuzeWorks MVC PHP FrameWork * The FuzeWorks MVC PHP FrameWork
* *
@ -19,79 +19,86 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
* *
* @author TechFuze * @author TechFuze
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
* @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/) * @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/)
* @license http://opensource.org/licenses/GPL-3.0 GPLv3 License * @license http://opensource.org/licenses/GPL-3.0 GPLv3 License
* @link http://fuzeworks.techfuze.net *
* @since Version 0.0.1 * @link http://fuzeworks.techfuze.net
* @version Version 0.0.1 * @since Version 0.0.1
*
* @version Version 0.0.1
*/ */
namespace Module\Admin; namespace Module\Admin;
use \FuzeWorks\Logger;
class AdvertiseFetcher { use FuzeWorks\Logger;
/** class AdvertiseFetcher
* Create a pageList using the advertisements from the admin module {
* @param array $advertisements The advertisement repository /**
* @throws AdminException On fatal and/or missing data * Create a pageList using the advertisements from the admin module.
* @return PageList An object oriented page list with details *
* @todo Implement Unit Test * @param array $advertisements The advertisement repository
*/ *
public static function getPageList($advertisements) { * @throws AdminException On fatal and/or missing data
// Prepare a pageList *
Logger::newLevel('Generating PageList'); * @return PageList An object oriented page list with details
$pageList = new PageList(); *
* @todo Implement Unit Test
*/
public static function getPageList($advertisements)
{
// Prepare a pageList
Logger::newLevel('Generating PageList');
$pageList = new PageList();
// First get the modules // First get the modules
foreach ($advertisements as $module => $data) { foreach ($advertisements as $module => $data) {
// Apple regular data // Apple regular data
$identifier = (isset($data['identifier']) ? $data['identifier'] : null); $identifier = (isset($data['identifier']) ? $data['identifier'] : null);
$pages = (isset($data['pages']) ? $data['pages'] : null); $pages = (isset($data['pages']) ? $data['pages'] : null);
// Check if everything is set, if not shout out in terror // Check if everything is set, if not shout out in terror
if (is_null($identifier) || is_null($pages)) if (is_null($identifier) || is_null($pages)) {
throw new AdminException("Incomplete data for module '".$module."'", 1); throw new AdminException("Incomplete data for module '".$module."'", 1);
}
// And then the pages // And then the pages
foreach ($pages as $pageData) { foreach ($pages as $pageData) {
// Create page variable and add module and identifier // Create page variable and add module and identifier
$page = new PageData(); $page = new PageData();
$page->setModule($module); $page->setModule($module);
$page->setIdentifier($identifier); $page->setIdentifier($identifier);
// First the required data for every page // First the required data for every page
$page_path = (isset($pageData['page_path']) ? $pageData['page_path'] : null); $page_path = (isset($pageData['page_path']) ? $pageData['page_path'] : null);
$name = (isset($pageData['name']) ? $pageData['name'] : null); $name = (isset($pageData['name']) ? $pageData['name'] : null);
// And throw errors if non-existent // And throw errors if non-existent
if (is_null($page_path) || is_null($name)) if (is_null($page_path) || is_null($name)) {
throw new AdminException("Incomplete data for module '".$module."'", 1); throw new AdminException("Incomplete data for module '".$module."'", 1);
}
// And set those values // And set those values
$page->setPagePath($page_path); $page->setPagePath($page_path);
$page->setName($name); $page->setName($name);
$unique_identifier = $identifier . "/" . $page_path; $unique_identifier = $identifier.'/'.$page_path;
Logger::log("Adding page '".$name."' on '".$unique_identifier."'"); Logger::log("Adding page '".$name."' on '".$unique_identifier."'");
// And at last for the optional values
$page->setIcon((isset($pageData['icon']) ? $pageData['icon'] : ''));
$page->setPermissionGroups((isset($pageData['permissionGroups']) ? $pageData['permissionGroups'] : array()));
$page->setPriority((isset($pageData['priority']) ? $pageData['priority'] : 1));
// And finally add the page
$pageList->addPage($page, $unique_identifier);
}
}
// And at last for the optional values // And finally return the pageList\
$page->setIcon( (isset($pageData['icon']) ? $pageData['icon'] : '') ); Logger::stopLevel();
$page->setPermissionGroups( (isset($pageData['permissionGroups']) ? $pageData['permissionGroups'] : array()) );
$page->setPriority( (isset($pageData['priority']) ? $pageData['priority'] : 1) );
// And finally add the page return $pageList;
$pageList->addPage($page, $unique_identifier); }
}
}
// And finally return the pageList\
Logger::stopLevel();
return $pageList;
}
} }
?>

View File

@ -1,6 +1,6 @@
<?php <?php
/** /**
* FuzeWorks * FuzeWorks.
* *
* The FuzeWorks MVC PHP FrameWork * The FuzeWorks MVC PHP FrameWork
* *
@ -19,93 +19,103 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
* *
* @author TechFuze * @author TechFuze
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
* @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/) * @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/)
* @license http://opensource.org/licenses/GPL-3.0 GPLv3 License * @license http://opensource.org/licenses/GPL-3.0 GPLv3 License
* @link http://fuzeworks.techfuze.net *
* @since Version 0.0.1 * @link http://fuzeworks.techfuze.net
* @version Version 0.0.1 * @since Version 0.0.1
*
* @version Version 0.0.1
*/ */
namespace Module\Admin; namespace Module\Admin;
use \FuzeWorks\Layout;
use \FuzeWorks\Config;
class LayoutManager { use FuzeWorks\Layout;
use FuzeWorks\Config;
private static $pageList; class LayoutManager
private static $matches; {
private static $pageList;
private static $matches;
/** /**
* Load the panel of this admin interface * Load the panel of this admin interface.
* @throws AdminException *
* @return string HTML * @throws AdminException
*/ *
public static function loadPanel() { * @return string HTML
// First check if the pageList is set and valid */
if (is_null(self::$pageList)) public static function loadPanel()
throw new AdminException("Can not load panel. PageList is not set", 1); {
// First check if the pageList is set and valid
if (is_null(self::$pageList)) {
throw new AdminException('Can not load panel. PageList is not set', 1);
}
// Load the theme // Load the theme
ThemeManager::loadTheme(); ThemeManager::loadTheme();
// Set the PageLoader variables // Set the PageLoader variables
PageLoader::setPageList(self::$pageList); PageLoader::setPageList(self::$pageList);
// Get the page we are trying to load // Get the page we are trying to load
PageLoader::loadPage(self::$matches); PageLoader::loadPage(self::$matches);
$html = PageLoader::getHtml(); $html = PageLoader::getHtml();
$activePage = PageLoader::getActivePage(); $activePage = PageLoader::getActivePage();
// And add the pageList // And add the pageList
Layout::assign('pageList', self::$pageList); Layout::assign('pageList', self::$pageList);
Layout::assign('activePage', $activePage); Layout::assign('activePage', $activePage);
Layout::assign('pageHTML', $html); Layout::assign('pageHTML', $html);
// And add more basic variables // And add more basic variables
foreach (self::getVariables() as $key => $value) { foreach (self::getVariables() as $key => $value) {
Layout::assign($key, $value); Layout::assign($key, $value);
} }
// And load the file // And load the file
return Layout::get('panel'); return Layout::get('panel');
} }
public static function loadPanelAPI() { public static function loadPanelAPI()
{
}
} public static function loadLogin()
{
}
public static function loadLogin() { public static function loadLoginAPI()
{
}
} /**
* Set the pageList.
*
* @param PageList $pageList PageList
*/
public static function setPageList($pageList)
{
self::$pageList = $pageList;
}
public static function loadLoginAPI() { public static function setMatches($matches)
{
self::$matches = $matches;
}
} /**
* Get all the basic variables required for every template.
/** *
* Set the pageList * @return array with settings
* @param PageList $pageList PageList */
*/ private static function getVariables()
public static function setPageList($pageList) { {
self::$pageList = $pageList; $vars = array();
} $vars['adminURL'] = Config::get('main')->SITE_URL.'admin/';
public static function setMatches($matches) {
self::$matches = $matches;
}
/**
* Get all the basic variables required for every template
* @return array with settings
*/
private static function getVariables() {
$vars = array();
$vars['adminURL'] = Config::get('main')->SITE_URL . "admin/";
return $vars;
}
return $vars;
}
} }
?>

View File

@ -1,6 +1,6 @@
<?php <?php
/** /**
* FuzeWorks * FuzeWorks.
* *
* The FuzeWorks MVC PHP FrameWork * The FuzeWorks MVC PHP FrameWork
* *
@ -19,24 +19,26 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
* *
* @author TechFuze * @author TechFuze
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
* @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/) * @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/)
* @license http://opensource.org/licenses/GPL-3.0 GPLv3 License * @license http://opensource.org/licenses/GPL-3.0 GPLv3 License
* @link http://fuzeworks.techfuze.net *
* @since Version 0.0.1 * @link http://fuzeworks.techfuze.net
* @version Version 0.0.1 * @since Version 0.0.1
*
* @version Version 0.0.1
*/ */
namespace Module\Admin; namespace Module\Admin;
class Page { class Page
{
private $pagePath; private $pagePath;
private $subPath = array(); private $subPath = array();
private $html; private $html;
private $title; private $title;
private $breadcrumbs = array(); private $breadcrumbs = array();
/** /**
* Gets the value of pagePath. * Gets the value of pagePath.
@ -158,5 +160,3 @@ class Page {
return $this; return $this;
} }
} }
?>

View File

@ -1,6 +1,6 @@
<?php <?php
/** /**
* FuzeWorks * FuzeWorks.
* *
* The FuzeWorks MVC PHP FrameWork * The FuzeWorks MVC PHP FrameWork
* *
@ -19,26 +19,28 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
* *
* @author TechFuze * @author TechFuze
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
* @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/) * @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/)
* @license http://opensource.org/licenses/GPL-3.0 GPLv3 License * @license http://opensource.org/licenses/GPL-3.0 GPLv3 License
* @link http://fuzeworks.techfuze.net *
* @since Version 0.0.1 * @link http://fuzeworks.techfuze.net
* @version Version 0.0.1 * @since Version 0.0.1
*
* @version Version 0.0.1
*/ */
namespace Module\Admin; namespace Module\Admin;
class PageData { class PageData
{
public $module; public $module;
public $identifier; public $identifier;
public $page_path; public $page_path;
public $icon; public $icon;
public $permissionGroups = array(); public $permissionGroups = array();
public $name; public $name;
public $priority; public $priority;
/** /**
* Gets the value of module. * Gets the value of module.
@ -208,5 +210,3 @@ class PageData {
return $this; return $this;
} }
} }
?>

View File

@ -1,6 +1,6 @@
<?php <?php
/** /**
* FuzeWorks * FuzeWorks.
* *
* The FuzeWorks MVC PHP FrameWork * The FuzeWorks MVC PHP FrameWork
* *
@ -19,20 +19,22 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
* *
* @author TechFuze * @author TechFuze
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
* @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/) * @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/)
* @license http://opensource.org/licenses/GPL-3.0 GPLv3 License * @license http://opensource.org/licenses/GPL-3.0 GPLv3 License
* @link http://fuzeworks.techfuze.net *
* @since Version 0.0.1 * @link http://fuzeworks.techfuze.net
* @version Version 0.0.1 * @since Version 0.0.1
*
* @version Version 0.0.1
*/ */
namespace Module\Admin; namespace Module\Admin;
class PageList { class PageList
{
public $pages = array(); public $pages = array();
/** /**
* Gets the value of pages. * Gets the value of pages.
@ -45,23 +47,24 @@ class PageList {
} }
/** /**
* Retrieve a page * Retrieve a page.
* @param string $unique_identifier Unique name for the page *
* @return PageData PageData Object * @param string $unique_identifier Unique name for the page
*
* @return PageData PageData Object
*/ */
public function getPage($unique_identifier) { public function getPage($unique_identifier)
{
return $this->pages[$unique_identifier]; return $this->pages[$unique_identifier];
} }
/** /**
* Add a page to the array * Add a page to the array.
* @param PageData $page PageData Object
* *
* @return void * @param PageData $page PageData Object
*/ */
public function addPage($page, $unique_identifier) { public function addPage($page, $unique_identifier)
$this->pages[$unique_identifier] = $page; {
$this->pages[$unique_identifier] = $page;
} }
} }
?>

View File

@ -1,6 +1,6 @@
<?php <?php
/** /**
* FuzeWorks * FuzeWorks.
* *
* The FuzeWorks MVC PHP FrameWork * The FuzeWorks MVC PHP FrameWork
* *
@ -19,126 +19,140 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
* *
* @author TechFuze * @author TechFuze
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
* @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/) * @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/)
* @license http://opensource.org/licenses/GPL-3.0 GPLv3 License * @license http://opensource.org/licenses/GPL-3.0 GPLv3 License
* @link http://fuzeworks.techfuze.net *
* @since Version 0.0.1 * @link http://fuzeworks.techfuze.net
* @version Version 0.0.1 * @since Version 0.0.1
*
* @version Version 0.0.1
*/ */
namespace Module\Admin; namespace Module\Admin;
use \FuzeWorks\Logger;
use \FuzeWorks\Layout;
use \FuzeWorks\Modules;
class PageLoader { use FuzeWorks\Logger;
use FuzeWorks\Layout;
use FuzeWorks\Modules;
private static $pageList; class PageLoader
private static $activePage; {
private static $html; private static $pageList;
private static $breadcrumbs = array(); private static $activePage;
private static $title; private static $html;
private static $breadcrumbs = array();
private static $title;
/** /**
* Set the pageList * Set the pageList.
* @param PageList $pageList PageList *
*/ * @param PageList $pageList PageList
public static function setPageList($pageList) { */
self::$pageList = $pageList; public static function setPageList($pageList)
} {
self::$pageList = $pageList;
}
public static function loadPage($matches) { public static function loadPage($matches)
// First check if any data is given at all {
Logger::newLevel("Retrieving page from module"); // First check if any data is given at all
if (!isset($matches['identifier']) && !isset($matches['page'])) { Logger::newLevel('Retrieving page from module');
// If nothing is provided, load the dashboard if (!isset($matches['identifier']) && !isset($matches['page'])) {
Logger::log("No input retrieved. Loading dashboard"); // If nothing is provided, load the dashboard
return self::dashboard(); Logger::log('No input retrieved. Loading dashboard');
} elseif (!isset($matches['identifier']) || !isset($matches['page'])) {
// If incomplete data is provided, load a 404
Logger::log("Invalid input retrieved. Loading 404 not found page");
return self::error404();
}
// If enough data is provided, try and load a page return self::dashboard();
Logger::log("Input received. Attempting to find page"); } elseif (!isset($matches['identifier']) || !isset($matches['page'])) {
$unique_identifier = $matches['identifier'] . '/' . $matches['page']; // If incomplete data is provided, load a 404
if (isset(self::$pageList->pages[$unique_identifier])) { Logger::log('Invalid input retrieved. Loading 404 not found page');
// Page found, start loading process
$page = self::$pageList->getPage($unique_identifier);
// Load the designated module return self::error404();
$module = Modules::get($page->getModule()); }
// Check if it implements the PageRouterInterface // If enough data is provided, try and load a page
if (method_exists($module, 'getAdminRouter')) { Logger::log('Input received. Attempting to find page');
$router = $module->getAdminRouter(); $unique_identifier = $matches['identifier'].'/'.$matches['page'];
if (isset(self::$pageList->pages[$unique_identifier])) {
// Page found, start loading process
$page = self::$pageList->getPage($unique_identifier);
// Then check if the router is valid, if not, return 500 // Load the designated module
if (!$router instanceof PageRouterInterface) { $module = Modules::get($page->getModule());
Logger::logError("Could not load '".$unique_identifier."' on module '".$page->getModule()."'. ".get_class($router)." does not implement \Module\Admin\PageRouterInterface");
return self::error500();
}
// Route the request into the module // Check if it implements the PageRouterInterface
Logger::log("Input valid and module loaded. Attempting to route request"); if (method_exists($module, 'getAdminRouter')) {
$router = $module->getAdminRouter();
// Generating page object // Then check if the router is valid, if not, return 500
$pageObject = new Page(); if (!$router instanceof PageRouterInterface) {
$pageObject->setPagePath($matches['page']); Logger::logError("Could not load '".$unique_identifier."' on module '".$page->getModule()."'. ".get_class($router)." does not implement \Module\Admin\PageRouterInterface");
$pageObject->setSubPath( (isset($matches['subdata']) ? $matches['subdata'] : null) );
// And send it return self::error500();
$router->importPage($pageObject); }
$router->route();
// And retrieve it // Route the request into the module
$pageObject = $router->getPage(); Logger::log('Input valid and module loaded. Attempting to route request');
// And retrieve some data // Generating page object
self::$html = $pageObject->getHtml(); $pageObject = new Page();
// $html = $pageObject->getHtml(); $pageObject->setPagePath($matches['page']);
$pageObject->setSubPath((isset($matches['subdata']) ? $matches['subdata'] : null));
Logger::stopLevel(); // And send it
return ''; $router->importPage($pageObject);
} else { $router->route();
// Error, router does not exist
Logger::logError("Could not load '".$unique_identifier."' on module '".$page->getModule()."'. ".get_class($module)." does not implement method getAdminRouter()");
Logger::stopLevel();
return self::error500();
}
}
Logger::log("Matching page was not found. Loading 404 not found page"); // And retrieve it
Logger::stopLevel(); $pageObject = $router->getPage();
return self::error404();
// And retrieve some data
self::$html = $pageObject->getHtml();
// $html = $pageObject->getHtml();
} Logger::stopLevel();
public static function getHtml() { return '';
return self::$html; } else {
} // Error, router does not exist
Logger::logError("Could not load '".$unique_identifier."' on module '".$page->getModule()."'. ".get_class($module).' does not implement method getAdminRouter()');
Logger::stopLevel();
public static function getActivePage() { return self::error500();
return 'fuzeadmin/testPage'; }
} }
public static function dashboard() { Logger::log('Matching page was not found. Loading 404 not found page');
Logger::stopLevel();
} return self::error404();
}
public static function error404() { public static function getHtml()
Logger::http_error(404, false); {
return Layout::get('404'); return self::$html;
} }
public static function error500() { public static function getActivePage()
Logger::http_error(500, false); {
return Layout::get('500'); return 'fuzeadmin/testPage';
} }
public static function dashboard()
{
}
public static function error404()
{
Logger::http_error(404, false);
return Layout::get('404');
}
public static function error500()
{
Logger::http_error(500, false);
return Layout::get('500');
}
} }
?>

View File

@ -1,6 +1,6 @@
<?php <?php
/** /**
* FuzeWorks * FuzeWorks.
* *
* The FuzeWorks MVC PHP FrameWork * The FuzeWorks MVC PHP FrameWork
* *
@ -19,22 +19,21 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
* *
* @author TechFuze * @author TechFuze
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
* @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/) * @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/)
* @license http://opensource.org/licenses/GPL-3.0 GPLv3 License * @license http://opensource.org/licenses/GPL-3.0 GPLv3 License
* @link http://fuzeworks.techfuze.net *
* @since Version 0.0.1 * @link http://fuzeworks.techfuze.net
* @version Version 0.0.1 * @since Version 0.0.1
*
* @version Version 0.0.1
*/ */
namespace Module\Admin; namespace Module\Admin;
interface PageRouterInterface { interface PageRouterInterface
{
public function importPage($pageObject); public function importPage($pageObject);
public function getPage(); public function getPage();
} }
?>

View File

@ -1,6 +1,6 @@
<?php <?php
/** /**
* FuzeWorks * FuzeWorks.
* *
* The FuzeWorks MVC PHP FrameWork * The FuzeWorks MVC PHP FrameWork
* *
@ -19,36 +19,38 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
* *
* @author TechFuze * @author TechFuze
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
* @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/) * @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/)
* @license http://opensource.org/licenses/GPL-3.0 GPLv3 License * @license http://opensource.org/licenses/GPL-3.0 GPLv3 License
* @link http://fuzeworks.techfuze.net *
* @since Version 0.0.1 * @link http://fuzeworks.techfuze.net
* @version Version 0.0.1 * @since Version 0.0.1
*
* @version Version 0.0.1
*/ */
namespace Module\Admin; namespace Module\Admin;
use \FuzeWorks\Layout;
use \FuzeWorks\Logger;
class ThemeManager { use FuzeWorks\Layout;
private static $themeDir = 'views/adminlte2.1/'; class ThemeManager
{
private static $themeDir = 'views/adminlte2.1/';
public static function loadTheme($theme = null) { public static function loadTheme($theme = null)
self::$themeDir = Main::getModulePath() . 'themes/adminlte2.1/'; {
Layout::setDirectory(self::$themeDir); self::$themeDir = Main::getModulePath().'themes/adminlte2.1/';
} Layout::setDirectory(self::$themeDir);
}
public static function getDirectory() {
// First check if the theme is actually loaded
if (empty(self::$themeDir))
throw new AdminException("Could not load panel. Theme not loaded", 1);
// And then return the theme Directory
return self::$themeDir;
}
public static function getDirectory()
{
// First check if the theme is actually loaded
if (empty(self::$themeDir)) {
throw new AdminException('Could not load panel. Theme not loaded', 1);
}
// And then return the theme Directory
return self::$themeDir;
}
} }
?>

View File

@ -1,6 +1,6 @@
<?php <?php
/** /**
* FuzeWorks * FuzeWorks.
* *
* The FuzeWorks MVC PHP FrameWork * The FuzeWorks MVC PHP FrameWork
* *
@ -19,33 +19,35 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
* *
* @author TechFuze * @author TechFuze
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
* @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/) * @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/)
* @license http://opensource.org/licenses/GPL-3.0 GPLv3 License * @license http://opensource.org/licenses/GPL-3.0 GPLv3 License
* @link http://fuzeworks.techfuze.net *
* @since Version 0.0.1 * @link http://fuzeworks.techfuze.net
* @version Version 0.0.1 * @since Version 0.0.1
*
* @version Version 0.0.1
*/ */
return array( return array(
'module_class' => 'Module\Admin\Main', 'module_class' => 'Module\Admin\Main',
'module_file' => 'class.main.php', 'module_file' => 'class.main.php',
'module_name' => 'Admin', 'module_name' => 'Admin',
'abstract' => false, 'abstract' => false,
'aliases' => array(), 'aliases' => array(),
'dependencies' => array(), 'dependencies' => array(),
'events' => array(), 'events' => array(),
'routes' => array('/^admin(|\/(?P<identifier>.*?)(|\/(?<page>.*?)(|\/(?P<subdata>.*?))))$/'), 'routes' => array('/^admin(|\/(?P<identifier>.*?)(|\/(?<page>.*?)(|\/(?P<subdata>.*?))))$/'),
'advertise' => array('admin' => array( 'identifier' => 'fuzeadmin', 'pages' => array( array( 'name' => 'TEST', 'page_path' => 'testPage', 'icon' => 'fa-plane')) )), 'advertise' => array('admin' => array('identifier' => 'fuzeadmin', 'pages' => array(array('name' => 'TEST', 'page_path' => 'testPage', 'icon' => 'fa-plane')))),
'listenFor' => array('admin'), 'listenFor' => array('admin'),
'name' => 'FuzeWorks Admin Panel', 'name' => 'FuzeWorks Admin Panel',
'description' => 'Control Panel for FuzeWorks Modules and FrameWork', 'description' => 'Control Panel for FuzeWorks Modules and FrameWork',
'author' => 'core', 'author' => 'core',
'version' => '1.0.0', 'version' => '1.0.0',
'website' => 'http://fuzeworks.techfuze.net/', 'website' => 'http://fuzeworks.techfuze.net/',
'date_created' => '13-01-2016', 'date_created' => '13-01-2016',
'date_updated' => '17-01-2016', 'date_updated' => '17-01-2016',
'enabled' => true 'enabled' => true,
); );

View File

@ -7,18 +7,18 @@
<!-- Tell the browser to be responsive to screen width --> <!-- Tell the browser to be responsive to screen width -->
<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport"> <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
<!-- Bootstrap 3.3.5 --> <!-- Bootstrap 3.3.5 -->
<link rel="stylesheet" href="<?php echo($vars['viewDir']); ?>/assets/bootstrap/css/bootstrap.min.css"> <link rel="stylesheet" href="<?php echo $vars['viewDir']; ?>/assets/bootstrap/css/bootstrap.min.css">
<!-- Font Awesome --> <!-- Font Awesome -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
<!-- Ionicons --> <!-- Ionicons -->
<link rel="stylesheet" href="https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css"> <link rel="stylesheet" href="https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css">
<!-- Theme style --> <!-- Theme style -->
<link rel="stylesheet" href="<?php echo($vars['viewDir']); ?>/assets/dist/css/AdminLTE.min.css"> <link rel="stylesheet" href="<?php echo $vars['viewDir']; ?>/assets/dist/css/AdminLTE.min.css">
<!-- AdminLTE Skins. We have chosen the skin-blue for this starter <!-- AdminLTE Skins. We have chosen the skin-blue for this starter
page. However, you can choose any other skin. Make sure you page. However, you can choose any other skin. Make sure you
apply the skin class to the body tag so the changes take effect. apply the skin class to the body tag so the changes take effect.
--> -->
<link rel="stylesheet" href="<?php echo($vars['viewDir']); ?>/assets/dist/css/skins/skin-blue.min.css"> <link rel="stylesheet" href="<?php echo $vars['viewDir']; ?>/assets/dist/css/skins/skin-blue.min.css">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
@ -131,7 +131,7 @@
<!-- Sidebar Menu --> <!-- Sidebar Menu -->
<ul class="sidebar-menu"> <ul class="sidebar-menu">
<li class="header">Navigate</li> <li class="header">Navigate</li>
<?php include('view.sidebar.php'); ?> <?php require 'view.sidebar.php'; ?>
</ul><!-- /.sidebar-menu --> </ul><!-- /.sidebar-menu -->
</section> </section>
<!-- /.sidebar --> <!-- /.sidebar -->
@ -153,7 +153,7 @@
<!-- Main content --> <!-- Main content -->
<section class="content"> <section class="content">
<?php echo($vars['pageHTML']); ?> <?php echo $vars['pageHTML']; ?>
<!-- Your Page Content Here --> <!-- Your Page Content Here -->
</section><!-- /.content --> </section><!-- /.content -->
@ -236,14 +236,14 @@
<!-- REQUIRED JS SCRIPTS --> <!-- REQUIRED JS SCRIPTS -->
<!-- jQuery 2.1.4 --> <!-- jQuery 2.1.4 -->
<script src="<?php echo($vars['viewDir']); ?>/assets/plugins/jQuery/jQuery-2.1.4.min.js"></script> <script src="<?php echo $vars['viewDir']; ?>/assets/plugins/jQuery/jQuery-2.1.4.min.js"></script>
<!-- Bootstrap 3.3.5 --> <!-- Bootstrap 3.3.5 -->
<script src="<?php echo($vars['viewDir']); ?>/assets/bootstrap/js/bootstrap.min.js"></script> <script src="<?php echo $vars['viewDir']; ?>/assets/bootstrap/js/bootstrap.min.js"></script>
<!-- AdminLTE App --> <!-- AdminLTE App -->
<script src="<?php echo($vars['viewDir']); ?>/assets/dist/js/app.min.js"></script> <script src="<?php echo $vars['viewDir']; ?>/assets/dist/js/app.min.js"></script>
<!-- SlimScroll --> <!-- SlimScroll -->
<script src="<?php echo($vars['viewDir']); ?>/assets/plugins/slimScroll/jquery.slimscroll.min.js"></script> <script src="<?php echo $vars['viewDir']; ?>/assets/plugins/slimScroll/jquery.slimscroll.min.js"></script>
<!-- Optionally, you can add Slimscroll and FastClick plugins. <!-- Optionally, you can add Slimscroll and FastClick plugins.
Both of these plugins are recommended to enhance the Both of these plugins are recommended to enhance the

View File

@ -4,10 +4,7 @@
$pageList = $vars['pageList']; $pageList = $vars['pageList'];
// The cycle through all and print the sidebar links // The cycle through all and print the sidebar links
foreach ($pageList->getPages() as $page) { foreach ($pageList->getPages() as $page) {
echo("<li name='sidebar:".$page->getIdentifier()."/".$page->getPagePath()."'><a href='".$vars['adminURL']. $page->getIdentifier()."/".$page->getPagePath()."'> echo "<li name='sidebar:".$page->getIdentifier().'/'.$page->getPagePath()."'><a href='".$vars['adminURL'].$page->getIdentifier().'/'.$page->getPagePath()."'>
<i class='".($page->getIcon() == '' ? '' : 'fa ' . $page->getIcon())."'></i> <span>".$page->getName()."</span></a></li>"); <i class='".($page->getIcon() == '' ? '' : 'fa '.$page->getIcon())."'></i> <span>".$page->getName().'</span></a></li>';
} }
?>

View File

@ -1,6 +1,6 @@
<?php <?php
/** /**
* FuzeWorks * FuzeWorks.
* *
* The FuzeWorks MVC PHP FrameWork * The FuzeWorks MVC PHP FrameWork
* *
@ -19,34 +19,39 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
* *
* @author TechFuze * @author TechFuze
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
* @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/) * @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/)
* @license http://opensource.org/licenses/GPL-3.0 GPLv3 License * @license http://opensource.org/licenses/GPL-3.0 GPLv3 License
* @link http://fuzeworks.techfuze.net *
* @since Version 0.0.1 * @link http://fuzeworks.techfuze.net
* @version Version 0.0.1 * @since Version 0.0.1
*
* @version Version 0.0.1
*/ */
namespace Module\Api; namespace Module\Api;
use \FuzeWorks\Module;
use FuzeWorks\Module;
/** /**
* Loading class for multiple API types * Loading class for multiple API types.
* *
* Currently loads a REST API class which controllers can extend so they provide a standardized API * Currently loads a REST API class which controllers can extend so they provide a standardized API
* @package net.techfuze.fuzeworks.core *
* @author Abel Hoogeveen <abel@techfuze.net> * @author Abel Hoogeveen <abel@techfuze.net>
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
*/ */
class Main { class Main
use Module; {
/** use Module;
* Gets loaded upon module initialization /**
* * Gets loaded upon module initialization.
* Loads all the API types *
*/ * Loads all the API types
public function onLoad() { */
require_once(self::getModulePath() . "/class.rest.php"); public function onLoad()
{
include_once self::getModulePath().'/class.rest.php';
} }
} }

View File

@ -1,6 +1,6 @@
<?php <?php
/** /**
* FuzeWorks * FuzeWorks.
* *
* The FuzeWorks MVC PHP FrameWork * The FuzeWorks MVC PHP FrameWork
* *
@ -19,73 +19,76 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
* *
* @author TechFuze * @author TechFuze
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
* @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/) * @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/)
* @license http://opensource.org/licenses/GPL-3.0 GPLv3 License * @license http://opensource.org/licenses/GPL-3.0 GPLv3 License
* @link http://fuzeworks.techfuze.net *
* @since Version 0.0.1 * @link http://fuzeworks.techfuze.net
* @version Version 0.0.1 * @since Version 0.0.1
*
* @version Version 0.0.1
*/ */
namespace Module\Api; namespace Module\Api;
use \FuzeWorks\Module;
use \FuzeWorks\Layout; use FuzeWorks\Layout;
/** /**
* RestAPI class for creating API's out of modules or contrllers * RestAPI class for creating API's out of modules or contrllers.
* *
* Extend a Controller with this class, and be sure to return the data from methods of your controller. * Extend a Controller with this class, and be sure to return the data from methods of your controller.
* This data will be parsed by this class and returned as valid JSON data. * This data will be parsed by this class and returned as valid JSON data.
* The necessity of API keys can be configured in the controller by settings $this->requireApiKey = false; * The necessity of API keys can be configured in the controller by settings $this->requireApiKey = false;
* @package net.techfuze.fuzeworks.core *
* @author Abel Hoogeveen <abel@techfuze.net> * @author Abel Hoogeveen <abel@techfuze.net>
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
*/ */
abstract class RestAPI abstract class RestAPI
{ {
/** /**
* Property: method * Property: method
* The HTTP method this request was made in, either GET, POST, PUT or DELETE * The HTTP method this request was made in, either GET, POST, PUT or DELETE.
*/ */
protected $method = ''; protected $method = '';
/** /**
* Property: endpoint * Property: endpoint
* The Model requested in the URI. eg: /files * The Model requested in the URI. eg: /files.
*/ */
protected $endpoint = ''; protected $endpoint = '';
/** /**
* Property: verb * Property: verb
* An optional additional descriptor about the endpoint, used for things that can * An optional additional descriptor about the endpoint, used for things that can
* not be handled by the basic methods. eg: /files/process * not be handled by the basic methods. eg: /files/process.
*/ */
protected $verb = ''; protected $verb = '';
/** /**
* Property: args * Property: args
* Any additional URI components after the endpoint and verb have been removed, in our * Any additional URI components after the endpoint and verb have been removed, in our
* case, an integer ID for the resource. eg: /<endpoint>/<verb>/<arg0>/<arg1> * case, an integer ID for the resource. eg: /<endpoint>/<verb>/<arg0>/<arg1>
* or /<endpoint>/<arg0> * or /<endpoint>/<arg0>.
*/ */
protected $args = Array(); protected $args = array();
/** /**
* Property: file * Property: file
* Stores the input of the PUT request * Stores the input of the PUT request.
*/ */
protected $file = Null; protected $file = null;
/** /**
* Whether API authentication is needed before interacting with the API * Whether API authentication is needed before interacting with the API.
*/ */
protected $requireApiKey = true; protected $requireApiKey = true;
/** /**
* Constructor: __construct * Constructor: __construct
* Allow for CORS, assemble and pre-process the data * Allow for CORS, assemble and pre-process the data.
*/ */
public function __construct($request) { public function __construct($request)
header("Access-Control-Allow-Orgin: *"); {
header("Access-Control-Allow-Methods: *"); header('Access-Control-Allow-Orgin: *');
header("Content-Type: application/json"); header('Access-Control-Allow-Methods: *');
header('Content-Type: application/json');
// Return layout data as string // Return layout data as string
Layout::setEngine('JSON'); Layout::setEngine('JSON');
@ -101,28 +104,28 @@ abstract class RestAPI
if ($this->method == 'POST' && array_key_exists('HTTP_X_HTTP_METHOD', $_SERVER)) { if ($this->method == 'POST' && array_key_exists('HTTP_X_HTTP_METHOD', $_SERVER)) {
if ($_SERVER['HTTP_X_HTTP_METHOD'] == 'DELETE') { if ($_SERVER['HTTP_X_HTTP_METHOD'] == 'DELETE') {
$this->method = 'DELETE'; $this->method = 'DELETE';
} else if ($_SERVER['HTTP_X_HTTP_METHOD'] == 'PUT') { } elseif ($_SERVER['HTTP_X_HTTP_METHOD'] == 'PUT') {
$this->method = 'PUT'; $this->method = 'PUT';
} else { } else {
throw new Exception("Unexpected Header"); throw new Exception('Unexpected Header');
} }
} }
switch($this->method) { switch ($this->method) {
case 'DELETE': case 'DELETE':
case 'POST': case 'POST':
$this->request = $this->_cleanInputs($_POST); $this->request = $this->_cleanInputs($_POST);
break; break;
case 'GET': case 'GET':
$this->request = $this->_cleanInputs($_GET); $this->request = $this->_cleanInputs($_GET);
break; break;
case 'PUT': case 'PUT':
$this->request = $this->_cleanInputs($_GET); $this->request = $this->_cleanInputs($_GET);
$this->file = file_get_contents("php://input"); $this->file = file_get_contents('php://input');
break; break;
default: default:
$this->_response('Invalid Method', 405); $this->_response('Invalid Method', 405);
break; break;
} }
// And afterwards process the data // And afterwards process the data
@ -134,23 +137,29 @@ abstract class RestAPI
} }
/** /**
* Process an API request when retrieving * Process an API request when retrieving.
* @return String JSON encoded response *
* @return string JSON encoded response
*/ */
public function processAPI() { public function processAPI()
{
if (method_exists($this, $this->endpoint)) { if (method_exists($this, $this->endpoint)) {
return $this->_response($this->{$this->endpoint}($this->args)); return $this->_response($this->{$this->endpoint}($this->args));
} }
return $this->_response("No Endpoint: $this->endpoint", 404); return $this->_response("No Endpoint: $this->endpoint", 404);
} }
private function _response($data, $status = 200) { private function _response($data, $status = 200)
header("HTTP/1.1 " . $status . " " . $this->_requestStatus($status)); {
header('HTTP/1.1 '.$status.' '.$this->_requestStatus($status));
return json_encode($data); return json_encode($data);
} }
private function _cleanInputs($data) { private function _cleanInputs($data)
$clean_input = Array(); {
$clean_input = array();
if (is_array($data)) { if (is_array($data)) {
foreach ($data as $k => $v) { foreach ($data as $k => $v) {
$clean_input[$k] = $this->_cleanInputs($v); $clean_input[$k] = $this->_cleanInputs($v);
@ -158,16 +167,19 @@ abstract class RestAPI
} else { } else {
$clean_input = trim(strip_tags($data)); $clean_input = trim(strip_tags($data));
} }
return $clean_input; return $clean_input;
} }
private function _requestStatus($code) { private function _requestStatus($code)
$status = array( {
$status = array(
200 => 'OK', 200 => 'OK',
404 => 'Not Found', 404 => 'Not Found',
405 => 'Method Not Allowed', 405 => 'Method Not Allowed',
500 => 'Internal Server Error', 500 => 'Internal Server Error',
); );
return ($status[$code])?$status[$code]:$status[500];
return ($status[$code]) ? $status[$code] : $status[500];
} }
} }

View File

@ -1,6 +1,6 @@
<?php <?php
/** /**
* FuzeWorks * FuzeWorks.
* *
* The FuzeWorks MVC PHP FrameWork * The FuzeWorks MVC PHP FrameWork
* *
@ -19,35 +19,37 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
* *
* @author TechFuze * @author TechFuze
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
* @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/) * @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/)
* @license http://opensource.org/licenses/GPL-3.0 GPLv3 License * @license http://opensource.org/licenses/GPL-3.0 GPLv3 License
* @link http://fuzeworks.techfuze.net *
* @since Version 0.0.1 * @link http://fuzeworks.techfuze.net
* @version Version 0.0.1 * @since Version 0.0.1
*
* @version Version 0.0.1
*/ */
return array( return array(
'module_class' => 'Module\Api\Main', 'module_class' => 'Module\Api\Main',
'module_file' => 'class.main.php', 'module_file' => 'class.main.php',
'module_name' => 'Api', 'module_name' => 'Api',
'abstract' => false, 'abstract' => false,
'dependencies' => array(), 'dependencies' => array(),
'events' => array(), 'events' => array(),
'sections' => array(), 'sections' => array(),
'aliases' => array(), 'aliases' => array(),
'name' => 'FuzeWorks Api Module', 'name' => 'FuzeWorks Api Module',
'description' => 'A Controller server for multiple types of API\'s like REST and SOAP', 'description' => 'A Controller server for multiple types of API\'s like REST and SOAP',
'author' => 'core', 'author' => 'core',
'version' => '1.0.0', 'version' => '1.0.0',
'website' => 'http://fuzeworks.techfuze.net/', 'website' => 'http://fuzeworks.techfuze.net/',
'date_created' => '03-05-2015', 'date_created' => '03-05-2015',
'date_updated' => '06-09-2015', 'date_updated' => '06-09-2015',
'enabled' => true, 'enabled' => true,
); );

View File

@ -1,6 +1,6 @@
<?php <?php
/** /**
* FuzeWorks * FuzeWorks.
* *
* The FuzeWorks MVC PHP FrameWork * The FuzeWorks MVC PHP FrameWork
* *
@ -19,138 +19,149 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
* *
* @author TechFuze * @author TechFuze
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
* @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/) * @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/)
* @license http://opensource.org/licenses/GPL-3.0 GPLv3 License * @license http://opensource.org/licenses/GPL-3.0 GPLv3 License
* @link http://fuzeworks.techfuze.net *
* @since Version 0.0.1 * @link http://fuzeworks.techfuze.net
* @version Version 0.0.1 * @since Version 0.0.1
*
* @version Version 0.0.1
*/ */
namespace Module\Database; namespace Module\Database;
use \FuzeWorks\Module;
use \FuzeWorks\Config; use FuzeWorks\Module;
use \FuzeWorks\Logger; use FuzeWorks\Config;
use \FuzeWorks\Events; use FuzeWorks\Logger;
use \FuzeWorks\EventPriority; use FuzeWorks\Events;
use \PDO; use FuzeWorks\EventPriority;
use \FuzeWorks\DatabaseException; use PDO;
use FuzeWorks\DatabaseException;
/** /**
* Database Class * Database Class.
* *
* This class is a wrapper for PDO. * This class is a wrapper for PDO.
* *
* @package net.techfuze.fuzeworks.database * @author Abel Hoogeveen <abel@techfuze.net>
* @author Abel Hoogeveen <abel@techfuze.net> * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net)
*/ */
class Main { class Main
use Module; {
use Module;
/** /**
* The default database connection * The default database connection.
* @access private *
* @var PDO Class * @var PDO Class
*/ */
private $DBH; private $DBH;
public $prefix; public $prefix;
public function onLoad() { public function onLoad()
Config::$dbActive = true; {
Events::addListener(array($this, 'shutdown'), 'coreShutdownEvent', EventPriority::NORMAL); Config::$dbActive = true;
} Events::addListener(array($this, 'shutdown'), 'coreShutdownEvent', EventPriority::NORMAL);
}
/** /**
* Connect to a database * Connect to a database.
* @access public *
* @param StdObject Config, like the database config in Application/Config * @param StdObject Config, like the database config in Application/Config
*/ */
public function connect($config = null) { public function connect($config = null)
// If nothing is given, connect to database from the main config, otherwise use the served configuration {
if (is_null($config)) { // If nothing is given, connect to database from the main config, otherwise use the served configuration
$db = Config::get('database'); if (is_null($config)) {
} else { $db = Config::get('database');
$db = $config;
}
if (empty($db->type) || empty($db->host)) {
throw (new DatabaseException('Database is not configured!'));
}
// Get the DSN for popular types of databases or a custom DSN
switch (strtolower($db->type)) {
case 'mysql':
$dsn = "mysql:host=".$db->host.";";
$dsn .= (!empty($db->database) ? "dbname=".$db->database.";" : "");
break;
case 'custom':
$dsn = $db->dsn;
break;
}
try {
Logger::logInfo("Connecting to '".$dsn."'", "Database");
// And create the connection
$this->DBH = new PDO($dsn, $db->username, $db->password, (isset($db->options) ? $db->options : null));
$this->DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Logger::logInfo("Connected to database", "Database");
// And set the prefix
$this->prefix = $db->prefix;
} catch (Exception $e) {
throw (new DatabaseException('Could not connect to the database: "'. $e->getMessage() . '"'));
}
}
public function shutdown() {
Logger::log("Closing open database connections");
$this->DBH = null;
}
public function getPrefix() {
if (!$this->is_active()) {
$this->connect();
}
return $this->prefix;
}
public function is_active() {
if($this->DBH === null){
return false;
} else { } else {
return true; $db = $config;
} }
}
public function __call($name, $params) { if (empty($db->type) || empty($db->host)) {
if ($this->is_active()) { throw (new DatabaseException('Database is not configured!'));
return call_user_func_array(array($this->DBH, $name), $params); }
} else {
$this->connect();
return call_user_func_array(array($this->DBH, $name), $params);
}
}
public function __get($name) { // Get the DSN for popular types of databases or a custom DSN
if ($this->is_active()) { switch (strtolower($db->type)) {
return $this->DBH->$name; case 'mysql':
} else { $dsn = 'mysql:host='.$db->host.';';
$this->connect(); $dsn .= (!empty($db->database) ? 'dbname='.$db->database.';' : '');
return $this->DBH->$name; break;
} case 'custom':
} $dsn = $db->dsn;
break;
}
public function __set($name, $value) { try {
if ($this->is_active()) { Logger::logInfo("Connecting to '".$dsn."'", 'Database');
$this->DBH->$name = $value; // And create the connection
} else { $this->DBH = new PDO($dsn, $db->username, $db->password, (isset($db->options) ? $db->options : null));
$this->connect(); $this->DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->DBH->$name = $value; Logger::logInfo('Connected to database', 'Database');
}
} // And set the prefix
$this->prefix = $db->prefix;
} catch (Exception $e) {
throw (new DatabaseException('Could not connect to the database: "'.$e->getMessage().'"'));
}
}
public function shutdown()
{
Logger::log('Closing open database connections');
$this->DBH = null;
}
public function getPrefix()
{
if (!$this->is_active()) {
$this->connect();
}
return $this->prefix;
}
public function is_active()
{
if ($this->DBH === null) {
return false;
} else {
return true;
}
}
public function __call($name, $params)
{
if ($this->is_active()) {
return call_user_func_array(array($this->DBH, $name), $params);
} else {
$this->connect();
return call_user_func_array(array($this->DBH, $name), $params);
}
}
public function __get($name)
{
if ($this->is_active()) {
return $this->DBH->$name;
} else {
$this->connect();
return $this->DBH->$name;
}
}
public function __set($name, $value)
{
if ($this->is_active()) {
$this->DBH->$name = $value;
} else {
$this->connect();
$this->DBH->$name = $value;
}
}
} }
?>

View File

@ -1,6 +1,6 @@
<?php <?php
/** /**
* FuzeWorks * FuzeWorks.
* *
* The FuzeWorks MVC PHP FrameWork * The FuzeWorks MVC PHP FrameWork
* *
@ -19,35 +19,37 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
* *
* @author TechFuze * @author TechFuze
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
* @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/) * @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/)
* @license http://opensource.org/licenses/GPL-3.0 GPLv3 License * @license http://opensource.org/licenses/GPL-3.0 GPLv3 License
* @link http://fuzeworks.techfuze.net *
* @since Version 0.0.1 * @link http://fuzeworks.techfuze.net
* @version Version 0.0.1 * @since Version 0.0.1
*
* @version Version 0.0.1
*/ */
return array( return array(
'module_class' => 'Module\Database\Main', 'module_class' => 'Module\Database\Main',
'module_file' => 'class.main.php', 'module_file' => 'class.main.php',
'module_name' => 'Database', 'module_name' => 'Database',
'abstract' => false, 'abstract' => false,
'dependencies' => array(), 'dependencies' => array(),
'events' => array(), 'events' => array(),
'sections' => array(), 'sections' => array(),
'aliases' => array(), 'aliases' => array(),
'name' => 'FuzeWorks Database Module', 'name' => 'FuzeWorks Database Module',
'description' => 'PDO Wrapper class for FuzeWorks', 'description' => 'PDO Wrapper class for FuzeWorks',
'author' => 'core', 'author' => 'core',
'version' => '1.0.0', 'version' => '1.0.0',
'website' => 'http://fuzeworks.techfuze.net/', 'website' => 'http://fuzeworks.techfuze.net/',
'date_created' => '30-04-2015', 'date_created' => '30-04-2015',
'date_updated' => '30-04-2015', 'date_updated' => '30-04-2015',
'enabled' => true, 'enabled' => true,
); );

View File

@ -1,6 +1,6 @@
<?php <?php
/** /**
* FuzeWorks * FuzeWorks.
* *
* The FuzeWorks MVC PHP FrameWork * The FuzeWorks MVC PHP FrameWork
* *
@ -19,50 +19,54 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
* *
* @author TechFuze * @author TechFuze
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
* @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/) * @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/)
* @license http://opensource.org/licenses/GPL-3.0 GPLv3 License * @license http://opensource.org/licenses/GPL-3.0 GPLv3 License
* @link http://fuzeworks.techfuze.net *
* @since Version 0.0.1 * @link http://fuzeworks.techfuze.net
* @version Version 0.0.1 * @since Version 0.0.1
*
* @version Version 0.0.1
*/ */
namespace Module\DatabaseUtils; namespace Module\DatabaseUtils;
use \FuzeWorks\Module;
use \FuzeWorks\Modules; use FuzeWorks\Module;
use \FuzeWorks\Bus; use FuzeWorks\Modules;
use \FuzeWorks\ModelServer; use FuzeWorks\ModelServer;
use \FuzeWorks\DatabaseException; use FuzeWorks\DatabaseException;
use \FuzeWorks\Config; use FuzeWorks\Config;
use \FuzeWorks\Logger; use FuzeWorks\Logger;
use \PDOException; use PDOException;
/** /**
* Main class of the database utilities and model providers * Main class of the database utilities and model providers.
* @package net.techfuze.fuzeworks.databaseutils *
* @author Abel Hoogeveen <abel@techfuze.net> * @author Abel Hoogeveen <abel@techfuze.net>
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
*/ */
class Main implements ModelServer { class Main implements ModelServer
use Module; {
use Module;
public $fields = array(); public $fields = array();
public $primary = 'id'; public $primary = 'id';
public $table = ''; public $table = '';
public function onLoad() { public function onLoad()
require_once(self::getModulePath() . '/class.query.php'); {
include_once self::getModulePath().'/class.query.php';
} }
public function giveModel($type) { public function giveModel($type)
return new Model(); {
return new Model();
} }
} }
/** /**
* Class Model * Class Model.
* *
* Models provide an easy connection to database tables. Each table requires its own model. You don't need to worry about your queries or syntax anymore, because * Models provide an easy connection to database tables. Each table requires its own model. You don't need to worry about your queries or syntax anymore, because
* models will handle queries and error handling. Because of this, you can freely change your database infrastructure without fear of needing to change your * models will handle queries and error handling. Because of this, you can freely change your database infrastructure without fear of needing to change your
@ -71,142 +75,152 @@ class Main implements ModelServer {
* Models also allow custom methods to be created on them. You can use those methods to create specific operations or joins and then use the newly created method * Models also allow custom methods to be created on them. You can use those methods to create specific operations or joins and then use the newly created method
* everywhere in your project. The code is at one place, the usages all over your project. Isn't that great? * everywhere in your project. The code is at one place, the usages all over your project. Isn't that great?
* *
* @package net.techfuze.fuzeworks.databaseutils * @author GOScripting
* @author GOScripting * @copyright Copyright (c) 2014 - 2015, GOScripting B.V. (http://goscripting.com)
* @copyright Copyright (c) 2014 - 2015, GOScripting B.V. (http://goscripting.com) * @license http://opensource.org/licenses/GPL-3.0 GPLv3 License
* @license http://opensource.org/licenses/GPL-3.0 GPLv3 License *
* @link http://goframework.net * @link http://goframework.net
*/ */
class Model { class Model
{
/**
* @var string The name of the database table
*/
public $table = '';
/** /**
* @var string The name of the database table * Traditional query interface.
*/ *
public $table = ''; * @param string $query
* @param null $binds
*
* @return mixed returns fetched rows if available, otherwise returns number of affected rows
*
* @throws DatabaseException
*/
public function query($query, $binds = null)
{
if (Config::get('database')->debug) {
Logger::log('Manuel Query: '.$query, 'Database Model');
}
/** try {
* Traditional query interface $sth = Modules::get('core/database')->prepare($query);
* if ($binds === null) {
* @param string $query $sth->execute();
* @param null $binds } else {
* @return mixed returns fetched rows if available, otherwise returns number of affected rows $sth->execute($binds);
* @throws DatabaseException }
*/ } catch (PDOException $e) {
public function query($query, $binds = null){ throw new DatabaseException('Could not execute SQL-query due PDO-exception '.$e->getMessage());
}
if(Config::get('database')->debug)
Logger::log("Manuel Query: ".$query, "Database Model");
try{
$sth = Modules::get('core/database')->prepare($query);
if($binds === null){
$sth->execute();
}else{
$sth->execute($binds);
}
}catch (PDOException $e){
throw new DatabaseException('Could not execute SQL-query due PDO-exception '.$e->getMessage());
}
if($sth->columnCount() > 0){
if ($sth->columnCount() > 0) {
// Fetch results // Fetch results
$result = $sth->fetchAll(\PDO::FETCH_ASSOC); $result = $sth->fetchAll(\PDO::FETCH_ASSOC);
}else{ } else {
// Fetch number of affected rows // Fetch number of affected rows
$result = $sth->rowCount(); $result = $sth->rowCount();
} }
return $result; return $result;
} }
/** /**
* Set the table you wish to approach * Set the table you wish to approach.
* @param String $table Table name *
*/ * @param string $table Table name
public function setTable($table) { */
$this->table = $table; public function setTable($table)
return $this; {
} $this->table = $table;
/** return $this;
* The default table will be set to $this->table }
* @see Query::select
* @return Query
*/
public function select(){
$queryBuilder = new Query(); /**
$queryBuilder->setTable($this->table); * The default table will be set to $this->table.
*
* @see Query::select
*
* @return Query
*/
public function select()
{
$queryBuilder = new Query();
$queryBuilder->setTable($this->table);
call_user_func_array(array($queryBuilder, 'select'), func_get_args()); call_user_func_array(array($queryBuilder, 'select'), func_get_args());
$queryBuilder->from(); $queryBuilder->from();
return $queryBuilder; return $queryBuilder;
} }
/** /**
* The default table will be set to $this->table * The default table will be set to $this->table.
* @see Query::update *
* @return Query * @see Query::update
*/ *
* @return Query
*/
public function update()
{
$queryBuilder = new Query();
$queryBuilder->setTable($this->table);
$queryBuilder->update($this->table);
public function update(){ return $queryBuilder;
}
$queryBuilder = new Query(); /**
$queryBuilder->setTable($this->table); * The default table will be set to $this->table.
$queryBuilder->update($this->table); *
* @see Query::delete
return $queryBuilder; *
} * @return Query
*/
/** public function delete()
* The default table will be set to $this->table {
* @see Query::delete $queryBuilder = new Query();
* @return Query $queryBuilder->setTable($this->table);
*/
public function delete(){
$queryBuilder = new Query();
$queryBuilder->setTable($this->table);
call_user_func_array(array($queryBuilder, 'delete'), func_get_args()); call_user_func_array(array($queryBuilder, 'delete'), func_get_args());
$queryBuilder->from(); $queryBuilder->from();
return $queryBuilder; return $queryBuilder;
} }
/**
* The default table will be set to $this->table
* @see Query::insert
* @param $array Array with values
* @return Query
* @throws Exception
*/
public function insert($array){
$queryBuilder = new Query();
$queryBuilder->setTable($this->table);
call_user_func_array(array($queryBuilder, 'insert'), func_get_args());
return $queryBuilder;
}
/** /**
* The default table will be set to $this->table * The default table will be set to $this->table.
* @see Query::replace *
* @see Query::insert
*
* @param $array Array with values * @param $array Array with values
*
* @return Query * @return Query
*
* @throws Exception * @throws Exception
*/ */
public function insert($array)
{
$queryBuilder = new Query();
$queryBuilder->setTable($this->table);
call_user_func_array(array($queryBuilder, 'insert'), func_get_args());
public function replace($array){ return $queryBuilder;
}
/**
* The default table will be set to $this->table.
*
* @see Query::replace
*
* @param $array Array with values
*
* @return Query
*
* @throws Exception
*/
public function replace($array)
{
$queryBuilder = new Query(); $queryBuilder = new Query();
$queryBuilder->setTable($this->table); $queryBuilder->setTable($this->table);
call_user_func_array(array($queryBuilder, 'replace'), func_get_args()); call_user_func_array(array($queryBuilder, 'replace'), func_get_args());
@ -214,16 +228,18 @@ class Model {
return $queryBuilder; return $queryBuilder;
} }
/** /**
* Return latest insert id * Return latest insert id.
* *
* @return mixed * @return mixed
*/ */
public function getLastInsertId(){ public function getLastInsertId()
return Modules::get('core/database')->lastInsertId(); {
} return Modules::get('core/database')->lastInsertId();
}
public function __call($name, $params) { public function __call($name, $params)
return call_user_func_array(array(Modules::get('core/database'), $name), $params); {
} return call_user_func_array(array(Modules::get('core/database'), $name), $params);
} }
}

File diff suppressed because it is too large Load Diff

View File

@ -1,24 +1,25 @@
<?php <?php
return array( return array(
'module_class' => 'Module\DatabaseUtils\Main', 'module_class' => 'Module\DatabaseUtils\Main',
'module_file' => 'class.model.php', 'module_file' => 'class.model.php',
'module_name' => 'DatabaseUtils', 'module_name' => 'DatabaseUtils',
'abstract' => false, 'abstract' => false,
'dependencies' => array('core/database'), 'dependencies' => array('core/database'),
'events' => array(), 'events' => array(),
'sections' => array(), 'sections' => array(),
'aliases' => array(), 'aliases' => array(),
'name' => 'FuzeWorks Database Utilities', 'name' => 'FuzeWorks Database Utilities',
'description' => 'Automatically build SQL queries using methods in this class', 'description' => 'Automatically build SQL queries using methods in this class',
'author' => 'core', 'author' => 'core',
'version' => '1.0.0', 'version' => '1.0.0',
'website' => 'http://fuzeworks.techfuze.net/', 'website' => 'http://fuzeworks.techfuze.net/',
'date_created' => '29-04-2015', 'date_created' => '29-04-2015',
'date_updated' => '29-04-2015', 'date_updated' => '29-04-2015',
'enabled' => true, 'enabled' => true,
); );

View File

@ -1,6 +1,6 @@
<?php <?php
/** /**
* FuzeWorks * FuzeWorks.
* *
* The FuzeWorks MVC PHP FrameWork * The FuzeWorks MVC PHP FrameWork
* *
@ -19,116 +19,125 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
* *
* @author TechFuze * @author TechFuze
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
* @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/) * @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/)
* @license http://opensource.org/licenses/GPL-3.0 GPLv3 License * @license http://opensource.org/licenses/GPL-3.0 GPLv3 License
* @link http://fuzeworks.techfuze.net *
* @since Version 0.0.1 * @link http://fuzeworks.techfuze.net
* @version Version 0.0.1 * @since Version 0.0.1
*
* @version Version 0.0.1
*/ */
namespace Module\Example; namespace Module\Example;
use \FuzeWorks\Module;
use \FuzeWorks\Event; use FuzeWorks\Module;
use \FuzeWorks\EventPriority; use FuzeWorks\Event;
use \FuzeWorks\Events; use FuzeWorks\EventPriority;
use \FuzeWorks\Logger; use FuzeWorks\Events;
use FuzeWorks\Logger;
/** /**
* Example module. * Example module.
* *
* Use this is a reference to create new modules. * Use this is a reference to create new modules.
* @package net.techfuze.fuzeworks.example *
* @author Abel Hoogeveen <abel@techfuze.net> * @author Abel Hoogeveen <abel@techfuze.net>
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
*/ */
class Main { class Main
{
use Module;
use Module; /**
* Loads the module and registers the events.
*
* Every main moduleclass needs an onLoad method. This method is called first before anything else and cam be used to do some global actions.
*/
public function onLoad()
{
// Here we register an eventListener for the ExampleEvent. See ExampleListener for more info
Events::addListener(array($this, 'exampleListener'), 'ExampleEvent', EventPriority::NORMAL);
}
/** /**
* Loads the module and registers the events * Test method that can be called.
* *
* Every main moduleclass needs an onLoad method. This method is called first before anything else and cam be used to do some global actions. * @return string Example text
* @access public */
*/ public function test()
public function onLoad() { {
// Here we register an eventListener for the ExampleEvent. See ExampleListener for more info return 'It works!';
Events::addListener(array($this, 'exampleListener'), 'ExampleEvent', EventPriority::NORMAL); }
}
/** /**
* Test method that can be called * An example listener that introduces you to the basics of event handling.
* @return String Example text *
*/ * @param ExampleEvent $event The event to listen for
public function test() { *
return "It works!"; * @return ExampleEvent The event after it has been handled
} */
public function exampleListener($event)
{
Logger::log('Called the eventListener. This listener can now handle the event and change some data');
// For this listener, we only change one variable
$event->setVariable('New Value');
/** // And then we return it
* An example listener that introduces you to the basics of event handling return $event;
* @param ExampleEvent $event The event to listen for }
* @return ExampleEvent The event after it has been handled
*/
public function exampleListener($event) {
Logger::log("Called the eventListener. This listener can now handle the event and change some data");
// For this listener, we only change one variable
$event->setVariable("New Value");
// And then we return it /**
return $event; * In this example we create a simple event. This event will be created, passed around and then received in the example listener.
} */
public function createEvent()
{
// First we log some data
Logger::log('Now creating a test event.');
/** // First we create the event object and some variables to assign to it
* In this example we create a simple event. This event will be created, passed around and then received in the example listener. $eventObject = new ExampleEvent();
*/ $variable = 'Test Variable';
public function createEvent() {
// First we log some data
Logger::log("Now creating a test event.");
// First we create the event object and some variables to assign to it // Then we fire the event by parsing the event object and the variables into the fireEvent function.
$eventObject = new ExampleEvent(); $event = Events::fireEvent($eventObject, $variable);
$variable = "Test Variable";
// Then we fire the event by parsing the event object and the variables into the fireEvent function. // Here we can read some variables from the event
$event = Events::fireEvent($eventObject, $variable); $result = $event->getVariable();
// Here we can read some variables from the event // And now we can do things with the data. For now we just return it
$result = $event->getVariable(); return $result;
}
// And now we can do things with the data. For now we just return it
return $result;
}
/**
* Gets called when the path matches the regex of this module.
* @access public
* @param array Regex matches
* @return void
*/
public function route($matches = array()) {
// Just print the inputted data:
echo "<h3>Input data: ".$matches['data']."</h3>";
}
/**
* Gets called when the path matches the regex of this module.
*
* @param array Regex matches
*/
public function route($matches = array())
{
// Just print the inputted data:
echo '<h3>Input data: '.$matches['data'].'</h3>';
}
} }
class ExampleEvent extends Event { class ExampleEvent extends Event
{
private $var1;
private $var1; public function init($variable)
{
$this->var1 = $variable;
}
public function init($variable) { public function getVariable()
$this->var1 = $variable; {
} return $this->var1;
}
public function getVariable() { public function setVariable($var)
return $this->var1; {
} $this->var1 = $var;
}
public function setVariable($var) {
$this->var1 = $var;
}
} }
?>

View File

@ -1,6 +1,6 @@
<?php <?php
/** /**
* FuzeWorks * FuzeWorks.
* *
* The FuzeWorks MVC PHP FrameWork * The FuzeWorks MVC PHP FrameWork
* *
@ -19,71 +19,73 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
* *
* @author TechFuze * @author TechFuze
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
* @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/) * @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/)
* @license http://opensource.org/licenses/GPL-3.0 GPLv3 License * @license http://opensource.org/licenses/GPL-3.0 GPLv3 License
* @link http://fuzeworks.techfuze.net *
* @since Version 0.0.1 * @link http://fuzeworks.techfuze.net
* @version Version 0.0.1 * @since Version 0.0.1
*
* @version Version 0.0.1
*/ */
return array( return array(
// The class name of the module. This class will be loaded upon requesting the module // The class name of the module. This class will be loaded upon requesting the module
'module_class' => 'Module\Example\Main', 'module_class' => 'Module\Example\Main',
// The file that will be loaded upon requesting the module // The file that will be loaded upon requesting the module
'module_file' => 'class.main.php', 'module_file' => 'class.main.php',
// The name of the module; Appended into Modules::get('namespace/module_name'); // The name of the module; Appended into Modules::get('namespace/module_name');
'module_name' => 'Example', 'module_name' => 'Example',
// whether this module is an abstract. Making this abstract will only load the file, but not the class. // whether this module is an abstract. Making this abstract will only load the file, but not the class.
'abstract' => false, 'abstract' => false,
// Other names for this module. Setting an alias will allow you to load the module with a different name. // Other names for this module. Setting an alias will allow you to load the module with a different name.
'aliases' => array(), 'aliases' => array(),
// Array of modules that should be loaded before this module // Array of modules that should be loaded before this module
'dependencies' => array(), 'dependencies' => array(),
// Events that this module listens for. When the exampleEvent is fired, this module will be loaded so the module can handle the event // Events that this module listens for. When the exampleEvent is fired, this module will be loaded so the module can handle the event
'events' => array('exampleEvent'), 'events' => array('exampleEvent'),
// Routes that this module listens on. Any URL that matches this pattern will load this module // Routes that this module listens on. Any URL that matches this pattern will load this module
// If the URL /example/ gets called, this module will be loaded // If the URL /example/ gets called, this module will be loaded
// Everything after /example/ will be sent to the route() function in the matches array under the, in this example, 'data' key // Everything after /example/ will be sent to the route() function in the matches array under the, in this example, 'data' key
'routes' => array('/^example(|\/(?P<data>.*?))$/'), 'routes' => array('/^example(|\/(?P<data>.*?))$/'),
// Advertises some data with the key 'exampleAdvertisement'. This data will be sent to a module which listens for this key. // Advertises some data with the key 'exampleAdvertisement'. This data will be sent to a module which listens for this key.
// This allows for some data to be sent to a module which listens to this key. // This allows for some data to be sent to a module which listens to this key.
'advertise' => array('exampleAdvertisement' => array('exampleData')), 'advertise' => array('exampleAdvertisement' => array('exampleData')),
// Tells the module engine that this module would like all the data with the key 'exampleAdvertisement'. // Tells the module engine that this module would like all the data with the key 'exampleAdvertisement'.
'listenFor' => array('exampleAdvertisement'), 'listenFor' => array('exampleAdvertisement'),
// The name of the module as it will be logged. This does not affect usage of the module in any way // The name of the module as it will be logged. This does not affect usage of the module in any way
'name' => 'FuzeWorks Example Module', 'name' => 'FuzeWorks Example Module',
// A description of the module. // A description of the module.
'description' => 'A descriptive module that functions as an example', 'description' => 'A descriptive module that functions as an example',
// The author of the module. The author is the first part of the module name used for requesting. eg mycorp/example // The author of the module. The author is the first part of the module name used for requesting. eg mycorp/example
'author' => 'MyCorp', 'author' => 'MyCorp',
// The current version of the module. Will be used for looking for updates // The current version of the module. Will be used for looking for updates
'version' => '1.0.0', 'version' => '1.0.0',
// The website to look at for the module update // The website to look at for the module update
'website' => 'http://fuzeworks.techfuze.net/', 'website' => 'http://fuzeworks.techfuze.net/',
// The initial creation of the module. // The initial creation of the module.
'date_created' => '29-04-2015', 'date_created' => '29-04-2015',
// The last update of this module // The last update of this module
'date_updated' => '29-04-2015', 'date_updated' => '29-04-2015',
// whether the module is enabled or not. If it is disabled, it can not be loaded. // whether the module is enabled or not. If it is disabled, it can not be loaded.
'enabled' => true 'enabled' => true,
); );

View File

@ -1,6 +1,6 @@
<?php <?php
/** /**
* FuzeWorks * FuzeWorks.
* *
* The FuzeWorks MVC PHP FrameWork * The FuzeWorks MVC PHP FrameWork
* *
@ -19,95 +19,96 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
* *
* @author TechFuze * @author TechFuze
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
* @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/) * @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/)
* @license http://opensource.org/licenses/GPL-3.0 GPLv3 License * @license http://opensource.org/licenses/GPL-3.0 GPLv3 License
* @link http://fuzeworks.techfuze.net *
* @since Version 0.0.1 * @link http://fuzeworks.techfuze.net
* @version Version 0.0.1 * @since Version 0.0.1
*
* @version Version 0.0.1
*/ */
namespace Module\Mailer; namespace Module\Mailer;
use \FuzeWorks\Module;
use \FuzeWorks\ModuleException; use FuzeWorks\Module;
use \FuzeWorks\Config; use FuzeWorks\ModuleException;
use \FuzeWorks\Logger; use FuzeWorks\Config;
use \PHPMailer; use PHPMailer;
/** /**
* Main class for the Mailer module * Main class for the Mailer module.
* *
* This class is a simple wrapper for PHPMailer. It has a simple prepared config file and can create instances based on these config files. * This class is a simple wrapper for PHPMailer. It has a simple prepared config file and can create instances based on these config files.
* @package net.techfuze.fuzeworks.mailer *
* @author Abel Hoogeveen <abel@techfuze.net> * @author Abel Hoogeveen <abel@techfuze.net>
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
*/ */
class Main { class Main
{
use Module;
use Module; /**
* Array of all the active PHPMailer instances.
*
* @var array of \PHPMailer
*/
private $mailers = array();
/** /**
* Array of all the active PHPMailer instances * First function to get called. Initiates all module variables.
* @access private */
* @var Array of \PHPMailer public function onLoad()
*/ {
private $mailers = array(); if (!class_exists('\PHPMailer')) {
throw new ModuleException('PHPMailer class not found! Is composer installed?', 1);
}
}
/** /**
* First function to get called. Initiates all module variables * Return one of the instances of PHPMailer.
* @access public * If not found, it creates a new instance and returns that.
*/ *
public function onLoad() { * @param string instance name
if (!class_exists('\PHPMailer')) { *
throw new ModuleException("PHPMailer class not found! Is composer installed?", 1); * @return \PHPMailer instance
} */
} public function __get($name)
{
if (!isset($this->mailers[$name])) {
$this->mailers[$name] = new PHPMailer();
/** // Set settings
* Return one of the instances of PHPMailer. $cfg = self::$cfg;
* If not found, it creates a new instance and returns that
* @access public
* @param String instance name
* @return \PHPMailer instance
*/
public function __get($name) {
if (!isset($this->mailers[$name])) {
$this->mailers[$name] = new PHPMailer();
// Set settings // First check what is enabled
$cfg = self::$cfg; if ($cfg->sendmail_enabled && !$cfg->smtp_enabled) {
$this->mailers[$name]->isSendmail();
} elseif (!$cfg->sendmail_enabled && $cfg->smtp_enabled) {
// Set up all the SMTP details
$this->mailers[$name]->isSMTP();
$this->mailers[$name]->SMTPDebug = $cfg->smtp_debug_level;
$this->mailers[$name]->Debugoutput = 'html';
$this->mailers[$name]->Host = $cfg->smtp_host;
$this->mailers[$name]->Port = $cfg->smtp_port;
// First check what is enabled // SMTP Authentication
if ($cfg->sendmail_enabled && !$cfg->smtp_enabled) { if ($cfg->smtp_auth) {
$this->mailers[$name]->isSendmail(); $this->mailers[$name]->SMTPAuth = true;
} elseif (!$cfg->sendmail_enabled && $cfg->smtp_enabled) { $this->mailers[$name]->Username = $cfg->smtp_username;
// Set up all the SMTP details $this->mailers[$name]->Password = $cfg->smtp_password;
$this->mailers[$name]->isSMTP(); }
$this->mailers[$name]->SMTPDebug = $cfg->smtp_debug_level;
$this->mailers[$name]->Debugoutput = 'html';
$this->mailers[$name]->Host = $cfg->smtp_host;
$this->mailers[$name]->Port = $cfg->smtp_port;
// SMTP Authentication // Set the sender correctly
if ($cfg->smtp_auth) { if ($cfg->sender_name != '' && $cfg->sender_mail != '') {
$this->mailers[$name]->SMTPAuth = true; $this->mailers[$name]->setFrom($cfg->sender_mail, $cfg->sender_name);
$this->mailers[$name]->Username = $cfg->smtp_username; } elseif ($cfg->sender_name == '' && $cfg->sender_mail != '') {
$this->mailers[$name]->Password = $cfg->smtp_password; $mail->From = $cfg->sender_mail;
} }
}
}
// Set the sender correctly return $this->mailers[$name];
if ($cfg->sender_name != '' && $cfg->sender_mail != '') { }
$this->mailers[$name]->setFrom($cfg->sender_mail, $cfg->sender_name); }
} elseif ($cfg->sender_name == '' && $cfg->sender_mail != '') {
$mail->From = $cfg->sender_mail;
}
}
}
return $this->mailers[$name];
}
}
?>

View File

@ -1,6 +1,6 @@
<?php <?php
/** /**
* FuzeWorks * FuzeWorks.
* *
* The FuzeWorks MVC PHP FrameWork * The FuzeWorks MVC PHP FrameWork
* *
@ -19,37 +19,37 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
* *
* @author TechFuze * @author TechFuze
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
* @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/) * @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/)
* @license http://opensource.org/licenses/GPL-3.0 GPLv3 License * @license http://opensource.org/licenses/GPL-3.0 GPLv3 License
* @link http://fuzeworks.techfuze.net *
* @since Version 0.0.1 * @link http://fuzeworks.techfuze.net
* @version Version 0.0.1 * @since Version 0.0.1
*
* @version Version 0.0.1
*/ */
return array( return array(
# Sendmail Settings // Sendmail Settings
'sendmail_enabled' => true, 'sendmail_enabled' => true,
# SMTP Settings // SMTP Settings
'smtp_enabled' => false, 'smtp_enabled' => false,
'smtp_host' => '', 'smtp_host' => '',
'smtp_port' => 25, 'smtp_port' => 25,
'smtp_auth' => false, 'smtp_auth' => false,
'smtp_username' => '', 'smtp_username' => '',
'smtp_password' => '', 'smtp_password' => '',
/** /*
* 0 = off * 0 = off
* 1 = client messages * 1 = client messages
* 2 = client and server messages * 2 = client and server messages
*/ */
'smtp_debug_level' => 0, 'smtp_debug_level' => 0,
# Common sender information // Common sender information
'sender_name' => '', 'sender_name' => '',
'sender_mail' => '', 'sender_mail' => '',
); );
?>

View File

@ -1,6 +1,6 @@
<?php <?php
/** /**
* FuzeWorks * FuzeWorks.
* *
* The FuzeWorks MVC PHP FrameWork * The FuzeWorks MVC PHP FrameWork
* *
@ -19,30 +19,32 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
* *
* @author TechFuze * @author TechFuze
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
* @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/) * @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/)
* @license http://opensource.org/licenses/GPL-3.0 GPLv3 License * @license http://opensource.org/licenses/GPL-3.0 GPLv3 License
* @link http://fuzeworks.techfuze.net *
* @since Version 0.0.1 * @link http://fuzeworks.techfuze.net
* @version Version 0.0.1 * @since Version 0.0.1
*
* @version Version 0.0.1
*/ */
return array( return array(
'module_class' => '\Module\Mailer\Main', 'module_class' => '\Module\Mailer\Main',
'module_file' => 'class.mailer.php', 'module_file' => 'class.mailer.php',
'module_name' => 'Mailer', 'module_name' => 'Mailer',
'dependencies' => array(), 'dependencies' => array(),
'aliases' => array(), 'aliases' => array(),
'name' => 'Mailer', 'name' => 'Mailer',
'description' => 'PHPMailer wrapper for FuzeWorks', 'description' => 'PHPMailer wrapper for FuzeWorks',
'author' => 'core', 'author' => 'core',
'version' => '1.0.0', 'version' => '1.0.0',
'website' => 'http://fuzeworks.techfuze.net/', 'website' => 'http://fuzeworks.techfuze.net/',
'date_created' => '08-07-2015', 'date_created' => '08-07-2015',
'date_updated' => '08-07-2015', 'date_updated' => '08-07-2015',
); );

View File

@ -1,6 +1,6 @@
<?php <?php
/** /**
* FuzeWorks * FuzeWorks.
* *
* The FuzeWorks MVC PHP FrameWork * The FuzeWorks MVC PHP FrameWork
* *
@ -20,24 +20,23 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
* *
* @author TechFuze * @author TechFuze
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
* @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/) * @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/)
* @license http://opensource.org/licenses/GPL-3.0 GPLv3 License * @license http://opensource.org/licenses/GPL-3.0 GPLv3 License
*
* @link http://fuzeworks.techfuze.net * @link http://fuzeworks.techfuze.net
* @since Version 0.0.1 * @since Version 0.0.1
*
* @version Version 0.0.1 * @version Version 0.0.1
*/ */
use FuzeWorks\Core;
use \FuzeWorks\Core; use FuzeWorks\Router;
use \FuzeWorks\Router;
// Include framework // Include framework
require_once( dirname(__FILE__) . "/Core/System/class.core.php"); require_once dirname(__FILE__).'/Core/System/class.core.php';
// Load it // Load it
Core::init(); Core::init();
Router::setPath( (isset($_GET['path']) ? $_GET['path'] : null) ); Router::setPath((isset($_GET['path']) ? $_GET['path'] : null));
Router::route(); Router::route();
?>

View File

@ -1,6 +1,6 @@
<?php <?php
/** /**
* FuzeWorks * FuzeWorks.
* *
* The FuzeWorks MVC PHP FrameWork * The FuzeWorks MVC PHP FrameWork
* *
@ -20,32 +20,33 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
* *
* @author TechFuze * @author TechFuze
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
* @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/) * @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/)
* @license http://opensource.org/licenses/GPL-3.0 GPLv3 License * @license http://opensource.org/licenses/GPL-3.0 GPLv3 License
*
* @link http://fuzeworks.techfuze.net * @link http://fuzeworks.techfuze.net
* @since Version 0.0.1 * @since Version 0.0.1
*
* @version Version 0.0.1 * @version Version 0.0.1
*/ */
use FuzeWorks\Events; use FuzeWorks\Events;
use FuzeWorks\Layout; use FuzeWorks\Layout;
/** /**
* Class CoreTestAbstract * Class CoreTestAbstract.
* *
* Provides the event tests with some basic functionality * Provides the event tests with some basic functionality
*/ */
abstract class CoreTestAbstract extends PHPUnit_Framework_TestCase abstract class CoreTestAbstract extends PHPUnit_Framework_TestCase
{ {
/** /**
* Remove all listeners before the next test starts * Remove all listeners before the next test starts.
* *
* Reset the layout manager * Reset the layout manager
*/ */
public function tearDown(){ public function tearDown()
{
Events::$listeners = array(); Events::$listeners = array();
Layout::reset(); Layout::reset();
} }
} }

View File

@ -1,6 +1,6 @@
<?php <?php
/** /**
* FuzeWorks * FuzeWorks.
* *
* The FuzeWorks MVC PHP FrameWork * The FuzeWorks MVC PHP FrameWork
* *
@ -20,11 +20,13 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
* *
* @author TechFuze * @author TechFuze
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
* @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/) * @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/)
* @license http://opensource.org/licenses/GPL-3.0 GPLv3 License * @license http://opensource.org/licenses/GPL-3.0 GPLv3 License
*
* @link http://fuzeworks.techfuze.net * @link http://fuzeworks.techfuze.net
* @since Version 0.0.1 * @since Version 0.0.1
*
* @version Version 0.0.1 * @version Version 0.0.1
*/ */
// Load the abstract // Load the abstract
@ -32,8 +34,8 @@
use \FuzeWorks\Config; use \FuzeWorks\Config;
use \FuzeWorks\Core; use \FuzeWorks\Core;
require_once "abstract.coreTestAbstract.php"; require_once 'abstract.coreTestAbstract.php';
require_once( "Core/System/class.core.php"); require_once 'Core/System/class.core.php';
ob_start(); ob_start();
Core::init(); Core::init();
@ -43,5 +45,3 @@ $cfg = Config::get('error');
$cfg->debug = false; $cfg->debug = false;
$cfg->error_reporting = false; $cfg->error_reporting = false;
$cfg->commit(); $cfg->commit();
?>

View File

@ -1,6 +1,6 @@
<?php <?php
/** /**
* FuzeWorks * FuzeWorks.
* *
* The FuzeWorks MVC PHP FrameWork * The FuzeWorks MVC PHP FrameWork
* *
@ -20,29 +20,32 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
* *
* @author TechFuze * @author TechFuze
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
* @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/) * @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/)
* @license http://opensource.org/licenses/GPL-3.0 GPLv3 License * @license http://opensource.org/licenses/GPL-3.0 GPLv3 License
*
* @link http://fuzeworks.techfuze.net * @link http://fuzeworks.techfuze.net
* @since Version 0.0.1 * @since Version 0.0.1
*
* @version Version 0.0.1 * @version Version 0.0.1
*/ */
/** /**
* Class CoreTest * Class CoreTest.
* *
* Core testing suite, will test basic core functionality * Core testing suite, will test basic core functionality
*/ */
class CoreTest extends CoreTestAbstract class coreTest extends CoreTestAbstract
{ {
public function testCanLoadStartupFiles(){ public function testCanLoadStartupFiles()
{
// Assert // Assert
$this->assertTrue(class_exists('\FuzeWorks\Config')); $this->assertTrue(class_exists('\FuzeWorks\Config'));
$this->assertTrue(class_exists('\FuzeWorks\Logger')); $this->assertTrue(class_exists('\FuzeWorks\Logger'));
$this->assertTrue(class_exists('\FuzeWorks\Events')); $this->assertTrue(class_exists('\FuzeWorks\Events'));
$this->assertTrue(class_exists('\FuzeWorks\Router')); $this->assertTrue(class_exists('\FuzeWorks\Router'));
$this->assertTrue(class_exists('\FuzeWorks\Layout')); $this->assertTrue(class_exists('\FuzeWorks\Layout'));
$this->assertTrue(class_exists('\FuzeWorks\Models')); $this->assertTrue(class_exists('\FuzeWorks\Models'));
} }
} }

View File

@ -1,6 +1,6 @@
<?php <?php
/** /**
* FuzeWorks * FuzeWorks.
* *
* The FuzeWorks MVC PHP FrameWork * The FuzeWorks MVC PHP FrameWork
* *
@ -20,28 +20,26 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
* *
* @author TechFuze * @author TechFuze
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
* @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/) * @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/)
* @license http://opensource.org/licenses/GPL-3.0 GPLv3 License * @license http://opensource.org/licenses/GPL-3.0 GPLv3 License
*
* @link http://fuzeworks.techfuze.net * @link http://fuzeworks.techfuze.net
* @since Version 0.0.1 * @since Version 0.0.1
*
* @version Version 0.0.1 * @version Version 0.0.1
*/ */
use \FuzeWorks\Core;
use \FuzeWorks\Layout; use \FuzeWorks\Layout;
use \FuzeWorks\Events;
use \FuzeWorks\TemplateEngine\TemplateEngine;
/** /**
* Class LayoutTest * Class LayoutTest.
* *
* This test will test the layout manager and the default TemplateEngines * This test will test the layout manager and the default TemplateEngines
*/ */
class LayoutTest extends CoreTestAbstract class layoutTest extends CoreTestAbstract
{ {
public function testGetFileExtensions()
public function testGetFileExtensions() { {
// Test getting php files // Test getting php files
$this->assertEquals('php', Layout::getExtensionFromFile('class.test.php')); $this->assertEquals('php', Layout::getExtensionFromFile('class.test.php'));
$this->assertEquals('php', Layout::getExtensionFromFile('class.test.org.php')); $this->assertEquals('php', Layout::getExtensionFromFile('class.test.org.php'));
@ -49,9 +47,11 @@ class LayoutTest extends CoreTestAbstract
/** /**
* @depends testGetFileExtensions * @depends testGetFileExtensions
*
* @todo Add malformed paths * @todo Add malformed paths
*/ */
public function testGetFilePath(){ public function testGetFilePath()
{
// Extensions to be used in this test // Extensions to be used in this test
$extensions = array('php', 'json'); $extensions = array('php', 'json');
@ -75,7 +75,8 @@ class LayoutTest extends CoreTestAbstract
/** /**
* @expectedException \FuzeWorks\LayoutException * @expectedException \FuzeWorks\LayoutException
*/ */
public function testMissingDirectory() { public function testMissingDirectory()
{
// Directory that does not exist // Directory that does not exist
Layout::setFileFromString('test', 'tests/layout/doesNotExist/', array('php')); Layout::setFileFromString('test', 'tests/layout/doesNotExist/', array('php'));
} }
@ -83,18 +84,21 @@ class LayoutTest extends CoreTestAbstract
/** /**
* @expectedException \FuzeWorks\LayoutException * @expectedException \FuzeWorks\LayoutException
*/ */
public function testMissingFile() { public function testMissingFile()
{
Layout::setFileFromString('test', 'tests/layout/testMissingFile/', array('php')); Layout::setFileFromString('test', 'tests/layout/testMissingFile/', array('php'));
} }
/** /**
* @expectedException \FuzeWorks\LayoutException * @expectedException \FuzeWorks\LayoutException
*/ */
public function testUnknownFileExtension() { public function testUnknownFileExtension()
{
Layout::setFileFromString('test', 'tests/layout/testUnknownFileExtension/', array('php')); Layout::setFileFromString('test', 'tests/layout/testUnknownFileExtension/', array('php'));
} }
public function testGetEngineFromExtension() { public function testGetEngineFromExtension()
{
Layout::loadTemplateEngines(); Layout::loadTemplateEngines();
// Test all the default engines // Test all the default engines
@ -107,14 +111,16 @@ class LayoutTest extends CoreTestAbstract
* @depends testGetEngineFromExtension * @depends testGetEngineFromExtension
* @expectedException \FuzeWorks\LayoutException * @expectedException \FuzeWorks\LayoutException
*/ */
public function testGetEngineFromExtensionFail() { public function testGetEngineFromExtensionFail()
{
Layout::getEngineFromExtension('faulty'); Layout::getEngineFromExtension('faulty');
} }
/** /**
* @depends testGetEngineFromExtension * @depends testGetEngineFromExtension
*/ */
public function testCustomEngine() { public function testCustomEngine()
{
// Create the engine // Create the engine
$mock = $this->getMockBuilder('\FuzeWorks\TemplateEngine\TemplateEngine')->getMock(); $mock = $this->getMockBuilder('\FuzeWorks\TemplateEngine\TemplateEngine')->getMock();
@ -132,7 +138,8 @@ class LayoutTest extends CoreTestAbstract
$this->assertEquals('output', Layout::get('test', 'tests/layout/testCustomEngine/')); $this->assertEquals('output', Layout::get('test', 'tests/layout/testCustomEngine/'));
} }
public function testPHPEngine() { public function testPHPEngine()
{
// Directory of these tests // Directory of these tests
$directory = 'tests/layout/testEngines/'; $directory = 'tests/layout/testEngines/';
@ -140,11 +147,12 @@ class LayoutTest extends CoreTestAbstract
$this->assertEquals('PHP Template Check', Layout::get('php', $directory)); $this->assertEquals('PHP Template Check', Layout::get('php', $directory));
} }
public function testJSONEngine() { public function testJSONEngine()
{
// Directory of these tests // Directory of these tests
$directory = 'tests/layout/testEngines/'; $directory = 'tests/layout/testEngines/';
$this->assertEquals('JSON Template Check', json_decode(Layout::get('json', $directory), true)[0]); $this->assertEquals('JSON Template Check', json_decode(Layout::get('json', $directory), true)[0]);
} }
} }

View File

@ -1,6 +1,6 @@
<?php <?php
/** /**
* FuzeWorks * FuzeWorks.
* *
* The FuzeWorks MVC PHP FrameWork * The FuzeWorks MVC PHP FrameWork
* *
@ -20,91 +20,86 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
* *
* @author TechFuze * @author TechFuze
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
* @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/) * @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/)
* @license http://opensource.org/licenses/GPL-3.0 GPLv3 License * @license http://opensource.org/licenses/GPL-3.0 GPLv3 License
*
* @link http://fuzeworks.techfuze.net * @link http://fuzeworks.techfuze.net
* @since Version 0.0.1 * @since Version 0.0.1
*
* @version Version 0.0.1 * @version Version 0.0.1
*/ */
use \FuzeWorks\Core; use \FuzeWorks\Core;
use \FuzeWorks\Models; use \FuzeWorks\Models;
/** /**
* Class ModelTest * Class ModelTest.
* *
* Core model testing suite, will test basic model functionality * Core model testing suite, will test basic model functionality
*
*/ */
class ModelTest extends CoreTestAbstract class modelTest extends CoreTestAbstract
{ {
/** /**
* Select * Select.
*/ */
public function testSelectSimple() public function testSelectSimple()
{ {
$query = Models::get('sqltable')->select(); $query = Models::get('sqltable')->select();
$this->assertEquals('SELECT * FROM table', $query->getSql()); $this->assertEquals('SELECT * FROM table', $query->getSql());
} }
public function testSelectSimpleOneField(){ public function testSelectSimpleOneField()
{
$query = Models::get('sqltable')->select('field1'); $query = Models::get('sqltable')->select('field1');
$this->assertEquals('SELECT field1 FROM table', $query->getSql()); $this->assertEquals('SELECT field1 FROM table', $query->getSql());
} }
public function testSelectSimpleTwoFields(){ public function testSelectSimpleTwoFields()
{
$query = Models::get('sqltable')->select('field1', 'field2'); $query = Models::get('sqltable')->select('field1', 'field2');
$this->assertEquals('SELECT field1, field2 FROM table', $query->getSql()); $this->assertEquals('SELECT field1, field2 FROM table', $query->getSql());
} }
/** /**
* Delete * Delete.
*/ */
public function testDeleteSimple()
public function testDeleteSimple(){ {
$query = Models::get('sqltable')->delete()->from('table'); $query = Models::get('sqltable')->delete()->from('table');
$this->assertEquals('DELETE FROM table', $query->getSql()); $this->assertEquals('DELETE FROM table', $query->getSql());
} }
/** /**
* Insert * Insert.
*/ */
public function testInsertSimple()
public function testInsertSimple(){ {
$query = Models::get('sqltable')->insert(array('field' => 'value')); $query = Models::get('sqltable')->insert(array('field' => 'value'));
$this->assertEquals('INSERT INTO table (field) VALUES (?)', $query->getSql()); $this->assertEquals('INSERT INTO table (field) VALUES (?)', $query->getSql());
$this->assertEquals(array('value'), $query->getBinds()); $this->assertEquals(array('value'), $query->getBinds());
} }
public function testInsertMultiple(){ public function testInsertMultiple()
{
$query = Models::get('sqltable')->insert(array('field1' => 'value1', 'field2' => 'value2'), 'table'); $query = Models::get('sqltable')->insert(array('field1' => 'value1', 'field2' => 'value2'), 'table');
$this->assertEquals('INSERT INTO table (field1,field2) VALUES (?,?)', $query->getSql()); $this->assertEquals('INSERT INTO table (field1,field2) VALUES (?,?)', $query->getSql());
$this->assertEquals(array('value1', 'value2'), $query->getBinds()); $this->assertEquals(array('value1', 'value2'), $query->getBinds());
} }
/** /**
* Replace * Replace.
*/ */
public function testReplaceSimple()
public function testReplaceSimple(){ {
$query = Models::get('sqltable')->replace(array('field' => 'value')); $query = Models::get('sqltable')->replace(array('field' => 'value'));
$this->assertEquals('REPLACE INTO table (field) VALUES (?)', $query->getSql()); $this->assertEquals('REPLACE INTO table (field) VALUES (?)', $query->getSql());
$this->assertEquals(array('value'), $query->getBinds()); $this->assertEquals(array('value'), $query->getBinds());
} }
public function testReplaceMultiple(){ public function testReplaceMultiple()
{
$query = Models::get('sqltable')->replace(array('field1' => 'value1', 'field2' => 'value2'), 'table'); $query = Models::get('sqltable')->replace(array('field1' => 'value1', 'field2' => 'value2'), 'table');
$this->assertEquals('REPLACE INTO table (field1,field2) VALUES (?,?)', $query->getSql()); $this->assertEquals('REPLACE INTO table (field1,field2) VALUES (?,?)', $query->getSql());
$this->assertEquals(array('value1', 'value2'), $query->getBinds()); $this->assertEquals(array('value1', 'value2'), $query->getBinds());
} }
}
}

View File

@ -1,6 +1,6 @@
<?php <?php
/** /**
* FuzeWorks * FuzeWorks.
* *
* The FuzeWorks MVC PHP FrameWork * The FuzeWorks MVC PHP FrameWork
* *
@ -20,19 +20,20 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
* *
* @author TechFuze * @author TechFuze
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
* @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/) * @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/)
* @license http://opensource.org/licenses/GPL-3.0 GPLv3 License * @license http://opensource.org/licenses/GPL-3.0 GPLv3 License
*
* @link http://fuzeworks.techfuze.net * @link http://fuzeworks.techfuze.net
* @since Version 0.0.1 * @since Version 0.0.1
*
* @version Version 0.0.1 * @version Version 0.0.1
*/ */
use \FuzeWorks\Modules; use \FuzeWorks\Modules;
use \Module\DatabaseUtils\Query; use \Module\DatabaseUtils\Query;
class QueryTests extends \CoreTestAbstract { class QueryTests extends \CoreTestAbstract
{
/** /**
* @var Query * @var Query
*/ */
@ -43,16 +44,16 @@ class QueryTests extends \CoreTestAbstract {
/** /**
* @before * @before
*/ */
protected function setUp(){ protected function setUp()
{
Modules::get('core/databaseutils'); Modules::get('core/databaseutils');
$this->query = new Query(); $this->query = new Query();
} }
public function testConstructor(){ public function testConstructor()
{
$query = new Query('table'); $query = new Query('table');
$this->assertEquals('table', $query->getTable()); $this->assertEquals('table', $query->getTable());
} }
/* /*
* Select * Select
@ -64,9 +65,9 @@ class QueryTests extends \CoreTestAbstract {
$this->assertEquals('SELECT * FROM table', $this->query->getSql()); $this->assertEquals('SELECT * FROM table', $this->query->getSql());
} }
public function testSelectSimpleDefaultTable(){ public function testSelectSimpleDefaultTable()
{
$this->query->setTable("table")->select()->from(); $this->query->setTable('table')->select()->from();
$this->assertEquals('SELECT * FROM table', $this->query->getSql()); $this->assertEquals('SELECT * FROM table', $this->query->getSql());
} }
@ -88,14 +89,14 @@ class QueryTests extends \CoreTestAbstract {
$this->assertEquals('SELECT * FROM table t, table2 t2', $this->query->getSql()); $this->assertEquals('SELECT * FROM table t, table2 t2', $this->query->getSql());
} }
public function testSelectSimpleOneField(){ public function testSelectSimpleOneField()
{
$this->query->select('field1')->from('table'); $this->query->select('field1')->from('table');
$this->assertEquals('SELECT field1 FROM table', $this->query->getSql()); $this->assertEquals('SELECT field1 FROM table', $this->query->getSql());
} }
public function testSelectSimpleTwoFields(){ public function testSelectSimpleTwoFields()
{
$this->query->select('field1', 'field2')->from('table'); $this->query->select('field1', 'field2')->from('table');
$this->assertEquals('SELECT field1, field2 FROM table', $this->query->getSql()); $this->assertEquals('SELECT field1, field2 FROM table', $this->query->getSql());
} }
@ -104,36 +105,37 @@ class QueryTests extends \CoreTestAbstract {
* Where * Where
*/ */
public function testSelectWhere(){ public function testSelectWhere()
{
$this->query->select()->from('table')->where("field", "value"); $this->query->select()->from('table')->where('field', 'value');
$this->assertEquals('SELECT * FROM table WHERE field = ?', $this->query->getSql()); $this->assertEquals('SELECT * FROM table WHERE field = ?', $this->query->getSql());
$this->assertEquals(array('value'), $this->query->getBinds()); $this->assertEquals(array('value'), $this->query->getBinds());
} }
public function testSelectWhereLike(){ public function testSelectWhereLike()
{
$this->query->select()->from('table')->where("field", "like", '%value%'); $this->query->select()->from('table')->where('field', 'like', '%value%');
$this->assertEquals('SELECT * FROM table WHERE field LIKE ?', $this->query->getSql()); $this->assertEquals('SELECT * FROM table WHERE field LIKE ?', $this->query->getSql());
$this->assertEquals(array('%value%'), $this->query->getBinds()); $this->assertEquals(array('%value%'), $this->query->getBinds());
} }
public function testSelectWhereBetween(){ public function testSelectWhereBetween()
{
$this->query->select()->from('table')->where("field", "between", array(2, 4)); $this->query->select()->from('table')->where('field', 'between', array(2, 4));
$this->assertEquals('SELECT * FROM table WHERE field BETWEEN ? AND ?', $this->query->getSql()); $this->assertEquals('SELECT * FROM table WHERE field BETWEEN ? AND ?', $this->query->getSql());
$this->assertEquals(array(2, 4), $this->query->getBinds()); $this->assertEquals(array(2, 4), $this->query->getBinds());
} }
public function testSelectWhereIn(){ public function testSelectWhereIn()
{
$this->query->select()->from('table')->where("field", "in", array(2, 3, 4)); $this->query->select()->from('table')->where('field', 'in', array(2, 3, 4));
$this->assertEquals('SELECT * FROM table WHERE field IN (?,?,?)', $this->query->getSql()); $this->assertEquals('SELECT * FROM table WHERE field IN (?,?,?)', $this->query->getSql());
$this->assertEquals(array(2, 3, 4), $this->query->getBinds()); $this->assertEquals(array(2, 3, 4), $this->query->getBinds());
} }
/** /**
* @todo Make this work! * @todo Make this work!
*
* @return [type] [description] * @return [type] [description]
*/ */
/*public function testSelectWhereInSubQuery(){ /*public function testSelectWhereInSubQuery(){
@ -146,72 +148,72 @@ class QueryTests extends \CoreTestAbstract {
$this->assertEquals(array('value'), $this->query->getBinds()); $this->assertEquals(array('value'), $this->query->getBinds());
}*/ }*/
public function testSelectWhereNot(){ public function testSelectWhereNot()
{
$this->query->select()->from('table')->where("field", "<>", "value"); $this->query->select()->from('table')->where('field', '<>', 'value');
$this->assertEquals('SELECT * FROM table WHERE field <> ?', $this->query->getSql()); $this->assertEquals('SELECT * FROM table WHERE field <> ?', $this->query->getSql());
$this->assertEquals(array('value'), $this->query->getBinds()); $this->assertEquals(array('value'), $this->query->getBinds());
} }
public function testSelectWhereGreater(){ public function testSelectWhereGreater()
{
$this->query->select()->from('table')->where("field", ">", "value"); $this->query->select()->from('table')->where('field', '>', 'value');
$this->assertEquals('SELECT * FROM table WHERE field > ?', $this->query->getSql()); $this->assertEquals('SELECT * FROM table WHERE field > ?', $this->query->getSql());
$this->assertEquals(array('value'), $this->query->getBinds()); $this->assertEquals(array('value'), $this->query->getBinds());
} }
public function testSelectWhereGreaterEqual(){ public function testSelectWhereGreaterEqual()
{
$this->query->select()->from('table')->where("field", ">=", "value"); $this->query->select()->from('table')->where('field', '>=', 'value');
$this->assertEquals('SELECT * FROM table WHERE field >= ?', $this->query->getSql()); $this->assertEquals('SELECT * FROM table WHERE field >= ?', $this->query->getSql());
$this->assertEquals(array('value'), $this->query->getBinds()); $this->assertEquals(array('value'), $this->query->getBinds());
} }
public function testSelectWhereSmaller(){ public function testSelectWhereSmaller()
{
$this->query->select()->from('table')->where("field", "<", "value"); $this->query->select()->from('table')->where('field', '<', 'value');
$this->assertEquals('SELECT * FROM table WHERE field < ?', $this->query->getSql()); $this->assertEquals('SELECT * FROM table WHERE field < ?', $this->query->getSql());
$this->assertEquals(array('value'), $this->query->getBinds()); $this->assertEquals(array('value'), $this->query->getBinds());
} }
public function testSelectWhereSmallerEqual(){ public function testSelectWhereSmallerEqual()
{
$this->query->select()->from('table')->where("field", "<=", "value"); $this->query->select()->from('table')->where('field', '<=', 'value');
$this->assertEquals('SELECT * FROM table WHERE field <= ?', $this->query->getSql()); $this->assertEquals('SELECT * FROM table WHERE field <= ?', $this->query->getSql());
$this->assertEquals(array('value'), $this->query->getBinds()); $this->assertEquals(array('value'), $this->query->getBinds());
} }
public function testSelectWhereAnd(){ public function testSelectWhereAnd()
{
$this->query->select()->from('table')->where("field1", "value1")->and()->where("field2", "value2"); $this->query->select()->from('table')->where('field1', 'value1')->and()->where('field2', 'value2');
$this->assertEquals('SELECT * FROM table WHERE field1 = ? AND field2 = ?', $this->query->getSql()); $this->assertEquals('SELECT * FROM table WHERE field1 = ? AND field2 = ?', $this->query->getSql());
$this->assertEquals(array('value1', 'value2'), $this->query->getBinds()); $this->assertEquals(array('value1', 'value2'), $this->query->getBinds());
} }
public function testSelectWhereAndOpen(){ public function testSelectWhereAndOpen()
{
$this->query->select()->from('table')->where("field1", "value1")->and()->open()->where("field2", "value2")->or()->where("field3", "value3")->close(); $this->query->select()->from('table')->where('field1', 'value1')->and()->open()->where('field2', 'value2')->or()->where('field3', 'value3')->close();
$this->assertEquals('SELECT * FROM table WHERE field1 = ? AND ( field2 = ? OR field3 = ? )', $this->query->getSql()); $this->assertEquals('SELECT * FROM table WHERE field1 = ? AND ( field2 = ? OR field3 = ? )', $this->query->getSql());
$this->assertEquals(array('value1', 'value2', 'value3'), $this->query->getBinds()); $this->assertEquals(array('value1', 'value2', 'value3'), $this->query->getBinds());
} }
public function testSelectWhereOr(){ public function testSelectWhereOr()
{
$this->query->select()->from('table')->where("field1", "value1")->or()->where("field2", "value2"); $this->query->select()->from('table')->where('field1', 'value1')->or()->where('field2', 'value2');
$this->assertEquals('SELECT * FROM table WHERE field1 = ? OR field2 = ?', $this->query->getSql()); $this->assertEquals('SELECT * FROM table WHERE field1 = ? OR field2 = ?', $this->query->getSql());
$this->assertEquals(array('value1', 'value2'), $this->query->getBinds()); $this->assertEquals(array('value1', 'value2'), $this->query->getBinds());
} }
public function testSelectWhereOrOpen(){ public function testSelectWhereOrOpen()
{
$this->query->select()->from('table')->where("field1", "value1")->or()->open()->where("field2", "value2")->and()->where("field3", "value3")->close(); $this->query->select()->from('table')->where('field1', 'value1')->or()->open()->where('field2', 'value2')->and()->where('field3', 'value3')->close();
$this->assertEquals('SELECT * FROM table WHERE field1 = ? OR ( field2 = ? AND field3 = ? )', $this->query->getSql()); $this->assertEquals('SELECT * FROM table WHERE field1 = ? OR ( field2 = ? AND field3 = ? )', $this->query->getSql());
$this->assertEquals(array('value1', 'value2', 'value3'), $this->query->getBinds()); $this->assertEquals(array('value1', 'value2', 'value3'), $this->query->getBinds());
} }
public function testSelectWhereOpen(){ public function testSelectWhereOpen()
{
$this->query->select()->from('table') $this->query->select()->from('table')
->where()->open()->where("field1", "value1")->and()->where("field2", "value2")->close() ->where()->open()->where('field1', 'value1')->and()->where('field2', 'value2')->close()
->or()->where('field3', 'value3'); ->or()->where('field3', 'value3');
$this->assertEquals('SELECT * FROM table WHERE ( field1 = ? AND field2 = ? ) OR field3 = ?', $this->query->getSql()); $this->assertEquals('SELECT * FROM table WHERE ( field1 = ? AND field2 = ? ) OR field3 = ?', $this->query->getSql());
$this->assertEquals(array('value1', 'value2', 'value3'), $this->query->getBinds()); $this->assertEquals(array('value1', 'value2', 'value3'), $this->query->getBinds());
@ -221,20 +223,20 @@ class QueryTests extends \CoreTestAbstract {
* Order by * Order by
*/ */
public function testSelectOrderASC(){ public function testSelectOrderASC()
{
$this->query->select()->from('table')->order('field'); $this->query->select()->from('table')->order('field');
$this->assertEquals('SELECT * FROM table ORDER BY field ASC', $this->query->getSql()); $this->assertEquals('SELECT * FROM table ORDER BY field ASC', $this->query->getSql());
} }
public function testSelectOrderDESC(){ public function testSelectOrderDESC()
{
$this->query->select()->from('table')->order('-field'); $this->query->select()->from('table')->order('-field');
$this->assertEquals('SELECT * FROM table ORDER BY field DESC', $this->query->getSql()); $this->assertEquals('SELECT * FROM table ORDER BY field DESC', $this->query->getSql());
} }
public function testSelectOrderMultiple(){ public function testSelectOrderMultiple()
{
$this->query->select()->from('table')->order('field1', '-field2'); $this->query->select()->from('table')->order('field1', '-field2');
$this->assertEquals('SELECT * FROM table ORDER BY field1 ASC, field2 DESC', $this->query->getSql()); $this->assertEquals('SELECT * FROM table ORDER BY field1 ASC, field2 DESC', $this->query->getSql());
} }
@ -247,107 +249,106 @@ class QueryTests extends \CoreTestAbstract {
{ {
$this->query->select()->from('table')->limit(5, 10); $this->query->select()->from('table')->limit(5, 10);
$this->assertEquals('SELECT * FROM table LIMIT 10, 5', $this->query->getSql()); $this->assertEquals('SELECT * FROM table LIMIT 10, 5', $this->query->getSql());
} }
/* /*
* Having * Having
*/ */
public function testSelectHaving(){ public function testSelectHaving()
{
$this->query->select()->from('table')->having("field", "value"); $this->query->select()->from('table')->having('field', 'value');
$this->assertEquals('SELECT * FROM table HAVING field = ?', $this->query->getSql()); $this->assertEquals('SELECT * FROM table HAVING field = ?', $this->query->getSql());
$this->assertEquals(array('value'), $this->query->getBinds()); $this->assertEquals(array('value'), $this->query->getBinds());
} }
public function testSelectHavingLike(){ public function testSelectHavingLike()
{
$this->query->select()->from('table')->having("field", "like", '%value%'); $this->query->select()->from('table')->having('field', 'like', '%value%');
$this->assertEquals('SELECT * FROM table HAVING field LIKE ?', $this->query->getSql()); $this->assertEquals('SELECT * FROM table HAVING field LIKE ?', $this->query->getSql());
$this->assertEquals(array('%value%'), $this->query->getBinds()); $this->assertEquals(array('%value%'), $this->query->getBinds());
} }
public function testSelectHavingBetween(){ public function testSelectHavingBetween()
{
$this->query->select()->from('table')->having("field", "between", array(2, 4)); $this->query->select()->from('table')->having('field', 'between', array(2, 4));
$this->assertEquals('SELECT * FROM table HAVING field BETWEEN ? AND ?', $this->query->getSql()); $this->assertEquals('SELECT * FROM table HAVING field BETWEEN ? AND ?', $this->query->getSql());
$this->assertEquals(array(2, 4), $this->query->getBinds()); $this->assertEquals(array(2, 4), $this->query->getBinds());
} }
public function testSelectHavingIn(){ public function testSelectHavingIn()
{
$this->query->select()->from('table')->having("field", "in", array(2, 3, 4)); $this->query->select()->from('table')->having('field', 'in', array(2, 3, 4));
$this->assertEquals('SELECT * FROM table HAVING field IN (?,?,?)', $this->query->getSql()); $this->assertEquals('SELECT * FROM table HAVING field IN (?,?,?)', $this->query->getSql());
$this->assertEquals(array(2, 3, 4), $this->query->getBinds()); $this->assertEquals(array(2, 3, 4), $this->query->getBinds());
} }
public function testSelectHavingNot(){ public function testSelectHavingNot()
{
$this->query->select()->from('table')->having("field", "<>", "value"); $this->query->select()->from('table')->having('field', '<>', 'value');
$this->assertEquals('SELECT * FROM table HAVING field <> ?', $this->query->getSql()); $this->assertEquals('SELECT * FROM table HAVING field <> ?', $this->query->getSql());
$this->assertEquals(array('value'), $this->query->getBinds()); $this->assertEquals(array('value'), $this->query->getBinds());
} }
public function testSelectHavingGreater(){ public function testSelectHavingGreater()
{
$this->query->select()->from('table')->having("field", ">", "value"); $this->query->select()->from('table')->having('field', '>', 'value');
$this->assertEquals('SELECT * FROM table HAVING field > ?', $this->query->getSql()); $this->assertEquals('SELECT * FROM table HAVING field > ?', $this->query->getSql());
$this->assertEquals(array('value'), $this->query->getBinds()); $this->assertEquals(array('value'), $this->query->getBinds());
} }
public function testSelectHavingGreaterEqual(){ public function testSelectHavingGreaterEqual()
{
$this->query->select()->from('table')->having("field", ">=", "value"); $this->query->select()->from('table')->having('field', '>=', 'value');
$this->assertEquals('SELECT * FROM table HAVING field >= ?', $this->query->getSql()); $this->assertEquals('SELECT * FROM table HAVING field >= ?', $this->query->getSql());
$this->assertEquals(array('value'), $this->query->getBinds()); $this->assertEquals(array('value'), $this->query->getBinds());
} }
public function testSelectHavingSmaller(){ public function testSelectHavingSmaller()
{
$this->query->select()->from('table')->having("field", "<", "value"); $this->query->select()->from('table')->having('field', '<', 'value');
$this->assertEquals('SELECT * FROM table HAVING field < ?', $this->query->getSql()); $this->assertEquals('SELECT * FROM table HAVING field < ?', $this->query->getSql());
$this->assertEquals(array('value'), $this->query->getBinds()); $this->assertEquals(array('value'), $this->query->getBinds());
} }
public function testSelectHavingSmallerEqual(){ public function testSelectHavingSmallerEqual()
{
$this->query->select()->from('table')->having("field", "<=", "value"); $this->query->select()->from('table')->having('field', '<=', 'value');
$this->assertEquals('SELECT * FROM table HAVING field <= ?', $this->query->getSql()); $this->assertEquals('SELECT * FROM table HAVING field <= ?', $this->query->getSql());
$this->assertEquals(array('value'), $this->query->getBinds()); $this->assertEquals(array('value'), $this->query->getBinds());
} }
public function testSelectHavingAnd(){ public function testSelectHavingAnd()
{
$this->query->select()->from('table')->having("field1", "value1")->and()->where("field2", "value2"); $this->query->select()->from('table')->having('field1', 'value1')->and()->where('field2', 'value2');
$this->assertEquals('SELECT * FROM table HAVING field1 = ? AND field2 = ?', $this->query->getSql()); $this->assertEquals('SELECT * FROM table HAVING field1 = ? AND field2 = ?', $this->query->getSql());
$this->assertEquals(array('value1', 'value2'), $this->query->getBinds()); $this->assertEquals(array('value1', 'value2'), $this->query->getBinds());
} }
public function testSelectHavingAndOpen(){ public function testSelectHavingAndOpen()
{
$this->query->select()->from('table')->having("field1", "value1")->and()->open()->where("field2", "value2")->or()->where("field3", "value3")->close(); $this->query->select()->from('table')->having('field1', 'value1')->and()->open()->where('field2', 'value2')->or()->where('field3', 'value3')->close();
$this->assertEquals('SELECT * FROM table HAVING field1 = ? AND ( field2 = ? OR field3 = ? )', $this->query->getSql()); $this->assertEquals('SELECT * FROM table HAVING field1 = ? AND ( field2 = ? OR field3 = ? )', $this->query->getSql());
$this->assertEquals(array('value1', 'value2', 'value3'), $this->query->getBinds()); $this->assertEquals(array('value1', 'value2', 'value3'), $this->query->getBinds());
} }
public function testSelectHavingOr(){ public function testSelectHavingOr()
{
$this->query->select()->from('table')->having("field1", "value1")->or()->where("field2", "value2"); $this->query->select()->from('table')->having('field1', 'value1')->or()->where('field2', 'value2');
$this->assertEquals('SELECT * FROM table HAVING field1 = ? OR field2 = ?', $this->query->getSql()); $this->assertEquals('SELECT * FROM table HAVING field1 = ? OR field2 = ?', $this->query->getSql());
$this->assertEquals(array('value1', 'value2'), $this->query->getBinds()); $this->assertEquals(array('value1', 'value2'), $this->query->getBinds());
} }
public function testSelectHavingOrOpen(){ public function testSelectHavingOrOpen()
{
$this->query->select()->from('table')->having("field1", "value1")->or()->open()->where("field2", "value2")->and()->where("field3", "value3")->close(); $this->query->select()->from('table')->having('field1', 'value1')->or()->open()->where('field2', 'value2')->and()->where('field3', 'value3')->close();
$this->assertEquals('SELECT * FROM table HAVING field1 = ? OR ( field2 = ? AND field3 = ? )', $this->query->getSql()); $this->assertEquals('SELECT * FROM table HAVING field1 = ? OR ( field2 = ? AND field3 = ? )', $this->query->getSql());
$this->assertEquals(array('value1', 'value2', 'value3'), $this->query->getBinds()); $this->assertEquals(array('value1', 'value2', 'value3'), $this->query->getBinds());
} }
public function testSelectHavingOpen(){ public function testSelectHavingOpen()
{
$this->query->select()->from('table') $this->query->select()->from('table')
->having()->open()->where("field1", "value1")->and()->where("field2", "value2")->close() ->having()->open()->where('field1', 'value1')->and()->where('field2', 'value2')->close()
->or()->where('field3', 'value3'); ->or()->where('field3', 'value3');
$this->assertEquals('SELECT * FROM table HAVING ( field1 = ? AND field2 = ? ) OR field3 = ?', $this->query->getSql()); $this->assertEquals('SELECT * FROM table HAVING ( field1 = ? AND field2 = ? ) OR field3 = ?', $this->query->getSql());
$this->assertEquals(array('value1', 'value2', 'value3'), $this->query->getBinds()); $this->assertEquals(array('value1', 'value2', 'value3'), $this->query->getBinds());
@ -357,16 +358,16 @@ class QueryTests extends \CoreTestAbstract {
* Update * Update
*/ */
public function testUpdateSimple(){ public function testUpdateSimple()
{
$this->query->setTable('table')->update()->set(array('field' => 'value')); $this->query->setTable('table')->update()->set(array('field' => 'value'));
$this->assertEquals('UPDATE table SET field=?', $this->query->getSql()); $this->assertEquals('UPDATE table SET field=?', $this->query->getSql());
$this->assertEquals(array('value'), $this->query->getBinds()); $this->assertEquals(array('value'), $this->query->getBinds());
} }
public function testUpdateMultiple(){ public function testUpdateMultiple()
{
$this->query->setTable('table')->update()->set(array('field1' => 'value1', "field2" => 'value2')); $this->query->setTable('table')->update()->set(array('field1' => 'value1', 'field2' => 'value2'));
$this->assertEquals('UPDATE table SET field1=?, field2=?', $this->query->getSql()); $this->assertEquals('UPDATE table SET field1=?, field2=?', $this->query->getSql());
$this->assertEquals(array('value1', 'value2'), $this->query->getBinds()); $this->assertEquals(array('value1', 'value2'), $this->query->getBinds());
} }
@ -375,8 +376,8 @@ class QueryTests extends \CoreTestAbstract {
* Delete * Delete
*/ */
public function testDeleteSimple(){ public function testDeleteSimple()
{
$this->query->setTable('table')->delete(); $this->query->setTable('table')->delete();
$this->assertEquals('DELETE FROM table', $this->query->getSql()); $this->assertEquals('DELETE FROM table', $this->query->getSql());
} }
@ -385,120 +386,115 @@ class QueryTests extends \CoreTestAbstract {
* Insert * Insert
*/ */
public function testInsertSimple(){ public function testInsertSimple()
{
$this->query->insert(array('field' => 'value'), 'table'); $this->query->insert(array('field' => 'value'), 'table');
$this->assertEquals('INSERT INTO table (field) VALUES (?)', $this->query->getSql()); $this->assertEquals('INSERT INTO table (field) VALUES (?)', $this->query->getSql());
$this->assertEquals(array('value'), $this->query->getBinds()); $this->assertEquals(array('value'), $this->query->getBinds());
} }
public function testInsertMultiple(){ public function testInsertMultiple()
{
$this->query->insert(array('field1' => 'value1', 'field2' => 'value2'), 'table'); $this->query->insert(array('field1' => 'value1', 'field2' => 'value2'), 'table');
$this->assertEquals('INSERT INTO table (field1,field2) VALUES (?,?)', $this->query->getSql()); $this->assertEquals('INSERT INTO table (field1,field2) VALUES (?,?)', $this->query->getSql());
$this->assertEquals(array('value1', 'value2'), $this->query->getBinds()); $this->assertEquals(array('value1', 'value2'), $this->query->getBinds());
} }
/* /*
* Replace * Replace
*/ */
public function testReplaceSimple(){ public function testReplaceSimple()
{
$this->query->setTable('table')->replace(array('field' => 'value')); $this->query->setTable('table')->replace(array('field' => 'value'));
$this->assertEquals('REPLACE INTO table (field) VALUES (?)', $this->query->getSql()); $this->assertEquals('REPLACE INTO table (field) VALUES (?)', $this->query->getSql());
$this->assertEquals(array('value'), $this->query->getBinds()); $this->assertEquals(array('value'), $this->query->getBinds());
} }
public function testReplaceMultiple(){ public function testReplaceMultiple()
{
$this->query->setTable('table')->replace(array('field1' => 'value1', 'field2' => 'value2')); $this->query->setTable('table')->replace(array('field1' => 'value1', 'field2' => 'value2'));
$this->assertEquals('REPLACE INTO table (field1,field2) VALUES (?,?)', $this->query->getSql()); $this->assertEquals('REPLACE INTO table (field1,field2) VALUES (?,?)', $this->query->getSql());
$this->assertEquals(array('value1', 'value2'), $this->query->getBinds()); $this->assertEquals(array('value1', 'value2'), $this->query->getBinds());
} }
/* /*
* Joins * Joins
*/ */
public function testJoin(){ public function testJoin()
{
$this->query->select()->from('table')->join('other')->on("field", "value")->where("field", "value2"); $this->query->select()->from('table')->join('other')->on('field', 'value')->where('field', 'value2');
$this->assertEquals('SELECT * FROM table JOIN other ON field = ? WHERE field = ?', $this->query->getSql()); $this->assertEquals('SELECT * FROM table JOIN other ON field = ? WHERE field = ?', $this->query->getSql());
$this->assertEquals(array('value', 'value2'), $this->query->getBinds()); $this->assertEquals(array('value', 'value2'), $this->query->getBinds());
} }
public function testJoinLeft(){ public function testJoinLeft()
{
$this->query->select()->from('table')->left_join('other')->on("field", "value")->where("field", "value2"); $this->query->select()->from('table')->left_join('other')->on('field', 'value')->where('field', 'value2');
$this->assertEquals('SELECT * FROM table LEFT JOIN other ON field = ? WHERE field = ?', $this->query->getSql()); $this->assertEquals('SELECT * FROM table LEFT JOIN other ON field = ? WHERE field = ?', $this->query->getSql());
$this->assertEquals(array('value', 'value2'), $this->query->getBinds()); $this->assertEquals(array('value', 'value2'), $this->query->getBinds());
} }
public function testJoinRight(){ public function testJoinRight()
{
$this->query->select()->from('table')->right_join('other')->on("field", "value")->where("field", "value2"); $this->query->select()->from('table')->right_join('other')->on('field', 'value')->where('field', 'value2');
$this->assertEquals('SELECT * FROM table RIGHT JOIN other ON field = ? WHERE field = ?', $this->query->getSql()); $this->assertEquals('SELECT * FROM table RIGHT JOIN other ON field = ? WHERE field = ?', $this->query->getSql());
$this->assertEquals(array('value', 'value2'), $this->query->getBinds()); $this->assertEquals(array('value', 'value2'), $this->query->getBinds());
} }
public function testJoinFull(){ public function testJoinFull()
{
$this->query->select()->from('table')->full_join('other')->on("field", "value")->where("field", "value2"); $this->query->select()->from('table')->full_join('other')->on('field', 'value')->where('field', 'value2');
$this->assertEquals('SELECT * FROM table FULL JOIN other ON field = ? WHERE field = ?', $this->query->getSql()); $this->assertEquals('SELECT * FROM table FULL JOIN other ON field = ? WHERE field = ?', $this->query->getSql());
$this->assertEquals(array('value', 'value2'), $this->query->getBinds()); $this->assertEquals(array('value', 'value2'), $this->query->getBinds());
} }
public function testJoinAdvanced(){ public function testJoinAdvanced()
{
$this->query->select()->from('table') $this->query->select()->from('table')
->left_join('other_a')->on("field", "value") ->left_join('other_a')->on('field', 'value')
->right_join('other_b')->on("field", "value2") ->right_join('other_b')->on('field', 'value2')
->full_join('other_c')->on("field", "value3") ->full_join('other_c')->on('field', 'value3')
->where("field", "value4"); ->where('field', 'value4');
$this->assertEquals('SELECT * FROM table LEFT JOIN other_a ON field = ? RIGHT JOIN other_b ON field = ? FULL JOIN other_c ON field = ? WHERE field = ?', $this->query->getSql()); $this->assertEquals('SELECT * FROM table LEFT JOIN other_a ON field = ? RIGHT JOIN other_b ON field = ? FULL JOIN other_c ON field = ? WHERE field = ?', $this->query->getSql());
$this->assertEquals(array('value', 'value2', 'value3', 'value4'), $this->query->getBinds()); $this->assertEquals(array('value', 'value2', 'value3', 'value4'), $this->query->getBinds());
} }
/** /**
* Inline joins * Inline joins.
*/ */
public function testJoinInline(){ public function testJoinInline()
{
$this->query->select()->from('table t', 'other o')->where("o.field", "value"); $this->query->select()->from('table t', 'other o')->where('o.field', 'value');
$this->assertEquals('SELECT * FROM table t, other o WHERE o.field = ?', $this->query->getSql()); $this->assertEquals('SELECT * FROM table t, other o WHERE o.field = ?', $this->query->getSql());
$this->assertEquals(array('value'), $this->query->getBinds()); $this->assertEquals(array('value'), $this->query->getBinds());
} }
public function testJoinInlineAdvanced(){ public function testJoinInlineAdvanced()
{
$this->query->select()->from('table t', 'other o')->where("o.field = t.field"); $this->query->select()->from('table t', 'other o')->where('o.field = t.field');
$this->assertEquals('SELECT * FROM table t, other o WHERE o.field = t.field', $this->query->getSql()); $this->assertEquals('SELECT * FROM table t, other o WHERE o.field = t.field', $this->query->getSql());
$this->assertEmpty($this->query->getBinds()); $this->assertEmpty($this->query->getBinds());
} }
public function testJoinAllInOne(){ public function testJoinAllInOne()
{
$this->query->select() $this->query->select()
->from('table t', 'other o') ->from('table t', 'other o')
->left_join('third th')->on('th.field = o.field') ->left_join('third th')->on('th.field = o.field')
->where("o.field = t.field") ->where('o.field = t.field')
->and()->where('t.thing', '>', 25); ->and()->where('t.thing', '>', 25);
$this->assertEquals('SELECT * FROM table t, other o LEFT JOIN third th ON th.field = o.field WHERE o.field = t.field AND t.thing > ?', $this->query->getSql()); $this->assertEquals('SELECT * FROM table t, other o LEFT JOIN third th ON th.field = o.field WHERE o.field = t.field AND t.thing > ?', $this->query->getSql());
$this->assertEquals(array(25), $this->query->getBinds()); $this->assertEquals(array(25), $this->query->getBinds());
} }
/** /**
* Group by * Group by.
*/ */
public function testSelectGroupBy()
public function testSelectGroupBy(){ {
$this->query->groupBy('field1', 'field2'); $this->query->groupBy('field1', 'field2');
$this->assertEquals('GROUP BY field1, field2', $this->query->getSql()); $this->assertEquals('GROUP BY field1, field2', $this->query->getSql());
} }
} }

View File

@ -1,6 +1,6 @@
<?php <?php
/** /**
* FuzeWorks * FuzeWorks.
* *
* The FuzeWorks MVC PHP FrameWork * The FuzeWorks MVC PHP FrameWork
* *
@ -20,25 +20,26 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
* *
* @author TechFuze * @author TechFuze
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
* @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/) * @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/)
* @license http://opensource.org/licenses/GPL-3.0 GPLv3 License * @license http://opensource.org/licenses/GPL-3.0 GPLv3 License
*
* @link http://fuzeworks.techfuze.net * @link http://fuzeworks.techfuze.net
* @since Version 0.0.1 * @since Version 0.0.1
*
* @version Version 0.0.1 * @version Version 0.0.1
*/ */
use \FuzeWorks\Core;
use \FuzeWorks\Router; use \FuzeWorks\Router;
/** /**
* Class RouterTest * Class RouterTest.
* *
* This test will test the router * This test will test the router
*/ */
class RouterTest extends CoreTestAbstract class routerTest extends CoreTestAbstract
{ {
public function testParsePath(){ public function testParsePath()
{
// Act and assert // Act and assert
Router::setPath('a/b/c/d/'); Router::setPath('a/b/c/d/');
@ -63,7 +64,8 @@ class RouterTest extends CoreTestAbstract
/** /**
* @depends testParsePath * @depends testParsePath
*/ */
public function testDoRoute(){ public function testDoRoute()
{
// Act // Act
Router::setPath('a/b/c/d/'); Router::setPath('a/b/c/d/');
@ -71,7 +73,7 @@ class RouterTest extends CoreTestAbstract
// Assert // Assert
// Whole route // Whole route
$this->assertEquals(array('a','b','c/d'), array(Router::getMatches()['controller'], Router::getMatches()['function'], Router::getMatches()['parameters'])); $this->assertEquals(array('a', 'b', 'c/d'), array(Router::getMatches()['controller'], Router::getMatches()['function'], Router::getMatches()['parameters']));
$this->assertEquals('a', Router::getMatches()['controller']); $this->assertEquals('a', Router::getMatches()['controller']);
// Parameters // Parameters
@ -85,7 +87,8 @@ class RouterTest extends CoreTestAbstract
/** /**
* @depends testDoRoute * @depends testDoRoute
*/ */
public function testOddRoutes(){ public function testOddRoutes()
{
// Empty path // Empty path
Router::setPath(null); Router::setPath(null);
@ -95,23 +98,23 @@ class RouterTest extends CoreTestAbstract
// Double slashes // Double slashes
Router::setPath('a///b'); Router::setPath('a///b');
Router::route(false); Router::route(false);
$this->assertEquals(array('a','b'), array(Router::getMatches()['controller'], Router::getMatches()['function'])); $this->assertEquals(array('a', 'b'), array(Router::getMatches()['controller'], Router::getMatches()['function']));
// Escaped path path // Escaped path path
Router::setPath('/a\/b\/c/'); Router::setPath('/a\/b\/c/');
Router::route(false); Router::route(false);
$this->assertEquals(array('a\\','b\\','c'), array(Router::getMatches()['controller'], Router::getMatches()['function'], Router::getMatches()['parameters'])); $this->assertEquals(array('a\\', 'b\\', 'c'), array(Router::getMatches()['controller'], Router::getMatches()['function'], Router::getMatches()['parameters']));
$this->assertNotEquals('a', Router::getMatches()['controller']); $this->assertNotEquals('a', Router::getMatches()['controller']);
} }
public function testCustomRoute(){ public function testCustomRoute()
{
Router::addRoute('/test1\/test2/', 'callable'); Router::addRoute('/test1\/test2/', 'callable');
$this->assertArraySubset(array('/test1\/test2/' => 'callable'), Router::getRoutes()); $this->assertArraySubset(array('/test1\/test2/' => 'callable'), Router::getRoutes());
} }
public function testCustomRouteWithParameters(){ public function testCustomRouteWithParameters()
{
Router::addRoute('/^b\/(?P<controller>[^\/]+)\/?(?P<function>.+?)$/', 'callable'); Router::addRoute('/^b\/(?P<controller>[^\/]+)\/?(?P<function>.+?)$/', 'callable');
Router::addRoute('/e\/(?P<function>[^\/]+)/', 'callable'); Router::addRoute('/e\/(?P<function>[^\/]+)/', 'callable');
Router::addRoute('/b\/b$/', 'callable'); Router::addRoute('/b\/b$/', 'callable');
@ -136,4 +139,4 @@ class RouterTest extends CoreTestAbstract
$this->assertEquals('a', Router::getMatches()['controller']); $this->assertEquals('a', Router::getMatches()['controller']);
$this->assertEquals('b', Router::getMatches()['function']); $this->assertEquals('b', Router::getMatches()['function']);
} }
} }

View File

@ -1,6 +1,6 @@
<?php <?php
/** /**
* FuzeWorks * FuzeWorks.
* *
* The FuzeWorks MVC PHP FrameWork * The FuzeWorks MVC PHP FrameWork
* *
@ -20,32 +20,33 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
* *
* @author TechFuze * @author TechFuze
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
* @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/) * @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/)
* @license http://opensource.org/licenses/GPL-3.0 GPLv3 License * @license http://opensource.org/licenses/GPL-3.0 GPLv3 License
*
* @link http://fuzeworks.techfuze.net * @link http://fuzeworks.techfuze.net
* @since Version 0.0.1 * @since Version 0.0.1
*
* @version Version 0.0.1 * @version Version 0.0.1
*/ */
use \FuzeWorks\Core; use \FuzeWorks\Core;
use \FuzeWorks\Events; use \FuzeWorks\Events;
use \FuzeWorks\EventPriority; use \FuzeWorks\EventPriority;
/** /**
* Class CoreStartEventTest * Class CoreStartEventTest.
*/ */
class CoreStartEventTest extends CoreTestAbstract class coreStartEventTest extends CoreTestAbstract
{ {
/** /**
* Check if the event is fired when it should be * Check if the event is fired when it should be.
*/ */
public function testCoreStartEvent(){ public function testCoreStartEvent()
{
$mock = $this->getMock('MockEvent', array('mockMethod')); $mock = $this->getMock('MockEvent', array('mockMethod'));
$mock->expects($this->once())->method('mockMethod'); $mock->expects($this->once())->method('mockMethod');
Events::addListener(array($mock, 'mockMethod'), 'coreStartEvent', EventPriority::NORMAL); Events::addListener(array($mock, 'mockMethod'), 'coreStartEvent', EventPriority::NORMAL);
Core::init(); Core::init();
} }
} }

View File

@ -1,6 +1,6 @@
<?php <?php
/** /**
* FuzeWorks * FuzeWorks.
* *
* The FuzeWorks MVC PHP FrameWork * The FuzeWorks MVC PHP FrameWork
* *
@ -20,28 +20,29 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
* *
* @author TechFuze * @author TechFuze
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
* @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/) * @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/)
* @license http://opensource.org/licenses/GPL-3.0 GPLv3 License * @license http://opensource.org/licenses/GPL-3.0 GPLv3 License
*
* @link http://fuzeworks.techfuze.net * @link http://fuzeworks.techfuze.net
* @since Version 0.0.1 * @since Version 0.0.1
*
* @version Version 0.0.1 * @version Version 0.0.1
*/ */
use \FuzeWorks\Events; use \FuzeWorks\Events;
use \FuzeWorks\Layout; use \FuzeWorks\Layout;
use \FuzeWorks\EventPriority; use \FuzeWorks\EventPriority;
/** /**
* Class LayoutLoadViewEventTest * Class LayoutLoadViewEventTest.
*/ */
class LayoutLoadViewEventTest extends CoreTestAbstract{ class layoutLoadViewEventTest extends CoreTestAbstract
{
/** /**
* Check if the event is fired when it should be * Check if the event is fired when it should be.
*/ */
public function test_basic(){ public function test_basic()
{
$mock = $this->getMock('MockEvent', array('mockMethod')); $mock = $this->getMock('MockEvent', array('mockMethod'));
$mock->expects($this->once())->method('mockMethod'); $mock->expects($this->once())->method('mockMethod');
@ -52,31 +53,35 @@ class LayoutLoadViewEventTest extends CoreTestAbstract{
} }
/** /**
* Intercept and change the event * Intercept and change the event.
*
* @expectedException \FuzeWorks\LayoutException * @expectedException \FuzeWorks\LayoutException
*/ */
public function test_change(){ public function test_change()
{
Events::addListener(array($this, 'listener_change'), 'layoutLoadViewEvent', EventPriority::NORMAL); Events::addListener(array($this, 'listener_change'), 'layoutLoadViewEvent', EventPriority::NORMAL);
Layout::get('home'); Layout::get('home');
} }
// Change title from new to other // Change title from new to other
public function listener_change($event){ public function listener_change($event)
{
// This controller should not exist // This controller should not exist
$this->assertEquals('Application/Views/view.home.php', $event->file); $this->assertEquals('Application/Views/view.home.php', $event->file);
$this->assertEquals('Application/Views/', $event->directory); $this->assertEquals('Application/Views/', $event->directory);
// It should exist now // It should exist now
$event->file = 'Application/Views/view.test.not_found'; $event->file = 'Application/Views/view.test.not_found';
return $event; return $event;
} }
/** /**
* Cancel events * Cancel events.
*/ */
public function test_cancel(){ public function test_cancel()
{
// Listen for the event and cancel it // Listen for the event and cancel it
Events::addListener(array($this, 'listener_cancel'), 'layoutLoadViewEvent', EventPriority::NORMAL); Events::addListener(array($this, 'listener_cancel'), 'layoutLoadViewEvent', EventPriority::NORMAL);
@ -84,8 +89,8 @@ class LayoutLoadViewEventTest extends CoreTestAbstract{
} }
// Cancel all calls // Cancel all calls
public function listener_cancel($event){ public function listener_cancel($event)
{
$event->setCancelled(true); $event->setCancelled(true);
} }
} }

View File

@ -1,6 +1,6 @@
<?php <?php
/** /**
* FuzeWorks * FuzeWorks.
* *
* The FuzeWorks MVC PHP FrameWork * The FuzeWorks MVC PHP FrameWork
* *
@ -20,33 +20,37 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
* *
* @author TechFuze * @author TechFuze
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
* @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/) * @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/)
* @license http://opensource.org/licenses/GPL-3.0 GPLv3 License * @license http://opensource.org/licenses/GPL-3.0 GPLv3 License
*
* @link http://fuzeworks.techfuze.net * @link http://fuzeworks.techfuze.net
* @since Version 0.0.1 * @since Version 0.0.1
*
* @version Version 0.0.1 * @version Version 0.0.1
*/ */
use \FuzeWorks\Events; use \FuzeWorks\Events;
use \FuzeWorks\Router; use \FuzeWorks\Router;
use \FuzeWorks\EventPriority; use \FuzeWorks\EventPriority;
/** /**
* Class RouterLoadCallableEventTest * Class RouterLoadCallableEventTest.
*/ */
class RouterLoadCallableEventTest extends CoreTestAbstract{ class routerLoadCallableEventTest extends CoreTestAbstract
{
/** /**
* Check if the event is fired when it should be * Check if the event is fired when it should be.
*/ */
public function test_basic(){ public function test_basic()
{
$mock = $this->getMock('MockEvent', array('mockMethod')); $mock = $this->getMock('MockEvent', array('mockMethod'));
$mock->expects($this->once())->method('mockMethod'); $mock->expects($this->once())->method('mockMethod');
Router::setPath('/'); Router::setPath('/');
Events::addListener(function($event){$event->setCancelled(true);}, 'layoutLoadViewEvent', EventPriority::HIGHEST); Events::addListener(function ($event) {
$event->setCancelled(true);
}, 'layoutLoadViewEvent', EventPriority::HIGHEST);
Events::addListener(array($mock, 'mockMethod'), 'routerLoadCallableEvent', EventPriority::NORMAL); Events::addListener(array($mock, 'mockMethod'), 'routerLoadCallableEvent', EventPriority::NORMAL);
//Prevent ouputting HTML //Prevent ouputting HTML
@ -56,17 +60,23 @@ class RouterLoadCallableEventTest extends CoreTestAbstract{
} }
/** /**
* Intercept and change * Intercept and change.
*/ */
public function test_change(){ public function test_change()
{
Events::addListener(function ($event) {
$event->setCancelled(true);
Events::addListener(function($event){$event->setCancelled(true);}, 'layoutLoadViewEvent', EventPriority::HIGHEST); }, 'layoutLoadViewEvent', EventPriority::HIGHEST);
Events::addListener(array($this, 'listener_change'), 'routerLoadCallableEvent', EventPriority::NORMAL); Events::addListener(array($this, 'listener_change'), 'routerLoadCallableEvent', EventPriority::NORMAL);
Router::setPath('x/y/z'); Router::setPath('x/y/z');
Router::route(true); Router::route(true);
Events::$listeners = array(); Events::$listeners = array();
Events::addListener(function($event){$event->setCancelled(true);}, 'layoutLoadViewEvent', EventPriority::HIGHEST); Events::addListener(function ($event) {
$event->setCancelled(true);
}, 'layoutLoadViewEvent', EventPriority::HIGHEST);
Events::addListener(array($this, 'listener_change'), 'routerLoadCallableEvent', EventPriority::NORMAL); Events::addListener(array($this, 'listener_change'), 'routerLoadCallableEvent', EventPriority::NORMAL);
Router::setPath('x/y/z'); Router::setPath('x/y/z');
Router::route(true); Router::route(true);
@ -76,23 +86,25 @@ class RouterLoadCallableEventTest extends CoreTestAbstract{
} }
// Change title from new to other // Change title from new to other
public function listener_change($event){ public function listener_change($event)
{
// This controller should not exist // This controller should not exist
$this->assertEquals('x', $event->matches['controller']); $this->assertEquals('x', $event->matches['controller']);
$this->assertEquals('y', $event->matches['function']); $this->assertEquals('y', $event->matches['function']);
// It should exist now // It should exist now
$event->matches['controller'] = 'standard'; $event->matches['controller'] = 'standard';
$event->matches['function'] = 'index'; $event->matches['function'] = 'index';
return $event; return $event;
} }
/** /**
* Cancel events * Cancel events.
*/ */
public function test_cancel(){ public function test_cancel()
{
ob_start(); ob_start();
// When the callable may execute, the callable will change to the controller // When the callable may execute, the callable will change to the controller
// (because '' will trigger the default callable) // (because '' will trigger the default callable)
@ -105,7 +117,10 @@ class RouterLoadCallableEventTest extends CoreTestAbstract{
// When disabled, the default controller will be loaded and the callable will be overwritten // When disabled, the default controller will be loaded and the callable will be overwritten
// Remove the listener // Remove the listener
Events::$listeners = array(); Events::$listeners = array();
Events::addListener(function($event){$event->setCancelled(true);}, 'layoutLoadViewEvent', EventPriority::HIGHEST); Events::addListener(function ($event) {
$event->setCancelled(true);
}, 'layoutLoadViewEvent', EventPriority::HIGHEST);
Router::route(); Router::route();
$this->assertFalse(is_callable(Router::getCallable())); $this->assertFalse(is_callable(Router::getCallable()));
@ -113,8 +128,8 @@ class RouterLoadCallableEventTest extends CoreTestAbstract{
} }
// Cancel all calls // Cancel all calls
public function listener_cancel($event){ public function listener_cancel($event)
{
$event->setCancelled(true); $event->setCancelled(true);
} }
} }

View File

@ -1,6 +1,6 @@
<?php <?php
/** /**
* FuzeWorks * FuzeWorks.
* *
* The FuzeWorks MVC PHP FrameWork * The FuzeWorks MVC PHP FrameWork
* *
@ -20,28 +20,29 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
* *
* @author TechFuze * @author TechFuze
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
* @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/) * @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/)
* @license http://opensource.org/licenses/GPL-3.0 GPLv3 License * @license http://opensource.org/licenses/GPL-3.0 GPLv3 License
*
* @link http://fuzeworks.techfuze.net * @link http://fuzeworks.techfuze.net
* @since Version 0.0.1 * @since Version 0.0.1
*
* @version Version 0.0.1 * @version Version 0.0.1
*/ */
use \FuzeWorks\Events; use \FuzeWorks\Events;
use \FuzeWorks\Router; use \FuzeWorks\Router;
use \FuzeWorks\EventPriority; use \FuzeWorks\EventPriority;
/** /**
* Class RouterRouteEventTest * Class RouterRouteEventTest.
*/ */
class RouterRouteEventTest extends CoreTestAbstract{ class routerRouteEventTest extends CoreTestAbstract
{
/** /**
* Check if the event is fired when it should be * Check if the event is fired when it should be.
*/ */
public function test_basic(){ public function test_basic()
{
$mock = $this->getMock('MockEvent', array('mockMethod')); $mock = $this->getMock('MockEvent', array('mockMethod'));
$mock->expects($this->once())->method('mockMethod'); $mock->expects($this->once())->method('mockMethod');
@ -51,10 +52,10 @@ class RouterRouteEventTest extends CoreTestAbstract{
} }
/** /**
* Cancel events * Cancel events.
*/ */
public function test_cancel(){ public function test_cancel()
{
Router::setPath('x/y/z'); Router::setPath('x/y/z');
Events::addListener(array($this, 'listener_cancel'), 'routerRouteEvent', EventPriority::NORMAL); Events::addListener(array($this, 'listener_cancel'), 'routerRouteEvent', EventPriority::NORMAL);
@ -66,8 +67,8 @@ class RouterRouteEventTest extends CoreTestAbstract{
} }
// Cancel all calls // Cancel all calls
public function listener_cancel($event){ public function listener_cancel($event)
{
$event->setCancelled(true); $event->setCancelled(true);
} }
} }

View File

@ -1,6 +1,6 @@
<?php <?php
/** /**
* FuzeWorks * FuzeWorks.
* *
* The FuzeWorks MVC PHP FrameWork * The FuzeWorks MVC PHP FrameWork
* *
@ -20,28 +20,29 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
* *
* @author TechFuze * @author TechFuze
* @copyright Copyright (c) 2013 - 2015, Techfuze. (http://techfuze.net) * @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
* @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/) * @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/)
* @license http://opensource.org/licenses/GPL-3.0 GPLv3 License * @license http://opensource.org/licenses/GPL-3.0 GPLv3 License
*
* @link http://fuzeworks.techfuze.net * @link http://fuzeworks.techfuze.net
* @since Version 0.0.1 * @since Version 0.0.1
*
* @version Version 0.0.1 * @version Version 0.0.1
*/ */
use \FuzeWorks\Events; use \FuzeWorks\Events;
use \FuzeWorks\Router; use \FuzeWorks\Router;
use \FuzeWorks\EventPriority; use \FuzeWorks\EventPriority;
/** /**
* Class RouterSetPathEventTest * Class RouterSetPathEventTest.
*/ */
class RouterSetPathEventTest extends CoreTestAbstract{ class routerSetPathEventTest extends CoreTestAbstract
{
/** /**
* Check if the event is fired when it should be * Check if the event is fired when it should be.
*/ */
public function testRouterSetPathEvent(){ public function testRouterSetPathEvent()
{
$mock = $this->getMock('MockEvent', array('mockMethod')); $mock = $this->getMock('MockEvent', array('mockMethod'));
$mock->expects($this->once())->method('mockMethod'); $mock->expects($this->once())->method('mockMethod');
@ -50,10 +51,10 @@ class RouterSetPathEventTest extends CoreTestAbstract{
} }
/** /**
* Intercept and change * Intercept and change.
*/ */
public function testRouterSetPathEvent_change(){ public function testRouterSetPathEvent_change()
{
Events::addListener(array($this, 'listener_change'), 'routerSetPathEvent', EventPriority::NORMAL); Events::addListener(array($this, 'listener_change'), 'routerSetPathEvent', EventPriority::NORMAL);
Router::setPath('a/b/c'); Router::setPath('a/b/c');
@ -61,17 +62,17 @@ class RouterSetPathEventTest extends CoreTestAbstract{
} }
// Change title from new to other // Change title from new to other
public function listener_change($event){ public function listener_change($event)
{
$this->assertEquals('a/b/c', $event->path); $this->assertEquals('a/b/c', $event->path);
$event->path = 'x/y/z'; $event->path = 'x/y/z';
} }
/** /**
* Cancel events * Cancel events.
*/ */
public function testLayoutFunctionCallEvent_cancel(){ public function testLayoutFunctionCallEvent_cancel()
{
Router::setPath('a/b/c'); Router::setPath('a/b/c');
Events::addListener(array($this, 'listener_cancel'), 'routerSetPathEvent', EventPriority::NORMAL); Events::addListener(array($this, 'listener_cancel'), 'routerSetPathEvent', EventPriority::NORMAL);
@ -81,17 +82,16 @@ class RouterSetPathEventTest extends CoreTestAbstract{
} }
// Cancel all calls // Cancel all calls
public function listener_cancel($event){ public function listener_cancel($event)
{
$event->setCancelled(true); $event->setCancelled(true);
} }
/** /**
* Do not cancel events * Do not cancel events.
*/ */
public function testLayoutFunctionCallEvent_dontcancel(){ public function testLayoutFunctionCallEvent_dontcancel()
{
Router::setPath('a/b/c'); Router::setPath('a/b/c');
Events::addListener(array($this, 'listener_dontcancel'), 'routerSetPathEvent', EventPriority::NORMAL); Events::addListener(array($this, 'listener_dontcancel'), 'routerSetPathEvent', EventPriority::NORMAL);
@ -101,8 +101,8 @@ class RouterSetPathEventTest extends CoreTestAbstract{
} }
// Cancel all calls // Cancel all calls
public function listener_dontcancel($event){ public function listener_dontcancel($event)
{
$event->setCancelled(false); $event->setCancelled(false);
} }
} }

View File

@ -1 +1 @@
<?php echo "PHP Template Check"; ?> <?php echo 'PHP Template Check';