<?php
/**
 * PEAR_Frontend_CLI
 *
 * PHP versions 4 and 5
 *
 * @category   pear
 * @package    PEAR
 * @author     Stig Bakken <ssb@php.net>
 * @author     Greg Beaver <cellog@php.net>
 * @copyright  1997-2009 The Authors
 * @license    http://opensource.org/licenses/bsd-license.php New BSD License
 * @version    CVS: $Id: CLI.php 313023 2011-07-06 19:17:11Z dufuz $
 * @link       http://pear.php.net/package/PEAR
 * @since      File available since Release 0.1
 */
/**
 * base class
 */
require_once 'PEAR/Frontend.php';

/**
 * Command-line Frontend for the PEAR Installer
 * @category   pear
 * @package    PEAR
 * @author     Stig Bakken <ssb@php.net>
 * @author     Greg Beaver <cellog@php.net>
 * @copyright  1997-2009 The Authors
 * @license    http://opensource.org/licenses/bsd-license.php New BSD License
 * @version    Release: 1.9.4
 * @link       http://pear.php.net/package/PEAR
 * @since      Class available since Release 0.1
 */
class PEAR_Frontend_CLI extends PEAR_Frontend
{
    /**
     * What type of user interface this frontend is for.
     * @var string
     * @access public
     */
    var $type = 'CLI';
    var $lp = ''; // line prefix

    var $params = array();
    var $term = array(
        'bold'   => '',
        'normal' => '',
    );

    function PEAR_Frontend_CLI()
    {
        parent::PEAR();
        $term = getenv('TERM'); //(cox) $_ENV is empty for me in 4.1.1
        if (function_exists('posix_isatty') && !posix_isatty(1)) {
            // output is being redirected to a file or through a pipe
        } elseif ($term) {
            if (preg_match('/^(xterm|vt220|linux)/', $term)) {
                $this->term['bold']   = sprintf("%c%c%c%c", 27, 91, 49, 109);
                $this->term['normal'] = sprintf("%c%c%c", 27, 91, 109);
            } elseif (preg_match('/^vt100/', $term)) {
                $this->term['bold']   = sprintf("%c%c%c%c%c%c", 27, 91, 49, 109, 0, 0);
                $this->term['normal'] = sprintf("%c%c%c%c%c", 27, 91, 109, 0, 0);
            }
        } elseif (OS_WINDOWS) {
            // XXX add ANSI codes here
        }
    }

    /**
     * @param object PEAR_Error object
     */
    function displayError($e)
    {
        return $this->_displayLine($e->getMessage());
    }

    /**
     * @param object PEAR_Error object
     */
    function displayFatalError($eobj)
    {
        $this->displayError($eobj);
        if (class_exists('PEAR_Config')) {
            $config = &PEAR_Config::singleton();
            if ($config->get('verbose') > 5) {
                if (function_exists('debug_print_backtrace')) {
                    debug_print_backtrace();
                    exit(1);
                }

                $raised = false;
                foreach (debug_backtrace() as $i => $frame) {
                    if (!$raised) {
                        if (isset($frame['class'])
                            && strtolower($frame['class']) == 'pear'
                            && strtolower($frame['function']) == 'raiseerror'
                        ) {
                            $raised = true;
                        } else {
                            continue;
                        }
                    }

                    $frame['class']    = !isset($frame['class'])    ? '' : $frame['class'];
                    $frame['type']     = !isset($frame['type'])     ? '' : $frame['type'];
                    $frame['function'] = !isset($frame['function']) ? '' : $frame['function'];
                    $frame['line']     = !isset($frame['line'])     ? '' : $frame['line'];
                    $this->_displayLine("#$i: $frame[class]$frame[type]$frame[function] $frame[line]");
                }
            }
        }

        exit(1);
    }

    /**
     * Instruct the runInstallScript method to skip a paramgroup that matches the
     * id value passed in.
     *
     * This method is useful for dynamically configuring which sections of a post-install script
     * will be run based on the user's setup, which is very useful for making flexible
     * post-install scripts without losing the cross-Frontend ability to retrieve user input
     * @param string
     */
    function skipParamgroup($id)
    {
        $this->_skipSections[$id] = true;
    }

    function runPostinstallScripts(&$scripts)
    {
        foreach ($scripts as $i => $script) {
            $this->runInstallScript($scripts[$i]->_params, $scripts[$i]->_obj);
        }
    }

    /**
     * @param array $xml contents of postinstallscript tag
     * @param object $script post-installation script
     * @param string install|upgrade
     */
    function runInstallScript($xml, &$script)
    {
        $this->_skipSections = array();
        if (!is_array($xml) || !isset($xml['paramgroup'])) {
            $script->run(array(), '_default');
            return;
        }

        $completedPhases = array();
        if (!isset($xml['paramgroup'][0])) {
            $xml['paramgroup'] = array($xml['paramgroup']);
        }

        foreach ($xml['paramgroup'] as $group) {
            if (isset($this->_skipSections[$group['id']])) {
                // the post-install script chose to skip this section dynamically
                continue;
            }

            if (isset($group['name'])) {
                $paramname = explode('::', $group['name']);
                if ($lastgroup['id'] != $paramname[0]) {
                    continue;
                }

                $group['name'] = $paramname[1];
                if (!isset($answers)) {
                    return;
                }

                if (isset($answers[$group['name']])) {
                    switch ($group['conditiontype']) {
                        case '=' :
                            if ($answers[$group['name']] != $group['value']) {
                                continue 2;
                            }
                        break;
                        case '!=' :
                            if ($answers[$group['name']] == $group['value']) {
                                continue 2;
                            }
                        break;
                        case 'preg_match' :
                            if (!@preg_match('/' . $group['value'] . '/',
                                  $answers[$group['name']])) {
                                continue 2;
                            }
                        break;
                        default :
                        return;
                    }
                }
            }

            $lastgroup = $group;
            if (isset($group['instructions'])) {
                $this->_display($group['instructions']);
            }

            if (!isset($group['param'][0])) {
                $group['param'] = array($group['param']);
            }

            if (isset($group['param'])) {
                if (method_exists($script, 'postProcessPrompts')) {
                    $prompts = $script->postProcessPrompts($group['param'], $group['id']);
                    if (!is_array($prompts) || count($prompts) != count($group['param'])) {
                        $this->outputData('postinstall', 'Error: post-install script did not ' .
                            'return proper post-processed prompts');
                        $prompts = $group['param'];
                    } else {
                        foreach ($prompts as $i => $var) {
                            if (!is_array($var) || !isset($var['prompt']) ||
                                  !isset($var['name']) ||
                                  ($var['name'] != $group['param'][$i]['name']) ||
                                  ($var['type'] != $group['param'][$i]['type'])
                            ) {
                                $this->outputData('postinstall', 'Error: post-install script ' .
                                    'modified the variables or prompts, severe security risk. ' .
                                    'Will instead use the defaults from the package.xml');
                                $prompts = $group['param'];
                            }
                        }
                    }

                    $answers = $this->confirmDialog($prompts);
                } else {
                    $answers = $this->confirmDialog($group['param']);
                }
            }

            if ((isset($answers) && $answers) || !isset($group['param'])) {
                if (!isset($answers)) {
                    $answers = array();
                }

                array_unshift($completedPhases, $group['id']);
                if (!$script->run($answers, $group['id'])) {
                    $script->run($completedPhases, '_undoOnError');
                    return;
                }
            } else {
                $script->run($completedPhases, '_undoOnError');
                return;
            }
        }
    }

    /**
     * Ask for user input, confirm the answers and continue until the user is satisfied
     * @param array an array of arrays, format array('name' => 'paramname', 'prompt' =>
     *              'text to display', 'type' => 'string'[, default => 'default value'])
     * @return array
     */
    function confirmDialog($params)
    {
        $answers = $prompts = $types = array();
        foreach ($params as $param) {
            $prompts[$param['name']] = $param['prompt'];
            $types[$param['name']]   = $param['type'];
            $answers[$param['name']] = isset($param['default']) ? $param['default'] : '';
        }

        $tried = false;
        do {
            if ($tried) {
                $i = 1;
                foreach ($answers as $var => $value) {
                    if (!strlen($value)) {
                        echo $this->bold("* Enter an answer for #" . $i . ": ({$prompts[$var]})\n");
                    }
                    $i++;
                }
            }

            $answers = $this->userDialog('', $prompts, $types, $answers);
            $tried   = true;
        } while (is_array($answers) && count(array_filter($answers)) != count($prompts));

        return $answers;
    }

    function userDialog($command, $prompts, $types = array(), $defaults = array(), $screensize = 20)
    {
        if (!is_array($prompts)) {
            return array();
        }

        $testprompts = array_keys($prompts);
        $result      = $defaults;

        reset($prompts);
        if (count($prompts) === 1) {
            foreach ($prompts as $key => $prompt) {
                $type    = $types[$key];
                $default = @$defaults[$key];
                print "$prompt ";
                if ($default) {
                    print "[$default] ";
                }
                print ": ";

                $line         = fgets(STDIN, 2048);
                $result[$key] =  ($default && trim($line) == '') ? $default : trim($line);
            }

            return $result;
        }

        $first_run = true;
        while (true) {
            $descLength = max(array_map('strlen', $prompts));
            $descFormat = "%-{$descLength}s";
            $last       = count($prompts);

            $i = 0;
            foreach ($prompts as $n => $var) {
                $res = isset($result[$n]) ? $result[$n] : null;
                printf("%2d. $descFormat : %s\n", ++$i, $prompts[$n], $res);
            }
            print "\n1-$last, 'all', 'abort', or Enter to continue: ";

            $tmp = trim(fgets(STDIN, 1024));
            if (empty($tmp)) {
                break;
            }

            if ($tmp == 'abort') {
                return false;
            }

            if (isset($testprompts[(int)$tmp - 1])) {
                $var     = $testprompts[(int)$tmp - 1];
                $desc    = $prompts[$var];
                $current = @$result[$var];
                print "$desc [$current] : ";
                $tmp = trim(fgets(STDIN, 1024));
                if ($tmp !== '') {
                    $result[$var] = $tmp;
                }
            } elseif ($tmp == 'all') {
                foreach ($prompts as $var => $desc) {
                    $current = $result[$var];
                    print "$desc [$current] : ";
                    $tmp = trim(fgets(STDIN, 1024));
                    if (trim($tmp) !== '') {
                        $result[$var] = trim($tmp);
                    }
                }
            }

            $first_run = false;
        }

        return $result;
    }

    function userConfirm($prompt, $default = 'yes')
    {
        trigger_error("PEAR_Frontend_CLI::userConfirm not yet converted", E_USER_ERROR);
        static $positives = array('y', 'yes', 'on', '1');
        static $negatives = array('n', 'no', 'off', '0');
        print "$this->lp$prompt [$default] : ";
        $fp = fopen("php://stdin", "r");
        $line = fgets($fp, 2048);
        fclose($fp);
        $answer = strtolower(trim($line));
        if (empty($answer)) {
            $answer = $default;
        }
        if (in_array($answer, $positives)) {
            return true;
        }
        if (in_array($answer, $negatives)) {
            return false;
        }
        if (in_array($default, $positives)) {
            return true;
        }
        return false;
    }

    function outputData($data, $command = '_default')
    {
        switch ($command) {
            case 'channel-info':
                foreach ($data as $type => $section) {
                    if ($type == 'main') {
                        $section['data'] = array_values($section['data']);
                    }

                    $this->outputData($section);
                }
                break;
            case 'install':
            case 'upgrade':
            case 'upgrade-all':
                if (is_array($data) && isset($data['release_warnings'])) {
                    $this->_displayLine('');
                    $this->_startTable(array(
                        'border' => false,
                        'caption' => 'Release Warnings'
                    ));
                    $this->_tableRow(array($data['release_warnings']), null, array(1 => array('wrap' => 55)));
                    $this->_endTable();
                    $this->_displayLine('');
                }

                $this->_displayLine(is_array($data) ? $data['data'] : $data);
                break;
            case 'search':
                $this->_startTable($data);
                if (isset($data['headline']) && is_array($data['headline'])) {
                    $this->_tableRow($data['headline'], array('bold' => true), array(1 => array('wrap' => 55)));
                }

                $packages = array();
                foreach($data['data'] as $category) {
                    foreach($category as $name => $pkg) {
                        $packages[$pkg[0]] = $pkg;
                    }
                }

                $p = array_keys($packages);
                natcasesort($p);
                foreach ($p as $name) {
                    $this->_tableRow($packages[$name], null, array(1 => array('wrap' => 55)));
                }

                $this->_endTable();
                break;
            case 'list-all':
                if (!isset($data['data'])) {
                      $this->_displayLine('No packages in channel');
                      break;
                }

                $this->_startTable($data);
                if (isset($data['headline']) && is_array($data['headline'])) {
                    $this->_tableRow($data['headline'], array('bold' => true), array(1 => array('wrap' => 55)));
                }

                $packages = array();
                foreach($data['data'] as $category) {
                    foreach($category as $name => $pkg) {
                        $packages[$pkg[0]] = $pkg;
                    }
                }

                $p = array_keys($packages);
                natcasesort($p);
                foreach ($p as $name) {
                    $pkg = $packages[$name];
                    unset($pkg[4], $pkg[5]);
                    $this->_tableRow($pkg, null, array(1 => array('wrap' => 55)));
                }

                $this->_endTable();
                break;
            case 'config-show':
                $data['border'] = false;
                $opts = array(
                    0 => array('wrap' => 30),
                    1 => array('wrap' => 20),
                    2 => array('wrap' => 35)
                );

                $this->_startTable($data);
                if (isset($data['headline']) && is_array($data['headline'])) {
                    $this->_tableRow($data['headline'], array('bold' => true), $opts);
                }

                foreach ($data['data'] as $group) {
                    foreach ($group as $value) {
                        if ($value[2] == '') {
                            $value[2] = "<not set>";
                        }

                        $this->_tableRow($value, null, $opts);
                    }
                }

                $this->_endTable();
                break;
            case 'remote-info':
                $d = $data;
                $data = array(
                    'caption' => 'Package details:',
                    'border'  => false,
                    'data'    => array(
                        array("Latest",      $data['stable']),
                        array("Installed",   $data['installed']),
                        array("Package",     $data['name']),
                        array("License",     $data['license']),
                        array("Category",    $data['category']),
                        array("Summary",     $data['summary']),
                        array("Description", $data['description']),
                    ),
                );

                if (isset($d['deprecated']) && $d['deprecated']) {
                    $conf = &PEAR_Config::singleton();
                    $reg = $conf->getRegistry();
                    $name = $reg->parsedPackageNameToString($d['deprecated'], true);
                    $data['data'][] = array('Deprecated! use', $name);
                }
            default: {
                if (is_array($data)) {
                    $this->_startTable($data);
                    $count = count($data['data'][0]);
                    if ($count == 2) {
                        $opts = array(0 => array('wrap' => 25),
                                      1 => array('wrap' => 48)
                        );
                    } elseif ($count == 3) {
                        $opts = array(0 => array('wrap' => 30),
                                      1 => array('wrap' => 20),
                                      2 => array('wrap' => 35)
                        );
                    } else {
                        $opts = null;
                    }
                    if (isset($data['headline']) && is_array($data['headline'])) {
                        $this->_tableRow($data['headline'],
                                         array('bold' => true),
                                         $opts);
                    }

                    if (is_array($data['data'])) {
                        foreach($data['data'] as $row) {
                            $this->_tableRow($row, null, $opts);
                        }
                    } else {
                        $this->_tableRow(array($data['data']), null, $opts);
                     }
                    $this->_endTable();
                } else {
                    $this->_displayLine($data);
                }
            }
        }
    }

    function log($text, $append_crlf = true)
    {
        if ($append_crlf) {
            return $this->_displayLine($text);
        }

        return $this->_display($text);
    }

    function bold($text)
    {
        if (empty($this->term['bold'])) {
            return strtoupper($text);
        }

        return $this->term['bold'] . $text . $this->term['normal'];
    }

    function _displayHeading($title)
    {
        print $this->lp.$this->bold($title)."\n";
        print $this->lp.str_repeat("=", strlen($title))."\n";
    }

    function _startTable($params = array())
    {
        $params['table_data'] = array();
        $params['widest']     = array();  // indexed by column
        $params['highest']    = array(); // indexed by row
        $params['ncols']      = 0;
        $this->params         = $params;
    }

    function _tableRow($columns, $rowparams = array(), $colparams = array())
    {
        $highest = 1;
        for ($i = 0; $i < count($columns); $i++) {
            $col = &$columns[$i];
            if (isset($colparams[$i]) && !empty($colparams[$i]['wrap'])) {
                $col = wordwrap($col, $colparams[$i]['wrap']);
            }

            if (strpos($col, "\n") !== false) {
                $multiline = explode("\n", $col);
                $w = 0;
                foreach ($multiline as $n => $line) {
                    $len = strlen($line);
                    if ($len > $w) {
                        $w = $len;
                    }
                }
                $lines = count($multiline);
            } else {
                $w = strlen($col);
            }

            if (isset($this->params['widest'][$i])) {
                if ($w > $this->params['widest'][$i]) {
                    $this->params['widest'][$i] = $w;
                }
            } else {
                $this->params['widest'][$i] = $w;
            }

            $tmp = count_chars($columns[$i], 1);
            // handle unix, mac and windows formats
            $lines = (isset($tmp[10]) ? $tmp[10] : (isset($tmp[13]) ? $tmp[13] : 0)) + 1;
            if ($lines > $highest) {
                $highest = $lines;
            }
        }

        if (count($columns) > $this->params['ncols']) {
            $this->params['ncols'] = count($columns);
        }

        $new_row = array(
            'data'      => $columns,
            'height'    => $highest,
            'rowparams' => $rowparams,
            'colparams' => $colparams,
        );
        $this->params['table_data'][] = $new_row;
    }

    function _endTable()
    {
        extract($this->params);
        if (!empty($caption)) {
            $this->_displayHeading($caption);
        }

        if (count($table_data) === 0) {
            return;
        }

        if (!isset($width)) {
            $width = $widest;
        } else {
            for ($i = 0; $i < $ncols; $i++) {
                if (!isset($width[$i])) {
                    $width[$i] = $widest[$i];
                }
            }
        }

        $border = false;
        if (empty($border)) {
            $cellstart  = '';
            $cellend    = ' ';
            $rowend     = '';
            $padrowend  = false;
            $borderline = '';
        } else {
            $cellstart  = '| ';
            $cellend    = ' ';
            $rowend     = '|';
            $padrowend  = true;
            $borderline = '+';
            foreach ($width as $w) {
                $borderline .= str_repeat('-', $w + strlen($cellstart) + strlen($cellend) - 1);
                $borderline .= '+';
            }
        }

        if ($borderline) {
            $this->_displayLine($borderline);
        }

        for ($i = 0; $i < count($table_data); $i++) {
            extract($table_data[$i]);
            if (!is_array($rowparams)) {
                $rowparams = array();
            }

            if (!is_array($colparams)) {
                $colparams = array();
            }

            $rowlines = array();
            if ($height > 1) {
                for ($c = 0; $c < count($data); $c++) {
                    $rowlines[$c] = preg_split('/(\r?\n|\r)/', $data[$c]);
                    if (count($rowlines[$c]) < $height) {
                        $rowlines[$c] = array_pad($rowlines[$c], $height, '');
                    }
                }
            } else {
                for ($c = 0; $c < count($data); $c++) {
                    $rowlines[$c] = array($data[$c]);
                }
            }

            for ($r = 0; $r < $height; $r++) {
                $rowtext = '';
                for ($c = 0; $c < count($data); $c++) {
                    if (isset($colparams[$c])) {
                        $attribs = array_merge($rowparams, $colparams);
                    } else {
                        $attribs = $rowparams;
                    }

                    $w = isset($width[$c]) ? $width[$c] : 0;
                    //$cell = $data[$c];
                    $cell = $rowlines[$c][$r];
                    $l = strlen($cell);
                    if ($l > $w) {
                        $cell = substr($cell, 0, $w);
                    }

                    if (isset($attribs['bold'])) {
                        $cell = $this->bold($cell);
                    }

                    if ($l < $w) {
                        // not using str_pad here because we may
                        // add bold escape characters to $cell
                        $cell .= str_repeat(' ', $w - $l);
                    }

                    $rowtext .= $cellstart . $cell . $cellend;
                }

                if (!$border) {
                    $rowtext = rtrim($rowtext);
                }

                $rowtext .= $rowend;
                $this->_displayLine($rowtext);
            }
        }

        if ($borderline) {
            $this->_displayLine($borderline);
        }
    }

    function _displayLine($text)
    {
        print "$this->lp$text\n";
    }

    function _display($text)
    {
        print $text;
    }
}


<?php

namespace FlexPress\Components\PostType;

abstract class AbstractPostType
{

    /**
     * Gets the singular name
     *
     * @return string
     * @author Tim Perry
     */
    public function getSingularName()
    {
        return ucwords($this->getName());
    }

    /**
     * Gets the plural name
     *
     * @return string
     * @author Tim Perry
     */
    public function getPluralName()
    {
        return $this->getSingularName() . "s";
    }

    /**
     *
     * Gets the args
     *
     * @return array
     * @author Tim Perry
     */
    public function getArgs()
    {
        return array(
            'labels' => $this->getLabels(),
            'public' => true,
            'publicly_queryable' => true,
            'show_ui' => true,
            'show_in_menu' => true,
            'query_var' => true,
            'rewrite' => array('slug' => strtolower($this->getSingularName())),
            'capability_type' => 'post',
            'has_archive' => true,
            'hierarchical' => false,
            'menu_position' => null,
            'supports' => array('title', 'editor', 'thumbnail')
        );
    }

    /**
     * Gets the labels used in the args
     *
     * @return array
     * @author Tim Perry
     */
    protected function getLabels()
    {
        $pluralName = $this->getPluralName();
        $singularName = $this->getSingularName();

        return array(
            'name' => $singularName,
            'singular_name' => $singularName,
            'add_new' => 'Add New',
            'add_new_item' => 'Add New ' . $singularName,
            'edit_item' => 'Edit ' . $singularName,
            'new_item' => 'New ' . $singularName,
            'all_items' => 'All ' . $pluralName,
            'view_item' => 'View ' . $singularName,
            'search_items' => 'Search ' . $pluralName,
            'not_found' => 'No ' . $pluralName . ' found',
            'not_found_in_trash' => 'No ' . $pluralName . ' found in Trash',
            'parent_item_colon' => '',
            'menu_name' => $pluralName
        );
    }

    /**
     * Gets the name of the taxonomy
     *
     * @return string
     * @author Tim Perry
     */
    abstract public function getName();
}


<?php
/**
 * Extension for Controller class to give you some hooks for livepub in the template.
 *
 * @author Mark Guinn <mark@adaircreative.com>
 * @date 04.23.2013
 * @package livepub
 */
class LivePubControllerHooks extends Extension
{
    /**
     * The default base_tag implementation returns the full http://
     * url which causes issues with static publishing + https.
     * @return string
     */
    public function BaseTag()
    {
        return LivePubHelper::eval_php('
			$url = ((!isset($_SERVER["HTTPS"]) || $_SERVER["HTTPS"] == "off")
							&& !(isset($_SERVER["HTTP_X_FORWARDED_PROTOCOL"]) && strtolower($_SERVER["HTTP_X_FORWARDED_PROTOCOL"]) == "https"))
				? "http://"
				: "https://";
			$url .= $_SERVER["HTTP_HOST"] . "/";
			if (defined("BASE_URL") && BASE_URL) $url .= BASE_URL;
			if (substr($url, -1) != "/") $url .= "/";
			return "<base href=\"" . $url . "\"><!--[if lte IE 6]></base><![endif]-->";
		');
    }

    /**
     * allows you to include php templates that work even when static publishing is enabled
     */
    public function IncludePHP($tpl)
    {
        return LivePubHelper::include_php($tpl);
    }

    /**
     * returns a viewable wrapper around the session
     */
    public function WrappedSession()
    {
        LivePubHelper::require_session();
        $obj = LivePubHelper::wrap($_SESSION);
        $obj->setVar('_SESSION');
        return $obj;
    }

    public function LPH_Session()
    {
        return $this->WrappedSession();
    }

    /**
     * returns a viewable wrapper around the request
     */
    public function WrappedRequest()
    {
        $obj = LivePubHelper::wrap($_REQUEST);
        $obj->setVar('_REQUEST');
        return $obj;
    }

    public function LPH_Request()
    {
        return $this->WrappedRequest();
    }

    /**
     * are we currently publishing?
     */
    public function LPH_IsPublishing()
    {
        return LivePubHelper::is_publishing();
    }

    public function LPH_NotPublishing()
    {
        return !LivePubHelper::is_publishing();
    }

    /**
     * if we're publishing, outputs an if statement
     * $func should be something on the controller that
     * is livepub sensitive (either uses eval_php or
     * some other method to return code)
     */
    public function LPH_If($func)
    {
        if (LivePubHelper::is_publishing()) {
            LivePubHelper::$context = 'php';
            $str = $this->getOwner()->$func();
            LivePubHelper::$context = 'html';
            return '<?php if (' . $str . '): ?>';
        }
    }

    /**
     * is this an ajax request? NOTE: this will not actually function as an IF
     * statement in a live silverstripe template. You have to wrap them together
     * like this for it to work in both live and published modes:
     * <% if LPH_NotPublishing && isAjax %><% else %>$LPH_IfNotAjax
     * $LPH_EndIf<% end_if %>
     */
    public function LPH_IfAjax()
    {
        if (LivePubHelper::is_publishing()) {
            return '<?php if ($isAjax): ?>';
        }
    }

    public function LPH_IfNotAjax()
    {
        if (LivePubHelper::is_publishing()) {
            return '<?php if (!$isAjax): ?>';
        }
    }

    /**
     * output generic php closing the above functions
     */
    public function LPH_Else()
    {
        if (LivePubHelper::is_publishing()) {
            return '<?php else: ?>';
        }
    }

    public function LPH_EndIf()
    {
        if (LivePubHelper::is_publishing()) {
            return '<?php endif; ?>';
        }
    }
}


<?php
/**
 * ORM
 *
 * Простое объектно-реляционное отображение для Eresus.
 *
 * @version ${product.version}
 *
 * @copyright 2011, Михаил Красильников <m.krasilnikov@yandex.ru>
 * @license http://www.gnu.org/licenses/gpl.txt	GPL License 3
 * @author Михаил Красильников <m.krasilnikov@yandex.ru>
 *
 * Данная программа является свободным программным обеспечением. Вы
 * вправе распространять ее и/или модифицировать в соответствии с
 * условиями версии 3 либо (по вашему выбору) с условиями более поздней
 * версии Стандартной Общественной Лицензии GNU, опубликованной Free
 * Software Foundation.
 *
 * Мы распространяем эту программу в надежде на то, что она будет вам
 * полезной, однако НЕ ПРЕДОСТАВЛЯЕМ НА НЕЕ НИКАКИХ ГАРАНТИЙ, в том
 * числе ГАРАНТИИ ТОВАРНОГО СОСТОЯНИЯ ПРИ ПРОДАЖЕ и ПРИГОДНОСТИ ДЛЯ
 * ИСПОЛЬЗОВАНИЯ В КОНКРЕТНЫХ ЦЕЛЯХ. Для получения более подробной
 * информации ознакомьтесь со Стандартной Общественной Лицензией GNU.
 *
 * Вы должны были получить копию Стандартной Общественной Лицензии
 * GNU с этой программой. Если Вы ее не получили, смотрите документ на
 * <http://www.gnu.org/licenses/>
 *
 * @package ORM
 */

/**
 * Основной класс плагина
 *
 * @package ORM
 */
class ORM extends Eresus_Plugin
{
    /**
     * Версия плагина
     * @var string
     */
    public $version = '${product.version}';

    /**
     * Требуемая версия ядра
     * @var string
     */
    public $kernel = '3.01a';

    /**
     * Название плагина
     * @var string
     */
    public $title = 'ORM';

    /**
     * Описание плагина
     * @var string
     */
    public $description = 'Средства ORM для использования в других плагинах';

    /**
     * Менеджер
     * @var ORM_Manager
     * @since 3.00
     */
    private $manager = null;

    /**
     * Возвращает менеджера ORM
     * @return ORM_Manager
     */
    public static function getManager()
    {
        /** @var ORM $orm */
        $orm = Eresus_Plugin_Registry::getInstance()->load('orm');
        if (null === $orm->manager)
        {
            $orm->manager = new ORM_Manager();
        }
        return $orm->manager;
    }

    /**
     * Возвращает объект таблицы для указанной сущности указанного плагина
     *
     * @param Eresus_Plugin|string $plugin      плагин, которому принадлежит сущность
     * @param string               $entityName  имя сущности (без имени плагина и слова «Entity»)
     *
     * @return ORM_Table
     *
     * @throws InvalidArgumentException
     * @throws RuntimeException
     *
     * @since 1.00
     */
    public static function getTable($plugin, $entityName)
    {
        if (is_string($plugin))
        {
            $name = $plugin;
            $plugin = Eresus_Plugin_Registry::getInstance()->load($plugin);
            if (false === $plugin)
            {
                throw new RuntimeException(sprintf('Plugin "%s" not found or inactive', $name));
            }
        }
        return self::getManager()->getTable($plugin, $entityName);
    }
}


<?php

namespace Reaction\Db\Constraints;

use Reaction\Db\SchemaInterface;
use Reaction\Promise\ExtendedPromiseInterface;

/**
 * ConstraintFinderTrait provides methods for getting a table constraint information.
 *
 * @property CheckConstraint[][] $schemaChecks Check constraints for all tables in the database.
 * Each array element is an array of [[CheckConstraint]] or its child classes. This property is read-only.
 * @property DefaultValueConstraint[] $schemaDefaultValues Default value constraints for all tables in the database.
 * Each array element is an array of [[DefaultValueConstraint]] or its child classes. This property is read-only.
 * @property ForeignKeyConstraint[][] $schemaForeignKeys Foreign keys for all tables in the database. Each
 * array element is an array of [[ForeignKeyConstraint]] or its child classes. This property is read-only.
 * @property IndexConstraint[][] $schemaIndexes Indexes for all tables in the database. Each array element is
 * an array of [[IndexConstraint]] or its child classes. This property is read-only.
 * @property Constraint[] $schemaPrimaryKeys Primary keys for all tables in the database. Each array element
 * is an instance of [[Constraint]] or its child class. This property is read-only.
 * @property IndexConstraint[][] $schemaUniques Unique constraints for all tables in the database.
 * Each array element is an array of [[IndexConstraint]] or its child classes. This property is read-only.
 */
trait ConstraintFinderTrait
{
    /**
     * Returns the metadata of the given type for the given table.
     * @param string $name table name. The table name may contain schema name if any. Do not quote the table name.
     * @param string $type metadata type.
     * @param bool $refresh whether to reload the table metadata even if it is found in the cache.
     * @return mixed metadata.
     */
    abstract protected function getTableMetadata($name, $type, $refresh);

    /**
     * Returns the metadata of the given type for all tables in the given schema.
     * @param string $schema the schema of the metadata. Defaults to empty string, meaning the current or default schema name.
     * @param string $type metadata type.
     * @param bool $refresh whether to fetch the latest available table metadata. If this is `false`,
     * cached data may be returned if available.
     * @return ExtendedPromiseInterface with array array of metadata.
     */
    abstract protected function getSchemaMetadata($schema, $type, $refresh);

    /**
     * Loads a primary key for the given table.
     * @param string $tableName table name.
     * @return ExtendedPromiseInterface with Constraint|null primary key for the given table, `null` if the table has no primary key.
     */
    abstract protected function loadTablePrimaryKey($tableName);

    /**
     * Loads all foreign keys for the given table.
     * @param string $tableName table name.
     * @return ExtendedPromiseInterface with ForeignKeyConstraint[] foreign keys for the given table.
     */
    abstract protected function loadTableForeignKeys($tableName);

    /**
     * Loads all indexes for the given table.
     * @param string $tableName table name.
     * @return ExtendedPromiseInterface with IndexConstraint[] indexes for the given table.
     */
    abstract protected function loadTableIndexes($tableName);

    /**
     * Loads all unique constraints for the given table.
     * @param string $tableName table name.
     * @return ExtendedPromiseInterface with Constraint[] unique constraints for the given table.
     */
    abstract protected function loadTableUniques($tableName);

    /**
     * Loads all check constraints for the given table.
     * @param string $tableName table name.
     * @return ExtendedPromiseInterface with CheckConstraint[] check constraints for the given table.
     */
    abstract protected function loadTableChecks($tableName);

    /**
     * Loads all default value constraints for the given table.
     *
     * @param string $tableName table name.
     * @return ExtendedPromiseInterface with DefaultValueConstraint[] default value constraints for the given table.
     */
    abstract protected function loadTableDefaultValues($tableName);

    /**
     * Obtains the primary key for the named table.
     * @param string $name table name. The table name may contain schema name if any. Do not quote the table name.
     * @param bool $refresh whether to reload the information even if it is found in the cache.
     * @return Constraint|null table primary key, `null` if the table has no primary key.
     */
    public function getTablePrimaryKey($name, $refresh = false)
    {
        return $this->getTableMetadata($name, SchemaInterface::META_PK, $refresh);
    }

    /**
     * Returns primary keys for all tables in the database.
     * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema name.
     * @param bool $refresh whether to fetch the latest available table schemas. If this is `false`,
     * cached data may be returned if available.
     * @return ExtendedPromiseInterface with Constraint[] primary keys for all tables in the database.
     * Each array element is an instance of [[Constraint]] or its child class.
     */
    public function getSchemaPrimaryKeys($schema = '', $refresh = false)
    {
        return $this->getSchemaMetadata($schema, 'primaryKey', $refresh);
    }

    /**
     * Obtains the foreign keys information for the named table.
     * @param string $name table name. The table name may contain schema name if any. Do not quote the table name.
     * @param bool $refresh whether to reload the information even if it is found in the cache.
     * @return ForeignKeyConstraint[] table foreign keys.
     */
    public function getTableForeignKeys($name, $refresh = false)
    {
        return $this->getTableMetadata($name, SchemaInterface::META_FK, $refresh);
    }

    /**
     * Returns foreign keys for all tables in the database.
     * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema name.
     * @param bool $refresh whether to fetch the latest available table schemas. If this is false,
     * cached data may be returned if available.
     * @return ExtendedPromiseInterface with ForeignKeyConstraint[][] foreign keys for all tables in the database.
     * Each array element is an array of [[ForeignKeyConstraint]] or its child classes.
     */
    public function getSchemaForeignKeys($schema = '', $refresh = false)
    {
        return $this->getSchemaMetadata($schema, 'foreignKeys', $refresh);
    }

    /**
     * Obtains the indexes information for the named table.
     * @param string $name table name. The table name may contain schema name if any. Do not quote the table name.
     * @param bool $refresh whether to reload the information even if it is found in the cache.
     * @return IndexConstraint[] table indexes.
     */
    public function getTableIndexes($name, $refresh = false)
    {
        return $this->getTableMetadata($name, SchemaInterface::META_INDEXES, $refresh);
    }

    /**
     * Returns indexes for all tables in the database.
     * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema name.
     * @param bool $refresh whether to fetch the latest available table schemas. If this is false,
     * cached data may be returned if available.
     * @return ExtendedPromiseInterface with IndexConstraint[][] indexes for all tables in the database.
     * Each array element is an array of [[IndexConstraint]] or its child classes.
     */
    public function getSchemaIndexes($schema = '', $refresh = false)
    {
        return $this->getSchemaMetadata($schema, 'indexes', $refresh);
    }

    /**
     * Obtains the unique constraints information for the named table.
     * @param string $name table name. The table name may contain schema name if any. Do not quote the table name.
     * @param bool $refresh whether to reload the information even if it is found in the cache.
     * @return Constraint[] table unique constraints.
     */
    public function getTableUniques($name, $refresh = false)
    {
        return $this->getTableMetadata($name, SchemaInterface::META_UNIQUES, $refresh);
    }

    /**
     * Returns unique constraints for all tables in the database.
     * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema name.
     * @param bool $refresh whether to fetch the latest available table schemas. If this is false,
     * cached data may be returned if available.
     * @return ExtendedPromiseInterface with Constraint[][] unique constraints for all tables in the database.
     * Each array element is an array of [[Constraint]] or its child classes.
     */
    public function getSchemaUniques($schema = '', $refresh = false)
    {
        return $this->getSchemaMetadata($schema, 'uniques', $refresh);
    }

    /**
     * Obtains the check constraints information for the named table.
     * @param string $name table name. The table name may contain schema name if any. Do not quote the table name.
     * @param bool $refresh whether to reload the information even if it is found in the cache.
     * @return CheckConstraint[] table check constraints.
     */
    public function getTableChecks($name, $refresh = false)
    {
        return $this->getTableMetadata($name, SchemaInterface::META_CHECKS, $refresh);
    }

    /**
     * Returns check constraints for all tables in the database.
     * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema name.
     * @param bool $refresh whether to fetch the latest available table schemas. If this is false,
     * cached data may be returned if available.
     * @return ExtendedPromiseInterface with CheckConstraint[][] check constraints for all tables in the database.
     * Each array element is an array of [[CheckConstraint]] or its child classes.
     */
    public function getSchemaChecks($schema = '', $refresh = false)
    {
        return $this->getSchemaMetadata($schema, 'checks', $refresh);
    }

    /**
     * Obtains the default value constraints information for the named table.
     * @param string $name table name. The table name may contain schema name if any. Do not quote the table name.
     * @param bool $refresh whether to reload the information even if it is found in the cache.
     * @return DefaultValueConstraint[] table default value constraints.
     */
    public function getTableDefaultValues($name, $refresh = false)
    {
        return $this->getTableMetadata($name, SchemaInterface::META_DEFAULTS, $refresh);
    }

    /**
     * Returns default value constraints for all tables in the database.
     * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema name.
     * @param bool $refresh whether to fetch the latest available table schemas. If this is false,
     * cached data may be returned if available.
     * @return ExtendedPromiseInterface with DefaultValueConstraint[] default value constraints for all tables in the database.
     * Each array element is an array of [[DefaultValueConstraint]] or its child classes.
     */
    public function getSchemaDefaultValues($schema = '', $refresh = false)
    {
        return $this->getSchemaMetadata($schema, 'defaultValues', $refresh);
    }
}


<?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\Bridges;

use Interop\Container\ContainerInterface as InteropContainerInterface;
use Interop\Container\ServiceProviderInterface;
use League\Container\Container;
use League\Container\ContainerInterface;

/**
 * Credit goes to https://github.com/mint-php for original implementation.
 *
 * @mixin Container
 */
class LeagueContainerDecorator implements ContainerInterface
{
    /**
     * @var Container
     */
    protected $container;

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

    /**
     * @param ServiceProviderInterface|\League\Container\ServiceProvider\ServiceProviderInterface|string $provider
     *
     * @return $this
     */
    public function addServiceProvider($provider)
    {
        if ($provider instanceof ServiceProviderInterface) {
            foreach ($provider->getServices() as $key => $callable) {
                if (!$this->container->hasShared($key)) {
                    $this->container->share($key, function () use ($callable) {
                        return $callable($this);
                    });
                } else {
                    $previous = $this->container->get($key);
                    $this->container->share($key, function () use ($callable, $previous) {
                        return $callable($this, function () use ($previous) {
                            return $previous;
                        });
                    });
                }
            }
        } else {
            $this->container->addServiceProvider($provider);
        }

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function hasShared($alias, $resolved = false)
    {
        return $this->container->hasShared($alias, $resolved);
    }

    /**
     * {@inheritdoc}
     */
    public function delegate(InteropContainerInterface $container)
    {
        return $this->container->delegate($container);
    }

    /**
     * {@inheritdoc}
     */
    public function hasInDelegate($alias)
    {
        return $this->container->hasInDelegate($alias);
    }

    /**
     * {@inheritdoc}
     */
    public function add($alias, $concrete = null, $share = false)
    {
        return $this->container->add($alias, $concrete, $share);
    }

    /**
     * {@inheritdoc}
     */
    public function share($alias, $concrete = null)
    {
        return $this->container->share($alias, $concrete);
    }

    /**
     * {@inheritdoc}
     */
    public function extend($alias)
    {
        return $this->container->extend($alias);
    }

    /**
     * {@inheritdoc}
     */
    public function call(callable $callable, array $args = [])
    {
        return $this->container->call($callable, $args);
    }

    /**
     * {@inheritdoc}
     */
    public function get($id)
    {
        return $this->container->get($id);
    }

    /**
     * {@inheritdoc}
     */
    public function inflector($type, callable $callback = null)
    {
        return $this->container->inflector($type, $callback);
    }

    /**
     * {@inheritdoc}
     */
    public function has($id)
    {
        return $this->container->has($id);
    }
}


<?php

namespace Amulen\SettingsBundle\Model\Repository;

use Amulen\SettingsBundle\Model\SettingRepository;
use Symfony\Component\DependencyInjection\Container;

/**
 *
 */
class ParameterRepository implements SettingRepository
{

    /**
     * @var Container
     */
    protected $container;

    /**
     * ParameterRepository constructor.
     * @param Container $container
     */
    public function __construct(Container $container)
    {
        $this->container = $container;
    }

    /**
     * Get a setting value.
     *
     * @param $key string
     * @return string|null
     */
    public function get($key)
    {
        return $this->container->hasParameter($key) ? $this->container->getParameter($key) : null;
    }

    /**
     * Get all settings.
     */
    public function getAll()
    {
        return $this->container->getParameterBag()->all();
    }
}


<?php

namespace tourze\Http\Exception;

use tourze\Base\Exception\BaseException;
use tourze\Http\Http;

class Http405Exception extends ExpectedException
{

    /**
     * @var int
     */
    protected $_code = Http::METHOD_NOT_ALLOWED;

    /**
     * 指定允许使用的方法列表
     *
     * @param  array $methods 允许的方法列表
     * @return $this
     */
    public function allowed($methods)
    {
        if (is_array($methods))
        {
            $methods = implode(', ', $methods);
        }

        $this->headers('allow', $methods);

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function check()
    {
        if (null === ($location = $this->headers('allow')))
        {
            throw new BaseException('A list of allowed methods must be specified');
        }

        return true;
    }

}


<?php

namespace Smarch\Omac;

trait OmacTrait {

	/**
	 *
	 * @param [boolean] $acl	Whether or not ACL is enabled
	 * @param [string]	$driver Which method of authorization to use
	 *
	 */
	var $acl = false;
	var $driver = 'laravel';

	/**
	 * Will check user access depending on the driver being used.
	 * Defaults to using laravel Auth Guard driver
	 *
	 * @param  [string] $permission	Necessary permission to check
	 * @param  [mixed] $arguments	Additional arguments to pass
	 * @return [boolean]
	 */
	protected function checkAccess($permission, $arguments = '') {
		if ( $this->acl === false )
			return true;

		$driver = "acl" . ucfirst( $this->driver );

		return $this->$driver($permission, $arguments);
	}

	/**
	 * Using Laravel Authorization Driver
	 *
	 * @param  [string] $permission
	 * @param  [mixed] $arguments	Additional arguments to pass
	 * @package Laravel\Gate
	 * @return boolean
	 */
	protected function aclLaravel($permission, $arguments) {
		return \Auth::user()->can($permission, $arguments);
	}

	/**
	 * Using Shinobi Authorization Driver
	 *
	 * @param  [string] $permission
	 * @param  [mixed] $arguments	Additional arguments to pass
	 * @package Caffeinated\Shinobi
	 * @return boolean
	 */
	protected function aclShinobi($permission, $arguments) {
		return \Shinobi::can($permission, $arguments);
	}

	/**
	 * Using Sentinel Authorization Driver
	 *
	 * @param  [string] $permission
	 * @param  [null] $arguments None. Sentinel doesn't support arguments
	 * @package Cartalyst\Sentinel
	 * @return boolean
	 */
	protected function aclSentinel($permission, $arguments = NULL) {
		return \Sentinel::hasAccess($permission);
	}

	/**
	 * Using Entrust Authorization Driver
	 *
	 * @param  [string] $permission
	 * @param  [bool] $arguments
	 * @package Zizaco\Entrust
	 * @return boolean
	 */
	protected function aclEntrust($permission, $arguments = false) {
		return \Entrust::can($permission, $arguments);
	}
}


<?php

/*
 * This file is part of Core.
 *
 * (c) DraperStudio <hello@draperstudio.tech>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Apivore\Core\Response;

use Apivore\Core\Contracts\Response\Normaliser as NormaliserContract;
use InvalidArgumentException;

/**
 * Class Normaliser.
 */
class Normaliser implements NormaliserContract
{
    /**
     * @param $response
     * @param $format
     *
     * @return mixed
     */
    public function normalise($response, $format)
    {
        switch ($format) {
            case 'json':
                $response = $this->getJsonUnserialiser()->unserialise($response);
                break;

            case 'xml':
                $response = $this->getXmlUnserialiser()->unserialise($response);
                break;

            case 'plain':
            case 'stream':
                $response = $this->getPlainUnserialiser()->unserialise($response);
                break;

            default:
                throw new InvalidArgumentException('Invalid response format specified.');
                break;
        }

        return $response;
    }

    /**
     * @return Unserialisers\JsonUnserialiser
     */
    protected function getJsonUnserialiser()
    {
        return new Unserialisers\JsonUnserialiser();
    }

    /**
     * @return Unserialisers\XmlUnserialiser
     */
    protected function getXmlUnserialiser()
    {
        return new Unserialisers\XmlUnserialiser();
    }

    /**
     * @return Unserialisers\PlainUnserialiser
     */
    protected function getPlainUnserialiser()
    {
        return new Unserialisers\PlainUnserialiser();
    }
}


<?php

namespace ifcanduela\db;

use ifcanduela\db\traits\ConditionBuilder;

class SelectQuery extends Query
{
    /** @var bool */
    protected $distinct = false;

    /** @var string[] */
    protected $columns = ['*'];

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

    /** @var string[] */
    protected $groupBy;

    /** @var array */
    protected $having;

    /** @var string[] */
    protected $orderBy;

    /** @var int */
    protected $limit;

    /** @var int */
    protected $offset;

    use ConditionBuilder;

    /**
     * Create a SELECT query builder.
     *
     * @param string $columns
     */
    public function __construct(string ...$columns)
    {
        if ($columns) {
            $this->columns(...$columns);
        }
    }

    /**
     * Toggle the DISTINCT flag in a SELECT query.
     *
     * @param bool $enable
     * @return self
     */
    public function distinct(bool $enable = true)
    {
        $this->changed = true;
        $this->distinct = $enable;

        return $this;
    }

    /**
     * Set the columns for the SELECT query.
     *
     * @param string $column
     * @return self
     */
    public function columns(string ...$column)
    {
        $this->changed = true;
        $this->columns = $column;

        return $this;
    }

    /**
     * Append columns for the SELECT query.
     *
     * @param string $column [description]
     * @return self
     */
    public function addColumns(...$column)
    {
        $this->changed = true;
        $this->columns += $column;

        return $this;
    }

    /**
     * Setup a JOIN table.
     *
     * @param string $table
     * @param array $on
     * @return self
     */
    public function join(string $table, array $on)
    {
        $this->changed = true;
        $this->joins[] = ['JOIN', $table, $on];

        return $this;
    }

    /**
     * Setup a INNER JOIN table.
     *
     * @param string $table
     * @param array $on
     * @return self
     */
    public function innerJoin(string $table, array $on)
    {
        $this->changed = true;
        $this->joins[] = ['INNER JOIN', $table, $on];

        return $this;
    }

    /**
     * Setup a LEFT JOIN table.
     *
     * @param string $table
     * @param array $on
     * @return self
     */
    public function leftJoin(string $table, array $on)
    {
        $this->changed = true;
        $this->joins[] = ['LEFT JOIN', $table, $on];

        return $this;
    }

    /**
     * Setup a LEFT OUTER JOIN table.
     *
     * @param string $table
     * @param array $on
     * @return self
     */
    public function leftOuterJoin(string $table, array $on)
    {
        $this->changed = true;
        $this->joins[] = ['LEFT OUTER JOIN', $table, $on];

        return $this;
    }

    /**
     * Setup a RIGHT JOIN table.
     *
     * @param string $table
     * @param array $on
     * @return self
     */
    public function rightJoin(string $table, array $on)
    {
        $this->changed = true;
        $this->joins[] = ['RIGHT JOIN', $table, $on];

        return $this;
    }

    /**
     * Setup a OUTER JOIN table.
     *
     * @param string $table
     * @param array $on
     * @return self
     */
    public function outerJoin(string $table, array $on)
    {
        $this->changed = true;
        $this->joins[] = ['OUTER JOIN', $table, $on];

        return $this;
    }

    /**
     * Setup a FULL OUTER JOIN table.
     *
     * @param string $table
     * @param array $on
     * @return self
     */
    public function fullOuterJoin(string $table, array $on)
    {
        $this->changed = true;
        $this->joins[] = ['FULL OUTER JOIN', $table, $on];

        return $this;
    }

    /**
     * Set grouping fields to the query.
     *
     * @param string $field
     * @return self
     */
    public function groupBy(string ...$field)
    {
        $this->changed = true;
        $this->groupBy = $field;

        return $this;
    }

    /**
     * Set the conditions for groups in HAVING clauses.
     *
     * NOTE: Placeholders in HAVING clauses don't work with SQLite, according to
     * the PHP bug referenced in the @see tag below.
     *
     * @param array $conditions
     * @return self
     * @see https://bugs.php.net/bug.php?id=60281
     */
    public function having(array $conditions)
    {
        $this->changed = true;
        $this->having = $conditions;

        return $this;
    }

    /**
     * Add AND conditions for groups in HAVING clauses.
     *
     * NOTE: Placeholders in HAVING clauses don't work with SQLite, according to
     * the PHP bug referenced in the @see tag below.
     *
     * @param array $conditions
     * @return self
     * @see https://bugs.php.net/bug.php?id=60281
     */
    public function andHaving(array $conditions)
    {
        $this->changed = true;
        $this->having = [
            'AND',
            $this->having,
            $conditions,
        ];

        return $this;
    }

    /**
     * Add OR conditions for groups in HAVING clauses.
     *
     * NOTE: Placeholders in HAVING clauses don't work with SQLite, according to
     * the PHP bug referenced in the @see tag below.
     *
     * @param array $conditions
     * @return self
     * @see https://bugs.php.net/bug.php?id=60281
     */
    public function orHaving(array $conditions)
    {
        $this->changed = true;
        $this->having = [
            'OR',
            $this->having,
            $conditions,
        ];

        return $this;
    }

    /**
     * Setup fields for the ORDER BY clause.
     *
     * @param string $field
     * @return self
     */
    public function orderBy(string ...$field)
    {
        $this->changed = true;
        $this->orderBy = $field;

        return $this;
    }

    /**
     * Set a LIMIT and optional OFFSET.
     *
     * @param int $limit
     * @param int|null $offset
     * @return self
     */
    public function limit(int $limit, int $offset = null)
    {
        $this->changed = true;
        $this->limit = $limit;

        if ($offset !== null) {
            $this->offset = $offset;
        }

        return $this;
    }

    /**
     * Set an OFFSET to the LIMIT clause.
     *
     * @param int $offset
     * @return self
     */
    public function offset(int $offset)
    {
        $this->changed = true;
        $this->offset = $offset;

        return $this;
    }

    /**
     * Build the SELECT query.
     *
     * @return null
     */
    protected function build()
    {
        if (!$this->from) {
            throw new \RuntimeException("No tables provided for FROM clause");
        }

        $this->placeholders = [];
        $this->placeholderCounter = 1;

        $sql = ['SELECT'];

        if ($this->distinct) {
            $sql[] = 'DISTINCT';
        }

        $sql[] = implode(', ', $this->columns);

        $sql[] = 'FROM';
        $sql[] = implode(', ', $this->from);

        if ($this->joins) {
            foreach ($this->joins as $join) {
                $sql[] = $join[0];
                $sql[] = $join[1];
                $sql[] = 'ON';
                $sql[] = is_string($join[2])
                       ? $join[2]
                       : $this->buildConditions($join[2], false);
            }
        }

        if ($this->conditions) {
            $sql[] = 'WHERE';
            $sql[] = $this->buildConditions($this->conditions);
        }

        if ($this->groupBy) {
            $sql[] = 'GROUP BY';
            $sql[] = implode(', ', $this->groupBy);
        }

        if ($this->having) {
            $sql[] = 'HAVING';
            $sql[] = $this->buildConditions($this->having);
        }

        if ($this->orderBy) {
            $sql[] = 'ORDER BY';
            $sql[] = implode(', ', $this->orderBy);
        }

        if ($this->limit || $this->offset) {
            $sql[] = 'LIMIT';

            $parts = [];

            if ($this->offset) {
                if (!$this->limit) {
                    $this->limit = PHP_INT_MAX;
                }
                $parts[] = $this->addPlaceholder($this->offset);
            }

            if ($this->limit) {
                $parts[] = $this->addPlaceholder($this->limit);
            }

            $sql[] = implode(', ', $parts);
        }

        $this->sql = implode(' ', $sql);
        $this->changed = false;
    }

    /**
     * Get a string representation of the query.
     *
     * @return string
     */
    public function __toString()
    {
        if ($this->changed) {
            $this->build();
        }

        return $this->sql;
    }
}


<?php

declare(strict_types=1);

/**
 * States.
 *
 * LICENSE
 *
 * This source file is subject to the MIT license and the version 3 of the GPL3
 * license that are bundled with this package in the folder licences
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to richarddeloge@gmail.com so we can send you a copy immediately.
 *
 *
 * @copyright   Copyright (c) 2009-2017 Richard Déloge (richarddeloge@gmail.com)
 *
 * @link        http://teknoo.software/states Project website
 *
 * @license     http://teknoo.software/license/mit         MIT License
 * @author      Richard Déloge <richarddeloge@gmail.com>
 */

namespace Teknoo\States\LifeCycle\Observing;

use Teknoo\States\LifeCycle\StatedClass\LifeCyclableInterface;

/**
 * Class ObservedFactory
 * Default implementation of the factory to build new observed instance used
 * to manage observation between observed states class and its observer.
 *
 * @copyright   Copyright (c) 2009-2017 Richard Déloge (richarddeloge@gmail.com)
 *
 * @link        http://teknoo.software/states Project website
 *
 * @license     http://teknoo.software/license/mit         MIT License
 * @author      Richard Déloge <richarddeloge@gmail.com>
 */
class ObservedFactory implements ObservedFactoryInterface
{
    /**
     * @var string
     */
    private $observedClassName = '';

    /**
     * @var string
     */
    private $eventClassName = '';

    /**
     * @var string
     */
    private $traceClassName = '';

    /**
     * @param string $observedClassName
     * @param string $eventClassName
     * @param string $traceClassName
     */
    public function __construct(string $observedClassName, string $eventClassName, string $traceClassName)
    {
        $this->checkObservedClassName($observedClassName);
        $this->checkTraceClassName($traceClassName);
        $this->eventClassName = $eventClassName;
    }

    /**
     * @param string $observedClassName
     *
     * @return $this
     */
    private function checkObservedClassName(string $observedClassName)
    {
        if (!\class_exists($observedClassName)) {
            throw new \RuntimeException('Missing observed class '.$observedClassName);
        }

        $interfacesList = \class_implements($observedClassName);

        if (!isset($interfacesList['Teknoo\States\LifeCycle\Observing\ObservedInterface'])) {
            throw new \RuntimeException('The observed class does not implement the ObservedFactoryInterface');
        }

        $this->observedClassName = $observedClassName;

        return $this;
    }

    /**
     * @param string $traceClassName
     *
     * @return $this
     */
    private function checkTraceClassName(string $traceClassName)
    {
        if (!\class_exists($traceClassName)) {
            throw new \RuntimeException('Missing trace class '.$traceClassName);
        }

        $interfacesList = \class_implements($traceClassName);

        if (!isset($interfacesList['Teknoo\States\LifeCycle\Trace\TraceInterface'])) {
            throw new \RuntimeException('The trace class does not implement the ObservedFactoryInterface');
        }

        $this->traceClassName = $traceClassName;

        return $this;
    }

    /**
     * @param ObserverInterface     $observer
     * @param LifeCyclableInterface $lifeCyclableInstance
     *
     * @return ObservedInterface
     */
    public function create(ObserverInterface $observer, LifeCyclableInterface $lifeCyclableInstance): ObservedInterface
    {
        $traceClassName = $this->traceClassName;
        $observedClassName = $this->observedClassName;

        return new $observedClassName($lifeCyclableInstance, $observer, new $traceClassName(), $this->eventClassName);
    }
}


<?php

/**
 * MvcCore
 *
 * This source file is subject to the BSD 3 License
 * For the full copyright and license information, please view
 * the LICENSE.md file that are distributed with this source code.
 *
 * @copyright	Copyright (c) 2016 Tom Flídr (https://github.com/mvccore/mvccore)
 * @license		https://mvccore.github.io/docs/mvccore/4.0.0/LICENCE.md
 */

namespace MvcCore\Ext\Routers\MediaAndLocalization;

trait Routing
{
	/**
	 * Route current app request by configured routes lists or by query string.
	 * 1. Check if request is targeting any internal action in internal ctrl.
	 * 2. Choose route strategy by request path and existing query string
	 *    controller and/or action values - strategy by query string or by
	 *    rewrite routes.
	 * 3. If request is not internal, redirect to possible better URL form by
	 *    configured trailing slash strategy and return `FALSE` for redirection.
	 * 4. Prepare media site version and localization properties and redirect
	 *    if necessary by media configuration or by localization configuration.
	 * 5. Try to complete current route object by chosen strategy.
	 * 6. If there was not found any rewrite route in rewrite routes strategy,
	 *    also if there is no localization in request, disallow non localized
	 *    route and re-call localization preparing method and redirect if
	 *    necessary. It means any request path will be redirected into default
	 *    localization.
	 * 7. If any current route found and if route contains redirection, do it.
	 * 8. If there is no current route and request is targeting homepage, create
	 *    new empty route by default values if ctrl configuration allows it.
	 * 9. If there is any current route completed, complete self route name by
	 *    it to generate `self` routes and canonical URL later.
	 * 10.If there is necessary, try to complete canonical URL and if canonical
	 *    URL is shorter than requested URL, redirect user to shorter version.
	 * If there was necessary to redirect user in routing process, return
	 * immediately `FALSE` and return from this method. Else continue to next
	 * step and return `TRUE`. This method is always called from core routing by:
	 * `\MvcCore\Application::Run();` => `\MvcCore\Application::routeRequest();`.
	 * @throws \LogicException Route configuration property is missing.
	 * @throws \InvalidArgumentException Wrong route pattern format.
	 * @return bool
	 */
	public function Route () {
		$this->internalRequest = $this->request->IsInternalRequest();
		list($requestCtrlName, $requestActionName) = $this->routeDetectStrategy();
		if (!$this->internalRequest) {
			if (!$this->redirectToProperTrailingSlashIfNecessary()) return FALSE;
			$this->prepare();
			$this->prepareMedia();
			$this->prepareLocalization();
			if (!$this->preRouteMedia()) return FALSE;
			if (!$this->preRouteLocalization()) return FALSE;
		}
		if ($this->routeByQueryString) {
			$this->queryStringRouting(
				$requestCtrlName, $requestActionName
			);
		} else {
			$this->rewriteRouting($requestCtrlName, $requestActionName);
			if ($this->currentRoute === NULL && !$this->requestLocalization) {
				$this->allowNonLocalizedRoutes = FALSE;
				if (!$this->checkLocalizationWithUrlAndRedirectIfNecessary())
					return FALSE;
			}
		}
		if (!$this->routeProcessRouteRedirectionIfAny()) return FALSE;
		return $this->routeSetUpDefaultForHomeIfNoMatch()
					->routeSetUpSelfRouteNameIfAny()
					->canonicalRedirectIfAny();
	}
}


<?php

namespace Ekyna\Bundle\CoreBundle\Twig;

use Ekyna\Bundle\CoreBundle\Locale\LocaleProviderInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Intl\Intl;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
 * Class UiExtension
 * @package Ekyna\Bundle\CoreBundle\Twig
 * @author Étienne Dauvergne <contact@ekyna.com>
 */
class UiExtension extends \Twig_Extension
{
    /**
     * @var RequestStack
     */
    private $requestStack;

    /**
     * @var LocaleProviderInterface
     */
    private $localeProvider;

    /**
     * @var array
     */
    private $config;

    /**
     * @var \Twig_Template
     */
    private $controlsTemplate;

    /**
     * @var \Symfony\Component\OptionsResolver\OptionsResolver
     */
    private $buttonOptionsResolver;

    /**
     * Constructor.
     *
     * @param RequestStack            $requestStack
     * @param LocaleProviderInterface $localeProvider
     * @param array                   $config
     */
    public function __construct(RequestStack $requestStack, LocaleProviderInterface $localeProvider, array $config)
    {
        $this->requestStack   = $requestStack;
        $this->localeProvider = $localeProvider;
        $this->config         = $config;
    }

    /**
     * {@inheritdoc}
     */
    public function initRuntime(\Twig_Environment $twig)
    {
        $this->controlsTemplate = $twig->loadTemplate($this->config['controls_template']);
    }

    /**
     * {@inheritdoc}
     */
    public function getFunctions()
    {
        return [
            new \Twig_SimpleFunction('ui_no_image', [$this, 'renderNoImage'], ['is_safe' => ['html']]),
            new \Twig_SimpleFunction('ui_link', [$this, 'renderLink'], ['is_safe' => ['html']]),
            new \Twig_SimpleFunction('ui_button', [$this, 'renderButton'], ['is_safe' => ['html']]),
            new \Twig_SimpleFunction('ui_google_font', [$this, 'renderGoogleFontLink'], ['is_safe' => ['html']]),
            new \Twig_SimpleFunction('ui_locale_switcher', [$this, 'renderLocaleSwitcher'], ['is_safe' => ['html']]),
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function getFilters()
    {
        return [
            new \Twig_SimpleFilter('language', [$this, 'getLanguage']),
            new \Twig_SimpleFilter('country', [$this, 'getCountry']),
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function getGlobals()
    {
        return [
            'locales' => $this->config['locales'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function getTests ()
    {
        return [
            new \Twig_SimpleTest('form', function ($var) { return $var instanceof FormView; }),
        ];
    }

    /**
     * Renders the "no image" img.
     *
     * @param array $attributes
     * @return string
     */
    public function renderNoImage(array $attributes = [])
    {
        return $this->controlsTemplate->renderBlock('no_image', [
            'no_image_path' => $this->config['no_image_path'],
            'attr' => $attributes,
        ]);
    }

    /**
     * Renders the link.
     *
     * @param $href
     * @param string $label
     * @param array $options
     * @param array $attributes
     * @return string
     */
    public function renderLink($href, $label = '', array $options = [], array $attributes = [])
    {
        $options['type'] = 'link';
        $options['path'] = $href;

        return $this->renderButton($label, $options, $attributes);
    }

    /**
     * Renders the button.
     *
     * @param string $label
     * @param array $options
     * @param array $attributes
     * @return string
     * @throws \InvalidArgumentException
     */
    public function renderButton($label = '', array $options = [], array $attributes = [])
    {
        $options = $this->getButtonOptionsResolver()->resolve($options);

        $tag = 'button';
        $classes = ['btn', 'btn-'.$options['theme'], 'btn-'.$options['size']];
        $defaultAttributes = [
        	'class' => sprintf('btn btn-%s btn-%s', $options['theme'], $options['size']),
        ];
        if ($options['type'] == 'link') {
            if (0 == strlen($options['path'])) {
                throw new \InvalidArgumentException('"path" option must be defined for "link" button type.');
            }
            $tag = 'a';
            $defaultAttributes['href'] = $options['path'];
        } else {
            $defaultAttributes['type'] = $options['type'];
        }

        if (array_key_exists('class', $attributes)) {
            $classes = array_merge($classes, explode(' ', $attributes['class']));
            unset($attributes['class']);
        }
        $defaultAttributes['class'] = implode(' ', $classes);
        $attributes = array_merge($defaultAttributes, $attributes);

        $icon = '';
        if(0 < strlen($options['icon'])) {
            $icon = $options['fa_icon'] ? 'fa fa-'.$options['icon'] : 'glyphicon glyphicon-'.$options['icon'];
        }

        return $this->controlsTemplate->renderBlock('button', [
            'tag'   => $tag,
            'attr'  => $attributes,
            'label' => $label,
            'icon'  => $icon,
        ]);
    }

    /**
     * Renders the google font css link.
     *
     * @return string
     */
    public function renderGoogleFontLink()
    {
        if (0 < strlen($this->config['google_font_url'])) {
            return '<link href="' . $this->config['google_font_url'] . '" rel="stylesheet" type="text/css">' . "\n";
        }
        return '';
    }

    /**
     * Renders the locale switcher.
     *
     * @param array $attributes
     * @return string
     */
    public function renderLocaleSwitcher($attributes = [])
    {
        // TODO Check if this is a (esi) sub request, as this must never be used in a esi fragment.
        if (null === $request = $this->requestStack->getCurrentRequest()) {
            return '';
        }

        if (!array_key_exists('class', $attributes)) {
            $attributes['class'] = 'list-inline locale-switcher';
        }

        return $this->controlsTemplate->renderBlock('locale_switcher', [
            'locales' => $this->config['locales'],
            'request' => $request,
            'attr' => $attributes,
        ]);
    }

    /**
     * Display the language for the given locale.
     *
     * @param string $locale
     * @return string
     */
    public function getLanguage($locale)
    {
        return \Locale::getDisplayLanguage($locale, $this->localeProvider->getCurrentLocale());
    }

    /**
     * Display the country name for the given code.
     *
     * @param string $countryCode
     * @return string
     */
    public function getCountry($countryCode)
    {
        return Intl::getRegionBundle()->getCountryName($countryCode, $this->localeProvider->getCurrentLocale());
    }

    /**
     * Returns the button options resolver.
     *
     * @return OptionsResolver
     */
    private function getButtonOptionsResolver()
    {
        if (null === $this->buttonOptionsResolver) {
            $this->buttonOptionsResolver = new OptionsResolver();
            $this->buttonOptionsResolver
                ->setDefaults([
                    'type'    => 'button',
                    'theme'   => 'default',
                    'size'    => 'sm',
                    'icon'    => null,
                    'fa_icon' => false,
                    'path'    => null,
                ])
                ->setRequired(['type', 'theme', 'size'])

                ->setAllowedValues('type',  ['link', 'button', 'submit', 'reset'])
                ->setAllowedValues('theme', ['default', 'primary', 'success', 'warning', 'danger'])
                ->setAllowedValues('size',  ['xs', 'sm', 'md', 'lg'])

                ->setAllowedTypes('icon',    ['string', 'null'])
                ->setAllowedTypes('fa_icon', 'bool')
                ->setAllowedTypes('path',    ['string', 'null'])
            ;
        }

        return $this->buttonOptionsResolver;
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
    	return 'ekyna_core_ui';
    }
}


<?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\Geometry;

use \Maths\Maths;
use \Maths\Geometry\AbstractGeometricObject;
use \Maths\PointInterface;

/**
 * Line class : two points A -> B not limited
 *
 * @author  piwi <me@e-piwi.fr>
 */
class Line
    extends AbstractGeometricObject
{

    /**
     * Define here some `i` items
     * "i" may be lowercase only and is the point "name"
     * @var array
     */
    protected static $_magic_points_mapping = array(
        'a', 'b'
    );

    /**
     * @param   null|\Maths\PointInterface    $point_a
     * @param   null|\Maths\PointInterface    $point_b
     * @param   int                           $space_type
     */
    public function __construct(
        PointInterface $point_a = null, PointInterface $point_b = null, $space_type = Maths::CARTESIAN_2D
    ) {
        parent::__construct($space_type);
        if (!is_null($point_a)) {
            $this->setPointA($point_a);
        }
        if (!is_null($point_b)) {
            $this->setPointB($point_b);
        }
    }

    /**
     * Write a line object
     *
     * @return  string
     */
    public function __toString()
    {
        $str = '';
        $a = $this->getSlope();
        if ($a!=1) {
            $str .= "({$a}x)";
        } else {
            $str .= "x";
        }
        $b = $this->getYIntercept();
        if ($b!=0) {
            $str .= "+{$b}";
        }
        return "[y=({$str}]";
    }

    /**
     * Write an algebraic function of the line
     *
     *      y = (a * x) + b
     *
     * @return  string
     */
    public function __equationToString()
    {
        $str = '';
        $a = $this->getSlope();
        if ($a!=1) {
            $str .= "({$a} * x)";
        } else {
            $str .= "x";
        }
        $b = $this->getYIntercept();
        if ($b!=0) {
            $str .= " + {$b}";
        }
        return "y = f(x){ {$str} }";
    }

// Points

    /**
     * Define point A of the line
     *
     * @param   \Maths\PointInterface    $point
     * @return  $this
     * @throws  \Exception if the argument is not on of the `\Maths\PointInterface` classes
     */
    public function setPointA($point)
    {
        try {
            $this->setPoint('a', $point);
        } catch (\Exception $e) {
            throw $e;
        }
        return $this;
    }

    /**
     * Get the A point of the line
     *
     * @return  \Maths\PointInterface|null
     */
    public function getPointA()
    {
        return (isset($this->_points['a']) ? $this->_points['a'] : null);
    }

    /**
     * Define point B of the line
     *
     * @param   \Maths\PointInterface    $point
     * @return  $this
     * @throws  \Exception if the argument is not on of the `\Maths\PointInterface` classes
     */
    public function setPointB($point)
    {
        try {
            $this->setPoint('b', $point);
        } catch (\Exception $e) {
            throw $e;
        }
        return $this;
    }

    /**
     * Get the B point of the line
     *
     * @return  \Maths\PointInterface|null
     */
    public function getPointB()
    {
        return (isset($this->_points['b']) ? $this->_points['b'] : null);
    }

// Characteristics

    /**
     * Get the slope of the line: m = (By - Ay) / (Bx - Ax)
     *
     * @return  float
     */
    public function getSlope()
    {
        if ($this->isVertical()) {
            return Maths::INFINITY;
        } else {
            $r = ($this->getPointB()->getAbscissa() - $this->getPointA()->getAbscissa());
            return (
                ($this->getPointB()->getOrdinate() - $this->getPointA()->getOrdinate())
                /
                ($r!=0 ? $r : 1)
            );
        }
    }

    /**
     * Get the y-intercept of the line: b = Ay - (Ax * a)
     *
     * @return  float
     */
    public function getYIntercept()
    {
        return ($this->getPointA()->getOrdinate() - ($this->getPointA()->getAbscissa() * $this->getSlope()));
    }

// Specials

    /**
     * Rearrange a segment to have [A->B] in requested direction
     *
     * @param   int     $direction
     * @return  $this
     */
    public function rearrange($direction = Maths::DIRECTION_POSITIVE)
    {
        $a = $this->getPointA();
        $b = $this->getPointB();
        $directions = Maths::getDirectionByPoints($a, $b);
        if ($directions[0]!=$direction) {
            $this->setPointA($b);
            $this->setPointB($a);
        }
        return $this;
    }

// Utilities

    /**
     * Test if a line is vertical (constant X value)
     *
     * @return  bool
     */
    public function isVertical()
    {
        return (bool) ($this->getPointA()->getAbscissa() == $this->getPointB()->getAbscissa());
    }

    /**
     * Test if a line is horizontal (constant Y value)
     *
     * @return  bool
     */
    public function isHorizontal()
    {
        return (bool) ($this->getPointA()->getOrdinate() == $this->getPointB()->getOrdinate());
    }

    /**
     * Test if a line is linear (y-intercept = 0)
     *
     * @return  bool
     */
    public function isLinear()
    {
        return (bool) ($this->getYIntercept() == 0);
    }

    /**
     * @param   \Maths\PointInterface   $a
     * @return  bool
     */
    public function isValidPoint(PointInterface $a)
    {
        return (bool) ($a->getOrdinate() == (($this->getSlope() * $a->getAbscissa()) + $this->getYIntercept()));
    }

    /**
     * Get the ordinate of a point of the line by its abscissa
     *
     * @param   float   $x
     * @return  float
     */
    public function getOrdinateByAbscissa($x)
    {
        if ($this->isHorizontal()) {
            return $this->getPointA()->getOrdinate();
        }
        return (($this->getSlope() * $x) + $this->getYIntercept());
    }

    /**
     * Get the abscissa of a point of the line by its ordinate
     *
     * @param   float   $y
     * @return  float
     */
    public function getAbscissaByOrdinate($y)
    {
        if ($this->isVertical()) {
            return $this->getPointA()->getAbscissa();
        }
        return (($y - $this->getYIntercept()) / $this->getSlope());
    }
}