<?php

declare(strict_types=1);
/**
 * PHP simple library for managing of data types.
 *
 * @author    Josantonius <hello@josantonius.com>
 * @copyright 2018 (c) Josantonius - PHP-Validate
 * @license   https://opensource.org/licenses/MIT - The MIT License (MIT)
 * @link      https://github.com/Josantonius/PHP-Validate
 * @since     1.0.0
 */
namespace Josantonius\Validate;

/**
 * Validation or conversion of data types.
 */
class Validate
{
    /**
     * Parameter return as array.
     *
     * @param mixed $data    → data to convert
     * @param mixed $default → default value in error case
     *
     * @return mixed → value, null or customized return value
     */
    public static function asArray($data, $default = null)
    {
        $json = is_string($data) ? $data : json_encode($data);

        $array = json_decode($json, true) ?? null;

        $array = $array ? filter_var_array($array) : false;

        return $array !== false ? $array : $default;
    }

    /**
     * Parameter return as object.
     *
     * @param mixed $data    → data to convert
     * @param mixed $default → default value in error case
     *
     * @return mixed → value, null or customized return value
     */
    public static function asObject($data, $default = null)
    {
        $json = is_string($data) ? $data : json_encode($data);

        $object = json_decode($json);

        return is_object($object) ? $object : $default;
    }

    /**
     * Parameter return as JSON.
     *
     * @param mixed $data    → data to convert
     * @param mixed $default → default value in error case
     *
     * @return mixed → value, null or customized return value
     */
    public static function asJson($data, $default = null)
    {
        $json = is_string($data) ? $data : json_encode($data);

        return $json !== false ? $json : $default;
    }

    /**
     * Parameter return as string.
     *
     * @param mixed $data    → data to convert
     * @param mixed $default → default value in error case
     *
     * @return mixed → value, null or customized return value
     */
    public static function asString($data, $default = null)
    {
        $string = filter_var(
            $data ?? [],
            FILTER_SANITIZE_STRING,
            FILTER_FLAG_NO_ENCODE_QUOTES
        );

        return $string !== false ? $string : $default;
    }

    /**
     * Parameter return as integer.
     *
     * @param mixed $data    → data to convert
     * @param mixed $default → default value in error case
     *
     * @return mixed → value, null or customized return value
     */
    public static function asInteger($data, $default = null)
    {
        $int = filter_var($data ?? '', FILTER_VALIDATE_INT);

        return $int !== false ? $int : $default;
    }

    /**
     * Parameter return as float.
     *
     * @param mixed $data    → data to convert
     * @param mixed $default → default value in error case
     *
     * @return mixed → value, null or customized return value
     */
    public static function asFloat($data, $default = null)
    {
        $float = filter_var($data ?? '', FILTER_VALIDATE_FLOAT);

        return $float !== false ? $float : $default;
    }

    /**
     * Parameter return as boolean.
     *
     * @param mixed $data    → data to convert
     * @param mixed $default → default value in error case
     *
     * @return mixed → value, null or customized return value
     */
    public static function asBoolean($data, $default = null)
    {
        $boolean = filter_var($data ?? [], FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);

        return ! is_null($boolean) ? $boolean : $default;
    }

    /**
     * Parameter return as IP.
     *
     * @param mixed $data    → data to convert
     * @param mixed $default → default value in error case
     *
     * @return mixed → value, null or customized return value
     */
    public static function asIp($data, $default = null)
    {
        $isValid = filter_var($data ?? '', FILTER_VALIDATE_IP);

        return $isValid ? $data : $default;
    }

    /**
     * Parameter return as URL.
     *
     * @param mixed $data    → data to convert
     * @param mixed $default → default value in error case
     *
     * @return mixed → value, null or customized return value
     */
    public static function asUrl($data, $default = null)
    {
        $url = filter_var($data ?? '', FILTER_SANITIZE_URL);

        return $url ? $url : $default;
    }

    /**
     * Parameter return as email.
     *
     * @param mixed $data    → data to convert
     * @param mixed $default → default value in error case
     *
     * @return mixed → value, null or customized return value
     */
    public static function asEmail($data, $default = null)
    {
        $isValid = filter_var($data ?? '', FILTER_VALIDATE_EMAIL);

        return $isValid ? $data : $default;
    }
}


<?php
/*
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
 * and is licensed under the MIT license.
 */

declare(strict_types=1);

namespace GeneratedHydrator\ClassGenerator;

/**
 * Generator for highly performing {@see \Zend\Hydrator\HydratorInterface}
 * for objects
 *
 * {@inheritDoc}
 *
 * @author Marco Pivetta <ocramius@gmail.com>
 * @author Pierre Rineau <pierre.rineau@makina-corpus.com>
 * @license MIT
 */
class PHP5HydratorGenerator implements HydratorGeneratorInterface
{
    /**
     * Generates an hydrator class
     *
     *
     * @return string
     */
    public function generate(\ReflectionClass $originalClass, string $realClassName, string $originalClassName) : string
    {
        $position = \strrpos($realClassName, '\\');
        $namespace = \substr($realClassName, 0, $position);
        $className = \substr($realClassName, $position + 1);

        $visiblePropertyMap = [];
        $hiddenPropertyMap = [];

        foreach ($this->findAllInstanceProperties($originalClass) as $property) {
            $declaringClassName = $property->getDeclaringClass()->getName();

            if ($property->isPrivate() || $property->isProtected()) {
                $hiddenPropertyMap[$declaringClassName][] = $property->getName();
            } else {
                $visiblePropertyMap[] = $property->getName();
            }
        }

        return <<<EOT
<?php

namespace {$namespace};

use Zend\Hydrator\HydratorInterface;

/**
 * This is a generated hydrator for the {$originalClassName} class
 */
class {$className} implements HydratorInterface
{
    private \$hydrateCallbacks = [];
    private \$extractCallbacks = [];

    public function __construct()
    {
        {$this->createContructor($visiblePropertyMap, $hiddenPropertyMap)}
    }

    public function hydrate(array \$data, \$object)
    {
        {$this->createHydrateMethod($visiblePropertyMap, $hiddenPropertyMap)}
    }

    public function extract(\$object)
    {
        {$this->createExtractMethod($visiblePropertyMap, $hiddenPropertyMap)}
    }
}
EOT;
    }

    /**
     * Find all class properties recursively using class hierarchy without
     * removing name redefinitions
     *
     * @param \ReflectionClass $class
     *
     * @return \ReflectionProperty[]
     */
    private function findAllInstanceProperties(\ReflectionClass $class = null)
    {
        if (! $class) {
            return [];
        }

        return \array_values(\array_merge(
            $this->findAllInstanceProperties($class->getParentClass() ?: null), // of course PHP is shit.
            \array_values(\array_filter(
                $class->getProperties(),
                function (\ReflectionProperty $property) : bool {
                    return ! $property->isStatic();
                }
            ))
        ));
    }

    /**
     * Generate code for the hydrator constructor
     *
     * @param string[][] $visiblePropertyMap
     * @param string[] $hiddenPropertyMap
     *
     * @return string
     */
    private function createContructor(array $visiblePropertyMap, array $hiddenPropertyMap) : string
    {
        $content = [];

        // Create a set of closures that will be called to hydrate the object.
        // Array of closures in a naturally indexed array, ordered, which will
        // then be called in order in the hydrate() and extract() methods.
        foreach ($hiddenPropertyMap as $className => $propertyNames) {
            // Hydrate closures
            $content[] = "\$this->hydrateCallbacks[] = \\Closure::bind(function (\$object, \$values) {";
            foreach ($propertyNames as $propertyName) {
                $content[] = "    if (isset(\$values['" . $propertyName . "']) || \$object->" . $propertyName . " !== null && \\array_key_exists('" . $propertyName . "', \$values)) {";
                $content[] = "        \$object->" . $propertyName . " = \$values['" . $propertyName . "'];";
                $content[] = "    }";
            }
            $content[] = '}, null, ' . \var_export($className, true) . ');' . "\n";

            // Extract closures
            $content[] = "\$this->extractCallbacks[] = \\Closure::bind(function (\$object, &\$values) {";
            foreach ($propertyNames as $propertyName) {
                $content[] = "    \$values['" . $propertyName . "'] = \$object->" . $propertyName . ";";
            }
            $content[] = '}, null, ' . \var_export($className, true) . ');' . "\n";
        }

        return \implode("\n", \array_map(
            function ($line) {
                return "        " . $line;
            }, $content
        ));
    }

    /**
     * Generate code for the hydrate method
     *
     * @param string[][] $visiblePropertyMap
     * @param string[] $hiddenPropertyMap
     *
     * @return string
     */
    private function createHydrateMethod(array $visiblePropertyMap, array $hiddenPropertyMap) : string
    {
        $content = [];

        foreach ($visiblePropertyMap as $propertyName) {
            $content[] = "if (isset(\$data['" . $propertyName . "']) || \$object->" . $propertyName . " !== null && \\array_key_exists('" . $propertyName . "', \$data)) {";
            $content[] = "    \$object->" . $propertyName . " = \$data['" . $propertyName . "'];";
            $content[] = "}";
        }
        $index = 0;
        foreach ($hiddenPropertyMap as $className => $propertyNames) {
            $content[] = "\$this->hydrateCallbacks[" . ($index++) . "]->__invoke(\$object, \$data);";
        }

        $content[] = "return \$object;";

        return \implode("\n", \array_map(
            function ($line) {
                return "        " . $line;
            }, $content
        ));
    }

    /**
     * Generate code for the extract method
     *
     * @param string[][] $visiblePropertyMap
     * @param string[] $hiddenPropertyMap
     *
     * @return string
     */
    private function createExtractMethod(array $visiblePropertyMap, array $hiddenPropertyMap) : string
    {
        $content = [];

        $content[] = "\$ret = array();";
        foreach ($visiblePropertyMap as $propertyName) {
            $content[] = "\$ret['" . $propertyName . "'] = \$object->" . $propertyName . ";";
        }
        $index = 0;
        foreach ($hiddenPropertyMap as $className => $propertyNames) {
            $content[] = "\$this->extractCallbacks[" . ($index++) . "]->__invoke(\$object, \$ret);";
        }

        $content[] = "return \$ret;";

        return \implode("\n", \array_map(
            function ($line) {
                return "        " . $line;
            }, $content
        ));
    }
}


<?php

namespace DevGroup\ExtensionsManager\helpers;

use DevGroup\ExtensionsManager\ExtensionsManager;
use DevGroup\ExtensionsManager\components\ComposerInstalledSet;
use Yii;
use yii\base\Component;
use yii\helpers\FileHelper;
use yii\helpers\Json;

class ExtensionFileWriter extends Component
{
    /**
     * @param $config
     * @return array
     */
    private static function rebuldConfig($config)
    {
        $config = is_array($config) ? $config : [];
        foreach ($config as $i => $ext) {
            $config[$ext['name']] = [
                'composer_name' => $ext['name'],
                'composer_type' => $ext['type'],
                'is_active' => 0,
                //TODO implement core extensions checking
                'is_core' => 0,
            ];
        }
        return $config;
    }

    /**
     * Calculates differences between @vengor/composer/installed.json and ExtensionsManager::$extensionsStorage
     * and writes new ExtensionsManager::$extensionsStorage
     * @return bool Result, true if success
     */
    public static function updateConfig()
    {
        /** @var ExtensionsManager $module */
        $module = ExtensionsManager::module();
        $extensions = $module->getExtensions();
        $installed = ComposerInstalledSet::get(true)->getInstalled();
        $fileName = Yii::getAlias($module->extensionsStorage);
        $writer = new ApplicationConfigWriter(['filename' => $fileName]);
        $config = self::rebuldConfig($installed);
        if (false === empty($extensions)) {
            $toAdd = array_udiff($config, $extensions, [self::className(), 'arraysCompareCallback']);
            $toRemove = array_udiff($extensions, $config, [self::className(), 'arraysCompareCallback']);
            foreach ($toRemove as $name => $ext) {
                if (true === isset($extensions[$name])) {
                    unset($extensions[$name]);
                }
            }
            $config = array_merge($extensions, $toAdd);
        }
        $writer->addValues($config);
        return $writer->commit();
    }

    /**
     * @return bool
     */
    public static function generateConfig()
    {
        $installed = ComposerInstalledSet::get()->getInstalled();
        $fileName = Yii::getAlias(ExtensionsManager::module()->extensionsStorage);
        $writer = new ApplicationConfigWriter(['filename' => $fileName]);
        $config = self::rebuldConfig($installed);
        $writer->addValues($config);
        return $writer->commit();
    }

    /**
     * @param array $a
     * @param array $b
     * @return int
     */
    public static function arraysCompareCallback($a, $b)
    {
        if (true === isset($a['composer_name'], $b['composer_name'])) {
            return strcmp($a['composer_name'], $b['composer_name']);
        }
        //TODO implement checking of broken extension array and extension repair method
        return 0;
    }

    /**
     * Checks and creates if necessary and possible folder to store and local composer.json
     *
     * @param string $dir
     * @param array $data
     * @return bool|int
     * @throws \yii\base\Exception
     */
    public static function checkLocalStorage($dir, $data)
    {
        $fn = $dir . '/composer.json';
        $created = true;
        if (true === FileHelper::createDirectory($dir)) {
            if (false === file_exists($fn)) {
                $created = file_put_contents(
                    $fn,
                    Json::encode($data, JSON_FORCE_OBJECT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT)
                );
            }
            if (false === $created) {
                Yii::$app->session->setFlash(
                    'error',
                    Yii::t('extensions-manager', 'Unable to create local composer.json file')
                );
            }
        } else {
            Yii::$app->session->setFlash(
                'error',
                Yii::t('extensions-manager', 'Unable to create folder to store local composer.json file')
            );
            $created = false;
        }
        return $created;
    }
}


<?php
/**
 * @see https://github.com/dotkernel/dot-navigation/ for the canonical source repository
 * @copyright Copyright (c) 2017 Apidemia (https://www.apidemia.com)
 * @license https://github.com/dotkernel/dot-navigation/blob/master/LICENSE.md MIT License
 */

declare(strict_types = 1);

namespace Dot\Navigation;

/**
 * Class Container
 * @package Dot\Navigation
 */
class NavigationContainer implements \RecursiveIterator
{
    /**
     * Index of current active child
     * @var int
     */
    protected $index = 0;

    /**
     * Child nodes
     * @var array
     */
    protected $children = [];

    /**
     * NavigationContainer constructor.
     * @param array $pages
     */
    public function __construct(array $pages = [])
    {
        $this->addPages($pages);
    }

    /**
     * @param array $pages
     */
    public function addPages(array $pages)
    {
        foreach ($pages as $page) {
            $this->addPage($page);
        }
    }

    /**
     * @param Page $page
     */
    public function addPage(Page $page)
    {
        $this->children[] = $page;
    }

    /**
     * @return NavigationContainer
     */
    public function current(): NavigationContainer
    {
        return $this->children[$this->index];
    }

    /**
     * Increment current position to the next element
     */
    public function next()
    {
        $this->index++;
    }

    /**
     * @return int
     */
    public function key(): int
    {
        return $this->index;
    }

    /**
     * @return bool
     */
    public function valid(): bool
    {
        return isset($this->children[$this->index]);
    }

    /**
     * Reset position to the first element
     */
    public function rewind()
    {
        $this->index = 0;
    }

    /**
     * @return bool
     */
    public function hasChildren(): bool
    {
        return count($this->children) > 0;
    }

    /**
     * @return NavigationContainer
     */
    public function getChildren(): NavigationContainer
    {
        return $this->children[$this->index];
    }

    /**
     * Find a single child by attribute
     *
     * @param string $attribute
     * @param mixed $value
     * @return Page|null
     */
    public function findOneByAttribute(string $attribute, $value): ?Page
    {
        $iterator = new \RecursiveIteratorIterator($this, \RecursiveIteratorIterator::SELF_FIRST);
        /** @var Page $page */
        foreach ($iterator as $page) {
            if ($page->getAttribute($attribute) === $value) {
                return $page;
            }
        }
        return null;
    }

    /**
     * Find all children by attribute
     *
     * @param string $attribute
     * @param mixed $value
     * @return array
     */
    public function findByAttribute(string $attribute, $value): array
    {
        $result = [];
        $iterator = new \RecursiveIteratorIterator($this, \RecursiveIteratorIterator::SELF_FIRST);

        /** @var Page $page */
        foreach ($iterator as $page) {
            if ($page->getAttribute($attribute) == $value) {
                $result[] = $page;
            }
        }
        return $result;
    }

    /**
     * Finds a single child by option.
     *
     * @param string $option
     * @param mixed $value
     * @return Page|null
     */
    public function findOneByOption(string $option, $value): ?Page
    {
        $iterator = new \RecursiveIteratorIterator($this, \RecursiveIteratorIterator::SELF_FIRST);
        /** @var Page $page */
        foreach ($iterator as $page) {
            if ($page->getOption($option) == $value) {
                return $page;
            }
        }
        return null;
    }

    /**
     * Finds all children by option.
     *
     * @param string $option
     * @param mixed $value
     * @return array
     */
    public function findByOption(string $option, $value): array
    {
        $result = [];
        $iterator = new \RecursiveIteratorIterator($this, \RecursiveIteratorIterator::SELF_FIRST);
        /** @var Page $page */
        foreach ($iterator as $page) {
            if ($page->getOption($option) == $value) {
                $result[] = $page;
            }
        }
        return $result;
    }
}


<?php

namespace Encore\Wx;

use Illuminate\Filesystem\Filesystem;
use Encore\Wx\Command\Install as InstallCommand;
use Encore\View\Parser\View\Giml as ViewParser;
use Encore\Giml\NamespaceElementFactory;

class ServiceProvider extends \Encore\Container\ServiceProvider
{
    /**
     * Register the specified binding into the container
     *
     * @param  string $binding
     * @return void
     */
    public function register($binding)
    {
        if ( ! extension_loaded('wxwidgets')) {
            if ( ! @dl('wxwidgets.'.PHP_SHLIB_SUFFIX)) {
                echo 'wxWidgets extension not installed or dynamically loaded extensions are not enabled'.PHP_EOL;
                exit(1);
            }
        }

        switch ($binding) {
            case 'view.viewparser':
                $this->registerViewParser();
            break;

            case 'wx':
                $this->registerWx();
            break;

            case 'launcher':
                $this->registerLauncher();
            break;

            case 'giml.collection':
                $this->registerGimlCollection();
            break;

            default:
                $this->registerGimlCollection();
                $this->registerViewParser();
                $this->registerWx();
                $this->registerLauncher();
            break;
        }
    }

    /**
     * Register the view parser
     *
     * @return void
     */
    protected function registerViewParser()
    {
        $this->container->bind('view.viewparser', function() {
            return new ViewParser(
                $this->container['giml.reader'],
                $this->container['giml.collection'],
                new NamespaceElementFactory('Encore\Wx\Element')
            );
        });
    }

    /**
     * Register the GIML collection
     *
     * @return void
     */
    protected function registerGimlCollection()
    {
        $this->container['giml.collection'] = 'Encore\Wx\Collection';
    }

    /**
     * Register WxWidgets app handler
     *
     * @return void
     */
    protected function registerWx()
    {
        $this->container->bind('wx', new Widgets);
    }

    /**
     * Register the WxWidgets launcher
     *
     * @return void
     */
    protected function registerLauncher()
    {
        $this->container->bind('launcher', function() {
            wxInitAllImageHandlers();
            \wxApp::SetInstance($this->container['wx']);
            wxEntry();
        });
    }

    /**
     * Register the WxWidgets install command
     *
     * @return array
     */
    public function commands()
    {
        return ['Encore\Wx\Command\Install'];
    }

    /**
     * Set which services this provider provides
     *
     * @return array
     */
    public function provides()
    {
        return ['wx', 'launcher', 'view.viewparser', 'giml.collection'];
    }
}


<?php

namespace Rougin\Describe\Driver;

use Rougin\Describe\Exceptions\DriverNotFoundException;

/**
 * Database Driver
 *
 * A database driver for using available database drivers.
 *
 * @package Describe
 * @author  Rougin Gutib <rougingutib@gmail.com>
 */
class DatabaseDriver implements DriverInterface
{
    /**
     * @var array
     */
    protected $data = array();

    /**
     * @var \Rougin\Describe\Driver\DriverInterface
     */
    protected $driver;

    /**
     * @var array
     */
    protected $mysql = array('mysql', 'mysqli');

    /**
     * @var array
     */
    protected $sqlite = array('pdo', 'sqlite', 'sqlite3');

    /**
     * Initializes the driver instance.
     *
     * @param string $name
     * @param array  $data
     */
    public function __construct($name, $data = array())
    {
        $this->data = $data;

        $this->driver = $this->driver($name, $data);
    }

    /**
     * Returns an array of Column instances from a table.
     *
     * @param  string $table
     * @return \Rougin\Describe\Column[]
     */
    public function columns($table)
    {
        return $this->driver->columns($table);
    }

    /**
     * Returns an array of Column instances from a table.
     * NOTE: To be removed in v2.0.0. Use columns() instead.
     *
     * @param  string $table
     * @return \Rougin\Describe\Column[]
     */
    public function getColumns($table)
    {
        return $this->columns($table);
    }

    /**
     * Returns an array of Column instances from a table.
     * NOTE: To be removed in v2.0.0. Use getColumns() instead.
     *
     * @param  string $table
     * @return \Rougin\Describe\Column[]
     */
    public function getTable($table)
    {
        return $this->getColumns($table);
    }

    /**
     * Returns an array of table names.
     * NOTE: To be removed in v2.0.0. Use tables() instead.
     *
     * @return array
     */
    public function getTableNames()
    {
        return $this->tables();
    }

    /**
     * Returns an array of table names.
     * NOTE: To be removed in v2.0.0. Use getTableNames() instead.
     *
     * @return array
     */
    public function showTables()
    {
        return $this->getTableNames();
    }

    /**
     * Returns an array of Table instances.
     *
     * @return \Rougin\Describe\Table[]
     */
    public function tables()
    {
        return $this->driver->tables();
    }

    /**
     * Returns the Driver instance from the configuration.
     *
     * @param  string $name
     * @param  array  $data
     * @return \Rougin\Describe\Driver\DriverInterface
     *
     * @throws \Rougin\Describe\Exceptions\DriverNotFoundException
     */
    protected function driver($name, $data = array())
    {
        if (in_array($name, $this->mysql) === true) {
            $dsn = (string) 'mysql:host=%s;dbname=%s';

            $dsn = sprintf($dsn, $data['hostname'], $data['database']);

            $pdo = new \PDO($dsn, $data['username'], $data['password']);

            return new MySQLDriver($pdo, (string) $data['database']);
        }

        if (in_array($name, $this->sqlite)) {
            return new SQLiteDriver(new \PDO($data['hostname']));
        }

        $message = 'Database driver "%s" not found.';

        $message = sprintf($message, (string) $name);

        throw new DriverNotFoundException($message);
    }
}


<?php

/**
 * @file
 * TeamSpeak 3 PHP Framework
 *
 * $Id: Profiler.php 9/26/2011 7:06:29 scp@orilla $
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 *
 * @package   TeamSpeak3
 * @version   1.1.8-beta
 * @author    Sven 'ScP' Paulsen
 * @copyright Copyright (c) 2010 by Planet TeamSpeak. All rights reserved.
 */

namespace ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Helper;

/**
 * @class TeamSpeak3_Helper_Profiler
 * @brief Helper class for profiler handling.
 */
class Profiler
{
  /**
   * Stores various timers for code profiling.
   *
   * @var array
   */
  protected static $timers = array();

  /**
   * Inits a timer.
   *
   * @param  string $name
   * @return void
   */
  public static function init($name = "default")
  {
    self::$timers[$name] = new Profiler\Timer($name);
  }

  /**
   * Starts a timer.
   *
   * @param  string $name
   * @return void
   */
  public static function start($name = "default")
  {
    if(array_key_exists($name, self::$timers))
    {
      self::$timers[$name]->start();
    }
    else
    {
      self::$timers[$name] = new Profiler\Timer($name);
    }
  }

  /**
   * Stops a timer.
   *
   * @param  string $name
   * @return void
   */
  public static function stop($name = "default")
  {
    if(!array_key_exists($name, self::$timers))
    {
      self::init($name);
    }

    self::$timers[$name]->stop();
  }

  /**
   * Returns a timer.
   *
   * @param  string $name
   * @return Profiler\Timer
   */
  public static function get($name = "default")
  {
    if(!array_key_exists($name, self::$timers))
    {
      self::init($name);
    }

    return self::$timers[$name];
  }
}


<?php

/**
 * @file
 * TeamSpeak 3 PHP Framework
 *
 * $Id: Text.php 9/26/2011 7:06:29 scp@orilla $
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 *
 * @package   TeamSpeak3
 * @version   1.1.8-beta
 * @author    Sven 'ScP' Paulsen
 * @copyright Copyright (c) 2010 by Planet TeamSpeak. All rights reserved.
 */

namespace ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Viewer;

/**
 * @class TeamSpeak3_Viewer_Text
 * @brief Renders nodes used in ASCII-based TeamSpeak 3 viewers.
 */
class Text implements ViewerInterface
{
  /**
   * A pre-defined pattern used to display a node in a TeamSpeak 3 viewer.
   *
   * @var string
   */
  protected $pattern = "%0%1 %2\n";

  /**
   * Returns the code needed to display a node in a TeamSpeak 3 viewer.
   *
   * @param  \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Node\AbstractNode $node
   * @param  array $siblings
   * @return string
   */
  public function fetchObject(\ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Node\AbstractNode $node, array $siblings = array())
  {
    $this->currObj = $node;
    $this->currSib = $siblings;

    $args = array(
      $this->getPrefix(),
      $this->getCorpusIcon(),
      $this->getCorpusName(),
    );

    return \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Helper\String::factory($this->pattern)->arg($args);
  }

  /**
   * Returns the ASCII string to display the prefix of the current node.
   *
   * @return string
   */
  protected function getPrefix()
  {
    $prefix = "";

    if(count($this->currSib))
    {
      $last = array_pop($this->currSib);

      foreach($this->currSib as $sibling)
      {
        $prefix .=  ($sibling) ? "| " : "  ";
      }

      $prefix .= ($last) ? "\\-" : "|-";
    }

    return $prefix;
  }

  /**
   * Returns an ASCII string which can be used to display the status icon for a
   * TeamSpeak_Node_Abstract object.
   *
   * @return string
   */
  protected function getCorpusIcon()
  {
    return $this->currObj->getSymbol();
  }

  /**
   * Returns a string for the current corpus element which contains the display name
   * for the current TeamSpeak_Node_Abstract object.
   *
   * @return string
   */
  protected function getCorpusName()
  {
    return $this->currObj;
  }
}


<?php

/**
 * @file
 * TeamSpeak 3 PHP Framework
 *
 * $Id: Signal.php 9/26/2011 7:06:29 scp@orilla $
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 *
 * @package   TeamSpeak3
 * @version   1.1.8-beta
 * @author    Sven 'ScP' Paulsen
 * @copyright Copyright (c) 2010 by Planet TeamSpeak. All rights reserved.
 */

namespace ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Helper;

/**
 * @class TeamSpeak3_Helper_Signal
 * @brief Helper class for signal slots.
 */
class Signal
{
  /**
   * Stores the TeamSpeak3_Helper_Signal object.
   *
   * @var Signal
   */
  protected static $instance = null;

  /**
   * Stores subscribed signals and their slots.
   *
   * @var array
   */
  protected $sigslots = array();

  /**
   * Emits a signal with a given set of parameters.
   *
   * @param  string $signal
   * @param  mixed  $params
   * @return mixed
   */
  public function emit($signal, $params = null)
  {
    if(!$this->hasHandlers($signal))
    {
      return;
    }

    if(!is_array($params))
    {
      $params = func_get_args();
      $params = array_slice($params, 1);
    }

    foreach($this->sigslots[$signal] as $slot)
    {
      $return = $slot->call($params);
    }

    return $return;
  }

  /**
   * Subscribes to a signal and returns the signal handler.
   *
   * @param  string $signal
   * @param  mixed  $callback
   * @return Signal\Handler
   */
  public function subscribe($signal, $callback)
  {
    if(empty($this->sigslots[$signal]))
    {
      $this->sigslots[$signal] = array();
    }

    $index = md5(serialize($callback));

    if(!array_key_exists($index, $this->sigslots[$signal]))
    {
      $this->sigslots[$signal][$index] = new Signal\Handler($signal, $callback);
    }

    return $this->sigslots[$signal][$index];
  }

  /**
   * Unsubscribes from a signal.
   *
   * @param  string $signal
   * @param  mixed  $callback
   * @return void
   */
  public function unsubscribe($signal, $callback = null)
  {
    if(!$this->hasHandlers($signal))
    {
      return;
    }

    if($callback !== null)
    {
      $index = md5(serialize($callback));

      if(!array_key_exists($index, $this->sigslots[$signal]))
      {
        return;
      }

      unset($this->sigslots[$signal][$index]);
    }
    else
    {
      unset($this->sigslots[$signal]);
    }
  }

  /**
   * Returns all registered signals.
   *
   * @return array
   */
  public function getSignals()
  {
    return array_keys($this->sigslots);
  }

  /**
   * Returns TRUE there are slots subscribed for a specified signal.
   *
   * @param  string $signal
   * @return boolean
   */
  public function hasHandlers($signal)
  {
    return empty($this->sigslots[$signal]) ? FALSE : TRUE;
  }

  /**
   * Returns all slots for a specified signal.
   *
   * @param  string $signal
   * @return array
   */
  public function getHandlers($signal)
  {
    if(!$this->hasHandlers($signal))
    {
      return $this->sigslots[$signal];
    }

    return array();
  }

  /**
   * Clears all slots for a specified signal.
   *
   * @param  string $signal
   * @return void
   */
  public function clearHandlers($signal)
  {
    if(!$this->hasHandlers($signal))
    {
      unset($this->sigslots[$signal]);
    }
  }

  /**
   * Returns a singleton instance of TeamSpeak3_Helper_Signal.
   *
   * @return Signal
   */
  public static function getInstance()
  {
    if(self::$instance === null)
    {
      self::$instance = new self();
    }

    return self::$instance;
  }
}


<?php

namespace DevGroup\Entity\widgets;

use DevGroup\Users\helpers\ModelMapHelper;
use yii\base\Widget;
use yii\db\ActiveRecord;
use yii\db\Expression;

/**
 * Class BaseActionsInfoWidget
 * @package DevGroup\Entity\widgets
 */
class BaseActionsInfoWidget extends Widget
{
    const ATTRIBUTE_TYPE_USER = 'user';
    const ATTRIBUTE_TYPE_DATE = 'date';

    /**
     * @var array
     */
    protected $attributesList = [
        'createdByAttribute' => self::ATTRIBUTE_TYPE_USER,
        'createdAtAttribute' => self::ATTRIBUTE_TYPE_DATE,
        'updatedByAttribute' => self::ATTRIBUTE_TYPE_USER,
        'updatedAtAttribute' => self::ATTRIBUTE_TYPE_DATE,
    ];

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

    /**
     * @var ActiveRecord
     */
    public $model;

    /**
     * @var string
     */
    public $viewFile = 'base-actions-info-default';

    /**
     * @inheritdoc
     */
    public function run()
    {
        $attributes = [];
        foreach ($this->attributesList as $attributeNameAttribute => $type) {
            $attributeName = $this->model->{$attributeNameAttribute};
            if ($this->model->hasAttribute($attributeName)) {
                $attributes[] = [
                    'label' => $this->model->getAttributeLabel($attributeName),
                    'value' => $this->getValue($this->model->{$attributeName}, $type),
                    'type' => $type,
                ];
            }
        }
        echo $this->render(
            $this->viewFile,
            [
                'attributes' => $attributes,
            ]
        );
    }

    /**
     * Get pretty value by type
     * @param mixed $value
     * @param string $type
     * @return mixed
     */
    protected function getValue($value, $type)
    {
        switch ($type) {
            case self::ATTRIBUTE_TYPE_USER:
                return $this->getUsername($value);
            case self::ATTRIBUTE_TYPE_DATE:
                return date('Y-m-d h:i:s', $value);
            default:
                return $value;
        }
    }

    /**
     * @param int $id
     * @return string
     */
    protected function getUsername($id)
    {
        if (empty($id)) {
            return \Yii::t('entity', 'Guest');
        }
        if (!isset($this->users[$id])) {
            $this->users[$id] = call_user_func([ModelMapHelper::User()['class'], 'find'])
                ->select(new Expression("CONCAT(`username`, ' (', `id`, ')')"))
                ->where(['id' => $id])
                ->scalar();
        }
        return isset($this->users[$id]) ? $this->users[$id] : \Yii::t('entity', 'Unknown user');
    }
}


<?php

namespace Rougin\Describe\Driver;

use Rougin\Describe\Column;
use Rougin\Describe\Exceptions\TableNotFoundException;
use Rougin\Describe\Table;

/**
 * MySQL Driver
 *
 * A database driver extension for MySQL.
 * NOTE: Should be renamed to "MySqlDriver" in v2.0.0.
 *
 * @package Describe
 * @author  Rougin Gutib <rougingutib@gmail.com>
 */
class MySQLDriver implements DriverInterface
{
    /**
     * @var string
     */
    protected $database;

    /**
     * @var \PDO
     */
    protected $pdo;

    /**
     * @var string
     */
    protected $script = '';

    /**
     * Initializes the driver instance.
     *
     * @param \PDO   $pdo
     * @param string $database
     */
    public function __construct(\PDO $pdo, $database)
    {
        $this->database = $database;

        $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);

        $this->pdo = $pdo;

        $this->script = 'SELECT COLUMN_NAME as "column", REFERENCED_COLUMN_NAME as ' .
            '"referenced_column", CONCAT(REFERENCED_TABLE_SCHEMA, ".", ' .
            'REFERENCED_TABLE_NAME) as "referenced_table" FROM INFORMATION_SCHEMA' .
            '.KEY_COLUMN_USAGE WHERE CONSTRAINT_SCHEMA = "%s" AND TABLE_NAME = "%s";';
    }

    /**
     * Returns an array of Column instances from a table.
     *
     * @param  string $table
     * @return \Rougin\Describe\Column[]
     */
    public function columns($table)
    {
        return $this->query($table, 'DESCRIBE ' . $table);
    }

    /**
     * Returns an array of Column instances from a table.
     * NOTE: To be removed in v2.0.0. Use columns() instead.
     *
     * @param  string $table
     * @return \Rougin\Describe\Column[]
     */
    public function getColumns($table)
    {
        return $this->columns($table);
    }

    /**
     * Returns an array of Column instances from a table.
     * NOTE: To be removed in v2.0.0. Use getColumns() instead.
     *
     * @param  string $table
     * @return \Rougin\Describe\Column[]
     */
    public function getTable($table)
    {
        return $this->getColumns($table);
    }

    /**
     * Returns an array of table names.
     * NOTE: To be removed in v2.0.0. Use tables() instead.
     *
     * @return array
     */
    public function getTableNames()
    {
        return $this->items(false);
    }

    /**
     * Returns an array of table names.
     * NOTE: To be removed in v2.0.0. Use getTableNames() instead.
     *
     * @return array
     */
    public function showTables()
    {
        return $this->getTableNames();
    }

    /**
     * Returns an array of Table instances.
     *
     * @return \Rougin\Describe\Table[]
     */
    public function tables()
    {
        return $this->items(true);
    }

    /**
     * Prepares the defined columns.
     *
     * @param  \Rougin\Describe\Column $column
     * @param  string                  $table
     * @param  mixed                   $row
     * @return \Rougin\Describe\Column
     */
    protected function column(Column $column, $table, $row)
    {
        preg_match('/(.*?)\((.*?)\)/', $row->Type, $match);

        $column->setDataType($row->Type);

        $column->setDefaultValue($row->Default);

        $column->setField($row->Field);

        if (isset($match[1]) === true) {
            $column->setDataType($match[1]);

            $column->setLength($match[2]);
        }

        $column = $this->properties($row, $column);

        $column = $this->keys($row, $column);

        return $this->foreign($table, $row, $column);
    }

    /**
     * Sets the properties of a column if it does exists.
     *
     * @param  string                  $name
     * @param  mixed                   $row
     * @param  \Rougin\Describe\Column $column
     * @return \Rougin\Describe\Column
     */
    protected function foreign($name, $row, Column $column)
    {
        $query = sprintf($this->script, $this->database, $name);

        $table = $this->pdo->prepare($query);

        $table->execute();

        $table->setFetchMode(\PDO::FETCH_OBJ);

        while ($item = $table->fetch()) {
            if ($item->column === $row->Field) {
                $referenced = $this->strip($item->referenced_table);

                $column->setReferencedField($item->referenced_column);

                $column->setReferencedTable($referenced);
            }
        }

        return $column;
    }

    /**
     * Returns an array of table names or Table instances.
     * NOTE: To be removed in v2.0.0. Move to tables() instead.
     *
     * @param  boolean $instance
     * @param  array   $tables
     * @return array|\Rougin\Describe\Table[]
     */
    protected function items($instance = false, $tables = array())
    {
        $information = $this->pdo->prepare('SHOW TABLES');

        $information->execute();

        while ($row = $information->fetch()) {
            // NOTE: To be removed in v2.0.0. Always return Table instance.
            $instance && $row[0] = new Table($row[0], $this);

            array_push($tables, $row[0]);
        }

        return $tables;
    }

    /**
     * Sets the key of a column.
     *
     * @param  mixed                   $row
     * @param  \Rougin\Describe\Column $column
     * @return \Rougin\Describe\Column
     */
    protected function keys($row, Column $column)
    {
        switch ($row->Key) {
            case 'PRI':
                $column->setPrimary(true);

                break;

            case 'MUL':
                $column->setForeign(true);

                break;

            case 'UNI':
                $column->setUnique(true);

                break;
        }

        return $column;
    }

    /**
     * Returns the list of columns based on a query.
     *
     * @param  string $table
     * @param  string $query
     * @param  array  $columns
     * @return \Rougin\Describe\Column[]
     */
    protected function query($table, $query, $columns = array())
    {
        $result = $this->pdo->prepare($query);

        $result->execute();

        $result->setFetchMode(\PDO::FETCH_OBJ);

        while ($row = $result->fetch()) {
            $column = $this->column(new Column, $table, $row);

            array_push($columns, $column);
        }

        if (empty($columns) === true) {
            $message = 'Table "' . $table . '" does not exists!';

            throw new TableNotFoundException($message);
        }

        return $columns;
    }

    /**
     * Sets the properties of a column.
     *
     * @param  mixed                   $row
     * @param  \Rougin\Describe\Column $column
     * @return \Rougin\Describe\Column
     */
    protected function properties($row, Column $column)
    {
        $increment = $row->Extra === 'auto_increment';

        $column->setAutoIncrement($increment);

        $column->setNull($row->{'Null'} === 'YES');

        return $column;
    }

    /**
     * Strips the table schema from the table name.
     *
     * @param  string $table
     * @return string
     */
    protected function strip($table)
    {
        $exists = strpos($table, '.') !== false;

        $updated = substr($table, strpos($table, '.') + 1);

        return $exists ? $updated : $table;
    }
}


<?php

use Illuminate\Database\Seeder;

class RolesTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        DB::table('roles')->insert([
            [
                'name' => 'admin',
				'created_at' => \Carbon\Carbon::now(),
                'updated_at' => \Carbon\Carbon::now()
            ], [
                'name' => 'user',
				'created_at' => \Carbon\Carbon::now(),
                'updated_at' => \Carbon\Carbon::now()
            ],
        ]);
    }
}


<?php namespace Gears\Arrays;
////////////////////////////////////////////////////////////////////////////////
// __________ __             ________                   __________
// \______   \  |__ ______  /  _____/  ____ _____ ______\______   \ _______  ___
//  |     ___/  |  \\____ \/   \  ____/ __ \\__  \\_  __ \    |  _//  _ \  \/  /
//  |    |   |   Y  \  |_> >    \_\  \  ___/ / __ \|  | \/    |   (  <_> >    <
//  |____|   |___|  /   __/ \______  /\___  >____  /__|  |______  /\____/__/\_ \
//                \/|__|           \/     \/     \/             \/            \/
// -----------------------------------------------------------------------------
//          Designed and Developed by Brad Jones <brad @="bjc.id.au" />
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////

use \RecursiveArrayIterator;
use \InvalidArgumentException;
use \Gears\Arrays\Fluent;

class Iterator extends RecursiveArrayIterator
{
	/**
	 * Method: current
	 * =========================================================================
	 * Return current array entry
	 * See: http://php.net/manual/en/arrayiterator.current.php
	 *
	 * We overload this method so that we can provide a recursive
	 * interface for the \Gears\Arrays\Fluent class.
	 *
	 * Parameters:
	 * -------------------------------------------------------------------------
	 * n/a
	 *
	 * Returns:
	 * -------------------------------------------------------------------------
	 * mixed
	 */
	public function current()
	{
		$key = parent::key();

		$value = parent::offsetGet($key);

		if (is_array($value)) $this->offsetSet($key, new Fluent($value));

		return parent::offsetGet($key);
	}

	/**
	 * Method: hasChildren
	 * =========================================================================
	 * Check to see if we have children, ie: multi-dimensional array.
	 * See: http://php.net/manual/en/recursivearrayiterator.haschildren.php
	 *
	 * Parameters:
	 * -------------------------------------------------------------------------
	 * n/a
	 *
	 * Returns:
	 * -------------------------------------------------------------------------
	 * boolean
	 */
	public function hasChildren()
	{
		return isArrayLike($this->current());
	}

	/**
	 * Method: getChildren
	 * =========================================================================
	 * Returns our children.
	 * See: http://php.net/manual/en/recursivearrayiterator.getchildren.php
	 *
	 * Parameters:
	 * -------------------------------------------------------------------------
	 * n/a
	 *
	 * Returns:
	 * -------------------------------------------------------------------------
	 * mixed
	 */
	public function getChildren()
	{
		if ($this->hasChildren()) return $this->current()->getIterator();

		throw new InvalidArgumentException('Current item not an array!');
	}
}


<?php

/**
 * @file
 * TeamSpeak 3 PHP Framework
 *
 * $Id: Host.php 9/26/2011 7:06:29 scp@orilla $
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 *
 * @package   TeamSpeak3
 * @version   1.1.8-beta
 * @author    Sven 'ScP' Paulsen
 * @copyright Copyright (c) 2010 by Planet TeamSpeak. All rights reserved.
 */

namespace ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Node;

/**
 * @class TeamSpeak3_Node_Host
 * @brief Class describing a TeamSpeak 3 server instance and all it's parameters.
 */
class Host extends AbstractNode
{
  /**
   * @ignore
   */
  protected $whoami = null;

  /**
   * @ignore
   */
  protected $version = null;

  /**
   * @ignore
   */
  protected $serverList = null;

  /**
   * @ignore
   */
  protected $permissionList = null;

  /**
   * @ignore
   */
  protected $predefined_query_name = null;

  /**
   * @ignore
   */
  protected $exclude_query_clients = FALSE;

  /**
   * @ignore
   */
  protected $start_offline_virtual = FALSE;

  /**
   * @ignore
   */
  protected $sort_clients_channels = FALSE;

  /**
   * The TeamSpeak3_Node_Host constructor.
   *
   * @param  \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Adapter\ServerQuery $squery
   * @return Host
   */
  public function __construct(\ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Adapter\ServerQuery $squery)
  {
    $this->parent = $squery;
  }

  /**
   * Returns the primary ID of the selected virtual server.
   *
   * @return integer
   */
  public function serverSelectedId()
  {
    return $this->whoamiGet("virtualserver_id", 0);
  }

  /**
   * Returns the primary UDP port of the selected virtual server.
   *
   * @return integer
   */
  public function serverSelectedPort()
  {
    return $this->whoamiGet("virtualserver_port", 0);
  }

  /**
   * Returns the servers version information including platform and build number.
   *
   * @param  string $ident
   * @return mixed
   */
  public function version($ident = null)
  {
    if($this->version === null)
    {
      $this->version = $this->request("version")->toList();
    }

    return ($ident && array_key_exists($ident, $this->version)) ? $this->version[$ident] : $this->version;
  }

  /**
   * Selects a virtual server by ID to allow further interaction.
   *
   * @param  integer $sid
   * @param  boolean $virtual
   * @return void
   */
  public function serverSelect($sid, $virtual = null)
  {
    if($this->whoami !== null && $this->serverSelectedId() == $sid) return;

    $virtual = ($virtual !== null) ? $virtual : $this->start_offline_virtual;
    $getargs = func_get_args();

    $this->execute("use", array("sid" => $sid, $virtual ? "-virtual" : null));

    if($sid != 0 && $this->predefined_query_name !== null)
    {
      $this->execute("clientupdate", array("client_nickname" => (string) $this->predefined_query_name));
    }

    $this->whoamiReset();

    $this->setStorage("_server_use", array(__FUNCTION__, $getargs));

    \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Helper\Signal::getInstance()->emit("notifyServerselected", $this);
  }

  /**
   * Alias for serverSelect().
   *
   * @param  integer $sid
   * @param  boolean $virtual
   * @return void
   */
  public function serverSelectById($sid, $virtual = null)
  {
    $this->serverSelect($sid, $virtual);
  }

  /**
   * Selects a virtual server by UDP port to allow further interaction.
   *
   * @param  integer $port
   * @param  boolean $virtual
   * @return void
   */
  public function serverSelectByPort($port, $virtual = null)
  {
    if($this->whoami !== null && $this->serverSelectedPort() == $port) return;

    $virtual = ($virtual !== null) ? $virtual : $this->start_offline_virtual;
    $getargs = func_get_args();

    $this->execute("use", array("port" => $port, $virtual ? "-virtual" : null));

    if($port != 0 && $this->predefined_query_name !== null)
    {
      $this->execute("clientupdate", array("client_nickname" => (string) $this->predefined_query_name));
    }

    $this->whoamiReset();

    $this->setStorage("_server_use", array(__FUNCTION__, $getargs));

    \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Helper\Signal::getInstance()->emit("notifyServerselected", $this);
  }

  /**
   * Deselects the active virtual server.
   *
   * @return void
   */
  public function serverDeselect()
  {
    $this->serverSelect(0);

    $this->delStorage("_server_use");
  }

  /**
   * Returns the ID of a virtual server matching the given port.
   *
   * @param  integer $port
   * @return integer
   */
  public function serverIdGetByPort($port)
  {
    $sid = $this->execute("serveridgetbyport", array("virtualserver_port" => $port))->toList();

    return $sid["server_id"];
  }

  /**
   * Returns the port of a virtual server matching the given ID.
   *
   * @param  integer $sid
   * @return integer
   */
  public function serverGetPortById($sid)
  {
    if(!array_key_exists((string) $sid, $this->serverList()))
    {
      throw new \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Adapter\ServerQuery\Exception("invalid serverID", 0x400);
    }

    return $this->serverList[intval((string) $sid)]["virtualserver_port"];
  }

  /**
   * Returns the TeamSpeak3_Node_Server object matching the currently selected ID.
   *
   * @return Server
   */
  public function serverGetSelected()
  {
    return $this->serverGetById($this->serverSelectedId());
  }

  /**
   * Returns the TeamSpeak3_Node_Server object matching the given ID.
   *
   * @param  integer $sid
   * @return Server
   */
  public function serverGetById($sid)
  {
    $this->serverSelectById($sid);

    return new Server($this, array("virtualserver_id" => intval($sid)));
  }

  /**
   * Returns the TeamSpeak3_Node_Server object matching the given port number.
   *
   * @param  integer $port
   * @return Server
   */
  public function serverGetByPort($port)
  {
    $this->serverSelectByPort($port);

    return new Server($this, array("virtualserver_id" => $this->serverSelectedId()));
  }

  /**
   * Returns the first TeamSpeak3_Node_Server object matching the given name.
   *
   * @param  string $name
   * @throws \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Adapter\ServerQuery\Exception
   * @return Server
   */
  public function serverGetByName($name)
  {
    foreach($this->serverList() as $server)
    {
      if($server["virtualserver_name"] == $name) return $server;
    }

    throw new \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Adapter\ServerQuery\Exception("invalid serverID", 0x400);
  }

  /**
   * Returns the first TeamSpeak3_Node_Server object matching the given unique identifier.
   *
   * @param  string $uid
   * @throws \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Adapter\ServerQuery\Exception
   * @return Server
   */
  public function serverGetByUid($uid)
  {
    foreach($this->serverList() as $server)
    {
      if($server["virtualserver_unique_identifier"] == $uid) return $server;
    }

    throw new \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Adapter\ServerQuery\Exception("invalid serverID", 0x400);
  }

  /**
   * Returns the first TeamSpeak3_Node_Server object matching the given TSDNS hostname. Like the
   * TeamSpeak 3 Client, this method will start looking for a TSDNS server on the second-level
   * domain including a fallback to the third-level domain of the specified $tsdns parameter.
   *
   * @param  string $tsdns
   * @throws \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Adapter\ServerQuery\Exception
   * @return Server
   */
  public function serverGetByTSDNS($tsdns)
  {
    $parts = \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Helper\Uri::getFQDNParts($tsdns);
    $query = \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Helper\String::factory(array_shift($parts));

    while($part = array_shift($parts))
    {
      $query->prepend($part);

      try
      {
        $port = \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::factory("tsdns://" . $query . "/?timeout=3")->resolve($tsdns)->section(":", 1);

        return $this->serverGetByPort($port == "" ? 9987 : $port);
      }
      catch(\ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Transport\Exception $e)
      {
        /* skip "Connection timed out" and "Connection refused" */
        if($e->getCode() != 10060 && $e->getCode() != 10061) throw $e;
      }
    }

    throw new \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Adapter\ServerQuery\Exception("invalid serverID", 0x400);
  }

  /**
   * Creates a new virtual server using given properties and returns an assoc
   * array containing the new ID and initial admin token.
   *
   * @param  array $properties
   * @return array
   */
  public function serverCreate(array $properties = array())
  {
    $this->serverListReset();

    $detail = $this->execute("servercreate", $properties)->toList();
    $server = new Server($this, array("virtualserver_id" => intval($detail["sid"])));

    \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Helper\Signal::getInstance()->emit("notifyServercreated", $this, $detail["sid"]);
    \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Helper\Signal::getInstance()->emit("notifyTokencreated", $server, $detail["token"]);

    return $detail;
  }

  /**
   * Deletes the virtual server specified by ID.
   *
   * @param  integer $sid
   * @return void
   */
  public function serverDelete($sid)
  {
    $this->serverListReset();

    $this->execute("serverdelete", array("sid" => $sid));

    \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Helper\Signal::getInstance()->emit("notifyServerdeleted", $this, $sid);
  }

  /**
   * Starts the virtual server specified by ID.
   *
   * @param  integer $sid
   * @return void
   */
  public function serverStart($sid)
  {
    if($sid == $this->serverSelectedId())
    {
      $this->serverDeselect();
    }

    $this->execute("serverstart", array("sid" => $sid));
    $this->serverListReset();

    \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Helper\Signal::getInstance()->emit("notifyServerstarted", $this, $sid);
  }

  /**
   * Stops the virtual server specified by ID.
   *
   * @param  integer $sid
   * @return void
   */
  public function serverStop($sid)
  {
    if($sid == $this->serverSelectedId())
    {
      $this->serverDeselect();
    }

    $this->execute("serverstop", array("sid" => $sid));
    $this->serverListReset();

    \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Helper\Signal::getInstance()->emit("notifyServerstopped", $this, $sid);
  }

  /**
   * Stops the entire TeamSpeak 3 Server instance by shutting down the process.
   *
   * @return void
   */
  public function serverStopProcess()
  {
    \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Helper\Signal::getInstance()->emit("notifyServershutdown", $this);

    $this->execute("serverprocessstop");
  }

  /**
   * Returns an array filled with TeamSpeak3_Node_Server objects.
   *
   * @param  array $filter
   * @return array
   */
  public function serverList(array $filter = array())
  {
    if($this->serverList === null)
    {
      $servers = $this->request("serverlist -uid")->toAssocArray("virtualserver_id");

      $this->serverList = array();

      foreach($servers as $sid => $server)
      {
        $this->serverList[$sid] = new Server($this, $server);
      }

      $this->resetNodeList();
    }

    return $this->filterList($this->serverList, $filter);
  }

  /**
   * Resets the list of virtual servers.
   *
   * @return void
   */
  public function serverListReset()
  {
    $this->resetNodeList();
    $this->serverList = null;
  }

  /**
   * Returns a list of IP addresses used by the server instance on multi-homed machines.
   *
   * @return array
   */
  public function bindingList()
  {
    return $this->request("bindinglist")->toArray();
  }

  /**
   * Returns a list of permissions available on the server instance.
   *
   * @return array
   */
  public function permissionList()
  {
    if($this->permissionList === null)
    {
      $this->permissionList = $this->request("permissionlist")->toAssocArray("permname");
    }

    return $this->permissionList;
  }

  /**
   * Returns the IDs of all clients, channels or groups using the permission with the
   * specified ID.
   *
   * @param  integer $permid
   * @return array
   */
  public function permissionFind($permid)
  {
    $permident = (is_numeric($permid)) ? "permid" : "permsid";

    return $this->execute("permfind", array($permident => $permid))->toArray();
  }

  /**
   * Returns the ID of the permission matching the given name.
   *
   * @param  string $name
   * @throws \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Adapter\ServerQuery\Exception
   * @return integer
   */
  public function permissionGetIdByName($name)
  {
    if(!array_key_exists((string) $name, $this->permissionList()))
    {
      throw new \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Adapter\ServerQuery\Exception("invalid permission ID", 0xA02);
    }

    return $this->permissionList[(string) $name]["permid"];
  }

  /**
   * Returns the name of the permission matching the given ID.
   *
   * @param  integer $permid
   * @throws \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Adapter\ServerQuery\Exception
   * @return \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Helper\String
   */
  public function permissionGetNameById($permid)
  {
    foreach($this->permissionList() as $name => $perm)
    {
      if($perm["permid"] == $permid) return new \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Helper\String($name);
    }

    throw new \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Adapter\ServerQuery\Exception("invalid permission ID", 0xA02);
  }

  /**
   * Returns the internal category of the permission matching the given ID.
   *
   * All permission IDs are are 2 bytes wide. The first byte identifies the category while the second
   * byte is the permission count within that group.
   *
   * @param  integer $permid
   * @return integer
   */
  public function permissionGetCategoryById($permid)
  {
    if(!is_numeric($permid))
    {
      $permid = $this->permissionGetIdByName($permid);
    }

    return (int) $permid >> 8;
  }

  /**
   * Returns an array containing the value of a specified permission for your own client.
   *
   * @param  integer $permid
   * @return array
   */
  public function selfPermCheck($permid)
  {
    $permident = (is_numeric($permid)) ? "permid" : "permsid";

    return $this->execute("permget", array($permident => $permid))->toAssocArray("permsid");
  }

  /**
   * Changes the server instance configuration using given properties.
   *
   * @param  array $properties
   * @return void
   */
  public function modify(array $properties)
  {
    $this->execute("instanceedit", $properties);
    $this->resetNodeInfo();
  }

  /**
   * Sends a text message to all clients on all virtual servers in the TeamSpeak 3 Server instance.
   *
   * @param  string $msg
   * @return void
   */
  public function message($msg)
  {
    $this->execute("gm", array("msg" => $msg));
  }

  /**
   * Displays a specified number of entries (1-100) from the servers log.
   *
   * @param  integer $lines
   * @param  integer $begin_pos
   * @param  boolean $instance
   * @param  boolean $reverse
   * @return array
   */
  public function logView($lines = 30, $begin_pos = null, $instance = null, $reverse = null)
  {
    return $this->execute("logview", array("lines" => $lines, "begin_pos" => $begin_pos, "instance" => $instance, "reverse" => $reverse))->toArray();
  }

  /**
   * Writes a custom entry into the server instance log.
   *
   * @param  string  $logmsg
   * @param  integer $loglevel
   * @return void
   */
  public function logAdd($logmsg, $loglevel = \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::LOGLEVEL_INFO)
  {
    $sid = $this->serverSelectedId();

    $this->serverDeselect();
    $this->execute("logadd", array("logmsg" => $logmsg, "loglevel" => $loglevel));
    $this->serverSelect($sid);
  }

  /**
   * Authenticates with the TeamSpeak 3 Server instance using given ServerQuery login credentials.
   *
   * @param  string $username
   * @param  string $password
   * @return void
   */
  public function login($username, $password)
  {
    $this->execute("login", array("client_login_name" => $username, "client_login_password" => $password));
    $this->whoamiReset();

    $crypt = new \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Helper\Crypt($username);

    $this->setStorage("_login_user", $username);
    $this->setStorage("_login_pass", $crypt->encrypt($password));

    \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Helper\Signal::getInstance()->emit("notifyLogin", $this);
  }

  /**
   * Deselects the active virtual server and logs out from the server instance.
   *
   * @return void
   */
  public function logout()
  {
    $this->request("logout");
    $this->whoamiReset();

    $this->delStorage("_login_user");
    $this->delStorage("_login_pass");

    \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Helper\Signal::getInstance()->emit("notifyLogout", $this);
  }

  /**
   * Returns information about your current ServerQuery connection.
   *
   * @return array
   */
  public function whoami()
  {
    if($this->whoami === null)
    {
      $this->whoami = $this->request("whoami")->toList();
    }

    return $this->whoami;
  }

  /**
   * Returns a single value from the current ServerQuery connection info.
   *
   * @param  string $ident
   * @param  mixed  $default
   * @return mixed
   */
  public function whoamiGet($ident, $default = null)
  {
    if(array_key_exists($ident, $this->whoami()))
    {
      return $this->whoami[$ident];
    }

    return $default;
  }

  /**
   * Sets a single value in the current ServerQuery connection info.
   *
   * @param  string $ident
   * @param  mixed  $value
   * @return mixed
   */
  public function whoamiSet($ident, $value = null)
  {
    $this->whoami();

    $this->whoami[$ident] = (is_numeric($value)) ? intval($value) : \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Helper\String::factory($value);
  }

  /**
   * Resets the current ServerQuery connection info.
   *
   * @return void
   */
  public function whoamiReset()
  {
    $this->whoami = null;
  }

  /**
   * Returns the hostname or IPv4 address the adapter is connected to.
   *
   * @return string
   */
  public function getAdapterHost()
  {
    return $this->getParent()->getTransportHost();
  }

  /**
   * Returns the network port the adapter is connected to.
   *
   * @return string
   */
  public function getAdapterPort()
  {
    return $this->getParent()->getTransportPort();
  }

  /**
   * @ignore
   */
  protected function fetchNodeList()
  {
    $servers = $this->serverList();

    foreach($servers as $server)
    {
      $this->nodeList[] = $server;
    }
  }

  /**
   * @ignore
   */
  protected function fetchNodeInfo()
  {
    $info1 = $this->request("hostinfo")->toList();
    $info2 = $this->request("instanceinfo")->toList();

    $this->nodeInfo = array_merge($this->nodeInfo, $info1, $info2);
  }

  /**
   * Sets a pre-defined nickname for ServerQuery clients which will be used automatically
   * after selecting a virtual server.
   *
   * @param  string $name
   * @return void
   */
  public function setPredefinedQueryName($name = null)
  {
    $this->setStorage("_query_nick", $name);

    $this->predefined_query_name = $name;
  }

  /**
   * Returns the pre-defined nickname for ServerQuery clients which will be used automatically
   * after selecting a virtual server.
   *
   * @return string
   */
  public function getPredefinedQueryName()
  {
    return $this->predefined_query_name;
  }

  /**
   * Sets the option to decide whether ServerQuery clients should be excluded from node
   * lists or not.
   *
   * @param  boolean $exclude
   * @return void
   */
  public function setExcludeQueryClients($exclude = FALSE)
  {
    $this->setStorage("_query_hide", $exclude);

    $this->exclude_query_clients = $exclude;
  }

  /**
   * Returns the option to decide whether ServerQuery clients should be excluded from node
   * lists or not.
   *
   * @return boolean
   */
  public function getExcludeQueryClients()
  {
    return $this->exclude_query_clients;
  }

  /**
   * Sets the option to decide whether offline servers will be started in virtual mode
   * by default or not.
   *
   * @param  boolean $virtual
   * @return void
   */
  public function setUseOfflineAsVirtual($virtual = FALSE)
  {
    $this->setStorage("_do_virtual", $virtual);

    $this->start_offline_virtual = $virtual;
  }

  /**
   * Returns the option to decide whether offline servers will be started in virtual mode
   * by default or not.
   *
   * @return boolean
   */
  public function getUseOfflineAsVirtual()
  {
    return $this->start_offline_virtual;
  }

  /**
   * Sets the option to decide whether clients should be sorted before sub-channels to support
   * the new TeamSpeak 3 Client display mode or not.
   *
   * @param  boolean $first
   * @return void
   */
  public function setLoadClientlistFirst($first = FALSE)
  {
    $this->setStorage("_client_top", $first);

    $this->sort_clients_channels = $first;
  }

  /**
   * Returns the option to decide whether offline servers will be started in virtual mode
   * by default or not.
   *
   * @return boolean
   */
  public function getLoadClientlistFirst()
  {
    return $this->sort_clients_channels;
  }

  /**
   * Returns the underlying \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Adapter\ServerQuery object.
   *
   * @return \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Adapter\ServerQuery
   */
  public function getAdapter()
  {
    return $this->getParent();
  }

  /**
   * Returns a unique identifier for the node which can be used as a HTML property.
   *
   * @return string
   */
  public function getUniqueId()
  {
    return "ts3_h";
  }

  /**
   * Returns the name of a possible icon to display the node object.
   *
   * @return string
   */
  public function getIcon()
  {
    return "host";
  }

  /**
   * Returns a symbol representing the node.
   *
   * @return string
   */
  public function getSymbol()
  {
    return "+";
  }

  /**
   * Re-authenticates with the TeamSpeak 3 Server instance using given ServerQuery login
   * credentials and re-selects a previously selected virtual server.
   *
   * @return void
   */
  public function __wakeup()
  {
    $username = $this->getStorage("_login_user");
    $password = $this->getStorage("_login_pass");

    if($username && $password)
    {
      $crypt = new \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Helper\Crypt($username);

      $this->login($username, $crypt->decrypt($password));
    }

    $this->predefined_query_name = $this->getStorage("_query_nick");
    $this->exclude_query_clients = $this->getStorage("_query_hide", FALSE);
    $this->start_offline_virtual = $this->getStorage("_do_virtual", FALSE);
    $this->sort_clients_channels = $this->getStorage("_client_top", FALSE);

    if($server = $this->getStorage("_server_use"))
    {
      $func = array_shift($server);
      $args = array_shift($server);

      call_user_func_array(array($this, $func), $args);
    }
  }

  /**
   * Returns a string representation of this node.
   *
   * @return string
   */
  public function __toString()
  {
    return (string) $this->getAdapterHost();
  }
}


<?php
/**
 * This file is a part of the page-fetcher package.
 *
 * Read more at https://github.com/themichaelhall/page-fetcher
 */
declare(strict_types=1);

namespace MichaelHall\PageFetcher;

use DataTypes\Interfaces\FilePathInterface;
use MichaelHall\PageFetcher\Interfaces\PageFetcherInterface;
use MichaelHall\PageFetcher\Interfaces\PageFetcherRequestInterface;
use MichaelHall\PageFetcher\Interfaces\PageFetcherResponseInterface;

/**
 * Page fetcher class.
 *
 * @since 1.0.0
 */
class PageFetcher implements PageFetcherInterface
{
    /**
     * Constructs the page fetcher.
     *
     * @since 1.0.0
     */
    public function __construct()
    {
        $this->cookieFile = tempnam(sys_get_temp_dir(), 'page-fetcher-cookies-');
    }

    /**
     * Fetches the content from a request.
     *
     * @since 1.0.0
     *
     * @param PageFetcherRequestInterface $request The page fetcher request.
     *
     * @return PageFetcherResponseInterface The page fetcher response.
     */
    public function fetch(PageFetcherRequestInterface $request): PageFetcherResponseInterface
    {
        $curl = curl_init();

        curl_setopt($curl, CURLOPT_URL, $request->getUrl()->__toString());
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, true);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $request->getMethod());
        curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 30);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $request->getHeaders());
        curl_setopt($curl, CURLOPT_COOKIEJAR, $this->cookieFile);
        curl_setopt($curl, CURLOPT_COOKIEFILE, $this->cookieFile);

        $this->setCurlContent($curl, $request);

        $result = curl_exec($curl);
        if ($result === false) {
            $error = curl_error($curl);
            curl_close($curl);

            return new PageFetcherResponse(0, $error);
        }
        curl_close($curl);

        return $this->parseResult($result);
    }

    /**
     * Destructs the page fetcher.
     *
     * @since 1.0.0
     */
    public function __destruct()
    {
        if (file_exists($this->cookieFile)) {
            unlink($this->cookieFile);
        }
    }

    /**
     * Sets the CURL content from request.
     *
     * @param resource                    $curl    The CURL instance.
     * @param PageFetcherRequestInterface $request The request.
     */
    private function setCurlContent($curl, PageFetcherRequestInterface $request): void
    {
        $rawContent = $request->getRawContent();
        if ($rawContent !== '') {
            curl_setopt($curl, CURLOPT_POSTFIELDS, $rawContent);

            return;
        }

        $postFields = [];
        $hasFiles = false;

        foreach ($request->getFiles() as $name => $filePath) {
            /** @var FilePathInterface $filePath */
            $curlFile = curl_file_create($filePath->__toString(), mime_content_type($filePath->__toString()), $filePath->getFilename());
            $postFields[$name] = $curlFile;
            $hasFiles = true;
        }

        foreach ($request->getPostFields() as $name => $value) {
            $postFields[$name] = $value;
        }

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

        curl_setopt($curl, CURLOPT_POSTFIELDS, $hasFiles ? $postFields : http_build_query($postFields));
    }

    /**
     * Parses the CURL result into a PageFetcherResponse.
     *
     * @param string $result The CURL result.
     *
     * @return PageFetcherResponseInterface The PageFetcherResponse.
     */
    private function parseResult(string $result): PageFetcherResponseInterface
    {
        $resultParts = explode("\r\n\r\n", $result, 2);

        $headers = explode("\r\n", $resultParts[0]);
        $statusLine = array_shift($headers);
        $statusLineParts = explode(' ', $statusLine);
        $httpCode = intval($statusLineParts[1]);
        if ($httpCode === 100) {
            return $this->parseResult($resultParts[1]);
        }

        $content = count($resultParts) > 1 ? $resultParts[1] : '';

        $response = new PageFetcherResponse($httpCode, $content);
        foreach ($headers as $header) {
            $response->addHeader(trim($header));
        }

        return $response;
    }

    /**
     * @var string My cookie file.
     */
    private $cookieFile;
}


<?php

namespace Encore\Wx\Element;

use wxMenuItem;
use Encore\Giml\ElementTrait;
use Encore\Wx\Element\Traits\Wx;
use Encore\Wx\Element\Traits\Events;
use Encore\Giml\ElementInterface;

class MenuItem implements ElementInterface
{
    use ElementTrait;
    use Events;
    use Wx;

    protected $events = [
        'onSelect' => wxEVT_COMMAND_MENU_SELECTED
    ];

    /**
     * Initialise the object
     *
     * @return void
     */
    public function init()
    {
        if ($this->type == 'separator') {
            return $this->parent->getRaw()->AppendSeparator();
        }

        $id = $this->collection->getTrueId($this->id);

        $title = "&{$this->title}";

        if ($this->shortcut) $title .= "\t{$this->shortcut}";

        $this->element = new wxMenuItem($this->parent->getRaw(), wxID_ANY, $title, $this->description, wxITEM_NORMAL);

        $this->bindEvents();

        $this->parent->getRaw()->Append($this->element);
    }

    /**
     * Get the menu item type
     *
     * @return integer
     */
    protected function getType()
    {
        switch ($this->type) {
            case 'about':
                return wxID_ABOUT;

            case 'exit':
                return wxID_EXIT;

            case 'preferences':
                return wxID_PREFERENCES;

            case 'help':
                return wxID_HELP;

            default:
                return wxID_ANY;
        }
    }
}


<?php

namespace Encore\Wx\Element;

use wxMenu;
use Encore\Giml\ElementTrait;
use Encore\Giml\ElementInterface;
use Encore\Wx\Element\Traits\Wx;

class Menu implements ElementInterface
{
    use ElementTrait;
    use Wx;

    /**
     * Initialise the object
     *
     * @return void
     */
    public function init()
    {
        $this->element = new wxMenu;

        $rawParent = $this->parent->getRaw();

        if ($rawParent instanceof wxMenuBar or $rawParent instanceof wxMenu) {
            $rawParent->Append($this->element, $this->title);
        }
    }
}


<?php

namespace DevGroup\ExtensionsManager\models;

use DevGroup\ExtensionsManager\ExtensionsManager;
use DevGroup\ExtensionsManager\commands\ExtensionController;
use Yii;

/**
 * Class ExtensionsConfiguration
 *
 * @package DevGroup\ExtensionsManager\models
 * @codeCoverageIgnore
 */
class ExtensionsConfiguration extends BaseConfigurationModel
{
    /**
     * @inheritdoc
     */
    public function getModuleClassName()
    {
        return ExtensionsManager::className();
    }

    public function rules()
    {
        return [
            [
                [
                    'extensionsStorage',
                    'packagistUrl',
                    'githubAccessToken',
                    'applicationName',
                    'githubApiUrl',
                    'composerPath'
                ],
                'string',
                'max' => 180
            ],
            [['extensionsPerPage', 'verbose'], 'integer'],
            [['packagistUrl', 'applicationName'], 'required'],
            [['extensionsStorage', 'packagistUrl', 'githubAccessToken', 'applicationName', 'githubApiUrl'], 'string'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'packagistUrl' => Yii::t('extensions-manager', 'Packagist URL'),
            'githubAccessToken' => Yii::t('extensions-manager', 'Github API access token'),
            'applicationName' => Yii::t('extensions-manager', 'Github application name'),
            'githubApiUrl' => Yii::t('extensions-manager', 'Github API URL'),
            'extensionsStorage' => Yii::t('extensions-manager', 'Extensions storage'),
            'extensionsPerPage' => Yii::t('extensions-manager', 'Extensions per page'),
            'composerPath' => Yii::t('extensions-manager', 'Path to Composer'),
            'verbose' => Yii::t('extensions-manager', 'Verbose output'),
        ];
    }

    /**
     * Returns array of module configuration that should be stored in application config.
     * Array should be ready to merge in app config.
     * Used both for web only.
     *
     * @return array
     */
    public function webApplicationAttributes()
    {
        return [];
    }

    /**
     * Returns array of module configuration that should be stored in application config.
     * Array should be ready to merge in app config.
     * Used both for console only.
     *
     * @return array
     */
    public function consoleApplicationAttributes()
    {
        return
            [
                'controllerMap' => [
                    'extension' => ExtensionController::class,
                ]
            ];
    }

    /**
     * Returns array of module configuration that should be stored in application config.
     * Array should be ready to merge in app config.
     * Used both for web and console.
     *
     * @return array
     */
    public function commonApplicationAttributes()
    {
        return [
            'components' => [
                'i18n' => [
                    'translations' => [
                        'extensions-manager' => [
                            'class' => 'yii\i18n\PhpMessageSource',
                            'basePath' => __DIR__ . '/messages',
                        ]
                    ]
                ],
            ],
            'modules' => [
                'extensions-manager' => [
                    'class' => ExtensionsManager::class,
                    'extensionsStorage' => $this->extensionsStorage,
                    'packagistUrl' => $this->packagistUrl,
                    'githubAccessToken' => $this->githubAccessToken,
                    'applicationName' => $this->applicationName,
                    'githubApiUrl' => $this->githubApiUrl,
                    'extensionsPerPage' => $this->extensionsPerPage,
                    'composerPath' => $this->composerPath,
                    'verbose' => $this->verbose,
                ]
            ],
        ];
    }

    /**
     * Returns array of key=>values for configuration.
     *
     * @return mixed
     */
    public function appParams()
    {
        return [];
    }

    /**
     * Returns array of aliases that should be set in common config
     *
     * @return array
     */
    public function aliases()
    {
        return [];
    }
}


<?php

namespace Encore\Wx\Element\Traits;

trait Options
{
    /**
     * Get a option constant from its name
     *
     * @param  string $option
     * @return integer
     */
    protected function getOption($option)
    {
        return in_array($option, $this->getOptions())
            ? $this->getOptions()[$option]
            : null;
    }

    /**
     * Get the option to constant map
     *
     * @return array
     */
    protected function getOptions()
    {
        return $this->options;
    }

    /**
     * Build the options constant using the bitwise operator
     *
     * @param  array $defaults
     * @return integer
     */
    protected function buildOptions(array $defaults = null)
    {
        $options = $this->getOptions();

        if ($defaults) $options = array_merge($defaults, $options);

        foreach ($options as $option) {
            if ( ! array_key_exists($option, $this->options)) continue;

            if ( ! isset($optionsBitwise)) {
                $optionsBitwise = $this->options[$option];
                continue;
            }

            $optionsBitwise = $optionsBitwise | $this->options[$option];
        }

        return isset($optionsBitwise) ? $optionsBitwise : null;
    }
}


<?php

/*
 * admin42
 *
 * @package admin42
 * @link https://github.com/kiwi-suite/admin42
 * @copyright Copyright (c) 2010 - 2017 kiwi suite (https://www.kiwi-suite.com)
 * @license MIT License
 * @author kiwi suite <tech@kiwi-suite.com>
 */

namespace Admin42\FormElements;

use Core42\Hydrator\Strategy\ArrayStrategy;
use Zend\Filter\Callback;
use Zend\Form\Element;
use Zend\Hydrator\Strategy\StrategyInterface;
use Zend\InputFilter\InputProviderInterface;
use Zend\Validator\Explode;
use Zend\Validator\InArray;

class MultiCheckbox extends Element implements AngularAwareInterface, InputProviderInterface, StrategyAwareInterface
{
    use ElementTrait;

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

    /**
     * @param array|\Traversable $options
     * @return $this
     */
    public function setOptions($options)
    {
        if (isset($options['values'])) {
            $this->setValueOptions($options['values']);
        }

        return $this;
    }

    /**
     * @return array
     */
    public function getValueOptions()
    {
        return $this->valueOptions;
    }

    /**
     * @param array $valueOptions
     * @return $this
     */
    public function setValueOptions(array $valueOptions)
    {
        $this->valueOptions = $valueOptions;

        return $this;
    }

    /**
     * Should return an array specification compatible with
     * {@link Zend\InputFilter\Factory::createInput()}.
     *
     * @return array
     */
    public function getInputSpecification()
    {
        $haystack = \array_keys($this->getValueOptions());

        return [
            'name' => $this->getName(),
            'required' => $this->isRequired(),
            'filters' => [
                [
                    'name' => Callback::class,
                    'options' => [
                        'callback' => function ($value) {
                            if (!\is_array($value)) {
                                return [];
                            }

                            return $value;
                        },
                    ],
                ],
            ],
            'validators' => [
                [
                    'name' => Explode::class,
                    'options' => [
                        'valueDelimiter' => null,
                        'validator' => [
                            'name' => InArray::class,
                            'options' => ['haystack' => $haystack],
                        ],
                    ],
                ],

            ],
        ];
    }

    /**
     * @param array $value
     * @return $this
     */
    public function setValue($value)
    {
        if (!\is_array($value)) {
            $value = [];
        }

        $this->value = \array_values($value);

        return $this;
    }

    /**
     * @return string|StrategyInterface
     */
    public function getStrategy()
    {
        return ArrayStrategy::class;
    }
}


<?php

/*
 * This file is part of the Securepass package.
 *
 * (c) Paolo Mainardi <paolo@twinbit.it>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Securepass;
use Guzzle\Common\Collection;
use Securepass\Exception\Exception as SecurepassException;
use Guzzle\Common\Exception\InvalidArgumentException;

class Securepass extends AbstractSecurepass {

 /**
  * User API callback
  *
  * @param string $type API call type
  * @param string $config API parameters
  *
  * @return array|null Response array
  * @throws InvalidArgumentException
  */
  public function user($type, $params = array()) {
    $command_mapping = array(
      'auth'      => 'UserAuth',
      'info'      => 'UserInfo',
      'add'       => 'UserAdd',
      'provision' => 'UserProvision',
      'list'      => 'UserList',
      'delete'    => 'UserDelete'
    );

    if (!isset($command_mapping[$type])) {
      throw new InvalidArgumentException(sprintf('"%s" is not a valid user command.', $type));
    }

    // check if exists a specific implementation for this command
    $override_func = 'user' . ucfirst($type);
    if (function_exists($override_func)) {
      return $override_func($params);
    }

    $command = $this->client->getCommand($command_mapping[$type], $params);
    return $this->execute($command);
  }

  /**
  * Ping Securepass API
  *
  * @return array|null Response array
  */
  public function ping()
  {
    $command = $this->client->getCommand('Ping');
    $res = $this->execute($command);
    return $res;
  }

}


<?php

namespace Encore\Wx\Element;

use wxBoxSizer;
use Encore\Giml\ElementTrait;
use Encore\Wx\Element\Traits\Wx;
use Encore\Giml\ElementInterface;

class BoxSizer implements ElementInterface
{
    use ElementTrait;
    use Wx;

    /**
     * Initialise the object
     *
     * @return void
     */
    public function init()
    {
        $this->element = new wxBoxSizer($this->orientation == 'horizontal'
            ? wxHORIZONTAL
            : wxVERTICAL);

        if ($this->parent instanceof Frame) {
            $this->parent->getRaw()->SetSizer($this->getRaw());
        } elseif ($this->parent instanceof static) {
            $this->parent->getRaw()->Add($this->getRaw());
        }
    }

    /**
     * Set the an element attribute
     *
     * @param string $key
     * @param mixed $value
     */
    public function setAttribute($key, $value)
    {
        switch ($key) {
            case 'orientation':
                $this->attributes[$key] =
                    $value == 'horizontal' ?
                    wxHORIZONTAL :
                    wxVERTICAL
                ;
            default:
                $this->attributes[$key] = $value;
            break;
        }
    }
}


<?php namespace Votemike\Money;

use DomainException;
use InvalidArgumentException;
use Symfony\Component\Intl\Intl;
use Symfony\Component\Intl\NumberFormatter\NumberFormatter;

class Money
{
    /**
     * @var float
     */
    private $amount;
    /**
     * @var string
     */
    private $currency;

    /**
     * @param float|int|string $amount
     * @param string $currency
     */
    public function __construct($amount, string $currency)
    {
        if (!is_numeric($amount)) {
            throw new InvalidArgumentException('Money only accepts numeric amounts');
        }

        if (!array_key_exists($currency, Intl::getCurrencyBundle()->getCurrencyNames())) {
            throw new InvalidArgumentException($currency . ' is not a supported currency');
        }
        $this->amount = (float)$amount;
        $this->currency = $currency;
    }

    public function __toString(): string
    {
        return $this->format();
    }

    /**
     * Returns a positive clone of Money object
     */
    public function abs(): Money
    {
        return new static(abs($this->amount), $this->currency);
    }

    public function add(Money $money): Money
    {
        $this->assertCurrencyMatches($money);

        return new static($this->amount + $money->getAmount(), $this->currency);
    }

    /**
     * @param float $operator
     * @return static
     */
    public function divide($operator): Money
    {
        if ($operator == 0) {
            throw new InvalidArgumentException('Cannot divide by zero');
        }
        return new static($this->amount / $operator, $this->currency);
    }

    /**
     * Returns a rounded string with the currency symbol
     *
     * @param bool $displayCountryForUS Set to true if you would like 'US$' instead of just '$'
     * @return string
     */
    public function format(bool $displayCountryForUS = false): string
    {
        $formatter = new NumberFormatter('en', NumberFormatter::CURRENCY);

        if ($displayCountryForUS && $this->currency === 'USD') {
            if ($this->amount >= 0) {
                return 'US' . $formatter->formatCurrency($this->amount, $this->currency);
            }
            return '-US' . $formatter->formatCurrency(-$this->amount, $this->currency);
        }
        return $formatter->formatCurrency($this->amount, $this->currency);
    }

    /**
     * Returns a rounded number without currency
     * If the number is negative, the currency is within parentheses
     */
    public function formatForAccounting(): string
    {
        $amount = $this->getRoundedAmount();
        $negative = 0 > $amount;
        if ($negative) {
            $amount *= -1;
        }
        $amount = number_format($amount, Intl::getCurrencyBundle()->getFractionDigits($this->currency));
        return $negative ? '(' . $amount . ')' : $amount;
    }

    /**
     * Returns a string consisting of the currency symbol, a rounded int and a suffix
     * e.g. $33k instead of $3321.12
     */
    public function formatShorthand(): string
    {
        $amount = $this->amount;
        $negative = 0 > $amount;
        if ($negative) {
            $amount *= -1;
        }
        $units = ['', 'k', 'm', 'bn', 'tn'];
        $power = $amount > 0 ? floor(log(round($amount), 1000)) : 0;
        $ret = Intl::getCurrencyBundle()->getCurrencySymbol($this->currency, 'en').round($amount / pow(1000, $power), 0). $units[$power];
        return $negative ? '-'.$ret : $ret;
    }

    /**
     * The same as format() except that positive numbers always include the + sign
     *
     * @param bool $displayCountryForUS Set to true if you would like 'US$' instead of just '$'
     * @return string
     */
    public function formatWithSign(bool $displayCountryForUS = false): string
    {
        $string = $this->format($displayCountryForUS);

        if ($this->amount <= 0) {
            return $string;
        }

        return '+' . $string;
    }

    public function getAmount(): float
    {
        return $this->amount;
    }

    public function getCurrency(): string
    {
        return $this->currency;
    }

    /**
     * Returns the amount rounded to the correct number of decimal places for that currency
     */
    public function getRoundedAmount(): float
    {
        $fractionDigits = Intl::getCurrencyBundle()->getFractionDigits($this->currency);
        $roundingIncrement = Intl::getCurrencyBundle()->getRoundingIncrement($this->currency);

        $value = round($this->amount, $fractionDigits);

        // Swiss rounding
        if (0 < $roundingIncrement && 0 < $fractionDigits) {
            $roundingFactor = $roundingIncrement / pow(10, $fractionDigits);
            $value = round($value / $roundingFactor) * $roundingFactor;
        }

        return $value;
    }

    /**
     * Invert the amount
     */
    public function inv(): Money
    {
        return new static(-$this->amount, $this->currency);
    }

    /**
     * @param float $operator
     * @return static
     */
    public function multiply($operator): Money
    {
        return new static($this->amount * $operator, $this->currency);
    }

    /**
     * A number between 0 and 100
     *
     * @param float $percentage
     * @return static
     */
    public function percentage($percentage): Money
    {
        return new static(($this->amount * $percentage) / 100, $this->currency);
    }

    /**
     * Returns rounded clone of Money object, rounded to the correct number of decimal places for that currency
     */
    public function round(): Money
    {
        return new static($this->getRoundedAmount(), $this->currency);
    }

    /**
     * Pass in an array of percentages to allocate Money in those amounts.
     * Final entry in array gets any remaining units.
     * If the percentages total less than 100, remaining money is allocated to an extra return value.
     *
     * By default, the amounts are rounded to the correct number of decimal places for that currency. This can be disabled by passing false as the second argument.
     *
     * @param float[] $percentages An array of percentages that must total 100 or less
     * @param bool $round
     * @return Money[]
     */
    public function split(array $percentages, bool $round = true): array
    {
        $totalPercentage = array_sum($percentages);
        if ($totalPercentage > 100) {
            throw new InvalidArgumentException('Only 100% can be allocated');
        }
        $amounts = [];
        $total = 0;
        if (!$round) {
            foreach ($percentages as $percentage) {
                $share = $this->percentage($percentage);
                $total += $share->getAmount();
                $amounts[] = $share;
            }
            if ($totalPercentage != 100) {
                $amounts[] = new static($this->amount - $total, $this->currency);
            }
            return $amounts;
        }

        $count = 0;

        if ($totalPercentage != 100) {
            $percentages[] = 0; //Dummy record to trigger the rest of the amount being assigned to a final pot
        }

        foreach ($percentages as $percentage) {
            ++$count;
            if ($count == count($percentages)) {
                $amounts[] = new static($this->amount - $total, $this->currency);
            } else {
                $share = $this->percentage($percentage)->round();
                $total += $share->getAmount();
                $amounts[] = $share;
            }
        }

        return $amounts;
    }

    /**
     * @param Money $money
     * @return static
     */
    public function sub(Money $money): Money
    {
        $this->assertCurrencyMatches($money);

        return new static($this->amount - $money->getAmount(), $this->currency);
    }

    /**
     * @param Money $money
     */
    private function assertCurrencyMatches(Money $money)
    {
        if ($this->currency !== $money->getCurrency()) {
            throw new DomainException('Currencies must match');
        }
    }
}