Implemented the Libraries system.

The system has been simplified and amended to implement all outstanding issues.
This commit is contained in:
Abel Hoogeveen 2018-10-07 21:29:48 +02:00
parent 1721869932
commit cc351c1a02
No known key found for this signature in database
GPG Key ID: 96C2234920BF4292
11 changed files with 431 additions and 807 deletions

View File

@ -84,10 +84,11 @@ class Configurator
/**
* Sets path to temporary directory.
*
* @param string $path
* @return Configurator
* @throws InvalidArgumentException
*/
public function setLogDirectory($path)
public function setLogDirectory(string $path)
{
if (!is_dir($path))
throw new InvalidArgumentException("Could not set log directory. Directory does not exist", 1);
@ -99,10 +100,11 @@ class Configurator
/**
* Sets path to temporary directory.
*
* @param string $path
* @return Configurator
* @throws InvalidArgumentException
*/
public function setTempDirectory($path)
public function setTempDirectory(string $path)
{
if (!is_dir($path))
throw new InvalidArgumentException("Could not set temp directory. Directory does not exist", 1);

View File

@ -35,432 +35,227 @@
*/
namespace FuzeWorks;
use FuzeWorks\Exception\LibraryException;
use FuzeWorks\Exception\ConfigException;
/**
* Libraries Class.
*
* FuzeWorks allows the user to use the built-in libraries as-is, and use it's functionality to get jobs done.
*
* If a user wants to make their own libraries, they have, in general, 3 options:
* 1. Create a completely new library
* 2. Extend an existing library
* 3. Replace an existing library
*
* The first option is done by adding a new library to the Application/Libraries folder. If the library name is 'Example' then the
* file should be 'Application/Libraries/Example.php' and the classname should be Example. Code can be added and it can be
* loaded through Libraries->get('example');.
*
* The second option allows the user to extend an existing core library. All functionality will be inherited in that situation. Let's take
* the 'Zip' library as an example. The user needs to create a file in Application/Libraries. The name of the file and the class depend on
* the configuration of FuzeWorks. The extended class needs to get a prefix, which is defined in config.main.php. By default, this is 'MY_'.
* The user needs to create the file 'Application/Libraries/MY_Zip.php' with the classname MY_Zip. It can be loaded through Libraries->get('zip');.
*
* The third option allows the user to replace a system library with their own. Doing so could potentially break systems, so be careful.
* If, for example we want to replace the Zip library, we need to create the file 'Application/Libraries/Zip.php' with the classname FW_Zip.
* 'FW_' is the prefix for all FuzeWorks core libraries. And that's it. It can be loaded through Libraries->get('zip');.
*
* @todo Implement events
* @author TechFuze <contact@techfuze.net>
* @copyright Copyright (c) 2013 - 2018, Techfuze. (http://techfuze.net)
*/
use FuzeWorks\Exception\ConfigException;
use FuzeWorks\Exception\LibraryException;
class Libraries
{
/**
* Array of all the paths where libraries can be found
*
* @var array Library paths
*/
protected $libraryPaths = [];
/**
* Factory object for interaction with FuzeWorks
*
* @var Factory
*/
protected $factory;
/**
* Array of loaded library objects
*
* @var array Library objects
*/
protected $libraryObjects = [];
/**
* Array of all the paths where libraries can be found
*
* @var array Library paths
*/
protected $libraryPaths = array();
/**
* Array of libraries with their classnames, so they can be easily loaded
*
* @var array Library classes
*/
protected $libraryClasses = [];
/**
* Array of all the loaded library objects
*
* @var array All the loaded library objects, so they can be returned when reloading
*/
protected $libraries = array();
/**
* FuzeWorks Factory object. For internal use.
*
* @var Factory
*/
protected $factory;
/**
* Attach the Factory to this class
*/
public function __construct()
{
$this->factory = Factory::getInstance();
$this->libraryPaths = Core::$appDirs;
$this->libraryPaths[] = Core::$coreDir . DS . 'Libraries';
}
/**
* Libraries constructor.
*
* @codeCoverageIgnore
*/
public function __construct()
{
$this->factory = Factory::getInstance();
}
/**
* Library Loader
*
* Loads, instantiates and returns libraries.
*
* @param string $library Library name
* @param array $params Optional parameters to pass to the library class constructor
* @param array $directory Optional list of directories where the library can be found. Overrides default list
* @param bool $newInstance Whether to return a new instance of the library or the same one
* @return object
* @throws LibraryException
*/
public function get($libraryName, array $parameters = null, array $directory = null, $newInstance = false)
{
if (empty($libraryName))
{
throw new LibraryException("Could not load library. No name provided", 1);
}
/**
* Add a library to FuzeWorks by adding an object.
*
* @param string $libraryName
* @param object $libraryObject
*/
public function addLibraryObject(string $libraryName, $libraryObject)
{
$this->libraryObjects[strtolower($libraryName)] = $libraryObject;
}
return $this->loadLibrary($libraryName, $parameters, $directory, $newInstance);
}
/**
* Add a library to FuzeWorks by adding its class name.
*
* @param string $libraryName
* @param string $libraryClass
* @throws LibraryException
*/
public function addLibraryClass(string $libraryName, string $libraryClass)
{
if (!class_exists($libraryClass, false))
throw new LibraryException("Could not add library class. '" . $libraryClass . "' could not be loaded.", 1);
/**
* Driver Library Loader
*
* Loads, instantiates and returns driver libraries.
*
* @param string $library Driver Library name
* @param array $params Optional parameters to pass to the library class constructor
* @param array $directory Optional list of directories where the library can be found. Overrides default list
* @param bool $newInstance Whether to return a new instance of the library or the same one
* @return object
* @throws LibraryException
*/
public function getDriver($libraryName, array $parameters = null, array $directory = null, $newInstance = false)
{
if (empty($libraryName))
{
throw new LibraryException("Could not load driver. No name provided", 1);
}
$this->libraryClasses[strtolower($libraryName)] = $libraryClass;
}
// Load the driver class if it is not yet loaded
if ( ! class_exists('FuzeWorks\FW_Driver_Library', false))
{
require_once(Core::$coreDir . DS . 'Libraries'.DS.'Driver.php');
}
/**
* Retrieve a library.
*
* Loads a library from one of the following sources in the following order:
* - From the loaded libraries
* - From the known libraryClasses
* - From the provided alternate library directory
* - From the earlier provided libraryPaths
*
* @param string $libraryName
* @param array $parameters
* @param string $altDirectory
* @return object
* @throws LibraryException
*/
public function get(string $libraryName, array $parameters = [], string $altDirectory = '')
{
// Test for empty string
if (empty($libraryName))
{
throw new LibraryException("Could not load library. No name provided", 1);
}
// And then load and return the library
return $this->loadLibrary($libraryName, $parameters, $directory, $newInstance);
}
// Test if the library already exists
$libraryNameLowerCase = strtolower($libraryName);
$libraryClassname = '\Application\Library\\' . ucfirst($libraryName);
$libraryFilename = ucfirst($libraryName);
if (isset($this->libraryObjects[$libraryNameLowerCase]))
return $this->libraryObjects[$libraryNameLowerCase];
/**
* Internal Library Loader
*
* Determines what type of library needs to be loaded
*
* @param string $library Library name
* @param array $params Optional parameters to pass to the library class constructor
* @param array $directory Optional list of directories where the library can be found. Overrides default list
* @param bool $newInstance Whether to return a new instance of the library or the same one
* @return object
* @throws LibraryException
*/
protected function loadLibrary($libraryName, $parameters = null, array $directory = null, $newInstance = false)
{
// First get the directories where the library can be located
$directories = (is_null($directory) ? $this->libraryPaths : $directory);
// Library not found. First test if the libraryClass exists
if (isset($this->libraryClasses[$libraryNameLowerCase]))
return $this->initLibrary($libraryName, $this->libraryClasses[$libraryNameLowerCase], $parameters);
// Now figure out the className and subdir
$class = trim($libraryName, '/');
if (($last_slash = strrpos($class, '/')) !== FALSE)
{
// Extract the path
$subdir = substr($class, 0, ++$last_slash);
// Try and load from the alternate directory if provided
$paths = $this->libraryPaths;
if (!empty($altDirectory))
array_unshift($paths, $altDirectory);
// Get the filename from the path
$class = substr($class, $last_slash);
}
else
{
$subdir = '';
}
// Try and find the library in the libraryPaths
foreach ($paths as $path)
{
// First look if a .php file exists in the libraryPath
$classFile = $path . DS . $libraryFilename . '.php';
if (file_exists($classFile))
{
require_once($classFile);
return $this->initLibrary($libraryName, $libraryClassname);
}
$class = ucfirst($class);
$classFile = $path . DS . $libraryFilename . DS . $libraryFilename . '.php';
if (file_exists($classFile))
{
require_once($classFile);
return $this->initLibrary($libraryName, $libraryClassname);
}
}
// Is the library a core library, then load a core library
if (file_exists(Core::$coreDir . DS . 'Libraries'.DS.$subdir.$class.'.php'))
{
// Load base library
return $this->loadCoreLibrary($class, $subdir, $parameters, $directories, $newInstance);
}
// Throw exception if not found
throw new LibraryException("Could not load library. Library not found.", 1);
}
// Otherwise try and load an Application Library
return $this->loadAppLibrary($class, $subdir, $parameters, $directories, $newInstance);
}
/**
* Library Initializer
*
* Instantiates and returns a library.
* Determines whether to use the parameters array or a config file
*
* @param string $libraryName
* @param string $libraryClass
* @param array $parameters
* @throws LibraryException
* @return object
*/
protected function initLibrary(string $libraryName, string $libraryClass, array $parameters = [])
{
// First check to see if the library is already loaded
if (!class_exists($libraryClass, false))
{
throw new LibraryException("Could not initiate library. Class not found", 1);
}
/**
* Core Library Loader
*
* Loads, instantiates and returns a core library.
*
* @param string $class Classname
* @param string $subdir Sub directory in which the final class can be found
* @param array $params Optional parameters to pass to the library class constructor
* @param array $directory Optional list of directories where the library can be found. Overrides default list
* @param bool $newInstance Whether to return a new instance of the library or the same one
* @return object
* @throws LibraryException
*/
protected function loadCoreLibrary($class, $subdir, array $parameters = null, array $directories, $newInstance = false)
{
// First check if the input is correct
if (!is_array($directories))
{
throw new LibraryException("Could not load module. \$directory variable was not an array", 1);
}
// Determine what parameters to use
if (empty($parameters))
{
try {
$parameters = $this->factory->config->getConfig(strtolower($libraryName))->toArray();
} catch (ConfigException $e) {
// No problem, just use an empty array instead
$parameters = array();
}
}
// Retrieve the subclass prefix
$corePrefix = '\FuzeWorks\Library\FW_';
$appPrefix = '\Application\Library\\' . $this->factory->config->get('main')->application_prefix;
$prefix = $corePrefix;
// Load the class object
$classObject = new $libraryClass($parameters);
// Perform a check to see if the library is already loaded
if (class_exists($prefix.$class, false))
{
// Then check if an application extension also exists
if (class_exists($appPrefix.$class, false))
{
$prefix = $appPrefix;
}
// Check if the address is already reserved, if it is, we can presume that a new instance is requested.
// Otherwise this code would not be reached
if (!isset($this->libraries[$prefix.$class]))
{
return $this->initLibrary($prefix.$class, $parameters);
}
// Now load the class
$this->libraryObjects[strtolower($libraryName)] = $classObject;
$this->factory->logger->log("Loaded Library: ".$libraryName);
return $this->libraryObjects[strtolower($libraryName)];
}
// If required to do so, return the existing instance or load a new one
if ($newInstance)
{
$this->factory->logger->log("Library '".$prefix.$class."' already loaded. Returning existing instance");
return $this->libraries[$prefix.$class];
}
$this->factory->logger->log("Library '".$prefix.$class."' already loaded. Returning new instance");
return $this->initLibrary($prefix.$class, $parameters);
}
// Remove the core directory from the checklist
if (in_array(Core::$coreDir . DS . 'Libraries', $directories))
{
array_shift($directories);
}
// First check the directories for the core library (the FW_ class)
foreach ($directories as $directory)
{
$file = $directory . DS . $subdir . $class . '.php';
// Load if it exists
if (file_exists($file))
{
// First base; if an app library is found with FW_, load that one. There can be no extensions
include_once($file);
if (class_exists($prefix.$class, false))
{
return $this->initLibrary($prefix.$class, $parameters);
}
else
{
// Otherwise log a message
$this->factory->logger->logWarning("File ".$file." exists but does not declare $prefix$class");
}
}
}
// Second base; if no base class is found in the app folder, load it from the core folder
include_once(Core::$coreDir . DS . 'Libraries'.DS.$subdir.$class.'.php');
// Now let's check for extensions
$subclass = $this->factory->config->getConfig('main')->application_prefix . $class;
foreach ($directories as $directory)
{
$file = $directory . DS . $subdir . $subclass . '.php';
// Load if it exists
if (file_exists($file))
{
include_once($file);
if (class_exists($appPrefix.$class, false))
{
return $this->initLibrary($appPrefix.$class, $parameters);
}
else
{
$this->factory->logger->logWarning("File ".$file." exists but does not declare $prefix$class");
}
}
}
// Third and last base; just load the FW_ core class
if (class_exists('\FuzeWorks\Library\FW_'.$class, false))
{
return $this->initLibrary('\FuzeWorks\Library\FW_'.$class, $parameters);
}
throw new LibraryException("Could not load library. File ".'Core'.DS.'Libraries'.DS.$subdir.$class.'.php'." exists but does not declare \FuzeWorks\Library\FW_$class", 1);
}
/**
* Application Library Loader
*
* Loads, instantiates and returns an application library.
* Could possibly extend a core library if requested.
*
* @param string $class Classname
* @param string $subdir Sub directory in which the final class can be found
* @param array $params Optional parameters to pass to the library class constructor
* @param array $directory Optional list of directories where the library can be found. Overrides default list
* @param bool $newInstance Whether to return a new instance of the library or the same one
* @return object
* @throws LibraryException
*/
protected function loadAppLibrary($class, $subdir, array $parameters = null, array $directories, $newInstance = false)
{
// First check if the input is correct
if (!is_array($directories))
{
throw new LibraryException("Could not load library. \$directory variable was not an array", 1);
}
// Search for the file
foreach ($directories as $directory)
{
// Skip the core directory
if ($directory === Core::$coreDir . DS . 'Libraries')
{
continue;
}
// Determine the file
$file = $directory . DS . $subdir . $class . '.php';
$className = '\Application\Library\\'.$class;
// Check if the file was already loaded
if (class_exists($className, false))
{
// Return existing instance
if (!isset($this->libraries[$className]))
{
return $this->initLibrary($className, $parameters);
}
// If required to do so, return the existing instance or load a new one
if (!$newInstance)
{
$this->factory->logger->log("Library '".$className."' already loaded. Returning existing instance");
return $this->libraries[$className];
}
$this->factory->logger->log("Library '".$className."' already loaded. Returning new instance");
return $this->initLibrary($className, $parameters);
}
// Otherwise load the file first
if (file_exists($file))
{
include_once($file);
return $this->initLibrary($className, $parameters);
}
}
// Maybe it's in a subdirectory with the same name as the class
if ($subdir === '')
{
return $this->loadLibrary($class."/".$class, $parameters, $directories, $newInstance);
}
throw new LibraryException("Could not load library. Library was not found", 1);
}
/**
* Library Initializer
*
* Instantiates and returns a library.
* Determines whether to use the parameters array or a config file
*
* @param string $class Classname
* @param array $params Optional parameters to pass to the library class constructor
* @return object
* @throws LibraryException
*/
protected function initLibrary($class, array $parameters = null)
{
// First check to see if the library is already loaded
if (!class_exists($class, false))
{
throw new LibraryException("Could not initiate library. Class not found", 1);
}
// Determine what parameters to use
if (is_null($parameters) || empty($parameters))
{
try {
$parameters = $this->factory->config->getConfig(strtolower($class))->toArray();
} catch (ConfigException $e) {
// No problem, just use an empty array instead
$parameters = array();
}
}
// Check if the adress is already reserved, if it is, we can presume that a new instance is requested.
// Otherwise this code would not be reached
if (isset($this->libraries[$class]))
{
$classObject = new $class($parameters);
$this->factory->logger->log("Loaded new Library instance of: ".$class);
return $classObject;
}
else
{
// Now load the class
$this->libraries[$class] = new $class($parameters);
$this->factory->logger->log("Loaded Library: ".$class);
return $this->libraries[$class];
}
}
/**
* Set the directories. Automatically gets invoked if libraryPaths are added to FuzeWorks\Configurator.
*
* @param array $directories
*/
public function setDirectories(array $directories)
{
$this->libraryPaths = $directories;
}
/**
* Add a path where libraries can be found
*
*
* @param string $directory The directory
* @return void
*/
public function addLibraryPath($directory)
{
if (!in_array($directory, $this->libraryPaths))
{
$this->libraryPaths[] = $directory;
}
}
public function addLibraryPath($directory)
{
if (!in_array($directory, $this->libraryPaths))
{
$this->libraryPaths[] = $directory;
}
}
/**
* Remove a path where libraries can be found
*
*
* @param string $directory The directory
* @return void
*/
public function removeLibraryPath($directory)
{
if (($key = array_search($directory, $this->libraryPaths)) !== false)
{
unset($this->libraryPaths[$key]);
}
}
*/
public function removeLibraryPath($directory)
{
if (($key = array_search($directory, $this->libraryPaths)) !== false)
{
unset($this->libraryPaths[$key]);
}
}
/**
* Get a list of all current libraryPaths
*
*
* @return array Array of paths where libraries can be found
*/
public function getLibraryPaths(): array
{
return $this->libraryPaths;
}
public function getLibraryPaths(): array
{
return $this->libraryPaths;
}
}

View File

@ -1,346 +0,0 @@
<?php
/**
* FuzeWorks Framework Core.
*
* The FuzeWorks PHP FrameWork
*
* Copyright (C) 2013-2018 TechFuze
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* @author TechFuze
* @copyright Copyright (c) 2013 - 2018, Techfuze. (http://techfuze.net)
* @license https://opensource.org/licenses/MIT MIT License
*
* @link http://techfuze.net/fuzeworks
* @since Version 0.0.1
*
* @version Version 1.2.0
*/
namespace FuzeWorks\Library;
use FuzeWorks\Exception\LibraryException;
use FuzeWorks\Factory;
use FuzeWorks\Core;
use ReflectionObject;
/**
* FuzeWorks Driver Library Class
*
* Converted from CodeIgniter.
*
* This class enables you to create "Driver" libraries that add runtime ability
* to extend the capabilities of a class via additional driver objects
*
* @author EllisLab Dev Team
* @license http://opensource.org/licenses/MIT MIT License
*/
class FW_Driver_Library {
/**
* Array of drivers that are available to use with the driver class
*
* @var array
*/
protected $valid_drivers = array();
/**
* Name of the current class - usually the driver class
*
* @var string
*/
protected $lib_name;
/**
* Get magic method
*
* The first time a child is used it won't exist, so we instantiate it
* subsequents calls will go straight to the proper child.
*
* @param string Child class name
* @return object Child class
*/
public function __get($child)
{
// Try to load the driver
return $this->load_driver($child);
}
/**
* Load driver
*
* Separate load_driver call to support explicit driver load by library or user
*
* @param string Driver name (w/o parent prefix)
* @return object Child class
*/
public function load_driver($child)
{
// Get the subclass prefix
$prefix = Factory::getInstance()->config->get('main')->application_prefix;
if ( ! isset($this->lib_name))
{
// Get library name without any prefix
$this->lib_name = str_replace(array('FW_', $prefix), '{prefix}', get_class($this));
}
// Sanitize the library name
$clean_class = str_replace(array('Application\Library\\','FuzeWorks\Library\\', '{prefix}'), '', $this->lib_name);
// The child will be prefixed with the parent lib
$child_name = $this->lib_name.'_'.$child;
// See if requested child is a valid driver
if ( ! in_array($child, $this->valid_drivers))
{
// The requested driver isn't valid!
$msg = 'Invalid driver requested: '.$child_name;
throw new LibraryException($msg, 1);
}
// Get package paths and filename case variations to search
$paths = Factory::getInstance()->libraries->getLibraryPaths();
// Is there an extension?
$class_name = str_replace('{prefix}', $prefix, $child_name);
$found = class_exists($class_name, FALSE);
if ( ! $found)
{
// Check for subclass file
foreach ($paths as $path)
{
// Does the file exist?
$file = $path.DS.$clean_class.DS.'drivers'.DS.$prefix.$clean_class.'_'.$child.'.php';
if (file_exists($file))
{
// Yes - require base class from BASEPATH
$basepath = Core::$coreDir . DS. 'Libraries'.DS.$clean_class.DS.'drivers'.DS.$clean_class.'_'.$child.'.php';
if ( ! file_exists($basepath))
{
$msg = 'Unable to load the requested class: FW_'.$child_name;
throw new LibraryException($msg, 1);
}
// Include both sources and mark found
include_once($basepath);
include_once($file);
$found = TRUE;
break;
}
}
}
// Do we need to search for the class?
if ( ! $found)
{
// Use standard class name
$class_name = str_replace('{prefix}', 'FW_', $child_name);
if ( ! class_exists($class_name, FALSE))
{
// Check package paths
foreach ($paths as $path)
{
// Does the file exist?
$file = $path.DS.$clean_class.DS.'drivers'.DS.$clean_class.'_'.$child.'.php';
if (file_exists($file))
{
// Include source
include_once($file);
break;
}
}
}
}
// Did we finally find the class?
if ( ! class_exists($class_name, FALSE))
{
if (class_exists($child_name, FALSE))
{
$class_name = $child_name;
}
else
{
$msg = 'Unable to load the requested driver: '.$class_name;
throw new LibraryException($msg, 1);
}
}
// Instantiate, decorate and add child
$obj = new $class_name();
$obj->decorate($this);
$this->$child = $obj;
return $this->$child;
}
}
// --------------------------------------------------------------------------
/**
* FuzeWorks Driver Class
*
* Converted from CodeIgniter
*
* This class enables you to create drivers for a Library based on the Driver Library.
* It handles the drivers' access to the parent library
*
* @package FuzeWorks
* @subpackage Libraries
* @category Libraries
* @author EllisLab Dev Team
* @link
*/
class FW_Driver {
/**
* Instance of the parent class
*
* @var object
*/
protected $_parent;
/**
* List of methods in the parent class
*
* @var array
*/
protected $_methods = array();
/**
* List of properties in the parent class
*
* @var array
*/
protected $_properties = array();
/**
* Array of methods and properties for the parent class(es)
*
* @static
* @var array
*/
protected static $_reflections = array();
/**
* Decorate
*
* Decorates the child with the parent driver lib's methods and properties
*
* @param object
* @return void
*/
public function decorate($parent)
{
$this->_parent = $parent;
// Lock down attributes to what is defined in the class
// and speed up references in magic methods
$class_name = get_class($parent);
if ( ! isset(self::$_reflections[$class_name]))
{
$r = new ReflectionObject($parent);
foreach ($r->getMethods() as $method)
{
if ($method->isPublic())
{
$this->_methods[] = $method->getName();
}
}
foreach ($r->getProperties() as $prop)
{
if ($prop->isPublic())
{
$this->_properties[] = $prop->getName();
}
}
self::$_reflections[$class_name] = array($this->_methods, $this->_properties);
}
else
{
list($this->_methods, $this->_properties) = self::$_reflections[$class_name];
}
}
// --------------------------------------------------------------------
/**
* __call magic method
*
* Handles access to the parent driver library's methods
*
* @param string
* @param array
* @return mixed
*/
public function __call($method, $args = array())
{
if (in_array($method, $this->_methods))
{
return call_user_func_array(array($this->_parent, $method), $args);
}
throw new LibraryException('No such method: '.$method.'()');
}
// --------------------------------------------------------------------
/**
* __get magic method
*
* Handles reading of the parent driver library's properties
*
* @param string
* @return mixed
*/
public function __get($var)
{
if (in_array($var, $this->_properties))
{
return $this->_parent->$var;
}
}
// --------------------------------------------------------------------
/**
* __set magic method
*
* Handles writing to the parent driver library's properties
*
* @param string
* @param array
* @return mixed
*/
public function __set($var, $val)
{
if (in_array($var, $this->_properties))
{
$this->_parent->$var = $val;
}
}
}

View File

@ -35,7 +35,7 @@
*/
use FuzeWorks\Factory;
use FuzeWorks\Core;
use FuzeWorks\Libraries;
/**
* Class LibraryTest.
@ -45,6 +45,9 @@ use FuzeWorks\Core;
class libraryTest extends CoreTestAbstract
{
/**
* @var Libraries
*/
protected $libraries;
public function setUp()
@ -52,68 +55,16 @@ class libraryTest extends CoreTestAbstract
$factory = Factory::getInstance();
$this->libraries = $factory->libraries;
// Modify the libraries class
// First remove
//$this->libraries->removeLibraryPath(Core::$coreDir . DS . 'Libraries');
$this->libraries->removeLibraryPath(dirname(__DIR__) . '/application');
// And then add
$this->libraries->addLibraryPath('tests'.DS.'libraries'.DS.'testCoreLibraries');
// And then remove all paths
$this->libraries->setDirectories([]);
}
public function testGetLibrariesClass()
public function testLibrariesClass()
{
$this->assertInstanceOf('FuzeWorks\Libraries', $this->libraries);
}
/**
* @depends testGetLibrariesClass
*/
public function testLoadBasicLibrary()
{
// Simple test of loading a library and checking if it exists
$this->assertInstanceOf('Application\Library\TestLoadBasicLibrary',
$this->libraries->get('TestLoadBasicLibrary', null, array('tests'.DS.'libraries'.DS.'testLoadBasicLibrary')));
}
/**
* @depends testLoadBasicLibrary
*/
public function testLoadExtendedLibrary()
{
// Load an extended library Zip class
$library = $this->libraries->get('Extended', null, array('tests'.DS.'libraries'.DS.'testLoadExtendedLibrary'));
$this->assertInstanceOf('Application\Library\MY_Extended', $library);
// Test if it's also an instance of the parent class
$this->assertInstanceOf('FuzeWorks\Library\FW_Extended', $library);
}
/**
* @depends testLoadBasicLibrary
* @expectedException FuzeWorks\Exception\LibraryException
*/
public function testFailLoadLibrary()
{
$library = $this->libraries->get('FailLoadLibrary');
}
/**
* @depends testLoadExtendedLibrary
*/
public function testDifferentPrefix()
{
// Test if the prefix can be changed
Factory::getInstance()->config->getConfig('main')->application_prefix = 'unit_test_';
// Let's extend the Encryption class
$library = $this->libraries->get('Encryption', null, array('tests'.DS.'libraries'.DS.'testDifferentPrefix'));
// Test if it has both instances
$this->assertInstanceOf('FuzeWorks\Library\FW_Encryption', $library);
$this->assertInstanceOf('Application\Library\unit_test_Encryption', $library);
}
/* ---------------------------------- LibraryPaths ---------------------------------------------- */
/**
* @expectedException FuzeWorks\Exception\LibraryException
@ -157,6 +108,106 @@ class libraryTest extends CoreTestAbstract
$this->assertFalse(in_array('tests'.DS.'libraries'.DS.'testRemoveLibraryPath', $this->libraries->getLibraryPaths()));
}
/* ---------------------------------- Load library from directories ------------------- */
/**
* @depends testLibrariesClass
*/
public function testGetLibraryFromDirectory()
{
// Add test directory path
$this->libraries->addLibraryPath('tests'.DS.'libraries'.DS.'testGetLibraryFromDirectory');
$this->assertInstanceOf('Application\Library\TestGetLibraryFromDirectory', $this->libraries->get('TestGetLibraryFromDirectory'));
}
/**
* @depends testGetLibraryFromDirectory
*/
public function testGetLibraryFromSubdirectory()
{
// Add test directory path
$this->libraries->addLibraryPath('tests'.DS.'libraries'.DS.'testGetLibraryFromSubdirectory');
$this->assertInstanceOf('Application\Library\TestGetLibraryFromSubdirectory', $this->libraries->get('TestGetLibraryFromSubdirectory'));
}
/**
* @depends testGetLibraryFromDirectory
*/
public function testGetLibraryFromAltDirectory()
{
// Simple test of loading a library and checking if it exists
$this->assertInstanceOf('Application\Library\TestGetLibraryFromAltDirectory',
$this->libraries->get('TestGetLibraryFromAltDirectory', [], 'tests'.DS.'libraries'.DS.'testGetLibraryFromAltDirectory'));
}
/**
* @expectedException FuzeWorks\Exception\LibraryException
*/
public function testGetLibraryFail()
{
$this->libraries->get('FailLoadLibrary');
}
/**
* @expectedException FuzeWorks\Exception\LibraryException
*/
public function testGetLibraryNoName()
{
$this->libraries->get('');
}
/**
* @expectedException FuzeWorks\Exception\LibraryException
*/
public function testGetLibraryNoClass()
{
$this->libraries->get('TestGetLibraryNoClass', [], 'tests'.DS.'libraries'.DS.'testGetLibraryNoClass');
}
public function testGetLibraryParametersFromConfig()
{
// Prepare the config file
$libraryName = 'TestGetLibraryParametersFromConfig';
$libraryDir = 'tests'.DS.'libraries'.DS.'testGetLibraryParametersFromConfig';
$config = Factory::getInstance()->config->getConfig(strtolower($libraryName), [$libraryDir]);
// Load the library
$lib = $this->libraries->get('TestGetLibraryParametersFromConfig', [], $libraryDir);
$this->assertInstanceOf('Application\Library\TestGetLibraryParametersFromConfig', $lib);
// And check the parameters
$this->assertEquals(5, $lib->parameters['provided']);
}
/* ---------------------------------- Add libraries --------------------------------------------- */
public function testAddLibraryObject()
{
$this->libraries->addLibraryObject('TestAddLibraryObject', 5);
$this->assertEquals(5, $this->libraries->get('TestAddLibraryObject'));
}
public function testAddLibraryClass()
{
require_once('tests'.DS.'libraries'.DS.'testAddLibraryClass'.DS.'TestAddLibraryClass.php');
$this->libraries->addLibraryClass('LibraryClass', '\Custom\Spaces\TestAddLibraryClass');
$this->assertInstanceOf('\Custom\Spaces\TestAddLibraryClass', $this->libraries->get('LibraryClass'));
}
/**
* @depends testAddLibraryClass
* @expectedException \FuzeWorks\Exception\LibraryException
*/
public function testAddLibraryClassFail()
{
$this->libraries->addLibraryClass('LibraryClassFail', '\Case\Not\Exist');
}
public function tearDown()
{
Factory::getInstance()->config->getConfig('main')->revert();

View File

@ -0,0 +1,40 @@
<?php
/**
* FuzeWorks Framework Core.
*
* The FuzeWorks PHP FrameWork
*
* Copyright (C) 2013-2018 TechFuze
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* @author TechFuze
* @copyright Copyright (c) 2013 - 2018, Techfuze. (http://techfuze.net)
* @license https://opensource.org/licenses/MIT MIT License
*
* @link http://techfuze.net/fuzeworks
* @since Version 1.2.0
*
* @version Version 1.2.0
*/
namespace Custom\Spaces;
class TestAddLibraryClass {
}

View File

@ -34,8 +34,7 @@
* @version Version 1.2.0
*/
namespace Application\Library;
use FuzeWorks\Library\FW_Extended;
class MY_Extended extends FW_Extended {
public $child = 'someValue';
class TestGetLibraryFromAltDirectory {
}

View File

@ -34,8 +34,7 @@
* @version Version 1.2.0
*/
namespace Application\Library;
use FuzeWorks\Library\FW_Encryption;
class unit_test_Encryption extends FW_Encryption {
public $child = 'someValue';
class TestGetLibraryFromDirectory {
}

View File

@ -0,0 +1,40 @@
<?php
/**
* FuzeWorks Framework Core.
*
* The FuzeWorks PHP FrameWork
*
* Copyright (C) 2013-2018 TechFuze
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* @author TechFuze
* @copyright Copyright (c) 2013 - 2018, Techfuze. (http://techfuze.net)
* @license https://opensource.org/licenses/MIT MIT License
*
* @link http://techfuze.net/fuzeworks
* @since Version 1.2.0
*
* @version Version 1.2.0
*/
namespace Application\Library;
class TestGetLibraryFromSubdirectory {
}

View File

@ -35,6 +35,6 @@
*/
namespace Application\Library;
class TestLoadBasicLibrary {
class TestGetLibraryNotExist {
}

View File

@ -0,0 +1,47 @@
<?php
/**
* FuzeWorks Framework Core.
*
* The FuzeWorks PHP FrameWork
*
* Copyright (C) 2013-2018 TechFuze
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* @author TechFuze
* @copyright Copyright (c) 2013 - 2018, Techfuze. (http://techfuze.net)
* @license https://opensource.org/licenses/MIT MIT License
*
* @link http://techfuze.net/fuzeworks
* @since Version 1.2.0
*
* @version Version 1.2.0
*/
namespace Application\Library;
class TestGetLibraryParametersFromConfig {
public $parameters;
public function __construct($parameters)
{
$this->parameters = $parameters;
}
}

View File

@ -33,9 +33,6 @@
*
* @version Version 1.2.0
*/
namespace FuzeWorks\Library;
class FW_Extended
{
}
return [
'provided' => 5,
];