<?php
/**
 * OpenWebPresence Support Library - openwebpresence.com
 *
 * @copyright 2001 - 2017, Brian Tafoya.
 * @package   OwpSettings
 * @author    Brian Tafoya <btafoya@briantafoya.com>
 * @version   1.0
 * @license   MIT
 * @license   https://opensource.org/licenses/MIT The MIT License
 * @category  OpenWebPresence_Support_Library
 * @link      http://openwebpresence.com OpenWebPresence
 *
 * Copyright (c) 2017, Brian Tafoya
 *
 * 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.
 */

/**
 * This class provides settings data management functionality.
 */
class OwpSettings
{

    /**
     * @var array $settings_data Data storage array
     */
    static protected $settings_data = array();

    /**
     * @var array $ezSqlDB Data storage array
     */
    static public $ezSqlDB = array();

    /**
     * Constructor.
     *
     * @method mixed __construct()
     * @access public
     */
    function __construct()
    {
        $dotenv = new Dotenv\Dotenv(ROOT_PATH, '.env');
        $dotenv->load();

        $dotenv->required(['DB_HOST', 'DB_NAME', 'DB_USER', 'DB_PASS']);

        /*
            * Init the database class
         */
        self::$ezSqlDB = new OwpDBMySQLi($_ENV["DB_USER"], $_ENV["DB_PASS"], $_ENV["DB_NAME"], $_ENV["DB_HOST"]);
        self::$ezSqlDB->use_disk_cache = false;
        self::$ezSqlDB->cache_queries  = false;
        self::$ezSqlDB->hide_errors();

        self::loadSettings();

    }//end __construct()

    /**
     * __debugInfo
     *
     * @method mixed __debugInfo()
     * @access public
     *
     * @return mixed settings_data
     *
     * @author  Brian Tafoya <btafoya@briantafoya.com>
     * @version 1.0
     */
    public function __debugInfo()
    {
        return [
                'settings_data' => self::$settings_data,
               ];

    }//end __debugInfo()

    /**
     * __get
     *
     * @method mixed __get($itemName) Add mod data by key
     * @access public
     *
     * @param string $itemName Mod data array key
     *
     * @return mixed Array value
     *
     * @throws InvalidArgumentException Mod data key does not exist, code 20
     *
     * @author  Brian Tafoya <btafoya@briantafoya.com>
     * @version 1.0
     */
    public function __get($itemName)
    {
        return self::getModDataItem($itemName);

    }//end __get()

    /**
     * __isset
     *
     * @method mixed __isset($itemName) Add mod data by key
     * @access public
     *
     * @param string $itemName Mod data array key
     *
     * @return boolean
     *
     * @author  Brian Tafoya <btafoya@briantafoya.com>
     * @version 1.0
     */
    public function __isset($itemName)
    {
        return isset(self::$settings_data[$itemName]);

    }//end __isset()

    /**
     * __set
     *
     * @method mixed __set($itemName, $itemValue) Add mod data by key
     * @access public
     *
     * @param string $itemName  Mod data array key
     * @param mixed  $itemValue Mod data value
     *
     * @author  Brian Tafoya <btafoya@briantafoya.com>
     * @version 1.0
     */
    public function __set($itemName, $itemValue)
    {
        self::setModDataItem($itemName, $itemValue);

    }//end __set()

    /**
     * __unset
     *
     * @method mixed __unset($itemName) Add mod data by key
     * @access public
     *
     * @param string $itemName Mod data array key
     *
     * @author  Brian Tafoya <btafoya@briantafoya.com>
     * @version 1.0
     */
    public function __unset($itemName)
    {
        if(isset(self::$settings_data[$itemName])) {
            self::deleteModDataItem($itemName);
        }

    }//end __unset()

    /**
     * deleteModDataItem
     *
     * @method mixed deleteModDataItem($itemName) Add mod data by key
     * @access public
     *
     * @param  string $itemName Mod data array key
     * @return boolean Array value
     * @throws Exception SQL exception
     *
     * @author  Brian Tafoya <btafoya@briantafoya.com>
     * @version 1.0
     */
    static public function deleteModDataItem($itemName)
    {
        self::$ezSqlDB->query('BEGIN');
        self::$ezSqlDB->query("DELETE FROM tbl_settings WHERE tbl_settings.setting_name = '".self::$ezSqlDB->escape($itemName)."' LIMIT 1");
        if (self::$ezSqlDB->query('COMMIT') !== false) {
            self::loadSettings();
        } else {
            self::$ezSqlDB->query('ROLLBACK');
            throw new Exception("SQL error while attempting to update ".$itemName.": ".self::$ezSqlDB->last_error);
        }

        return true;

    }//end deleteModDataItem()

    /**
     * getModDataItem
     *
     * @method mixed getModDataItem($itemName) Add mod data by key
     * @access public
     *
     * @param string $itemName Mod data array key
     *
     * @return mixed Array value
     *
     * @throws InvalidArgumentException Mod data key does not exist, code 20
     *
     * @author  Brian Tafoya <btafoya@briantafoya.com>
     * @version 1.0
     */
    static public function getModDataItem($itemName)
    {
        if(isset(self::$settings_data[$itemName])) {
            return self::$settings_data[$itemName];
        } else {
            throw new InvalidArgumentException("Data item ".$itemName." does not exist.", 20);
        }

    }//end getModDataItem()

    /**
     * setModDataItem
     *
     * @method mixed setModDataItem($itemName, $itemValue) Add mod data by key
     * @access public
     *
     * @param  string $itemName  Mod data array key
     * @param  mixed  $itemValue Mod data value
     * @throws Exception SQL exception
     *
     * @author  Brian Tafoya <btafoya@briantafoya.com>
     * @version 1.0
     */
    static public function setModDataItem($itemName, $itemValue)
    {
        self::$ezSqlDB->query('BEGIN');
        self::$ezSqlDB->query(
            "
			REPLACE INTO tbl_settings
			SET
				tbl_settings.setting_name = '".self::$ezSqlDB->escape($itemName)."',
				tbl_settings.setting_value = '".self::$ezSqlDB->escape(json_encode($itemValue))."',
				tbl_settings.setting_last_updated = SYSDATE(),
				tbl_settings.setting_last_updated_by_userID = 0
		"
        );
        if (self::$ezSqlDB->query('COMMIT') !== false) {
            self::loadSettings();
        } else {
            self::$ezSqlDB->query('ROLLBACK');
            throw new Exception("SQL error while attempting to update ".$itemName.": ".self::$ezSqlDB->last_error);
        }

    }//end setModDataItem()

    /**
     * loadSettings
     *
     * @method mixed loadSettings() Add mod data by key
     * @access private
     *
     * @author  Brian Tafoya <btafoya@briantafoya.com>
     * @version 1.0
     */
    static private function loadSettings()
    {
        $tmp = self::$ezSqlDB->get_results("SELECT * FROM tbl_settings ORDER BY tbl_settings.setting_name");
        self::$settings_data = array();
        if($tmp) {
            foreach ($tmp as $t) {
                self::$settings_data[$t->setting_name] = json_decode($t->setting_value, true);
            }
        }

    }//end loadSettings()

}//end class


<?php

declare(strict_types = 1);

namespace Speicher210\BusinessHours\Day\Time;

/**
 * Represents a time.
 */
class Time implements \JsonSerializable
{
    /**
     * The hours part of the time.
     *
     * @var integer
     */
    protected $hours;

    /**
     * The minutes part of the time.
     *
     * @var integer
     */
    protected $minutes = 0;

    /**
     * The seconds part of the time.
     *
     * @var integer
     */
    protected $seconds = 0;

    /**
     * @param integer $hours The hours.
     * @param integer $minutes The minutes.
     * @param integer $seconds The seconds.
     */
    public function __construct(int $hours, int $minutes = 0, int $seconds = 0)
    {
        $this->setHours($hours);
        $this->setMinutes($minutes);
        $this->setSeconds($seconds);
    }

    /**
     * Checks if this time is before or equal to an other time.
     *
     * @param Time $other The time to compare it against.
     * @return boolean
     */
    public function isBeforeOrEqual(Time $other): bool
    {
        return $this->toSeconds() <= $other->toSeconds();
    }

    /**
     * Checks if this time is after or equal to an other time.
     *
     * @param Time $other The time to compare it against.
     * @return boolean
     */
    public function isAfterOrEqual(Time $other): bool
    {
        return $this->toSeconds() >= $other->toSeconds();
    }

    /**
     * Check if this time is equal to another time.
     *
     * @param Time $other The time to compare it against.
     * @return boolean
     */
    public function isEqual(Time $other): bool
    {
        return $this->toSeconds() === $other->toSeconds();
    }

    /**
     * Get the time representation in seconds.
     *
     * @return integer
     */
    public function toSeconds(): int
    {
        return 3600 * $this->hours + 60 * $this->minutes + $this->seconds;
    }

    /**
     * Set the hours.
     *
     * @param integer $hours The hours.
     */
    public function setHours(int $hours): void
    {
        $this->timeElementsAreValid($hours, $this->minutes, $this->seconds);

        $this->hours = $hours;
    }

    /**
     * Get the hours.
     *
     * @return integer
     */
    public function getHours(): int
    {
        return $this->hours;
    }

    /**
     * Set the minutes.
     *
     * @param integer $minutes The minutes
     */
    public function setMinutes(int $minutes): void
    {
        $this->timeElementsAreValid($this->hours, $minutes, $this->seconds);

        $this->minutes = $minutes;
    }

    /**
     * Get the minutes.
     *
     * @return integer
     */
    public function getMinutes(): int
    {
        return $this->minutes;
    }

    /**
     * Set the seconds.
     *
     * @param integer $seconds The seconds.
     */
    public function setSeconds(int $seconds): void
    {
        $this->timeElementsAreValid($this->hours, $this->minutes, $seconds);

        $this->seconds = $seconds;
    }

    /**
     * Get the seconds.
     *
     * @return integer
     */
    public function getSeconds(): int
    {
        return $this->seconds;
    }

    /**
     * Check if the time elements are valid.
     *
     * @param integer $hours The hours.
     * @param integer $minutes The minutes.
     * @param integer $seconds The seconds.
     * @return boolean
     * @throws \InvalidArgumentException If the elements are not valid.
     */
    private function timeElementsAreValid($hours, $minutes, $seconds): bool
    {
        $exception = new \InvalidArgumentException(
            \sprintf('Invalid time "%02d:%02d:%02d".', $hours, $minutes, $seconds)
        );

        if ((int)\sprintf('%d%02d%02d', $hours, $minutes, $seconds) > 240000) {
            throw $exception;
        }
        if ($hours < 0 || $minutes < 0 || $seconds < 0) {
            throw $exception;
        }
        if ($hours <= 24 && $minutes <= 59 && $seconds <= 59) {
            return true;
        }

        throw $exception;
    }

    /**
     * {@inheritdoc}
     */
    public function jsonSerialize()
    {
        return [
            'hours' => $this->hours,
            'minutes' => $this->minutes,
            'seconds' => $this->seconds,
        ];
    }

    /**
     * Returns a string representation of the time.
     *
     * @return string
     */
    public function __toString()
    {
        return \sprintf('%02d:%02d:%02d', $this->hours, $this->minutes, $this->seconds);
    }
}


<?php
/**
 * This file is part of the Maths package.
 *
 * Copyright (c) 2014-2016 Pierre Cassat <me@e-piwi.fr> and contributors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * The source code of this package is available online at
 * <http://github.com/atelierspierrot/maths>.
 */

namespace Maths\Helper;

use \Maths\PointInterface;
use \Maths\Geometry\Point;
use \Maths\Geometry\Line;
use \Maths\Geometry\Segment;
use \Maths\Geometry\Quadrilateral;
use \Maths\Geometry\Circle;

/**
 * Helper class to use the JSXgraph javascript library to render mathematics forms
 *
 * @link    http://jsxgraph.uni-bayreuth.de/
 * @author  piwi <me@e-piwi.fr>
 */
class JSXgraph
{

    const ORIGIN_NAME       = 'origin';
    const ORIGIN_PREFIX     = 'origin_';
    const BOARD_PREFIX      = 'board_';
    const SEGMENT_PREFIX    = 'segment_';
    const GHOST_LINE_PREFIX = 'ghostline_';
    const POLYGONE_PREFIX   = 'polygon_';
    const CIRCLE_PREFIX     = 'circle_';
    const CIRCLE_POINT_PREFIX = 'circle_point_';

    public $output;

    protected $_options = array(
        // global board
        'draw_board'            => true,
        'board_boundingbox'     => array(-10,10,10,-10),
        'board_axis'            => true,
        'board_width'           => 500,
        'board_height'          => 500,
        // origin point
        'draw_origin'           => true,
        'origin_name'           => 'O',
        'origin_color'          => '#404040',
        'origin_face'           => '[]',
        // circle
        'circle_strokeWidth'    => 2,
        'circle_fillColor'      => "#ffff00",
        'circle_fillOpacity'    => 0.3,
        // circle point
        'circle_point_color'    => '#404040',
        'circle_point_face'     => '+',
        // straight segment
        'segment_straightFirst' => false,
        'segment_straightLast'  => false,
        'segment_strokeWidth'   => 2,
        // segment associated line
        'ghostline_strokeWidth' => 1,
        'ghostline_dash'        => 2,
        // presets
        'build_polygon_group'   => true,
        'build_segment_ghost'   => true,
    );

    protected $_points = array();

    protected $_brd;

    public function __construct($id, array $options = array())
    {
        $this
            ->setOptions($options)
            ->resetOutput()
            ->init($id)
            ;
    }

    public function __toString()
    {
        return $this->getOutput();
    }

// Setters / Getters

    public function setOptions(array $options)
    {
        $this->_options = array_merge($this->_options, $options);
        return $this;
    }

    public function getOptions()
    {
        return $this->_options;
    }

    public function getOptionsByPrefix($prefix)
    {
        $opts = array();
        foreach ($this->_options as $n=>$v) {
            if (substr($n, 0, strlen($prefix))==$prefix) {
                $opts[substr($n, strlen($prefix))] = $v;
            }
        }
        return $opts;
    }

    public function getOption($index, $default = null)
    {
        return (isset($this->_options[$index]) ? $this->_options[$index] : $default);
    }

    public function resetOutput()
    {
        $this->output = '';
        return $this;
    }

    public function addOutput($str)
    {
        $this->output .= $str.PHP_EOL;
        return $this;
    }

    public function getOutput($reset = true)
    {
        $str = $this->output;
        if (true==$reset) {
            $this->resetOutput();
        }
        return $str;
    }

    public function addPoint($name, PointInterface $point, array $options = array(), $alt_name = null, $overload = false)
    {
        if (!array_key_exists($name, $this->_points) || $overload==true) {
            $this->_points[$name] = array(
                'name'  =>(!is_null($alt_name) ? $alt_name : $name),
                'point' =>$point,
                'data'  =>$options
            );
        }
    }

    public function getPoint($name)
    {
        return (array_key_exists($name, $this->_points) ? $this->_points[$name] : null);
    }

// Drawings

    public function init($id)
    {
        $this->_brd_id = $id;
        if ($this->getOption('draw_board', false)==true) {
            $this->drawBoard($id);
        }
        if ($this->getOption('draw_origin', false)==true) {
            $this->drawOrigin();
        }
    }

    public function drawBoard($id, array $options = array())
    {
        $options = array_merge(
            $this->getOptionsByPrefix(self::BOARD_PREFIX), $options
        );
        $data = json_encode($options, JSON_NUMERIC_CHECK);
        $this->_brd = 'brd'.uniqid();
        $this->addOutput(
            "var {$this->_brd} = JXG.JSXGraph.initBoard('{$id}', {$data});"
        );
        return $this->_brd;
    }

    public function drawPoint(PointInterface $point, array $options = array())
    {
        if (array_key_exists('x', $options)) {
            $x = $options['x'];
            unset($options['x']);
        } else {
            $x = $point->getAbscissa();
        }
        if (array_key_exists('y', $options)) {
            $y = $options['y'];
            unset($options['y']);
        } else {
            $y = $point->getOrdinate();
        }
        if (array_key_exists('prefix', $options)) {
            $p = $options['prefix'];
            unset($options['prefix']);
        } else {
            $p = 'p';
        }
        $data = json_encode($options, JSON_NUMERIC_CHECK);
        $name = $p.count($this->_points);
        $this->addOutput(
            "var {$name} = {$this->_brd}.create('point', [{$x},{$y}], {$data});"
        );
        $this->addPoint($name, $point, $options);
        return $name;
    }

    public function drawOrigin(array $options = array())
    {
        $origin = new Point(0, 0);
        $options = array_merge(
            $this->getOptionsByPrefix(self::ORIGIN_PREFIX), $options
        );
        $name = $this->drawPoint($origin, $options);
        $this->addPoint(self::ORIGIN_NAME, $origin, $options, $name);
        return self::ORIGIN_NAME;
    }

    public function drawHorizontalPoint(PointInterface $point, array $options = array())
    {
        $o = $this->getPoint(self::ORIGIN_NAME);
        return $this->drawPoint($point, array_merge($options, array('y'=>"function(){return {$o['name']}.Y();}")));
    }

    public function drawVerticalPoint(PointInterface $point, array $options = array())
    {
        $o = $this->getPoint(self::ORIGIN_NAME);
        return $this->drawPoint($point, array_merge($options, array('x'=>"function(){return {$o['name']}.X();}")));
    }

    public function drawSegment(Line $line, array $options = array())
    {
        $point1 = $this->drawPoint($line->getPointA(), $options);
        $point2 = $this->drawPoint($line->getPointB(), $options);
        $data_segment = json_encode(
            array_merge($options, $this->getOptionsByPrefix(self::SEGMENT_PREFIX)),
            JSON_NUMERIC_CHECK
        );
        $name_segment = 'l'.uniqid();
        $data_ghostline = json_encode(
            array_merge($options, $this->getOptionsByPrefix(self::GHOST_LINE_PREFIX)),
            JSON_NUMERIC_CHECK
        );
        $name_ghostline = 'gl'.uniqid();
        if ($this->getOption('build_segment_ghost')==true && (!array_key_exists('build_segment_ghost', $options) || $options['build_segment_ghost']==true)) {
            $this->addOutput(
                "var {$name_ghostline} = {$this->_brd}.create('line', [{$point1},{$point2}], {$data_ghostline});"
            );
        }
        $this->addOutput(
            "var {$name_segment} = {$this->_brd}.create('line', [{$point1},{$point2}], {$data_segment});"
        );
        return $name_segment;
    }

    public function drawQuadrilateral(Quadrilateral $quadri, array $options = array())
    {
        $point1 = $this->drawPoint($quadri->getPointA(), $options);
        $point2 = $this->drawPoint($quadri->getPointB(), $options);
        $point3 = $this->drawPoint($quadri->getPointC(), $options);
        $point4 = $this->drawPoint($quadri->getPointD(), $options);
        $data = json_encode(
            array_merge($options, $this->getOptionsByPrefix(self::POLYGONE_PREFIX)),
            JSON_NUMERIC_CHECK
        );
        $name_quadri = 'pol'.uniqid();
        $this->addOutput(
            "var {$name_quadri} = {$this->_brd}.create('polygon', [{$point1},{$point2},{$point3},{$point4}], {$data});"
        );
        if ($this->getOption('build_polygon_group')==true && (!array_key_exists('build_polygon_group', $options) || $options['build_polygon_group']==true)) {
            $this->addOutput(
                "var gr{$name_quadri} = {$this->_brd}.create('group', [{$point1},{$point2},{$point3},{$point4}]);"
            );
        }
        return $name_quadri;
    }

    public function drawCircle(Circle $circ, array $options = array())
    {
        $pointO = $this->drawPoint($circ->getPointO(), $options);
        $tmp_point1 = new Point(($circ->getPointO()->getAbscissa() + $circ->getRadius()), $circ->getPointO()->getOrdinate());
        $point1 = $this->drawPoint($tmp_point1, array_merge($options, $this->getOptionsByPrefix(self::CIRCLE_POINT_PREFIX)));
        $data = json_encode(
            array_merge($options, $this->getOptionsByPrefix(self::CIRCLE_PREFIX)),
            JSON_NUMERIC_CHECK
        );
        $name_circle = 'circ'.uniqid();
        $this->addOutput(
            "var {$name_circle} = {$this->_brd}.create('circle', [{$pointO},{$point1}], {$data});"
        );
        return $name_circle;
    }

// Specials

    public function demonstrateThales(Line $line1, Line $line2)
    {
    }
}


<?php

namespace RMoore\ChangeRecorder;

use Illuminate\Routing\Router;
use Illuminate\Support\ServiceProvider;

class ChangeRecorderServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        $this->loadMigrationsFrom(__DIR__.'/../database/migrations');

        Router::macro('history', function ($name, $class) {
            $this->get($name.'/history', function () use ($class) {
                return Change::where('subject_type', $class);
            });
            $this->get("$name/{key}/history", function ($key) use ($class) {
                $field = (new $class)->getRouteKeyName() ?: 'id';

                return $class::where($field, $key)->firstOrFail()->getHistory();
            });
            $this->get("$name/{key}/collaborators", function ($key) use ($class) {
                $field = (new $class)->getRouteKeyName() ?: 'id';

                return $class::where($field, $key)->firstOrFail()->collaborators;
            });
        });
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}


<?php

/*
 * This file is part of the Valkyrja framework.
 *
 * (c) Melech Mizrachi
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Valkyrja\Filesystem;

use Aws\S3\S3Client;
use League\Flysystem\Adapter\AbstractAdapter;
use League\Flysystem\Adapter\Local;
use League\Flysystem\AwsS3v3\AwsS3Adapter;
use League\Flysystem\Filesystem as FlySystem;
use Valkyrja\Application;
use Valkyrja\Support\Providers\Provides;

/**
 * Class Filesystem.
 *
 * @author Melech Mizrachi
 */
class FlyFilesystem implements Filesystem
{
    use Provides;

    /**
     * The application.
     *
     * @var \Valkyrja\Application
     */
    protected $app;

    /**
     * The Fly Filesystem.
     *
     * @var \League\Flysystem\Filesystem
     */
    protected $flySystem;

    /**
     * The adapters.
     *
     * @var array
     */
    protected static $adapters = [];

    /**
     * FlyFilesystem constructor.
     *
     * @param Application                       $application The application
     * @param \League\Flysystem\Filesystem|null $flySystem   [optional] The
     *                                                       FlyFilesystem
     */
    public function __construct(Application $application, FlySystem $flySystem = null)
    {
        $this->app       = $application;
        $this->flySystem = $flySystem
            ?? new FlySystem(
                $this->flyAdapter($this->app->config()['filesystem']['default'])
            );
    }

    /**
     * Determine whether a path exists.
     *
     * @param string $path The path
     *
     * @return bool
     */
    public function exists(string $path): bool
    {
        return $this->flySystem->has($path);
    }

    /**
     * Read a file.
     *
     * @param string $path The path
     *
     * @throws \League\Flysystem\FileNotFoundException
     *
     * @return string|null The contents or null on failure
     */
    public function read(string $path): ? string
    {
        $read = $this->flySystem->read($path);

        return false !== $read ? $read : null;
    }

    /**
     * Write a file.
     *
     * @param string $path     The path
     * @param string $contents The contents
     *
     * @throws \League\Flysystem\FileExistsException
     *
     * @return bool
     */
    public function write(string $path, string $contents): bool
    {
        return $this->flySystem->write($path, $contents);
    }

    /**
     * Write a file with a stream.
     *
     * @param string   $path     The path
     * @param resource $resource The resource
     *
     * @throws \InvalidArgumentException
     * @throws \League\Flysystem\FileExistsException
     *
     * @return bool
     */
    public function writeStream(string $path, $resource): bool
    {
        return $this->flySystem->writeStream($path, $resource);
    }

    /**
     * Update an existing file.
     *
     * @param string $path     The path
     * @param string $contents The contents
     *
     * @throws \League\Flysystem\FileNotFoundException
     *
     * @return bool
     */
    public function update(string $path, string $contents): bool
    {
        return $this->flySystem->update($path, $contents);
    }

    /**
     * Update an existing file with a stream.
     *
     * @param string   $path     The path
     * @param resource $resource The resource
     *
     * @throws \InvalidArgumentException
     * @throws \League\Flysystem\FileNotFoundException
     *
     * @return bool
     */
    public function updateStream(string $path, $resource): bool
    {
        return $this->flySystem->updateStream($path, $resource);
    }

    /**
     * Write a file or update a file depending on existence.
     *
     * @param string $path     The path
     * @param string $contents The contents
     *
     * @return bool
     */
    public function put(string $path, string $contents): bool
    {
        return $this->flySystem->put($path, $contents);
    }

    /**
     * Write a file or update a file depending on existence with a stream.
     *
     * @param string   $path     The path
     * @param resource $resource The resource
     *
     * @throws \InvalidArgumentException
     *
     * @return bool
     */
    public function putStream(string $path, $resource): bool
    {
        return $this->flySystem->putStream($path, $resource);
    }

    /**
     * Rename a file.
     *
     * @param string $path    The existing path
     * @param string $newPath The new path
     *
     * @throws \League\Flysystem\FileExistsException
     * @throws \League\Flysystem\FileNotFoundException
     *
     * @return bool
     */
    public function rename(string $path, string $newPath): bool
    {
        return $this->flySystem->rename($path, $newPath);
    }

    /**
     * Copy a file.
     *
     * @param string $path    The existing path
     * @param string $newPath The new path
     *
     * @throws \League\Flysystem\FileExistsException
     * @throws \League\Flysystem\FileNotFoundException
     *
     * @return bool
     */
    public function copy(string $path, string $newPath): bool
    {
        return $this->flySystem->copy($path, $newPath);
    }

    /**
     * Delete a file.
     *
     * @param string $path The path
     *
     * @throws \League\Flysystem\FileNotFoundException
     *
     * @return bool
     */
    public function delete(string $path): bool
    {
        return $this->flySystem->delete($path);
    }

    /**
     * Get a file's meta data.
     *
     * @param string $path The path
     *
     * @throws \League\Flysystem\FileNotFoundException
     *
     * @return array|null An array of meta data or null on failure
     */
    public function metadata(string $path): ? array
    {
        $metadata = $this->flySystem->getMetadata($path);

        return false !== $metadata ? $metadata : null;
    }

    /**
     * Get a file's mime type.
     *
     * @param string $path The path
     *
     * @throws \League\Flysystem\FileNotFoundException
     *
     * @return string|null The mime type or null on failure
     */
    public function mimetype(string $path): ? string
    {
        $mimetype = $this->flySystem->getMimetype($path);

        return false !== $mimetype ? $mimetype : null;
    }

    /**
     * Get a file's size.
     *
     * @param string $path The path
     *
     * @return int|null The size in bytes or null on failure
     */
    public function size(string $path): ? int
    {
        $size = $this->flySystem->getSize($path);

        return false !== $size ? $size : null;
    }

    /**
     * Get a file's timestamp.
     *
     * @param string $path The path
     *
     * @throws \League\Flysystem\FileNotFoundException
     *
     * @return int|null The timestamp or null on failure
     */
    public function timestamp(string $path): ? int
    {
        $timestamp = $this->flySystem->getTimestamp($path);

        return false !== $timestamp ? $timestamp : null;
    }

    /**
     * Get a file's visibility.
     *
     * @param string $path The path
     *
     * @throws \League\Flysystem\FileNotFoundException
     *
     * @return string|null
     *      The visibility ('public' or 'private') or null on failure
     */
    public function visibility(string $path): ? string
    {
        $visibility = $this->flySystem->getVisibility($path);

        return false !== $visibility ? $visibility : null;
    }

    /**
     * Set a file's visibility.
     *
     * @param string     $path       The path
     * @param Visibility $visibility The visibility
     *
     * @return bool
     */
    public function setVisibility(string $path, Visibility $visibility): bool
    {
        return $this->flySystem->setVisibility($path, $visibility->getValue());
    }

    /**
     * Set a file's visibility to public.
     *
     * @param string $path The path
     *
     * @return bool
     */
    public function setVisibilityPublic(string $path): bool
    {
        return $this->flySystem->setVisibility($path, Visibility::PUBLIC);
    }

    /**
     * Set a file's visibility to private.
     *
     * @param string $path The path
     *
     * @return bool
     */
    public function setVisibilityPrivate(string $path): bool
    {
        return $this->flySystem->setVisibility($path, Visibility::PRIVATE);
    }

    /**
     * Create a new directory.
     *
     * @param string $path The path
     *
     * @return bool
     */
    public function createDir(string $path): bool
    {
        return $this->flySystem->createDir($path);
    }

    /**
     * Delete a directory.
     *
     * @param string $path The path
     *
     * @throws \League\Flysystem\RootViolationException
     *
     * @return bool
     */
    public function deleteDir(string $path): bool
    {
        return $this->flySystem->deleteDir($path);
    }

    /**
     * List the contents of a directory.
     *
     * @param string $directory [optional] The directory
     * @param bool   $recursive [optional] Whether to recurse through the
     *                          directory
     *
     * @return array
     */
    public function listContents(string $directory = null, bool $recursive = false): array
    {
        return $this->flySystem->listContents($directory ?? '', $recursive);
    }

    /**
     * Get a filesystem for an adapter.
     *
     * @param string $adapter The adapter
     *
     * @return \Valkyrja\Filesystem\Filesystem
     */
    public function adapter(string $adapter): Filesystem
    {
        $flyAdapter = $this->{$adapter . 'Adapter'}();

        return new static($flyAdapter);
    }

    /**
     * Get a flysystem abstract adapter.
     *
     * @param string $adapter The adapter
     *
     * @return \League\Flysystem\Adapter\AbstractAdapter
     */
    protected function flyAdapter(string $adapter): AbstractAdapter
    {
        return $this->{$adapter . 'Adapter'}();
    }

    /**
     * Get the local filesystem.
     *
     * @throws \LogicException
     *
     * @return \Valkyrja\Filesystem\Filesystem
     */
    public function local(): Filesystem
    {
        return new static($this->app, $this->localAdapter());
    }

    /**
     * Get the local flysystem adapter.
     *
     * @throws \LogicException
     *
     * @return \League\Flysystem\Adapter\Local
     */
    protected function localAdapter(): Local
    {
        return self::$adapters['local']
            ?? self::$adapters['local'] = new Local(
                $this->app->config()['filesystem']['adapters']['s3']['dir']
            );
    }

    /**
     * Get the s3 filesystem.
     *
     * @throws \InvalidArgumentException
     *
     * @return \Valkyrja\Filesystem\Filesystem
     */
    public function s3(): Filesystem
    {
        return new static($this->app, $this->s3Adapter());
    }

    /**
     * Get the s3 flysystem adapter.
     *
     * @throws \InvalidArgumentException
     *
     * @return \League\Flysystem\AwsS3v3\AwsS3Adapter
     */
    protected function s3Adapter(): AwsS3Adapter
    {
        if (isset(self::$adapters['s3'])) {
            return self::$adapters['s3'];
        }

        $config       = $this->app->config()['filesystem']['adapters']['s3'];
        $clientConfig = [
            'credentials' => [
                'key'    => $config['key'],
                'secret' => $config['secret'],
            ],
            'region'      => $config['region'],
            'version'     => $config['version'],
        ];

        self::$adapters['s3'] = new AwsS3Adapter(
            new S3Client($clientConfig),
            $config['bucket'],
            $config['dir']
        );

        return self::$adapters['s3'];
    }

    /**
     * The items provided by this provider.
     *
     * @return array
     */
    public static function provides(): array
    {
        return [
            Filesystem::class,
        ];
    }

    /**
     * Publish the provider.
     *
     * @param Application $app The application
     *
     * @return void
     */
    public static function publish(Application $app): void
    {
        $app->container()->singleton(
            Filesystem::class,
            new static($app)
        );
    }
}


<?php

namespace Reaction\Web;

use Reaction;
use Reaction\Base\RequestAppComponent;
use Reaction\Exceptions\InvalidConfigException;
use Reaction\Helpers\Url;

/**
 * UrlManager handles HTTP request parsing and creation of URLs based on a set of rules.
 *
 * UrlManager is configured as an application component in [[\yii\base\Application]] by default.
 * You can access that instance via `Yii::$app->urlManager`.
 *
 * You can modify its configuration by adding an array to your application config under `components`
 * as it is shown in the following example:
 *
 * ```php
 * 'urlManager' => [
 *     'enablePrettyUrl' => true,
 *     'rules' => [
 *         // your rules go here
 *     ],
 *     // ...
 * ]
 * ```
 *
 * Rules are classes implementing the [[UrlRuleInterface]], by default that is [[UrlRule]].
 * For nesting rules, there is also a [[GroupUrlRule]] class.
 *
 * For more details and usage information on UrlManager, see the [guide article on routing](guide:runtime-routing).
 *
 * @property string $baseUrl The base URL that is used by [[createUrl()]] to prepend to created URLs.
 * @property string $hostInfo The host info (e.g. `http://www.example.com`) that is used by
 * [[createAbsoluteUrl()]] to prepend to created URLs.
 * @property string $scriptUrl The entry script URL that is used by [[createUrl()]] to prepend to created
 * URLs.
 */
class UrlManager extends RequestAppComponent implements Reaction\Base\ComponentAutoloadInterface
{
    /**
     * @var array the rules for creating and parsing URLs when [[enablePrettyUrl]] is `true`.
     * This property is used only if [[enablePrettyUrl]] is `true`. Each element in the array
     * is the configuration array for creating a single URL rule. The configuration will
     * be merged with [[ruleConfig]] first before it is used for creating the rule object.
     *
     * A special shortcut format can be used if a rule only specifies [[UrlRule::pattern|pattern]]
     * and [[UrlRule::route|route]]: `'pattern' => 'route'`. That is, instead of using a configuration
     * array, one can use the key to represent the pattern and the value the corresponding route.
     * For example, `'post/<id:\d+>' => 'post/view'`.
     *
     * For RESTful routing the mentioned shortcut format also allows you to specify the
     * [[UrlRule::verb|HTTP verb]] that the rule should apply for.
     * You can do that  by prepending it to the pattern, separated by space.
     * For example, `'PUT post/<id:\d+>' => 'post/update'`.
     * You may specify multiple verbs by separating them with comma
     * like this: `'POST,PUT post/index' => 'post/create'`.
     * The supported verbs in the shortcut format are: GET, HEAD, POST, PUT, PATCH and DELETE.
     * Note that [[UrlRule::mode|mode]] will be set to PARSING_ONLY when specifying verb in this way
     * so you normally would not specify a verb for normal GET request.
     *
     * Here is an example configuration for RESTful CRUD controller:
     *
     * ```php
     * [
     *     'dashboard' => 'site/index',
     *
     *     'POST <controller:[\w-]+>s' => '<controller>/create',
     *     '<controller:[\w-]+>s' => '<controller>/index',
     *
     *     'PUT <controller:[\w-]+>/<id:\d+>'    => '<controller>/update',
     *     'DELETE <controller:[\w-]+>/<id:\d+>' => '<controller>/delete',
     *     '<controller:[\w-]+>/<id:\d+>'        => '<controller>/view',
     * ];
     * ```
     *
     * Note that if you modify this property after the UrlManager object is created, make sure
     * you populate the array with rule objects instead of rule configurations.
     */
    public $rules = [];
    /**
     * @var string the URL suffix used when [[enablePrettyUrl]] is `true`.
     * For example, ".html" can be used so that the URL looks like pointing to a static HTML page.
     * This property is used only if [[enablePrettyUrl]] is `true`.
     */
    public $suffix;
    /**
     * @var bool whether to show entry script name in the constructed URL. Defaults to `true`.
     * This property is used only if [[enablePrettyUrl]] is `true`.
     */
    public $showScriptName = true;
    /**
     * @var string the GET parameter name for route. This property is used only if [[enablePrettyUrl]] is `false`.
     */
    public $routeParam = 'r';
    /**
     * @var CacheInterface|string the cache object or the application component ID of the cache object.
     * Compiled URL rules will be cached through this cache object, if it is available.
     *
     * After the UrlManager object is created, if you want to change this property,
     * you should only assign it with a cache object.
     * Set this property to `false` if you do not want to cache the URL rules.
     *
     * Cache entries are stored for the time set by [[\yii\caching\Cache::$defaultDuration|$defaultDuration]] in
     * the cache configuration, which is unlimited by default. You may want to tune this value if your [[rules]]
     * change frequently.
     */
    public $cache = 'cache';
    /**
     * @var array the default configuration of URL rules. Individual rule configurations
     * specified via [[rules]] will take precedence when the same property of the rule is configured.
     */
    public $ruleConfig = ['class' => 'yii\web\UrlRule'];

    /**
     * @var string the cache key for cached rules
     */
    protected $cacheKey = __CLASS__;

    private $_baseUrl;
    private $_scriptUrl;
    private $_hostInfo;
    private $_homeUrl;

    /**
     * Initializes UrlManager.
     */
    public function init()
    {
        parent::init();
        $this->processRequest();
    }

    /**
     * Process current request
     */
    protected function processRequest()
    {
        if (!Reaction::$app->getI18n()->detectLanguageByUrl) {
            return;
        }
        $langPrefixes = Reaction::$app->getI18n()->languagePrefixes;
        $rawUrl = trim($this->app->reqHelper->getPathInfo(), '/');
        $requestPrefix = '';
        $rawUrlParts = explode('/', $rawUrl);
        if (!empty($rawUrlParts) && isset($langPrefixes[$rawUrlParts[0]])) {
            $requestPrefix = $rawUrlParts[0];
            $this->baseUrl = $requestPrefix;
            array_shift($rawUrlParts);
        }
        $rawUrl = '/' . trim(implode('/', $rawUrlParts), '/');
        $requestLanguage = $langPrefixes[$requestPrefix];
        $this->app->reqHelper->setPathInfo($rawUrl);
        $this->app->language = $requestLanguage;
    }

    /**
     * Creates a URL using the given route and query parameters.
     *
     * You may specify the route as a string, e.g., `site/index`. You may also use an array
     * if you want to specify additional query parameters for the URL being created. The
     * array format must be:
     *
     * ```php
     * // generates: /index.php?r=site%2Findex&param1=value1&param2=value2
     * ['site/index', 'param1' => 'value1', 'param2' => 'value2']
     * ```
     *
     * If you want to create a URL with an anchor, you can use the array format with a `#` parameter.
     * For example,
     *
     * ```php
     * // generates: /index.php?r=site%2Findex&param1=value1#name
     * ['site/index', 'param1' => 'value1', '#' => 'name']
     * ```
     *
     * The URL created is a relative one. Use [[createAbsoluteUrl()]] to create an absolute URL.
     *
     * Note that unlike [[\yii\helpers\Url::toRoute()]], this method always treats the given route
     * as an absolute route.
     *
     * @param string|array $params use a string to represent a route (e.g. `site/index`),
     * or an array to represent a route with query parameters (e.g. `['site/index', 'param1' => 'value1']`).
     * @return string the created URL
     */
    public function createUrl($params)
    {
        $params = (array)$params;
        $anchor = isset($params['#']) ? '#' . $params['#'] : '';
        if (isset($params['#'])) {
            unset($params['#']);
        }

        $route = trim($params[0], '/');
        unset($params[0]);

        $baseUrl = $this->getBaseUrl();

        $cacheKey = $route . '?';
        foreach ($params as $key => $value) {
            if ($value !== null) {
                $cacheKey .= $key . '&';
            }
        }

        if ($this->suffix !== null) {
            $route .= $this->suffix;
        }
        if (!empty($params) && ($query = http_build_query($params)) !== '') {
            $route .= '?' . $query;
        }

        $route = ltrim($route, '/');
        $url = "{$baseUrl}/{$route}";
        $url = $url !== "/" ? rtrim($url, '/') : $url;

        return "{$url}{$anchor}";
    }

    /**
     * Creates an absolute URL using the given route and query parameters.
     *
     * This method prepends the URL created by [[createUrl()]] with the [[hostInfo]].
     *
     * Note that unlike [[\yii\helpers\Url::toRoute()]], this method always treats the given route
     * as an absolute route.
     *
     * @param string|array $params use a string to represent a route (e.g. `site/index`),
     * or an array to represent a route with query parameters (e.g. `['site/index', 'param1' => 'value1']`).
     * @param string|null  $scheme the scheme to use for the URL (either `http`, `https` or empty string
     * for protocol-relative URL).
     * If not specified the scheme of the current request will be used.
     * @return string the created URL
     * @see createUrl()
     * @throws InvalidConfigException
     */
    public function createAbsoluteUrl($params, $scheme = null)
    {
        $params = (array)$params;
        $url = $this->createUrl($params);
        if (strpos($url, '://') === false) {
            $hostInfo = $this->getHostInfo();
            if (strncmp($url, '//', 2) === 0) {
                $url = substr($hostInfo, 0, strpos($hostInfo, '://')) . ':' . $url;
            } else {
                $url = $hostInfo . $url;
            }
        }

        return Url::ensureScheme($url, $scheme);
    }

    /**
     * Returns the base URL that is used by [[createUrl()]] to prepend to created URLs.
     * It defaults to [[Request::baseUrl]].
     * This is mainly used when [[enablePrettyUrl]] is `true` and [[showScriptName]] is `false`.
     * @return string the base URL that is used by [[createUrl()]] to prepend to created URLs.
     * @throws InvalidConfigException if running in console application and [[baseUrl]] is not configured.
     */
    public function getBaseUrl()
    {
        if ($this->_baseUrl === null) {
            $request = $this->app->reqHelper;
            if ($request instanceof RequestHelper) {
                $this->_baseUrl = $request->getBaseUrl();
            } else {
                throw new InvalidConfigException('Please configure UrlManager::baseUrl correctly as you are running a console application.');
            }
        }

        return $this->_baseUrl;
    }

    /**
     * Sets the base URL that is used by [[createUrl()]] to prepend to created URLs.
     * This is mainly used when [[enablePrettyUrl]] is `true` and [[showScriptName]] is `false`.
     * @param string $value the base URL that is used by [[createUrl()]] to prepend to created URLs.
     */
    public function setBaseUrl($value)
    {
        $this->_baseUrl = $value === null ? null : '/' . trim(Reaction::$app->getAlias($value), '/');
    }

    /**
     * Returns the entry script URL that is used by [[createUrl()]] to prepend to created URLs.
     * It defaults to [[Request::scriptUrl]].
     * This is mainly used when [[enablePrettyUrl]] is `false` or [[showScriptName]] is `true`.
     * @return string the entry script URL that is used by [[createUrl()]] to prepend to created URLs.
     * @throws InvalidConfigException if running in console application and [[scriptUrl]] is not configured.
     */
    public function getScriptUrl()
    {
        if ($this->_scriptUrl === null) {
            if ($this->app->reqHelper instanceof RequestHelper) {
                $this->_scriptUrl = $this->app->reqHelper->getScriptUrl();
            } else {
                throw new InvalidConfigException('Please configure UrlManager::scriptUrl correctly as you are running a console application.');
            }
        }

        return $this->_scriptUrl;
    }

    /**
     * Sets the entry script URL that is used by [[createUrl()]] to prepend to created URLs.
     * This is mainly used when [[enablePrettyUrl]] is `false` or [[showScriptName]] is `true`.
     * @param string $value the entry script URL that is used by [[createUrl()]] to prepend to created URLs.
     */
    public function setScriptUrl($value)
    {
        $this->_scriptUrl = $value;
    }

    /**
     * Returns the host info that is used by [[createAbsoluteUrl()]] to prepend to created URLs.
     * @return string the host info (e.g. `http://www.example.com`) that is used by [[createAbsoluteUrl()]] to prepend to created URLs.
     * @throws InvalidConfigException if running in console application and [[hostInfo]] is not configured.
     */
    public function getHostInfo()
    {
        if ($this->_hostInfo === null) {
            if ($this->app->reqHelper instanceof RequestHelper) {
                $this->_hostInfo = $this->app->reqHelper->getHostInfo();
            } else {
                throw new InvalidConfigException('Please configure UrlManager::hostInfo correctly as you are running a console application.');
            }
        }

        return $this->_hostInfo;
    }

    /**
     * Sets the host info that is used by [[createAbsoluteUrl()]] to prepend to created URLs.
     * @param string $value the host info (e.g. "http://www.example.com") that is used by [[createAbsoluteUrl()]] to prepend to created URLs.
     */
    public function setHostInfo($value)
    {
        $this->_hostInfo = $value === null ? null : rtrim($value, '/');
    }

    /**
     * Getter for $homeUrl
     * @return string
     */
    public function getHomeUrl() {
        return $this->_homeUrl !== null ? $this->_homeUrl : Reaction::$app->urlManager->getHomeUrl();
    }

    /**
     * Setter for $homeUrl
     * @param string $homeUrl
     */
    public function setHomeUrl($homeUrl) {
        $this->_homeUrl = $homeUrl;
    }
}


<?php

namespace JDesrosiers\Silex\Provider\ContentNegotiation;

use Silex\Application;
use Symfony\Component\HttpFoundation\Response;

/**
 * This class provides helper methods for serializing responses and deserializing requests using JMS Serializer.
 */
class JmsSerializerContentNegotiation implements ContentNegotiation
{
    protected $app;

    /**
     * @param Application $app
     */
    public function __construct(Application $app)
    {
        $this->app = $app;
    }

    /**
     * This method can be used in place of Response::create to automatically serialize your response into the requested
     * format.
     *
     * @param object $responseObject
     * @param int $status
     * @param array $headers
     * @return Response
     */
    public function createResponse($responseObject, $status = 200, array $headers = array())
    {
        $request = $this->app["request_stack"]->getCurrentRequest();
        $format = $request->getRequestFormat($this->app["conneg.defaultFormat"]);

        $serializedContent = $this->app["serializer"]->serialize(
            $responseObject,
            $format,
            $this->app["conneg.serializationContext"]
        );

        return new Response($serializedContent, $status, $headers);
    }

    /**
     * This method retrieves the request body in any supported format and deserializes it.
     *
     * @param string $className
     * @return object
     */
    public function deserializeRequest($className)
    {
        $request = $this->app["request_stack"]->getCurrentRequest();

        return $this->app["serializer"]->deserialize(
            $request->getContent(),
            $className,
            $request->getContentType(),
            $this->app["conneg.deserializationContext"]
        );
    }
}


<?php

namespace PhpPlatform\Persist;

use PhpPlatform\Config\Settings;
use PhpPlatform\Errors\Exceptions\Persistence\BadQueryException;
use PhpPlatform\Errors\Exceptions\Persistence\DataNotFoundException;
use PhpPlatform\Errors\Exceptions\Persistence\NoAccessException;
use PhpPlatform\Persist\Exception\InvalidForeignClassException;
use PhpPlatform\Persist\Exception\InvalidInputException;
use PhpPlatform\Persist\Exception\TriggerException;
use PhpPlatform\Persist\Connection\Connection;
use PhpPlatform\Annotations\Annotation;
use PhpPlatform\Session\Factory;

abstract class Model implements Constants{

    private static $_lastFindQuery = null;

    private static $_triggers = null;
    const TRIGGER_TYPE_PRE  = "PRE";
    const TRIGGER_TYPE_POST = "POST";
    const TRIGGER_EVENT_CREATE = "CREATE";
    const TRIGGER_EVENT_READ   = "READ";
    const TRIGGER_EVENT_UPDATE = "UPDATE";
    const TRIGGER_EVENT_DELETE = "DELETE";

    function __construct(){

    	if(TransactionManager::getAttribute("isFromNewInstanceWithoutConstructor") === true){
    		return ;
    	}

		$args = array();

		$classList = RelationalMappingUtil::getClassConfiguration($this);
        foreach($classList as $className=>$class){
            foreach(array_keys($class['fields']) as $fieldName){
                $fieldValue = Reflection::getValue($className, $fieldName, $this);
				if($fieldValue !== null){
					$args[$fieldName] = $fieldValue;
				}
            }
        }

        if(count($args) == 0){
            throw new BadQueryException(get_class($this)." can not be constructed with empty arguments");
        }

        $resultList = static::find($args);

        if(count($resultList) == 0){
        	$inputArgsStr = "";
        	foreach($args as $key=>$value){
        		if($inputArgsStr != ""){
        			$inputArgsStr .= ", ";
        		}
        		$inputArgsStr .= $key." = ".$value;
        	}
            throw new DataNotFoundException(get_class($this)." with ".$inputArgsStr." does not exist");
        }

        $classList = RelationalMappingUtil::getClassConfiguration(get_class($this));
        foreach($classList as $className=>$class){
            foreach(array_keys($class['fields']) as $fieldName){
                Reflection::setValue($className, $fieldName, $this,Reflection::getValue($className, $fieldName, $resultList[0]));
            }
        }
    }

    /**
     * @param string $className
     * @throws Exception
     * @return Model
     */
    private static function __newInstanceWithoutConstructor($className){
    	try{
    		TransactionManager::startTransaction();
    		TransactionManager::setAttribute("isFromNewInstanceWithoutConstructor",true);
    		$newInstance = Reflection::newInstanceArgs($className,array());
    		TransactionManager::commitTransaction();
    	}catch (\Exception $e){
    		TransactionManager::abortTransaction();
    		throw $e;
    	}
    	return $newInstance;
    }

    /**
     * checks the access for this operation based on the annotations defined for this operation
     * @param string|Model $object on which access needs to be validated
     * @param string $errorMessage error message to be set as exception message if access is denied
     * @throws NoAccessException
     * @return boolean|string True or Valid where expression for Read access on Success otherwise false
     */
    private static function checkAccess($object,$errorMessage){

    	if(is_string($object)){
    		$className = $object;
    		$object = null;
    	}else{
    		$className = get_class($object);
    	}

    	if(TransactionManager::isSuperUser()){
    		return true;
    	}

    	$hasAccess = false;
    	$hasAccessChecks = false;
    	try{
    		TransactionManager::startTransaction(null,true);

    		$debugBacktraces = debug_backtrace(false);
    		$args = null;
    		$function = null;
    		foreach($debugBacktraces as $debugBacktrace){
    			if($debugBacktrace["class"] == $className){
    				$args = $debugBacktrace["args"];
    				$function = $debugBacktrace["function"];
    				break;
    			}
    		}

    		$accessAnnotations = self::getAccessAnnotation($className, $function);

    		if(is_array($accessAnnotations) && count($accessAnnotations) > 0){
    			$hasAccessChecks = true;

    			//
    			// access annotations will be of the form
    			// array(
    			//      "key1|value1",
    			//      "key2|value2",
    			//      ...
    			//      "function|functionName"
    			// )
    			//
    			// Access is granted if session contains value for the specified key
    			// "function" is the special reserved key for which a function mentioned as value is called instead of checking for the value in session

    			// group access annotations by key
    			$accessMasks = array();
    			foreach ($accessAnnotations as $accessMask){
    				$accessMaskArr = preg_split('/\|/', $accessMask);
    				$accessMaskKey = $accessMaskArr[0];
    				$accessMaskValue = $accessMaskArr[1];
    				if(!array_key_exists($accessMaskKey, $accessMasks)){
    					$accessMaskValues = array();
    				}else{
    					$accessMaskValues = $accessMasks[$accessMaskKey];
    				}
    				$accessMaskValues[] = $accessMaskValue;
    				$accessMasks[$accessMaskKey] = $accessMaskValues;
    			}

    			$session = Factory::getSession();
    			foreach ($accessMasks as $accessKey=>$accessValues){
    				if($accessKey == "function"){
    					continue;
    				}
    				$sessionValues = $session->get($accessKey);

    				if(count(array_intersect($sessionValues, $accessValues)) > 0){
    					$hasAccess = true;
    					break;
    				}
    			}

    			if(!$hasAccess && array_key_exists("function", $accessMasks)){
    				foreach ($accessMasks["function"] as $function){
    					$result = Reflection::invokeArgs($className, $function, $object, $args);
    					if($result instanceof Expression){
    						$hasAccess = $result;
    						break;
    					}else if(isset($result) && $result){
    						$hasAccess = true;
    						break;
    					}
    				}
    			}
    		}

    		TransactionManager::commitTransaction();
    	}catch (\Exception $e){
    		TransactionManager::abortTransaction();
    		throw $e;
    	}

    	if($hasAccessChecks){
    		if($hasAccess === false){
    			throw new NoAccessException($errorMessage);
    		}
    		return $hasAccess;
    	}
    	return true;
    }

    static private function getAccessAnnotation($class,$method){
    	if($class === false || $method === false){
    		return array();
    	}
    	$annotations = Annotation::getAnnotations($class,null,null,$method);
    	$annotations = $annotations["methods"][$method];

    	if(array_key_exists("access", $annotations)){
    		$accessAnnotations = $annotations["access"];
    	}
    	if(is_string($accessAnnotations)){
    		$accessAnnotations = array($accessAnnotations);
    	}
    	if(in_array("inherit", $accessAnnotations)){
    		$parentClass = get_parent_class($class);
    		$parentAccessAnnotations = self::getAccessAnnotation($parentClass, $method);
    		unset($accessAnnotations["inherit"]);
    		$accessAnnotations = array_merge($accessAnnotations,$parentAccessAnnotations);
    	}
    	return $accessAnnotations;
    }

    /**
     *
     * @param array $data
     * @throws NoAccessException
     * @throws InvalidInputException
     * @return Model
     */
    public static function create($data){

    	$thisModelObject = null;

    	try{

    		TransactionManager::startTransaction();

    		$connection = TransactionManager::getConnection();

    		$calledClass = get_called_class();

    		// check for Create Access
    		self::checkAccess($calledClass, "User don't have access to Create");

    		// create an instance of calledClass
    		$thisModelObject = self::__newInstanceWithoutConstructor($calledClass);

    		$classList = RelationalMappingUtil::getClassConfiguration($calledClass);
    		//getClassConfiguration will return the array of class config objects from child to parent , during creation values needs to be inserted from parent to child
    		$classList = array_reverse($classList);
    		foreach($classList as $className=>$class){
    			$columnNames = "";
    			$values = "";

    			$fields = $class['fields'];
    			foreach($fields as $fieldName=>$field){
    				if(!RelationalMappingUtil::_isAutoIncrement($field) && !RelationalMappingUtil::_isForeignField($field)){
    					if($columnNames != ""){
    						$columnNames .=",";
    					}
    					if($values != ""){
    						$values .=",";
    					}

    					$columnNames .= $field['columnName'];

    					$value = null;
    					if(RelationalMappingUtil::_isReference($field)){
    						$parentClassName = get_parent_class($className);
    						$parentClass = $classList[$parentClassName];
    						$value = Reflection::getValue($parentClassName, RelationalMappingUtil::getPrimaryKey($parentClass), $thisModelObject);
    					}else{
    						$value = $data[$fieldName];
    					}

    					Reflection::setValue($className, $fieldName, $thisModelObject, $value);

    					if($value === null){
    						$values .= 'NULL';
    					}else{
    						if(strtoupper($field['type']) == "DATE"){
    							$value = $connection->formatDate($value);
    						}elseif(strtoupper($field['type']) == "DATETIME" ||strtoupper($field['type']) == "TIMESTAMP"){
    							$value = $connection->formatDate($value,true);
    						}elseif(strtoupper($field['type']) == "BOOLEAN"){
    							try{
    								$value = $connection->formatBoolean($value);
    							}catch (InvalidInputException $e){
    								throw new InvalidInputException("Expected boolean value for $fieldName");
    							}
    						}
    						$value = $connection->encodeForSQLInjection($value);
    						$values .= "'$value'";
    					}
    				}
    			}

    			self::runTrigger($className, self::TRIGGER_EVENT_CREATE, self::TRIGGER_TYPE_PRE, array($thisModelObject));

    			$tableName = RelationalMappingUtil::getTableName($class, $thisModelObject);
    			$query = "INSERT INTO $tableName($columnNames) VALUES ($values)";

    			$result = $connection->query($query);

    			if($result === FALSE){
    				$errorMessage = "Error in creating $className \"".$connection->lastError()."\"";
    				throw new BadQueryException($errorMessage);
    			}

    			if(null !== RelationalMappingUtil::getAutoIncrementKey($class)){
    				$autoIncrementValue = $connection->lastInsertedId();
    				Reflection::setValue($className, RelationalMappingUtil::getAutoIncrementKey($class), $thisModelObject, $autoIncrementValue);
    			}
    			self::runTrigger($className, self::TRIGGER_EVENT_CREATE, self::TRIGGER_TYPE_POST, array($thisModelObject));
    		}

    		TransactionManager::commitTransaction();
    	}catch (\Exception $e){
    		TransactionManager::abortTransaction();
    		throw $e;
    	}
    	return $thisModelObject;
    }

    /**
     * This method finds the data from database and constructs appropriate php daos
     *
     * @param $filters array of fields to match for
     * @param null $sort array for sorting
     * @param null $pagination array(pageNumber,pageSize)
     * @param null $where Expression - complex SQL where expression
     * @return array
     * @throws \Exception
     *
     * @todo Add select option to select required values, in one loop, or a callback method to work with found objects
     */

    public static function find($filters,$sort = null,$pagination = null, $where = null){

        self::$_lastFindQuery = null;
        $calledClassName = get_called_class();

        $classList = RelationalMappingUtil::getClassConfiguration($calledClassName);
        $resultList = array();
        try{

        	TransactionManager::startTransaction();
        	$connection = TransactionManager::getConnection();

	        $readAccessWhereClause = self::checkAccess($calledClassName, "User don't have access to Read");

	        foreach ($classList as $className=>$class){
	        	self::runTrigger($className, self::TRIGGER_EVENT_READ, self::TRIGGER_TYPE_PRE, array(array("filters"=>$filters,"sort"=>$sort,"pagination"=>$pagination, "where"=>$where)));
	        }

	        if($readAccessWhereClause instanceof Expression){
	        	if($where instanceof Expression){
	        		$where = new Expression(self::OPERATOR_AND, array($where,$readAccessWhereClause));
	        	}else {
	        		$where = $readAccessWhereClause;
	        	}
	        }
	        $Clauses = self::generateClauses($connection,$classList, $filters, $sort, $where);

	        $selectClause  = $Clauses["selectClause"];
	        $fromClause    = $Clauses["fromClause"];
	        $whereClause   = $Clauses["whereClause"];
	        $groupByClause = $Clauses["groupByClause"];
	        $orderByClause = $Clauses["orderByClause"];

	        $i = 0;

	        $classCount = count($classList);
	        foreach($classList as $className=>$class){
	            //skip the last class
	            if($i < $classCount-1){
	                if($whereClause != ""){
	                    $whereClause .=" AND ";
	                }
	                $parentClass = $classList[get_parent_class($className)];
	                $whereClause .= $class['prefix'].".".$class['fields'][RelationalMappingUtil::getReferenceKey($class)]['columnName']." = ".
	                    $parentClass['prefix'].".".$parentClass['fields'][RelationalMappingUtil::getPrimaryKey($parentClass)]['columnName'];
	            }
	            $i++;
	        }

            if($whereClause != ""){
                $whereClause = "WHERE ".$whereClause;
            }

            $limit = "";
            if(is_array($pagination)){

                if(array_key_exists("start",$pagination) && array_key_exists("pageSize",$pagination)){
                    $limit = $pagination["start"].",".$pagination["pageSize"];
                }elseif(array_key_exists("pageNumber",$pagination) && array_key_exists("pageSize",$pagination)){
                    $limit = (($pagination["pageNumber"]-1)*$pagination["pageSize"]).",".$pagination["pageSize"];
                }elseif(array_key_exists("start",$pagination) && array_key_exists("end",$pagination)){
                    $limit = $pagination["start"].",".($pagination["end"]-$pagination["start"]);
                }

                if($limit != ""){
                	$limit = "LIMIT ".$connection->encodeForSQLInjection($limit);
                }

            }

            $query = "SELECT $selectClause FROM $fromClause $whereClause $groupByClause $orderByClause $limit";

            $result = $connection->query($query);

            if(!$result){
                throw new BadQueryException("Select Failed : "+$connection->lastError());
            }

            self::$_lastFindQuery = array("selectClause" =>$selectClause,
                "fromClause"=>$fromClause,
                "whereClause"=>$whereClause,
                "groupByClause"=>$groupByClause,
                "orderByClause"=>$orderByClause,
                "limit"=>$limit);

            $row = $result->fetch_assoc();

            while($row != null){
            	$resultObj = self::__newInstanceWithoutConstructor($calledClassName);
                foreach($classList as $className=>$class){
                	$fields = $class['fields'];
                    foreach($fields as $fieldName=>$field){
                        $fieldSelect = $field['fieldSelect'];
                        $value = $row[$fieldSelect];

                        if($field['group']){
                            $value = explode(" $$ ",$value);
                            $value = array_map(function($_v){
                                if($_v == "#NULL$"){
                                    return null;
                                }
                                return $_v;
                            },$value);
                        }

                        if(strtoupper($field['type']) === "BOOLEAN" ){
                            if($field['group']){
                                foreach($value as &$valueItem){
                                    if($valueItem == "1"){
                                        $valueItem = true;
                                    }else{
                                        $valueItem = false;
                                    }
                                }
                            }else{
                                if($value == "1"){
                                    $value = true;
                                }else{
                                    $value = false;
                                }
                            }
                        }

                        Reflection::setValue($className, $fieldName, $resultObj, $value);
                    }
                }

                $resultList[] = $resultObj;
                $row = $result->fetch_assoc();
            }

            foreach($classList as $className=>$class){
            	self::runTrigger($className, self::TRIGGER_EVENT_READ, self::TRIGGER_TYPE_POST, array($resultList));
            }

            TransactionManager::commitTransaction();
        }catch (DataNotFoundException $e){
            TransactionManager::abortTransaction();
            // don't throw for data not found exception
        }catch (\Exception $e){
            TransactionManager::abortTransaction();
            throw $e;
        }
        return $resultList;
    }

    /**
     *
     * @param Connection $connection
     * @param array $classList
     * @param array $filters
     * @param array $sort
     * @param array $where
     * @param string $readAccessWhereClause
     * @throws InvalidForeignClassException
     * @throws InvalidInputException
     * @return string[][]
     */
    private static function generateClauses($connection, &$classList,$filters,$sort,$where){
    	$fromClause = "";
    	$whereClause = "";
    	$selectClause = "";
    	$groupByClause = "";
    	$orderByClause = "";

    	$_processedSortArray = array();

    	$fieldToColumnNameMapping = array();
    	$filterWhereExpressions = array();

    	foreach($classList as $className=>&$class){
    		$prefix = $class['prefix'];

    		if($fromClause != ""){
    			$fromClause .= ", ";
    		}
    		$fromClause .= RelationalMappingUtil::getTableName($class, $className)." ".$prefix;

    		$sourceColumnsForForeignFields = array();

    		$fields = &$class['fields'];
    		foreach($fields as $fieldName=>&$field){
    			if($selectClause != ""){
    				$selectClause .= ", ";
    			}

    			$_prefix = $prefix;
    			$_columnName = $field['columnName'];

    			if(RelationalMappingUtil::_isForeignField($field)){

    				$foreignClassAndField = preg_split("/\-\>/",$field['foreignField']);
    				$foreignClassName = $foreignClassAndField[0];
    				$foreignFieldName = $foreignClassAndField[1];

    				if(!class_exists($foreignClassName,true)){
    					throw new InvalidForeignClassException("Foreign Class ($foreignClassName) does not exists");
    				}

    				$foreignClassConf = RelationalMappingCache::getInstance()->get($foreignClassName);

    				$foreignPrimaryField = RelationalMappingUtil::getPrimaryKey($foreignClassConf);

    				if($foreignPrimaryField == null){
    					throw new InvalidForeignClassException("foreign field ".$field['name']." doesn't have primary field on foreign Class ".$foreignClassName['name']);
    				}

    				$foreignFieldForeignColumnName = $foreignClassConf['fields'][$foreignFieldName]['columnName'];

    				$_prefix = $foreignClassConf['prefix']."_".$field['columnName'];
    				$_columnName = $foreignFieldForeignColumnName;
    				if(!in_array($field['columnName'],$sourceColumnsForForeignFields)){
    					$foreignClassTableName = RelationalMappingUtil::getTableName($foreignClassConf, $foreignClassName);
    					$fromClause .= " LEFT JOIN ".$foreignClassTableName." ".$_prefix." ON ".$_prefix.".".$foreignClassConf['fields'][$foreignPrimaryField]['columnName']." = ".$class['prefix'].".".$field['columnName'];
    					$sourceColumnsForForeignFields[] = $field['columnName'];
    				}
    			}
    			$fieldSelect = $_prefix.".".$_columnName;

    			$field['fieldSelect'] = $fieldSelect;

    			$_fieldSelect = $fieldSelect;
    			if(strtoupper($field['type']) == "DATE"){
    				$_fieldSelect = "date_format($fieldSelect,'".$connection->outputDateFormat()."')";
    			}elseif(strtoupper($field['type']) == "DATETIME" || strtoupper($field['type']) == "TIMESTAMP"){
    				$_fieldSelect = "date_format($fieldSelect,'".$connection->outputDateTimeFormat()."')";
    			}

    			if(isset($field['group']) && (strtoupper($field['group']) == "TRUE" || $field['group'] === true) ){
    				$field['group'] = true;
    				$_fieldSelect = "GROUP_CONCAT(IFNULL($_fieldSelect,'#NULL$') SEPARATOR ' $$ ')";
    			}else{
    				$field['group'] = false;
    			}

    			$selectClause .= "$_fieldSelect AS '$fieldSelect'";

    			if(isset($filters[$fieldName]) && RelationalMappingUtil::_isGet($field)){

    				if(!is_array($filters[$fieldName])){
    					$argObj = array();
    					$argObj[self::OPERATOR_EQUAL] = $filters[$fieldName];
    					$filters[$fieldName] = $argObj;
    				}

    				// $filters[$fieldName] = array(Model::Operator => VALUE)
    				foreach ($filters[$fieldName] as $operator=>$value){
    					$fieldObj = new Field($className, $fieldName);
    					switch ($operator){
    						case self::OPERATOR_EQUAL:
    							if($value === null){
    								$expression = new Expression(self::OPERATOR_IS_NULL, array($fieldObj));
    							}else{
    								$expression = new Expression($operator, array($fieldObj,$value));
    							}
    						    break;
    						case self::OPERATOR_NOT_EQUAL:
	    						if($value === null){
	    							$expression = new Expression(self::OPERATOR_IS_NOT_NULL, array($fieldObj));
	    						}else{
	    							$expression = new Expression($operator, array($fieldObj,$value));
	    						}
    						    break;
    						case self::OPERATOR_IN:
    							if(count($value) == 0){
    								throw new DataNotFoundException('No data for the filter array(IN=>array())');
    							}else{
    								$expression = new Expression($operator, array($fieldObj,$value));
    							}
   							    break;
    						case self::OPERATOR_BETWEEN:
    							$expression = new Expression($operator, array_merge(array($fieldObj),$value));
      						    break;
    						default:
    							$expression = new Expression($operator, array($fieldObj,$value));
    					}
    					$filterWhereExpressions[] = $expression;
    				}
    				unset($filters[$fieldName]);
    			}

    			$fieldToColumnNameMapping[$className.'::'.$fieldName] = $_prefix.".".$_columnName;

    			if(isset($field['groupBy']) && (strtoupper($field['groupBy']) == "TRUE" || $field['groupBy'] === true )){
    				$groupByClause = "GROUP BY $_prefix.$_columnName";
    			}

    			if(RelationalMappingUtil::_isGet($field) && is_array($sort) && array_key_exists($fieldName,$sort) &&
    					($sort[$fieldName] == self::SORTBY_ASC || $sort[$fieldName] == self::SORTBY_DESC) &&
    					!in_array($fieldName,$_processedSortArray) ){

    						$sort[$fieldName] = "$_prefix.$_columnName ".$sort[$fieldName];
    						$_processedSortArray[] = $fieldName;
    			}
    		}
    	}

    	if(!isset($where)){
    		// Dont do anything
    	}elseif($where instanceof Expression){
    		$filterWhereExpressions[] = $where;
    	}else{
    		throw new InvalidInputException('parameter "where" should be an instance of Expression');
    	}

    	if(count($filterWhereExpressions) == 1){
    		$whereClause = $filterWhereExpressions[0]->asString($fieldToColumnNameMapping);
    	}elseif(count($filterWhereExpressions) > 1){
    		$whereExpression = new Expression(self::OPERATOR_AND, $filterWhereExpressions);
    		$whereClause = $whereExpression->asString($fieldToColumnNameMapping);
    	}

    	if(is_array($sort) && count($sort) > 0 && count($sort) == count($_processedSortArray)){
    		$orderByClause = "ORDER BY ".implode(", ",$sort);
    	}

    	$Clauses = array();
    	$Clauses["selectClause"]  = $selectClause;
    	$Clauses["fromClause"]    = $fromClause;
    	$Clauses["whereClause"]   = $whereClause;
    	$Clauses["groupByClause"] = $groupByClause;
    	$Clauses["orderByClause"] = $orderByClause;

    	return $Clauses;

    }

    public static function getLastTotalRecords($pageSize = null){
        try{
            TransactionManager::startTransaction();
            $connection = TransactionManager::getConnection();
            $fromClause = self::$_lastFindQuery['fromClause'];
            $whereClause = self::$_lastFindQuery['whereClause'];
            $groupByClause = self::$_lastFindQuery['groupByClause'];
            $orderByClause = self::$_lastFindQuery['orderByClause'];

            $countResults = $connection->query("SELECT COUNT(*) FROM $fromClause $whereClause $groupByClause $orderByClause");
            if($countResults){
                $countRow = $countResults->fetch_assoc();
                $totalRecords = $countRow["COUNT(*)"];

                if(isset($pageSize) && is_numeric($pageSize)){
                    $totalPages = ceil($totalRecords/$pageSize);
                    $returnCount = $totalPages;
                }else{
                    $returnCount = $totalRecords;
                }
            }else{
                throw new DataNotFoundException("Error in getting total records of last find");
            }
            TransactionManager::commitTransaction();
            return $returnCount;
        }catch (\Exception $e){
            TransactionManager::abortTransaction();
            throw $e;
        }
    }

    protected function delete(){
        try{
            TransactionManager::startTransaction();
            $conection = TransactionManager::getConnection();

            $classList = RelationalMappingUtil::getClassConfiguration(get_class($this));

            // check for Delete Access
            self::checkAccess($this, "User don't have access to Delete");

            foreach($classList as $className=>$class){

                $recordIdentifier = $this->recordIdentifier($className, $class);
                $tableName = RelationalMappingUtil::getTableName($class, $this);
                $query = "DELETE FROM $tableName WHERE ".$recordIdentifier;

                self::runTrigger($className, self::TRIGGER_EVENT_DELETE, self::TRIGGER_TYPE_PRE, array($this));
                $result = $conection->query($query);

                if($result === FALSE){
                    $errorMessage = "Error in deleting ".get_class($this).":$className \"".$conection->lastError()."\"";
                    throw new BadQueryException($errorMessage);
                }
                self::runTrigger($className, self::TRIGGER_EVENT_DELETE, self::TRIGGER_TYPE_POST, array($this));

            }

            TransactionManager::commitTransaction();
        }catch (\Exception $exp){
            TransactionManager::abortTransaction();
            throw $exp;
        }
    }

    /**
     *
     * @param string $name
     * @param mixed $value
     * @return Model
     */
    protected function setAttribute($name,$value){
        $args = array();
        $args[$name] = $value;

        return $this->setAttributes($args);
    }

    /**
     * @param array $args
     * @return Model
     */
    protected function setAttributes($args){
        try{
            TransactionManager::startTransaction();
            $connection = TransactionManager::getConnection();

            $modifiedClasses = array();

            $classList = RelationalMappingUtil::getClassConfiguration(get_class($this));

            // check for Update Access
            self::checkAccess($this, "User don't have access to Update");

            foreach($classList as $className=>$class){
                $setClause = "";
                $modifiedFields = array();
                $reflectionClass = new \ReflectionClass($className);
                $fields = $class['fields'];
                foreach($fields as $fieldName=>$field){
                    if(RelationalMappingUtil::_isSet($field)){
                        if(isset($args[$fieldName])){

                            $value = $args[$fieldName];
                            if(is_array($args[$fieldName])){
                                $value = $args[$fieldName]["value"];
                            }

                            $originalVal = $value;

                            if(strtoupper($field['type']) == "DATE"){
                                $value = $connection->formatDate($value);
                            }elseif(strtoupper($field['type']) == "DATETIME" || strtoupper($field['type']) == "TIMESTAMP"){
                                $value = $connection->formatDate($value,true);
                            }elseif(strtoupper($field['type']) == "BOOLEAN"){
                                try{
                                    $value = $connection->formatBoolean($value);
                                }catch (InvalidInputException $e){
                                    throw new InvalidInputException("Expected boolean value for $fieldName");
                                }
                            }

                            if(RelationalMappingUtil::_isForeignField($field)){
                                $foreignClassAndField = preg_split("/\-\>/",$field['foreignField']);
                                $foreignClassName = $foreignClassAndField[0];
                                $foreignFieldName = $foreignClassAndField[1];

                                $foreignClassConf = RelationalMappingCache::getInstance()->get($foreignClassName);

                                $foreignPrimaryField = (object)array();
                                foreach($foreignClassConf['fields'] as $foreignField){
                                    if(RelationalMappingUtil::_isPrimary($foreignField)){
                                        $foreignPrimaryField = $foreignField;
                                        break;
                                    }
                                }

                                $foreignClassTableName = RelationalMappingUtil::getTableName($foreignClassConf, $foreignClassName);
                                $value = $connection->encodeForSQLInjection($value);
                                $result = $connection->query("SELECT ".$foreignPrimaryField['columnName']." FROM ".$foreignClassTableName." WHERE ".$foreignClassConf['fields'][$foreignFieldName]['columnName']." = '".$value."'");

                                if($result === FALSE){
                                    $errorMessage = "Error in updating $className \"".$connection->error."\"";
                                    throw new BadQueryException($errorMessage);
                                }

                                $row = $result->fetch_assoc();
                                $value = $row[$foreignPrimaryField['columnName']];
                            }

                            $reflectionProperty = $reflectionClass->getProperty($fieldName);
                            $reflectionProperty->setAccessible(true);
                            $existingValue = $reflectionProperty->getValue($this);

                            if($existingValue != $originalVal){
                                if($setClause != ""){
                                    $setClause .= ", ";
                                }
                                if($value === null ){
                                    $setClause .= $field['columnName']." = NULL";
                                }else if($value === true ){
                                    $setClause .= $field['columnName']." = true";
                                }else if($value === false ){
                                    $setClause .= $field['columnName']." = false";
                                }else{
                                	$value = $connection->encodeForSQLInjection($value);
                                    $setClause .= $field['columnName']." = '$value'";
                                }

                                $modifiedFields[$fieldName] = $originalVal;

                            }
                        }
                    }
                }

                if(count($modifiedFields)>0){
                    $modifiedClasses[$className] = $modifiedFields;
                }

                if(trim($setClause) == ""){
                    continue;
                }

                $recordIdentifier = $this->recordIdentifier($className, $class);
                $tableName = RelationalMappingUtil::getTableName($class, $this);
                $query = "UPDATE $tableName SET $setClause WHERE $recordIdentifier";

                self::runTrigger($className, self::TRIGGER_EVENT_UPDATE, self::TRIGGER_TYPE_PRE, array($this,$modifiedFields));
                $result = $connection->query($query);

                if($result === FALSE){
                    $errorMessage = "Error in updating ".get_class($this).":$className \"".$connection->lastError()."\"";
                    throw new BadQueryException($errorMessage);
                }
                self::runTrigger($className, self::TRIGGER_EVENT_UPDATE, self::TRIGGER_TYPE_POST, array($this,$modifiedFields));

            }

            // updating the modified values to object instance
            //$thisClassName = get_class();

            foreach($modifiedClasses as $className=>$modifiedFields){
                $reflectionClass = new \ReflectionClass($className);
                foreach($modifiedFields as $fieldName=>$value){
                    $reflectionProperty = $reflectionClass->getProperty($fieldName);
                    $reflectionProperty->setAccessible(true);
                    $reflectionProperty->setValue($this,$value);
                }
            }

            TransactionManager::commitTransaction();
        }catch (\Exception $exp){
            TransactionManager::abortTransaction();
            throw $exp;
        }

        return $this;

    }

    protected function getAttribute($name){
        $args = array();
        $args[] = $name;

        $attrValues = $this->getAttributes($args);
        return $attrValues[$name];
    }

    protected function getAttributes($args){
        try{

            $classList = RelationalMappingUtil::getClassConfiguration(get_class($this));

            if($args == "*"){
                $args = array();
                foreach($classList as $className=>$class){
                    $fields = $class['fields'];
                    foreach($fields as $fieldName=>$field){
                        if(!in_array($fieldName,$args)){
                            $args[] = $fieldName;
                        }
                    }
                }
            }

            $attributeValues = array();

            foreach($classList as $className=>$class){

                $reflectionClass = new \ReflectionClass($className);
                $fields = $class['fields'];
                foreach($fields as $fieldName=>$field){

                    if(RelationalMappingUtil::_isGet($field)){
                        if(in_array($fieldName,$args)){
                            $reflectionProperty = $reflectionClass->getProperty($fieldName);
                            $reflectionProperty->setAccessible(true);
                            $value = $reflectionProperty->getValue($this);
                            $attributeValues[$fieldName] = $value;
                            $index = array_search($fieldName,$args);
                            unset($args[$index]);
                        }
                    }
                }

            }
            return $attributeValues;
        }catch (\Exception $exp){
            throw $exp;
        }
    }

    private function recordIdentifier($className,$class){
    	$connection = TransactionManager::getConnection();
    	$fields = $class['fields'];
    	$reflectionClass = new \ReflectionClass($className);
    	$recordIdentifier = "";
    	$primaryKey = RelationalMappingUtil::getPrimaryKey($class);
    	if(isset($primaryKey)){
    		$reflectionProperty = $reflectionClass->getProperty($primaryKey);
    		$reflectionProperty->setAccessible(true);
    		$keyValue = $reflectionProperty->getValue($this);
    		$keyValue = $connection->encodeForSQLInjection($keyValue);
    		$recordIdentifier = $fields[$primaryKey]['columnName']." = '$keyValue'";
    	}else{
    		foreach($fields as $fieldName=>$field){
    			if(isset($field['columnName']) && !RelationalMappingUtil::_isForeignField($field)){
    				$reflectionProperty = $reflectionClass->getProperty($fieldName);
    				$reflectionProperty->setAccessible(true);
    				$fieldValue = $reflectionProperty->getValue($this);
    				if($fieldValue === null){
    					$fieldValue = ' IS NULL';
    				}else{
    					$fieldValue = " = '".$connection->encodeForSQLInjection($fieldValue)."'";
    				}

    				if($recordIdentifier != ""){
    					$recordIdentifier .= " AND ";
    				}
    				$recordIdentifier .= ($field['columnName']." = '$fieldValue'");
    			}
    		}
    	}
    	return $recordIdentifier;
    }

    private static function runTrigger($className,$triggerEvent,$triggerType,$parameters){
    	if(self::$_triggers == null){
    		self::$_triggers = Settings::getSettings('php-platform/persist','triggers');
    	}

    	if(isset(self::$_triggers[$className][$triggerEvent][$triggerType])){
    		$triggers = self::$_triggers[$className][$triggerEvent][$triggerType];
    		if(!is_array($triggers)){
    			throw new TriggerException("Invalid Trigger configuration : triggers[$className][$triggerEvent][$triggerType] should be an array");
    		}
    		foreach($triggers as $index => $trigger){
    			if(! isset($trigger["class"]) || ! isset($trigger["method"])){
    				throw new TriggerException("Invalid Trigger configuration : triggers[$className][$triggerEvent][$triggerType][$index] should have class and method");
    			}
    			$triggerClass = $trigger["class"];
    			$triggerMethod = $trigger["method"];
    			$triggerHashCode = "$className::$triggerEvent::$triggerType::$triggerClass::$triggerMethod";
    			try{
    				if(isset($_ENV[$triggerHashCode]) && $_ENV[$triggerHashCode] == true){
    					throw new TriggerException("Loop in the Trigger, ($className::$triggerEvent::$triggerType::$triggerClass::$triggerMethod) is repeated");
    				}
    				$_ENV[$triggerHashCode] = true;

    				$triggerClassObj = Reflection::newInstanceArgs($triggerClass);
    				Reflection::invokeArgs($triggerClass, $triggerMethod, $triggerClassObj,$parameters);
    				unset($_ENV[$triggerHashCode]);
    			}catch(\Exception $e){
    				unset($_ENV[$triggerHashCode]);
    				$triggerException = new TriggerException("Trigger([$className][$triggerEvent][$triggerType] => $triggerClass::$triggerMethod) Failed : ".$e->getMessage());
    				if(! isset($trigger["ignoreErrors"]) || $trigger["ignoreErrors"] === false){
    					throw $triggerException;
    				}
    			}
    		}
    	}
    }

}

?>


<?php namespace PhpPackages\Container;

class DocBlock
{

    /**
     * @var array
     */
    protected $lines = [];

    /**
     * @param \Reflector $reflector
     * @return DocBlock
     */
    public function __construct(\Reflector $reflector)
    {
        $this->setBlock($reflector->getDocComment());
    }

    /**
     * Returns a value associated with the given key, or null otherwise (if no such key).
     *
     * @param string $key
     * @return string|null
     */
    public function getValue($key)
    {
        foreach ($this->lines as $line) {
            if (strpos($line, "@".$key) === 0) {
                return trim(str_replace("@".$key, "", $line));
            }
        }

        return null;
    }

    /**
     * Whether the array of lines we are working with contains the given flag.
     *
     * @param string $name
     * @return boolean
     */
    public function hasFlag($name)
    {
        return in_array("@".$name, $this->lines);
    }

    /**
     * Parses the given DocBlock and assigns the produced array to a property.
     *
     * @param string $block
     * @return void
     */
    protected function setBlock($block)
    {
        $this->lines = $this->parseBlock($block);
    }

    /**
     * Returns the array of lines we are working with.
     *
     * @return array
     */
    public function getLines()
    {
        return $this->lines;
    }

    /**
     * Parses a DocBlock comment into an array of lines.
     *
     * @param string $block
     * @return array
     */
    protected function parseBlock($block)
    {
        $lines = array_filter(array_map(function($line)
        {
            $line = trim($line);

            if (strpos($line, "/**") !== false or strpos($line, "*/") !== false) {
                return null;
            }

            return trim(substr($line, 1));
        }, explode(PHP_EOL, $block)));

        return array_values($lines);
    }
}


<?php
/**
 * @file
 * Calculate the distance between two locations on the Earth and calculate ranges.
 *
 * The equations are from Ka-Ping Yee (http://zesty.ca/) and usage permission
 * was given on December 28, 2012 - https://twitter.com/zestyping/status/284747131867254784
 */

namespace Lootils\Geo\Method;

use \Lootils\Geo\Earth;
use \Lootils\Geo\LocationInterface;
use \Lootils\Geo\Method\DistanceInterface;

class Yee extends Earth implements DistanceInterface {

  /**
   * Calculate the distance between two locations.
   *
   * Note, this is an estimate. The further the two places are from each other
   * the less accurate the distance calculation will be. This method also assumes
   * all locations are at the equator.
   */
  public function distance(LocationInterface $location1, LocationInterface $location2) {
    $radLong1 = deg2rad($location1->longitude());
    $radLat1 = deg2rad($location1->latitude());
    $radLong2 = deg2rad($location2->longitude());
    $radLat2 = deg2rad($location2->latitude());

    $radius = $this->earthRadius(($location1->latitude() + $location2->latitude()) / 2);

    $cosangle = cos($radLat1)*cos($radLat2) *
      (cos($radLong1)*cos($radLong2) + sin($radLong1)*sin($radLong2)) +
      sin($radLat1)*sin($radLat2);

    return acos($cosangle) * $radius;
  }

}


<?php

/*
 * This file is part of madewithlove/service-providers
 *
 * (c) madewithlove <heroes@madewithlove.be>
 *
 * For the full copyright and license information, please view the LICENSE
 */

namespace Madewithlove\ServiceProviders\CommandBus;

use Interop\Container\ServiceProviderInterface;
use League\Tactician\CommandBus;
use League\Tactician\Handler\CommandHandlerMiddleware;
use League\Tactician\Handler\CommandNameExtractor\ClassNameExtractor;
use League\Tactician\Handler\CommandNameExtractor\CommandNameExtractor;
use League\Tactician\Handler\Locator\HandlerLocator;
use League\Tactician\Handler\Locator\InMemoryLocator;
use League\Tactician\Handler\MethodNameInflector\HandleInflector;
use League\Tactician\Handler\MethodNameInflector\MethodNameInflector;
use League\Tactician\Middleware;
use Madewithlove\ServiceProviders\Utilities\Alias;
use Psr\Container\ContainerInterface;

class TacticianServiceProvider implements ServiceProviderInterface
{
    /**
     * @var CommandNameExtractor
     */
    protected $extractor;

    /**
     * @var MethodNameInflector
     */
    protected $inflector;

    /**
     * @var HandlerLocator
     */
    protected $locator;

    /**
     * @param string $extractor
     * @param string $locator
     * @param string $inflector
     */
    public function __construct(
        $extractor = ClassNameExtractor::class,
        $locator = InMemoryLocator::class,
        $inflector = HandleInflector::class
    ) {
        $this->extractor = $extractor;
        $this->locator = $locator;
        $this->inflector = $inflector;
    }

    /**
     * {@inheritdoc}
     */
    public function getServices()
    {
        return [
            Middleware::class => [$this, 'getHandlerMiddleware'],
            CommandBus::class => [$this, 'getCommandBus'],
            'bus' => new Alias(CommandBus::class),
        ];
    }

    /**
     * @param ContainerInterface $container
     *
     * @return Middleware
     */
    public function getHandlerMiddleware(ContainerInterface $container)
    {
        return new CommandHandlerMiddleware(
            $container->get($this->extractor),
            $container->get($this->locator),
            $container->get($this->inflector)
        );
    }

    /**
     * @param ContainerInterface $container
     *
     * @return CommandBus
     */
    public function getCommandBus(ContainerInterface $container)
    {
        return new CommandBus([
            $container->get(Middleware::class),
        ]);
    }
}