<?php

namespace Scriptura\Color\Types;

use function Scriptura\Color\Helpers\HEXtoRGB;
use function Scriptura\Color\Helpers\RGBtoHSL;
use function Scriptura\Color\Helpers\RGBtoC256;
use Scriptura\Color\Color;
use Scriptura\Color\Exceptions\InvalidArgument;

class HEX implements Color
{
    /**
     * @var string (000000-FFFFFF)
     */
    private $code;

    /**
     * @var string
     */
    private $template = '#{code}';

    /**
     * Hex constructor.
     *
     * @param string $code
     * @param null|string $template
     *
     * @throws InvalidArgument
     */
    public function __construct($code = '000000', $template = null)
    {
        if (! $this->isHexColor($code)) {
            throw new InvalidArgument("Hex value was expected but [{$code}] was given.");
        }

        if ($template) {
            $this->template = $template;
        }

        $this->code = $this->sanitize($code);
    }

    /**
     * @return string
     */
    public function code()
    {
        return $this->code;
    }

    /**
     * Get a new instance with a new template.
     *
     * @param string $template
     *
     * @return static
     */
    public function withTemplate($template)
    {
        return new static($this->code(), $template);
    }

    /**
     * Get color in HEX.
     *
     * @return HEX
     */
    public function toHEX()
    {
        return new self($this->code());
    }

    /**
     * Get color in RGB.
     *
     * @return RGB
     */
    public function toRGB()
    {
        return new RGB(...HEXtoRGB($this->code()));
    }

    /**
     * Get color in HSL.
     *
     * @return HSL
     */
    public function toHSL()
    {
        return new HSL(...RGBtoHSL(...HEXtoRGB($this->code())));
    }

    /**
     * Get color in 256.
     *
     * @return C256
     */
    public function to256()
    {
        return new C256(RGBtoC256(...HEXtoRGB($this->code())));
    }

    /**
     * Cast to string.
     *
     * @return string
     */
    public function __toString()
    {
        return str_replace(
            [
                '{code}',
            ],
            [
                $this->code(),
            ],
            $this->template
        );
    }

    /**
     * @param string $value
     *
     * @return bool
     */
    private function isHexColor($value)
    {
        $value = ltrim((string) $value, '#');

        if (ctype_xdigit($value) && (strlen($value) == 6 || strlen($value) == 3)) {
            return true;
        }

        return false;
    }

    /**
     * @param string $value
     *
     * @return string
     */
    private function sanitize($value)
    {
        $value = (string) $value;
        $value = ltrim($value, '#');
        $value = strtoupper($value);

        if (strlen($value) === 3) {
            $value = $value[0] . $value[0] . $value[1] . $value[1] . $value[2] . $value[2];
        }

        return $value;
    }
}


<?php
namespace Perry\Representation\Eve\v1;

use \Perry\Representation\Reference as Reference;
use \Perry\Representation\Uri as Uri;
use \Perry\Representation\Base as Base;

class IndustrySpeciality extends Base
{
    public $id;

    public $groups = [];

    public $name;

    // by Warringer\Types\Long
    public function setId($id)
    {
        $this->id = $id;
    }

    // by Warringer\Types\ArrayType
    public function setGroups($groups)
    {
        // by Warringer\Types\Dict
        $converters = [];
        $converters['id'] = function ($value) { return $value; };

        $func = function ($value) use($converters) {
            $return = new \ArrayObject($value, \ArrayObject::ARRAY_AS_PROPS);
            $return['id'] = isset($value->{'id'}) ? $converters['id']($value->{'id'}) : null;
            return $return;
        };

        foreach ($groups as $key => $value) {
            $this->groups[$key] = $func($value);
        }
    }

    // by Warringer\Types\String
    public function setName($name)
    {
        $this->name = $name;
    }

}


<?php

/*
 * This file is part of the Ivory Google Map package.
 *
 * (c) Eric GELOEN <geloen.eric@gmail.com>
 *
 * For the full copyright and license information, please read the LICENSE
 * file that was distributed with this source code.
 */

namespace Ivory\GoogleMap\Helper\Controls;

use Ivory\GoogleMap\Controls\RotateControl;
use Ivory\GoogleMap\Helper\AbstractHelper;

/**
 * Rotate control helper.
 *
 * @author GeLo <geloen.eric@gmail.com>
 */
class RotateControlHelper extends AbstractHelper
{
    /** @var \Ivory\GoogleMap\Helper\Controls\ControlPositionHelper */
    protected $controlPositionHelper;

    /**
     * Creates a rotate control helper.
     *
     * @param \Ivory\GoogleMap\Helper\Controls\ControlPositionHelper $controlPositionHelper The control position helper.
     */
    public function __construct(ControlPositionHelper $controlPositionHelper = null)
    {
        parent::__construct();

        if ($controlPositionHelper === null) {
            $controlPositionHelper = new ControlPositionHelper();
        }

        $this->setControlPositionHelper($controlPositionHelper);
    }

    /**
     * Gets the control position helper.
     *
     * @return \Ivory\GoogleMap\Helper\Controls\ControlPositionHelper The control position helper.
     */
    public function getControlPositionHelper()
    {
        return $this->controlPositionHelper;
    }

    /**
     * Sets the control position helper.
     *
     * @param \Ivory\GoogleMap\Helper\Controls\ControlPositionHelper $controlPositionHelper The control position helper.
     */
    public function setControlPositionHelper(ControlPositionHelper $controlPositionHelper)
    {
        $this->controlPositionHelper = $controlPositionHelper;
    }

    /**
     * Renders a rotate control.
     *
     * @param \Ivory\GoogleMap\Controls\RotateControl $rotateControl The rotate control.
     *
     * @return string The JS output.
     */
    public function render(RotateControl $rotateControl)
    {
        return $this->jsonBuilder
            ->reset()
            ->setValue('[position]', $this->controlPositionHelper->render($rotateControl->getControlPosition()), false)
            ->build();
    }
}


<?php
namespace Perry\Representation\Eve\v1;

use \Perry\Representation\Reference as Reference;
use \Perry\Representation\Uri as Uri;
use \Perry\Representation\Base as Base;

class IndustryTeamCollection extends Base
{
    public $pageCount;

    public $items = [];

    public $totalCount;

    public $next;

    public $previous;

    // by Warringer\Types\Long
    public function setPageCount($pageCount)
    {
        $this->pageCount = $pageCount;
    }

    // by Warringer\Types\ArrayType
    public function setItems($items)
    {
        // by Warringer\Types\Base
        $converters = [];
        $converters['solarSystem'] = function ($value) { return $value; };
        $converters['specialization'] = function ($value) { return $value; };
        $converters['creationTime'] = function ($value) { return $value; };
        $converters['workers'] = function ($values) {
        // by Warringer\Types\Dict
        $converters = [];
        $converters['bonus'] = function ($value) { return $value; };
        $converters['specialization'] = function ($value) { return $value; };

        $func = function ($value) use($converters) {
            $return = new \ArrayObject($value, \ArrayObject::ARRAY_AS_PROPS);
            $return['bonus'] = isset($value->{'bonus'}) ? $converters['bonus']($value->{'bonus'}) : null;
            $return['specialization'] = isset($value->{'specialization'}) ? $converters['specialization']($value->{'specialization'}) : null;
            return $return;
        };

            foreach ($values as $key => $value) {
                 $values[$key] = $func($value);
            }
           return $values;
        };

        $converters['expiryTime'] = function ($value) { return $value; };
        $converters['solarSystemBids'] = function ($values) {
        // by Warringer\Types\Dict
        $converters = [];
        $converters['characterBids'] = function ($values) {
        // by Warringer\Types\Dict
        $converters = [];
        $converters['character'] = function ($value) { return $value; };
        $converters['bidAmount'] = function ($value) { return $value; };

        $func = function ($value) use($converters) {
            $return = new \ArrayObject($value, \ArrayObject::ARRAY_AS_PROPS);
            $return['character'] = isset($value->{'character'}) ? $converters['character']($value->{'character'}) : null;
            $return['bidAmount'] = isset($value->{'bidAmount'}) ? $converters['bidAmount']($value->{'bidAmount'}) : null;
            return $return;
        };

            foreach ($values as $key => $value) {
                 $values[$key] = $func($value);
            }
           return $values;
        };

        $converters['solarSystem'] = function ($value) { return $value; };
        $converters['bidAmount'] = function ($value) { return $value; };

        $func = function ($value) use($converters) {
            $return = new \ArrayObject($value, \ArrayObject::ARRAY_AS_PROPS);
            $return['characterBids'] = isset($value->{'characterBids'}) ? $converters['characterBids']($value->{'characterBids'}) : null;
            $return['solarSystem'] = isset($value->{'solarSystem'}) ? $converters['solarSystem']($value->{'solarSystem'}) : null;
            $return['bidAmount'] = isset($value->{'bidAmount'}) ? $converters['bidAmount']($value->{'bidAmount'}) : null;
            return $return;
        };

            foreach ($values as $key => $value) {
                 $values[$key] = $func($value);
            }
           return $values;
        };

        $converters['auctionExpiryTime'] = function ($value) { return $value; };
        $converters['activity'] = function ($value) { return $value; };
        $converters['costModifier'] = function ($value) { return $value; };
        $converters['id'] = function ($value) { return $value; };
        $converters['name'] = function ($value) { return $value; };

        $func = function ($value) use($converters) {
            $return = new \ArrayObject($value, \ArrayObject::ARRAY_AS_PROPS);
            $return['solarSystem'] = isset($value->{'solarSystem'}) ? $converters['solarSystem']($value->{'solarSystem'}) : null;
            $return['specialization'] = isset($value->{'specialization'}) ? $converters['specialization']($value->{'specialization'}) : null;
            $return['creationTime'] = isset($value->{'creationTime'}) ? $converters['creationTime']($value->{'creationTime'}) : null;
            $return['workers'] = isset($value->{'workers'}) ? $converters['workers']($value->{'workers'}) : null;
            $return['expiryTime'] = isset($value->{'expiryTime'}) ? $converters['expiryTime']($value->{'expiryTime'}) : null;
            $return['solarSystemBids'] = isset($value->{'solarSystemBids'}) ? $converters['solarSystemBids']($value->{'solarSystemBids'}) : null;
            $return['auctionExpiryTime'] = isset($value->{'auctionExpiryTime'}) ? $converters['auctionExpiryTime']($value->{'auctionExpiryTime'}) : null;
            $return['activity'] = isset($value->{'activity'}) ? $converters['activity']($value->{'activity'}) : null;
            $return['costModifier'] = isset($value->{'costModifier'}) ? $converters['costModifier']($value->{'costModifier'}) : null;
            $return['id'] = isset($value->{'id'}) ? $converters['id']($value->{'id'}) : null;
            $return['name'] = isset($value->{'name'}) ? $converters['name']($value->{'name'}) : null;
            return $return;
        };

        foreach ($items as $key => $value) {
            $this->items[$key] = $func($value);
        }
    }

    // by Warringer\Types\Long
    public function setTotalCount($totalCount)
    {
        $this->totalCount = $totalCount;
    }

    // by Warringer\Types\Reference
    public function setNext($next)
    {
        $this->next = new Reference($next);
    }

    // by Warringer\Types\Reference
    public function setPrevious($previous)
    {
        $this->previous = new Reference($previous);
    }

}


<?php
/**
 * HTML entity utilities.
 *
 * @author @jaswrks
 * @copyright WebSharks™
 */
declare(strict_types=1);
namespace WebSharks\Core\Classes\Core\Utils;

use WebSharks\Core\Classes;
use WebSharks\Core\Interfaces;
use WebSharks\Core\Traits;
#
use WebSharks\Core\Classes\Core\Error;
use WebSharks\Core\Classes\Core\Base\Exception;
#
use function assert as debug;
use function get_defined_vars as vars;

/**
 * HTML entity utilities.
 *
 * @since 150424 Initial release.
 */
class HtmlEntities extends Classes\Core\Base\Core
{
    /**
     * Escape HTML markup deeply.
     *
     * @since 150424 Initial release.
     *
     * @param mixed    $value         Any input value.
     * @param bool     $double_encode Encode existing entities? Defaults to `FALSE`.
     * @param int|null $flags         Optional. Defaults to `ENT_HTML5 | ENT_QUOTES | ENT_SUBSTITUTE`.
     *
     * @return string|array|object Value after having been escaped deeply.
     */
    public function encode($value, bool $double_encode = false, int $flags = null)
    {
        if (is_array($value) || is_object($value)) {
            foreach ($value as $_key => &$_value) {
                $_value = $this->encode($_value, $double_encode, $flags);
            } // unset($_key, $_value); // Housekeeping.
            return $value;
        }
        if (!($string = (string) $value)) {
            return $string; // Nothing to do.
        }
        if (!isset($flags)) {
            $flags = ENT_HTML5 | ENT_QUOTES | ENT_SUBSTITUTE;
        }
        return htmlspecialchars($string, $flags, 'UTF-8', $double_encode);
    }

    /**
     * Unescape HTML markup deeply.
     *
     * @since 150424 Initial release.
     *
     * @param mixed $value Any input value.
     * @param int   $flags Optional. Defaults to `ENT_HTML5 | ENT_QUOTES`.
     *
     * @return string|array|object Value after having been unescaped deeply.
     */
    public function decode($value, int $flags = null)
    {
        if (is_array($value) || is_object($value)) {
            foreach ($value as $_key => &$_value) {
                $_value = $this->decode($_value, $flags);
            } // unset($_key, $_value);
            return $value;
        }
        if (!($string = (string) $value)) {
            return $string; // Nothing to do.
        }
        if (!isset($flags)) {
            $flags = ENT_HTML5 | ENT_QUOTES;
        }
        return html_entity_decode($string, $flags, 'UTF-8');
    }
}


<?php
declare(strict_types=1);
namespace RabbitCMS\Modules;

use Illuminate\Foundation\Application;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Route;
use RabbitCMS\Modules\Support\ModuleConcerns;

/**
 * Class ModuleController.
 * @package RabbitCMS\Modules
 * @deprecated
 */
abstract class ModuleController extends BaseController
{
    use ModuleConcerns;

    /**
     * Page cache in seconds.
     *
     * @var int
     */
    protected $cache = 0;

    /**
     * @var Application
     */
    protected $app;

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

        if (method_exists($this, 'init')) {
            $this->app->call([$this, 'init']);
        }
    }

    /**
     * Execute an action on the controller.
     *
     * @param  string $method
     * @param  array  $parameters
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function callAction($method, $parameters)
    {
        if (method_exists($this, 'before')) {
            $this->app->call([$this, 'before'], ['method' => $method]);
        }

        $response = parent::callAction($method, $parameters);

        if ($this->cache > 0) {
            $response = Route::prepareResponse(App::make('request'), $response);
            $response->headers->addCacheControlDirective('public');
            $response->headers->addCacheControlDirective('max-age', (int)$this->cache);
        }

        return $response;
    }

}


<?php
namespace Perry\Representation\Eve\v1;

use \Perry\Representation\Reference as Reference;
use \Perry\Representation\Uri as Uri;
use \Perry\Representation\Base as Base;

class War extends Base
{
    public $timeFinished;

    public $openForAllies;

    public $allies = [];

    public $timeStarted;

    public $allyCount;

    public $timeDeclared;

    public $aggressor;

    public $mutual;

    public $killmails;

    public $timeRetracted;

    public $defender;

    public $id;

    // by Warringer\Types\String
    public function setTimeFinished($timeFinished)
    {
        $this->timeFinished = $timeFinished;
    }

    // by Warringer\Types\Base
    public function setOpenForAllies($openForAllies)
    {
        $this->openForAllies = $openForAllies;
    }

    // by Warringer\Types\ArrayType
    public function setAllies($allies)
    {
        // by Warringer\Types\Dict
        $converters = [];
        $converters['href'] = function ($value) { return new Uri($value); };
        $converters['id'] = function ($value) { return $value; };
        $converters['name'] = function ($value) { return $value; };
        $converters['icon'] = function ($value) { return new Reference($value); };

        $func = function ($value) use($converters) {
            $return = new \ArrayObject($value, \ArrayObject::ARRAY_AS_PROPS);
            $return['href'] = isset($value->{'href'}) ? $converters['href']($value->{'href'}) : null;
            $return['id'] = isset($value->{'id'}) ? $converters['id']($value->{'id'}) : null;
            $return['name'] = isset($value->{'name'}) ? $converters['name']($value->{'name'}) : null;
            $return['icon'] = isset($value->{'icon'}) ? $converters['icon']($value->{'icon'}) : null;
            return $return;
        };

        foreach ($allies as $key => $value) {
            $this->allies[$key] = $func($value);
        }
    }

    // by Warringer\Types\String
    public function setTimeStarted($timeStarted)
    {
        $this->timeStarted = $timeStarted;
    }

    // by Warringer\Types\Long
    public function setAllyCount($allyCount)
    {
        $this->allyCount = $allyCount;
    }

    // by Warringer\Types\String
    public function setTimeDeclared($timeDeclared)
    {
        $this->timeDeclared = $timeDeclared;
    }

    // by Warringer\Types\Dict
    public function setAggressor($aggressor)
    {
        // by Warringer\Types\Dict
        $converters = [];
        $converters['shipsKilled'] = function ($value) { return $value; };
        $converters['name'] = function ($value) { return $value; };
        $converters['href'] = function ($value) { return new Uri($value); };
        $converters['icon'] = function ($value) { return new Reference($value); };
        $converters['id'] = function ($value) { return $value; };
        $converters['iskKilled'] = function ($value) { return $value; };

        $func = function ($value) use($converters) {
            $return = new \ArrayObject($value, \ArrayObject::ARRAY_AS_PROPS);
            $return['shipsKilled'] = isset($value->{'shipsKilled'}) ? $converters['shipsKilled']($value->{'shipsKilled'}) : null;
            $return['name'] = isset($value->{'name'}) ? $converters['name']($value->{'name'}) : null;
            $return['href'] = isset($value->{'href'}) ? $converters['href']($value->{'href'}) : null;
            $return['icon'] = isset($value->{'icon'}) ? $converters['icon']($value->{'icon'}) : null;
            $return['id'] = isset($value->{'id'}) ? $converters['id']($value->{'id'}) : null;
            $return['iskKilled'] = isset($value->{'iskKilled'}) ? $converters['iskKilled']($value->{'iskKilled'}) : null;
            return $return;
        };
        $this->aggressor = $func($aggressor);
    }

    // by Warringer\Types\Base
    public function setMutual($mutual)
    {
        $this->mutual = $mutual;
    }

    // by Warringer\Types\Uri
    public function setKillmails($killmails)
    {
        $this->killmails = new Uri($killmails);
    }

    // by Warringer\Types\String
    public function setTimeRetracted($timeRetracted)
    {
        $this->timeRetracted = $timeRetracted;
    }

    // by Warringer\Types\Dict
    public function setDefender($defender)
    {
        // by Warringer\Types\Dict
        $converters = [];
        $converters['shipsKilled'] = function ($value) { return $value; };
        $converters['name'] = function ($value) { return $value; };
        $converters['href'] = function ($value) { return new Uri($value); };
        $converters['icon'] = function ($value) { return new Reference($value); };
        $converters['id'] = function ($value) { return $value; };
        $converters['iskKilled'] = function ($value) { return $value; };

        $func = function ($value) use($converters) {
            $return = new \ArrayObject($value, \ArrayObject::ARRAY_AS_PROPS);
            $return['shipsKilled'] = isset($value->{'shipsKilled'}) ? $converters['shipsKilled']($value->{'shipsKilled'}) : null;
            $return['name'] = isset($value->{'name'}) ? $converters['name']($value->{'name'}) : null;
            $return['href'] = isset($value->{'href'}) ? $converters['href']($value->{'href'}) : null;
            $return['icon'] = isset($value->{'icon'}) ? $converters['icon']($value->{'icon'}) : null;
            $return['id'] = isset($value->{'id'}) ? $converters['id']($value->{'id'}) : null;
            $return['iskKilled'] = isset($value->{'iskKilled'}) ? $converters['iskKilled']($value->{'iskKilled'}) : null;
            return $return;
        };
        $this->defender = $func($defender);
    }

    // by Warringer\Types\Long
    public function setId($id)
    {
        $this->id = $id;
    }

}


<?php

/*
 * This file is part of the Ivory Google Map package.
 *
 * (c) Eric GELOEN <geloen.eric@gmail.com>
 *
 * For the full copyright and license information, please read the LICENSE
 * file that was distributed with this source code.
 */

namespace Ivory\GoogleMap\Helper\Layers;

use Ivory\GoogleMap\Helper\AbstractHelper;
use Ivory\GoogleMap\Layers\KMLLayer;
use Ivory\GoogleMap\Map;

/**
 * KML Layer helper.
 *
 * @author GeLo <geloen.eric@gmail.com>
 */
class KMLLayerHelper extends AbstractHelper
{
    /**
     * Renders a kml layer.
     *
     * @param \Ivory\GoogleMap\Layers\KMLLayer $kmlLayer The KML layer.
     * @param \Ivory\GoogleMap\Map             $map      The map.
     *
     * @return string The JS output.
     */
    public function render(KMLLayer $kmlLayer, Map $map)
    {
        $this->jsonBuilder
            ->reset()
            ->setValue('[map]', $map->getJavascriptVariable(), false)
            ->setValues($kmlLayer->getOptions());

        return sprintf(
            '%s = new google.maps.KmlLayer("%s", %s);'.PHP_EOL,
            $kmlLayer->getJavascriptVariable(),
            $kmlLayer->getUrl(),
            $this->jsonBuilder->build()
        );
    }
}


<?php
/**
 * Memcache utilities.
 *
 * @author @jaswrks
 * @copyright WebSharks™
 */
declare(strict_types=1);
namespace WebSharks\Core\Classes\Core\Utils;

use WebSharks\Core\Classes;
use WebSharks\Core\Interfaces;
use WebSharks\Core\Traits;
#
use WebSharks\Core\Classes\Core\Error;
use WebSharks\Core\Classes\Core\Base\Exception;
#
use function assert as debug;
use function get_defined_vars as vars;

/**
 * Memcache utilities.
 *
 * @since 151216 Memcache utils.
 */
class Memcache extends Classes\Core\Base\Core
{
    /**
     * Pool.
     *
     * @since 151216
     *
     * @type \Memcached
     */
    protected $Pool;

    /**
     * Enable?
     *
     * @since 151216
     *
     * @type bool
     */
    protected $enabled;

    /**
     * Namespace.
     *
     * @since 151216
     *
     * @type string
     */
    protected $namespace;

    /**
     * Servers.
     *
     * @since 151216
     *
     * @type array
     */
    protected $servers;

    /**
     * Max attempts.
     *
     * @since 151216
     *
     * @type int
     */
    const MAX_WRITE_ATTEMPTS = 5;

    /**
     * Class constructor.
     *
     * @since 151216 Memcache utils.
     *
     * @param Classes\App $App Instance of App.
     */
    public function __construct(Classes\App $App)
    {
        parent::__construct($App);

        if (!($extension_loaded = extension_loaded('memcached'))) {
            $this->enabled = false; // Not possible.
            return; // Not possible; extension missing.
        }
        $this->enabled = $this->App->Config->©memcache['©enabled'];
        $this->enabled = $this->enabled ?? $extension_loaded;

        $this->namespace = $this->App->Config->©memcache['©namespace'];
        $this->servers   = $active_servers   = []; // Initialize.

        foreach ($this->App->Config->©memcache['©servers'] as $_server) {
            $_host                            = $_server['©host'];
            $_port                            = $_server['©port'] ?? 11211;
            $_weight                          = $_server['©weight'] ?? 0;
            $this->servers[$_host.':'.$_port] = [$_host, $_port, $_weight];
        } // unset($_server, $_host, $_port, $_weight);

        if (!$this->enabled || !$this->namespace || !$this->servers) {
            $this->enabled = false; // Not possible.
            return; // Disabled or lacking config values.
        }
        try { // Catch exceptions on init and fail gracefully.
            // This also covers a scenario where the extension is loaded in PHP,
            // but the `memcached` binary is not actually available on the server.
            $this->Pool = new \Memcached($this->App->namespace_sha1);
            $this->maybeAddServerConnections();
            //
        } catch (\Throwable $Exception) {
            $this->enabled = false; // Not possible.
            $this->c::issue(vars(), 'Memcached init failure. '.$Exception->getMessage());
        }
    }

    /**
     * Memcache enabled?
     *
     * @since 170215.53419 Memcache utils.
     *
     * @return bool True if enabled.
     */
    public function enabled(): bool
    {
        return $this->enabled;
    }

    /**
     * Memcache info.
     *
     * @since 170215.53419 Memcache utils.
     *
     * @return array Stats/keys/etc.
     */
    public function info(): array
    {
        if (!$this->enabled) {
            return []; // Not possible.
        }
        return [
            'stats' => $this->Pool->getStats() ?: [],
            'keys'  => $this->Pool->getAllKeys() ?: [],
            // NOTE: `getAllKeys()` returns `false` on some servers.
            // There is a bug in the libmemcached library that makes it unreliable.
            // See: <https://github.com/php-memcached-dev/php-memcached/issues/203>
        ];
    }

    /**
     * Get cache value by key.
     *
     * @since 151216 Memcache utils.
     *
     * @param string     $primary_key Primary key.
     * @param string|int $sub_key     Sub-key to get.
     *
     * @return mixed|null Null if missing, or on failure.
     */
    public function get(string $primary_key, $sub_key)
    {
        if (!$this->enabled) {
            return; // Not possible.
            //
        } elseif (!($key = $this->key($primary_key, $sub_key))) {
            return; // Fail; e.g., race condition.
        }
        $value = $this->Pool->get($key); // Possibly `false`.
        // See: <http://php.net/manual/en/memcached.get.php#92275>

        if ($this->Pool->getResultCode() === \Memcached::RES_SUCCESS) {
            return $value; // Return the value.
        }
    }

    /**
     * Set|update cache key.
     *
     * @since 151216 Memcache utils.
     *
     * @param string     $primary_key Primary key.
     * @param string|int $sub_key     Sub-key to set.
     * @param string     $value       Value to cache (1MB max).
     * @param int        $expires_in  Expires (in seconds).
     *
     * @return bool True on success.
     */
    public function set(string $primary_key, $sub_key, $value, int $expires_in = 0): bool
    {
        if (!$this->enabled) {
            return false; // Not possible.
        }
        $expires_in = max(0, $expires_in);
        $expires    = $expires_in ? time() + $expires_in : 0;

        if (!($key = $this->key($primary_key, $sub_key))) {
            return false; // Fail; e.g., race condition.
            //
        } elseif ($value === null || is_resource($value)) {
            throw $this->c::issue('Incompatible data type.');
        }
        do { // Avoid race issues.
            $cas      = $cas ?? 0;
            $attempts = $attempts ?? 0;
            ++$attempts; // Counter.

            $this->Pool->get($key, null, $cas);

            if ($this->Pool->getResultCode() === \Memcached::RES_NOTFOUND) {
                if ($this->Pool->add($key, $value, $expires)) {
                    return true; // All good; stop here.
                }
            } elseif ($this->Pool->cas($cas, $key, $value, $expires)) {
                return true; // All good; stop here.
            }
            $result_code = $this->Pool->getResultCode();
            //
        } while ($attempts < $this::MAX_WRITE_ATTEMPTS // Give up after X attempts.
                && ($result_code === \Memcached::RES_NOTSTORED || $result_code === \Memcached::RES_DATA_EXISTS));

        return false; // Fail; e.g., race condition or unexpected error.
    }

    /**
     * Touch a cache key (i.e., new expiration).
     *
     * @since 151216 Memcache utils.
     *
     * @param string     $primary_key Primary key.
     * @param string|int $sub_key     Sub-key to touch.
     * @param int        $expires_in  Expires (in seconds).
     *
     * @return bool True on success.
     */
    public function touch(string $primary_key, $sub_key, int $expires_in): bool
    {
        if (!$this->enabled) {
            return false; // Not possible.
        }
        $expires_in = max(0, $expires_in);
        $expires    = $expires_in ? time() + $expires_in : 0;

        if (!($key = $this->key($primary_key, $sub_key))) {
            return false; // Fail; e.g., race condition.
        }
        return $this->Pool->touch($key, $expires);
    }

    /**
     * Clear the cache.
     *
     * @since 151216 Memcache utils.
     *
     * @param string          $primary_key Primary key.
     * @param string|int|null $sub_key     Sub-key (optional).
     * @param int             $delay       Delay (in seconds).
     *
     * @return bool True on success.
     */
    public function clear(string $primary_key, $sub_key = null, int $delay = 0): bool
    {
        if (!$this->enabled) {
            return false; // Not possible.
        }
        if (!isset($sub_key)) {
            $key = $this->nspKey($primary_key);
        } else {
            $key = $this->key($primary_key, $sub_key);
        }
        return $key && $this->Pool->delete($key, $delay);
    }

    /**
     * Namespace a key.
     *
     * @since 151216 Memcache utils.
     *
     * @param string     $primary_key Primary key.
     * @param string|int $sub_key     Sub-key.
     *
     * @return string Full namespaced cache key.
     */
    protected function key(string $primary_key, $sub_key): string
    {
        if (!$this->enabled) {
            return ''; // Not possible.
            //
        } elseif (!($namespaced_primary_key = $this->nspKey($primary_key))) {
            return ''; // Not possible; e.g., empty key.
        }
        $namespaced_primary_key_uuid = ''; // Initialize.

        do { // Avoid race issues.
            $attempts = $attempts ?? 0;
            ++$attempts; // Counter.

            if (($existing_namespaced_primary_key_uuid = (string) $this->Pool->get($namespaced_primary_key))) {
                $namespaced_primary_key_uuid = $existing_namespaced_primary_key_uuid;
                break; // All good; stop here.
            }
            if (!isset($new_namespaced_primary_key_uuid)) {
                $new_namespaced_primary_key_uuid = $this->c::uuidV4();
            }
            if ($this->Pool->add($namespaced_primary_key, $new_namespaced_primary_key_uuid)) {
                $namespaced_primary_key_uuid = $new_namespaced_primary_key_uuid;
                break; // All good; stop here.
            }
            $result_code = $this->Pool->getResultCode();
            //
        } while ($attempts < $this::MAX_WRITE_ATTEMPTS && $result_code === \Memcached::RES_NOTSTORED);

        if (!$namespaced_primary_key_uuid) {
            return ''; // Failure; e.g., race condition.
        }
        $sub_key                            = (string) $sub_key;
        $namespaced_primary_key_uuid_prefix = $namespaced_primary_key_uuid.'\\';
        $namespaced_key                     = $namespaced_primary_key_uuid_prefix.$sub_key;

        if (isset($namespaced_key[251])) {
            throw $this->c::issue(sprintf('Sub key too long; %1$s bytes max.', 250 - strlen($namespaced_primary_key_uuid_prefix)));
        }
        return $namespaced_key;
    }

    /**
     * Namespace primary key.
     *
     * @since 151216 Memcache utils.
     *
     * @param string $primary_key Primary key.
     *
     * @return string Namespaced primary key.
     */
    protected function nspKey(string $primary_key): string
    {
        if (!$this->enabled) {
            return ''; // Not possible.
            //
        } elseif (!isset($primary_key[0])) {
            return ''; // Not possible.
        }
        $namespace_prefix       = 'x___'.$this->namespace.'\\';
        $namespaced_primary_key = $namespace_prefix.$primary_key;

        if (isset($namespaced_primary_key[251])) {
            throw $this->c::issue(sprintf('Primary key too long; %1$s bytes max.', 250 - strlen($namespace_prefix)));
        }
        return $namespaced_primary_key;
    }

    /**
     * Servers differ? i.e., current vs. active.
     *
     * @since 151216 Memcache utils.
     *
     * @return bool True if servers differ.
     */
    protected function serversDiffer(): bool
    {
        if (!$this->enabled) {
            return false; // Not possible.
        }
        $active_servers = []; // Initialize.

        foreach ($this->Pool->getServerList() as $_server) {
            $active_servers[$_server['host'].':'.$_server['port']] = $_server;
        } // unset($_server); // Housekeeping.

        if (count($this->servers) !== count($active_servers)) {
            return true; // They definitely differ.
        }
        foreach ($this->servers as $_key => $_server) {
            if (!isset($active_servers[$_key])) {
                return true;
            } // unset($_key, $_server);
        }
        foreach ($active_servers as $_key => $_server) {
            if (!isset($this->servers[$_key])) {
                return true;
            } // unset($_key, $_server);
        }
        return false;
    }

    /**
     * Maybe add server connections.
     *
     * @since 151216 Memcache utils.
     */
    protected function maybeAddServerConnections()
    {
        if (!$this->enabled) {
            return; // Not possible.
        }
        if ($this->serversDiffer()) {
            $this->Pool->quit();
            $this->Pool->resetServerList();

            $this->Pool->setOption(\Memcached::OPT_NO_BLOCK, true);
            $this->Pool->setOption(\Memcached::OPT_LIBKETAMA_COMPATIBLE, true);

            if (\Memcached::HAVE_IGBINARY) { // Size and speed gains.
                $this->Pool->setOption(\Memcached::OPT_BINARY_PROTOCOL, true);
                $this->Pool->setOption(\Memcached::OPT_SERIALIZER, \Memcached::SERIALIZER_IGBINARY);
            }
            $this->Pool->setOption(\Memcached::OPT_CONNECT_TIMEOUT, 1000);
            $this->Pool->setOption(\Memcached::OPT_POLL_TIMEOUT, 1000);
            $this->Pool->setOption(\Memcached::OPT_RETRY_TIMEOUT, 1);

            $this->Pool->setOption(\Memcached::OPT_SEND_TIMEOUT, 1000000);
            $this->Pool->setOption(\Memcached::OPT_RECV_TIMEOUT, 1000000);

            $this->Pool->addServers($this->servers);
        }
    }
}


<?php

/*
 * This file is part of the Ivory Google Map package.
 *
 * (c) Eric GELOEN <geloen.eric@gmail.com>
 *
 * For the full copyright and license information, please read the LICENSE
 * file that was distributed with this source code.
 */

namespace Ivory\GoogleMap\Helper\Places;

use Ivory\GoogleMap\Exception\HelperException;
use Ivory\GoogleMap\Helper\AbstractHelper;
use Ivory\GoogleMap\Helper\ApiHelper;
use Ivory\GoogleMap\Helper\Base\CoordinateHelper;
use Ivory\GoogleMap\Helper\Base\BoundHelper;
use Ivory\GoogleMap\Places\Autocomplete;

/**
 * Places autocomplete helper.
 *
 * @author GeLo <geloen.eric@gmail.com>
 */
class AutocompleteHelper extends AbstractHelper
{
    /** @var \Ivory\GoogleMap\Helper\ApiHelper */
    protected $apiHelper;

    /** @var \Ivory\GoogleMap\Helper\Base\CoordinateHelper */
    protected $coordinateHelper;

    /** @var \Ivory\GoogleMap\Helper\Base\BoundHelper */
    protected $boundHelper;

    /**
     * Creates an autocomplete helper.
     *
     * @param \Ivory\GoogleMap\Helper\ApiHelper             $apiHelper        The API helper.
     * @param \Ivory\GoogleMap\Helper\Base\CoordinateHelper $coordinateHelper The coordinate helper.
     * @param \Ivory\GoogleMap\Helper\Base\BoundHelper      $boundHelper      The bound helper.
     */
    public function __construct(
        ApiHelper $apiHelper = null,
        CoordinateHelper $coordinateHelper = null,
        BoundHelper $boundHelper = null
    )
    {
        parent::__construct();

        if ($apiHelper === null) {
            $apiHelper = new ApiHelper();
        }

        if ($coordinateHelper === null) {
            $coordinateHelper = new CoordinateHelper();
        }

        if ($boundHelper === null) {
            $boundHelper = new BoundHelper();
        }

        $this->setApiHelper($apiHelper);
        $this->setCoordinateHelper($coordinateHelper);
        $this->setBoundHelper($boundHelper);
    }

    /**
     * Gets the API helper.
     *
     * @return \Ivory\GoogleMap\Helper\ApiHelper The API helper.
     */
    public function getApiHelper()
    {
        return $this->apiHelper;
    }

    /**
     * Sets the API helper.
     *
     * @param \Ivory\GoogleMap\Helper\ApiHelper $apiHelper The API helper.
     */
    public function setApiHelper(ApiHelper $apiHelper)
    {
        $this->apiHelper = $apiHelper;
    }

    /**
     * Gets the coordinate helper.
     *
     * @return \Ivory\GoogleMap\Helper\Base\CoordinateHelper The coordinate helper.
     */
    public function getCoordinateHelper()
    {
        return $this->coordinateHelper;
    }

    /**
     * Sets the coordinate helper.
     *
     * @param \Ivory\GoogleMap\Helper\Base\CoordinateHelper $coordinateHelper The coordinate helper.
     */
    public function setCoordinateHelper(CoordinateHelper $coordinateHelper)
    {
        $this->coordinateHelper = $coordinateHelper;
    }

    /**
     * Gets the bound helper.
     *
     * @return \Ivory\GoogleMap\Helper\Base\BoundHelper The bound helper.
     */
    public function getBoundHelper()
    {
        return $this->boundHelper;
    }

    /**
     * Sets the bound helper.
     *
     * @param \Ivory\GoogleMap\Helper\Base\BoundHelper $boundHelper The bound helper.
     */
    public function setBoundHelper(BoundHelper $boundHelper)
    {
        $this->boundHelper = $boundHelper;
    }

    /**
     * Renders the autocomplete HTML container.
     *
     * @param \Ivory\GoogleMap\Places\Autocomplete $autocomplete The autocomplete.
     *
     * @return string The HTML output.
     */
    public function renderHtmlContainer(Autocomplete $autocomplete)
    {
        $inputAttributes = $autocomplete->getInputAttributes();

        $inputAttributes['id'] = $autocomplete->getInputId();

        if ($autocomplete->hasValue()) {
            $inputAttributes['value'] = $autocomplete->getValue();
        }

        $htmlAttributes = array();
        foreach ($inputAttributes as $attribute => $value) {
            $htmlAttributes[] = sprintf('%s="%s"', $attribute, $value);
        }

        return sprintf('<input %s />'.PHP_EOL, implode(' ', $htmlAttributes));
    }

    /**
     * Renders the autocomplete javascripts.
     *
     * @param \Ivory\GoogleMap\Places\Autocomplete $autocomplete The autocomplete.
     *
     * @throws \Ivory\GoogleMap\Exception\HelperException if the autocomplete bound does not have coordinates.
     *
     * @return string The HTML output.
     */
    public function renderJavascripts(Autocomplete $autocomplete)
    {
        $output = array();

        if (!$this->apiHelper->isLoaded() && !$autocomplete->isAsync()) {
            $output[] = $this->apiHelper->render($autocomplete->getLanguage(), array('places'));
        }

        $output[] = '<script type="text/javascript">'.PHP_EOL;

        if ($autocomplete->isAsync()) {
            $output[] = 'function load_ivory_google_place () {'.PHP_EOL;
        }

        if ($autocomplete->hasBound()) {
            if (!$autocomplete->getBound()->hasCoordinates()) {
                throw HelperException::invalidAutocompleteBound();
            }

            $output[] = $this->coordinateHelper->render($autocomplete->getBound()->getSouthWest());
            $output[] = $this->coordinateHelper->render($autocomplete->getBound()->getNorthEast());
            $output[] = $this->boundHelper->render($autocomplete->getBound());
        }

        $output[] = $this->renderAutocomplete($autocomplete);

        if ($autocomplete->isAsync()) {
            $output[] = '}'.PHP_EOL;
        }

        $output[] = '</script>'.PHP_EOL;

        if (!$this->apiHelper->isLoaded() && $autocomplete->isAsync()) {
            $output[] = $this->apiHelper->render(
                $autocomplete->getLanguage(),
                array('places'),
                'load_ivory_google_place'
            );
        }

        return implode('', $output);
    }

    /**
     * Renders the autocomplete.
     *
     * @param \Ivory\GoogleMap\Places\Autocomplete $autocomplete The autocomplete.
     *
     * @return string The JS output.
     */
    public function renderAutocomplete(Autocomplete $autocomplete)
    {
        $this->jsonBuilder->reset();

        if ($autocomplete->hasTypes()) {
            $this->jsonBuilder->setValue('[types]', $autocomplete->getTypes());
        }

        if ($autocomplete->hasBound()) {
            $this->jsonBuilder->setValue('[bounds]', $autocomplete->getBound()->getJavascriptVariable(), false);
        }

        if ($autocomplete->hasComponentRestrictions()) {
            $this->jsonBuilder->setValue('[componentRestrictions]', $autocomplete->getComponentRestrictions());
        }

        if (!$this->jsonBuilder->hasValues()) {
            $this->jsonBuilder->setJsonEncodeOptions(JSON_FORCE_OBJECT);
        }

        return sprintf(
            '%s = new google.maps.places.Autocomplete(document.getElementById(\'%s\'), %s);'.PHP_EOL,
            $autocomplete->getJavascriptVariable(),
            $autocomplete->getInputId(),
            $this->jsonBuilder->build()
        );
    }
}


<?php
declare(strict_types = 1);
namespace RabbitCMS\Modules\Providers;

use Illuminate\Support\ServiceProvider;
use RabbitCMS\Modules\Console\SeedCommand;
use RabbitCMS\Modules\Seeders\DatabaseSeeder;

/**
 * Class SeedServiceProvider.
 *
 * @package RabbitCMS\Modules
 */
class SeedServiceProvider extends ServiceProvider
{
    /**
     * {@inheritdoc}
     */
    //protected $defer = true;

    /**
     * Register the seed console command.
     */
    public function register()
    {
        $this->app->singleton(DatabaseSeeder::class);
        $this->app->extend('command.seed', function () {
            return new SeedCommand($this->app['db']);
        });
    }

    /**
     * {@inheritdoc}
     */
    public function provides()
    {
        return ['command.seed'];
    }
}


<?php
/**
 * Output utilities.
 *
 * @author @jaswrks
 * @copyright WebSharks™
 */
declare(strict_types=1);
namespace WebSharks\Core\Classes\Core\Utils;

use WebSharks\Core\Classes;
use WebSharks\Core\Interfaces;
use WebSharks\Core\Traits;
//
use WebSharks\Core\Classes\Core\Error;
use WebSharks\Core\Classes\Core\Base\Exception;
//
use function assert as debug;
use function get_defined_vars as vars;

/**
 * Output utilities.
 *
 * @since 150424 Initial release.
 */
class Output extends Classes\Core\Base\Core
{
    /**
     * Prepares for file output.
     *
     * @since 160622 Adding file output prep.
     * @since 170824.30708 `filePrep()` is now `prepFile()`.
     */
    public function prepFile()
    {
        $this->gzipOff();
        $this->buffersEndClean();
        $this->sessionWriteClose();
    }

    /**
     * Closes a request early.
     *
     * @since 170824.30708 Early close of request.
     */
    public function closeRequestEarly()
    {
        ignore_user_abort(true);
        $this->sessionWriteClose();

        if ($this->c::canCallFunc('fastcgi_finish_request')) {
            fastcgi_finish_request();
        } else {
            $this->buffersEndFlush();
            header('connection: close');
        }
    }

    /**
     * Disables GZIP compression.
     *
     * @since 150424 Initial release.
     */
    public function gzipOff()
    {
        if (headers_sent()) {
            throw $this->c::issue('Headers already sent!');
        }
        @ini_set('zlib.output_compression', 'off');

        if ($this->c::canCallFunc('apache_setenv')) {
            @apache_setenv('no-gzip', '1');
        }
    }

    /**
     * Writes/closes any open session data.
     *
     * @since 160622 Adding session write/close.
     */
    public function sessionWriteClose()
    {
        if (headers_sent()) {
            throw $this->c::issue('Headers already sent!');
        }
        @session_write_close(); // End and write session data.
    }

    /**
     * Ends/cleans any open output buffers.
     *
     * @since 150424 Initial release.
     */
    public function buffersEndClean()
    {
        if (headers_sent()) {
            throw $this->c::issue('Headers already sent!');
        }
        while (@ob_end_clean()) {
            // End & clean any open buffers.
        }
    }

    /**
     * Ends/flushes any open output buffers.
     *
     * @since 170824.30708 Buffer end/flush.
     */
    public function buffersEndFlush()
    {
        if (headers_sent()) {
            throw $this->c::issue('Headers already sent!');
        }
        while (@ob_end_flush()) {
            // End & flush any open buffers.
        }
    }
}


<?php
namespace Perry\Representation\Eve\v1;

use \Perry\Representation\Reference as Reference;
use \Perry\Representation\Uri as Uri;
use \Perry\Representation\Base as Base;

class System extends Base
{
    public $stats;

    public $name;

    public $securityStatus;

    public $securityClass;

    public $href;

    public $planets = [];

    public $position;

    public $sovereignty;

    public $constellation;

    // by Warringer\Types\Reference
    public function setStats($stats)
    {
        $this->stats = new Reference($stats);
    }

    // by Warringer\Types\String
    public function setName($name)
    {
        $this->name = $name;
    }

    // by Warringer\Types\Base
    public function setSecurityStatus($securityStatus)
    {
        $this->securityStatus = $securityStatus;
    }

    // by Warringer\Types\String
    public function setSecurityClass($securityClass)
    {
        $this->securityClass = $securityClass;
    }

    // by Warringer\Types\Uri
    public function setHref($href)
    {
        $this->href = new Uri($href);
    }

    // by Warringer\Types\ArrayType
    public function setPlanets($planets)
    {
        // by Warringer\Types\Dict
        $converters = [];
        $converters['href'] = function ($value) { return new Uri($value); };

        $func = function ($value) use($converters) {
            $return = new \ArrayObject($value, \ArrayObject::ARRAY_AS_PROPS);
            $return['href'] = isset($value->{'href'}) ? $converters['href']($value->{'href'}) : null;
            return $return;
        };

        foreach ($planets as $key => $value) {
            $this->planets[$key] = $func($value);
        }
    }

    // by Warringer\Types\Dict
    public function setPosition($position)
    {
        // by Warringer\Types\Dict
        $converters = [];
        $converters['y'] = function ($value) { return $value; };
        $converters['x'] = function ($value) { return $value; };
        $converters['z'] = function ($value) { return $value; };

        $func = function ($value) use($converters) {
            $return = new \ArrayObject($value, \ArrayObject::ARRAY_AS_PROPS);
            $return['y'] = isset($value->{'y'}) ? $converters['y']($value->{'y'}) : null;
            $return['x'] = isset($value->{'x'}) ? $converters['x']($value->{'x'}) : null;
            $return['z'] = isset($value->{'z'}) ? $converters['z']($value->{'z'}) : null;
            return $return;
        };
        $this->position = $func($position);
    }

    // by Warringer\Types\Reference
    public function setSovereignty($sovereignty)
    {
        $this->sovereignty = new Reference($sovereignty);
    }

    // by Warringer\Types\Reference
    public function setConstellation($constellation)
    {
        $this->constellation = new Reference($constellation);
    }

}


<?php

/*
 * This file is part of the Ivory Google Map package.
 *
 * (c) Eric GELOEN <geloen.eric@gmail.com>
 *
 * For the full copyright and license information, please read the LICENSE
 * file that was distributed with this source code.
 */

namespace Ivory\GoogleMap\Helper\Extension;

use Ivory\GoogleMap\Map;

/**
 * InfoBox extension helper.
 *
 * @author GeLo <geloen.eric@gmail.com>
 */
class InfoBoxExtensionHelper extends AbstractExtensionHelper
{
    /** @var string */
    protected $source;

    /** @var string */
    protected $callback;

    /**
     * Creates an info box extension helper.
     *
     * @param string $source   The info box source URL.
     * @param string $callback The info box callback.
     */
    public function __construct(
        $source = '//google-maps-utility-library-v3.googlecode.com/svn/trunk/infobox/src/infobox_packed.js',
        $callback = 'load_ivory_google_map_info_box'
    ) {
        $this->setSource($source);
        $this->setCallback($callback);
    }

    /**
     * Gets the info box source URL.
     *
     * @return string The info box source URL.
     */
    public function getSource()
    {
        return $this->source;
    }

    /**
     * Sets the info box source URL.
     *
     * @param string $source The info box source URL.
     */
    public function setSource($source)
    {
        $this->source = $source;
    }

    /**
     * Gets the javascript callback.
     *
     * @return string The javascript callback.
     */
    public function getCallback()
    {
        return $this->callback;
    }

    /**
     * Sets the javascript callback.
     *
     * @param string $callback The javascript callback.
     */
    public function setCallback($callback)
    {
        $this->callback = $callback;
    }

    /**
     * {@inheritdoc}
     */
    public function renderLibraries(Map $map)
    {
        if (!$map->isAsync()) {
            return $this->renderLibrary($this->source);
        }
    }

    /**
     * {@inheritdoc}
     */
    public function renderBefore(Map $map)
    {
        if ($map->isAsync()) {
            return sprintf('function %s () {'.PHP_EOL, $this->callback);
        }
    }

    /**
     * {@inheritdoc}
     */
    public function renderAfter(Map $map)
    {
        if ($map->isAsync()) {
            return '}'.PHP_EOL.$this->renderLibrary($this->source, $this->callback);
        }
    }
}


<?php

/*
 * This file is part of the Ivory Google Map package.
 *
 * (c) Eric GELOEN <geloen.eric@gmail.com>
 *
 * For the full copyright and license information, please read the LICENSE
 * file that was distributed with this source code.
 */

namespace Ivory\GoogleMap\Services\Directions;

use Ivory\GoogleMap\Base\Coordinate;
use Ivory\GoogleMap\Exception\DirectionsException;

/**
 * A directions waypoint which describes the google map directions waypoint.
 *
 * @see http://code.google.com/apis/maps/documentation/javascript/reference.html#DirectionsWaypoint
 * @author GeLo <geloen.eric@gmail.com>
 */
class DirectionsWaypoint
{
    /** @var string | \Ivory\GoogleMap\Base\Coordinate */
    protected $location;

    /** @var boolean */
    protected $stopover;

    /**
     * Checks if the directions waypoint has a location.
     *
     * @return boolean TRUE if the directions waypoint has a location else FALSE.
     */
    public function hasLocation()
    {
        return $this->location !== null;
    }

    /**
     * Gets the directions waypoint location.
     *
     * @return string | \Ivory\GoogleMap\Base\Coordinate The directions waypoint location.
     */
    public function getLocation()
    {
        return $this->location;
    }

    /**
     * Sets the directions waypoint location.
     *
     * Available prototypes:
     * - function setLocation(string $destination)
     * - function setLocation(Ivory\GoogleMap\Base\Coordinate $destination)
     * - function setLocation(double $latitude, double $longitude, boolean $noWrap)
     *
     * @throws \Ivory\GoogleMap\Exception\DirectionsException If the location is not valid (prototypes).
     */
    public function setLocation()
    {
        $args = func_get_args();

        if (isset($args[0]) && is_string($args[0])) {
            $this->location = $args[0];
        } elseif (isset($args[0]) && ($args[0] instanceof Coordinate)) {
            $this->location = $args[0];
        } elseif ((isset($args[0]) && is_numeric($args[0])) && (isset($args[1]) && is_numeric($args[1]))) {
            if ($this->location === null) {
                $this->location = new Coordinate();
            }

            $this->location->setLatitude($args[0]);
            $this->location->setLongitude($args[1]);

            if (isset($args[2]) && is_bool($args[2])) {
                $this->location->setNoWrap($args[2]);
            }
        } else {
            throw DirectionsException::invalidDirectionsWaypointLocation();
        }
    }

    /**
     * Checks if the directions waypoint has a stopover flag.
     *
     * @return boolean TRUE if the directions waypoint has a stopover flag else FALSE.
     */
    public function hasStopover()
    {
        return $this->stopover !== null;
    }

    /**
     * Gets the directions waypoint stopover flag.
     *
     * @return boolean The directions waypoint stopover flag.
     */
    public function getStopover()
    {
        return $this->stopover;
    }

    /**
     * Sets the directions waypoint stopover flag.
     *
     * @param boolean $stopover The directions waypoint stopover flag.
     */
    public function setStopover($stopover = null)
    {
        if (!is_bool($stopover) && ($stopover !== null)) {
            throw DirectionsException::invalidDirectionsWaypointStopover();
        }

        $this->stopover = $stopover;
    }

    /**
     * Checks if the directions waypoint is valid.
     *
     * @return boolean TRUE if the directions waypoint is valid else FALSE.
     */
    public function isValid()
    {
        return $this->hasLocation();
    }
}


<?php
/**
 * File upload utilities.
 *
 * @author @jaswrks
 * @copyright WebSharks™
 */
declare (strict_types = 1);
namespace WebSharks\Core\Classes\Core\Utils;

use WebSharks\Core\Classes;
use WebSharks\Core\Interfaces;
use WebSharks\Core\Traits;
#
use WebSharks\Core\Classes\Core\Error;
use WebSharks\Core\Classes\Core\Base\Exception;
#
use function assert as debug;
use function get_defined_vars as vars;

/**
 * File upload utilities.
 *
 * @since 150424 Initial release.
 */
class FileUpload extends Classes\Core\Base\Core
{
    /**
     * Error reason.
     *
     * @since 160926 Upload utils.
     *
     * @param int $code An upload error code.
     *
     * @return string An upload error reason.
     */
    public function errorReason(int $code): string
    {
        switch ($code) {
            case UPLOAD_ERR_INI_SIZE:
                return __('Exceeds `upload_max_filesize` directive in `php.ini`.');

            case UPLOAD_ERR_FORM_SIZE:
                return __('Exceeds `MAX_FILE_SIZE` directive in the HTML form.');

            case UPLOAD_ERR_PARTIAL:
                return __('Data missing; partial.');

            case UPLOAD_ERR_NO_FILE:
                return __('Missing file.');

            case UPLOAD_ERR_NO_TMP_DIR:
                return __('Missing temp dir.');

            case UPLOAD_ERR_CANT_WRITE:
                return __('Failed to write file to disk.');

            case UPLOAD_ERR_EXTENSION:
                return __('A PHP extension stopped the file upload.');

            default: // Unknown error code.
                return __('Unknown error.');
        }
    }
}


<?php
/**
 * File ext utilities.
 *
 * @author @jaswrks
 * @copyright WebSharks™
 */
declare(strict_types=1);
namespace WebSharks\Core\Classes\Core\Utils;

use WebSharks\Core\Classes;
use WebSharks\Core\Interfaces;
use WebSharks\Core\Traits;
//
use WebSharks\Core\Classes\Core\Error;
use WebSharks\Core\Classes\Core\Base\Exception;
//
use function assert as debug;
use function get_defined_vars as vars;

/**
 * File ext utilities.
 *
 * @since 150424 Initial release.
 */
class FileExt extends Classes\Core\Base\Core
{
    /**
     * File extension.
     *
     * @since 150424 Initial release.
     *
     * @param string $path A filesystem path.
     *
     * @return string File extension; or empty string.
     */
    public function __invoke(string $path): string
    {
        if (!$path) {
            return ''; // Not possible.
        }
        if (in_array(mb_substr($path, -1), ['/', '\\', DIRECTORY_SEPARATOR], true)) {
            return ''; // Directory, not a file.
        } elseif (!($basename = basename($path))) {
            return ''; // Not possible.
        } elseif (!($ext = mb_strrchr($basename, '.'))) {
            return ''; // No extension.
        }
        $ext        = $this->c::mbLTrim($ext, '.');
        return $ext = mb_strtolower($ext);
    }

    /**
     * Set file extension.
     *
     * @since 17xxxx Extension utils.
     *
     * @param string $file Image file.
     * @param string $ext  New extension.
     *
     * @return string File w/ extension.
     */
    public function set(string $file, string $ext): string
    {
        if (!$file || !$ext) {
            return $file; // Not possible.
        }
        return $file = preg_replace('/\.[^.]+$/ui', '', $file).'.'.$ext;
    }

    /**
     * Change file extension.
     *
     * @since 17xxxx Extension utils.
     *
     * @param string $file Image file.
     * @param string $ext  New extension.
     *
     * @return string File w/ possible extension.
     */
    public function change(string $file, string $ext): string
    {
        if (!$file || !$ext) {
            return $file; // Not possible.
        }
        return $file = preg_replace('/\.[^.]+$/ui', '.'.$ext, $file);
    }
}


<?php

/*
 * This file is part of the Ivory Google Map package.
 *
 * (c) Eric GELOEN <geloen.eric@gmail.com>
 *
 * For the full copyright and license information, please read the LICENSE
 * file that was distributed with this source code.
 */

namespace Ivory\GoogleMap\Assets;

use Ivory\GoogleMap\Exception\AssetException;

/**
 * Allow easy add of options for any class model that requires it.
 *
 * @author GeLo <geloen.eric@gmail.com>
 */
abstract class AbstractOptionsAsset extends AbstractJavascriptVariableAsset
{
    /** @var array */
    protected $options;

    /**
     * Creates an options asset.
     *
     * @param string $javascriptVariable The javascript variable.
     * @param array  $options            The options.
     */
    public function __construct($javascriptVariable = null, array $options = array())
    {
        parent::__construct($javascriptVariable);

        $this->setOptions($options);
    }

    /**
     * Checks if there is option.
     *
     * @return boolean TRUE if there is option else FALSE.
     */
    public function hasOptions()
    {
        return !empty($this->options);
    }

    /**
     * Checks if the option exists.
     *
     * @param string $option The option.
     *
     * @throws \Ivory\GoogleMap\Exception\AssetException If the option is not valid.
     *
     * @return boolean TRUE if the option exists else FALSE.
     */
    public function hasOption($option)
    {
        if (!is_string($option)) {
            throw AssetException::invalidOption();
        }

        return isset($this->options[$option]);
    }

    /**
     * Gets the options.
     *
     * @return array The options.
     */
    public function getOptions()
    {
        return $this->options;
    }

    /**
     * Sets the options.
     *
     * @param array $options The options.
     */
    public function setOptions(array $options)
    {
        $this->options = array();

        foreach ($options as $option => $value) {
            $this->setOption($option, $value);
        }
    }

    /**
     * Gets a specific option.
     *
     * @param string $option The option.
     *
     * @throws \Ivory\GoogleMap\Exception\AssetException If the option does not exist.
     *
     * @return mixed The option value.
     */
    public function getOption($option)
    {
        if (!$this->hasOption($option)) {
            throw AssetException::optionDoesNotExist($option);
        }

        return $this->options[$option];
    }

    /**
     * Sets a specific option.
     *
     * @param string $option The option
     * @param mixed  $value  The option value.
     *
     * @throws \Ivory\GoogleMap\Exception\AssetException If the option is not valid.
     */
    public function setOption($option, $value)
    {
        if (!is_string($option)) {
            throw AssetException::invalidOption();
        }

        $this->options[$option] = $value;
    }

    /**
     * Removes an option.
     *
     * @param string $option The option.
     *
     * @throws \Ivory\GoogleMap\Exception\AssetException If the option does not exist.
     */
    public function removeOption($option)
    {
        if (!$this->hasOption($option)) {
            throw AssetException::optionDoesNotExist($option);
        }

        unset($this->options[$option]);
    }
}


<?php

/*
 * This file is part of the Ivory Google Map package.
 *
 * (c) Eric GELOEN <geloen.eric@gmail.com>
 *
 * For the full copyright and license information, please read the LICENSE
 * file that was distributed with this source code.
 */

namespace Ivory\GoogleMap\Controls;

use Ivory\GoogleMap\Exception\ControlException;

/**
 * A zoom control describes a google map zoom control.
 *
 * @see http://code.google.com/apis/maps/documentation/javascript/reference.html#ZoomControlOptions
 * @author GeLo <geloen.eric@gmail.com>
 */
class ZoomControl
{
    /** @var string */
    protected $controlPosition;

    /** @var string */
    protected $zoomControlStyle;

    /**
     * Create a zoom control
     */
    public function __construct(
        $controlPosition = ControlPosition::TOP_LEFT,
        $zoomControlStyle = ZoomControlStyle::DEFAULT_
    ) {
        $this->setControlPosition($controlPosition);
        $this->setZoomControlStyle($zoomControlStyle);
    }

    /**
     * Gets the control position.
     *
     * @return string The control position.
     */
    public function getControlPosition()
    {
        return $this->controlPosition;
    }

    /**
     * Sets the control position.
     *
     * @param string $controlPosition The control position.
     *
     * @throws \Ivory\GoogleMap\Exception\ControlException If the control position is not valid.
     */
    public function setControlPosition($controlPosition)
    {
        if (!in_array($controlPosition, ControlPosition::getControlPositions())) {
            throw ControlException::invalidControlPosition();
        }

        $this->controlPosition = $controlPosition;
    }

    /**
     * Gets the zoom control style.
     *
     * @return string The zoom control style.
     */
    public function getZoomControlStyle()
    {
        return $this->zoomControlStyle;
    }

    /**
     * Sets the zoom control style.
     *
     * @param string $zoomControlStyle The zoom control style.
     *
     * @throws \Ivory\GoogleMap\Exception\ControlException If the zoom control style is not valid.
     */
    public function setZoomControlStyle($zoomControlStyle)
    {
        if (!in_array($zoomControlStyle, ZoomControlStyle::getZoomControlStyles())) {
            throw ControlException::invalidZoomControlStyle();
        }

        $this->zoomControlStyle = $zoomControlStyle;
    }
}


<?php
/**
 * Hash ID utilities.
 *
 * @author @jaswrks
 * @copyright WebSharks™
 */
declare(strict_types=1);
namespace WebSharks\Core\Classes\Core\Utils;

use WebSharks\Core\Classes;
use WebSharks\Core\Interfaces;
use WebSharks\Core\Traits;
#
use WebSharks\Core\Classes\Core\Error;
use WebSharks\Core\Classes\Core\Base\Exception;
#
use function assert as debug;
use function get_defined_vars as vars;
#
use Hashids\Hashids as Parser;

/**
 * Hash ID utilities.
 *
 * @since 150424 Initial release.
 */
class HashIds extends Classes\Core\Base\Core
{
    /**
     * Parser.
     *
     * @since 150424
     *
     * @type Parser
     */
    protected $Parser;

    /**
     * Class constructor.
     *
     * @since 150424 Adding hash IDs.
     * @since 17xxxx No constructor options.
     *
     * @param Classes\App $App Instance of App.
     */
    public function __construct(Classes\App $App)
    {
        parent::__construct($App);

        if (!($key = $this->App->Config->©hash_ids['©hash_key'])) {
            throw $this->c::issue('Missing HashIds hash key.');
        }
        $this->Parser = new Parser($key, 4, 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');
    }

    /**
     * Encodes integers.
     *
     * @since 150424 Adding hash IDs.
     *
     * @param int ...$integers Variadic integers to encode.
     *
     * @return string A hash ID; e.g., `wQoQjgr`
     */
    public function encode(int ...$integers): string
    {
        return $this->Parser->encode(...$integers);
    }

    /**
     * Decodes a hash ID.
     *
     * @since 150424 Adding hash IDs.
     *
     * @param string $hash_id Hash ID.
     *
     * @return array Array of decoded IDs.
     */
    public function decode(string $hash_id): array
    {
        return $this->Parser->decode($hash_id);
    }

    /**
     * Decodes a hash ID.
     *
     * @since 161003 Single hash ID.
     *
     * @param string $hash_id Hash ID.
     *
     * @return int One decoded ID.
     */
    public function decodeOne(string $hash_id): int
    {
        $ids       = $this->Parser->decode($hash_id);
        return $id = (int) ($ids[0] ?? 0);
    }
}


<?php

/*
 * This file is part of the Ivory Google Map package.
 *
 * (c) Eric GELOEN <geloen.eric@gmail.com>
 *
 * For the full copyright and license information, please read the LICENSE
 * file that was distributed with this source code.
 */

namespace Ivory\GoogleMap\Services\Geocoding\Result;

use Ivory\GoogleMap\Exception\GeocodingException;

/**
 * A geocoder response wraps the geocoder results & the response status.
 *
 * @author GeLo <geloen.eric@gmail.com>
 */
class GeocoderResponse
{
    /** @var array */
    protected $results;

    /** @var string */
    protected $status;

    /**
     * Create a geocoder results.
     *
     * @param array  $results The geocoder results.
     * @param string $status  The geocoder status.
     */
    public function __construct(array $results, $status)
    {
        $this->setResults($results);
        $this->setStatus($status);
    }

    /**
     * Gets the geocoder results.
     *
     * @return array The geocoder results.
     */
    public function getResults()
    {
        return $this->results;
    }

    /**
     * Sets the geocoder results
     *
     * @param array $results The geocoder results.
     */
    public function setResults(array $results)
    {
        $this->results = array();

        foreach ($results as $result) {
            $this->addResult($result);
        }
    }

    /**
     * Adds a geocoder result.
     *
     * @param \Ivory\GoogleMap\Services\Result\GeocoderResult $result The geocoder result to add.
     */
    public function addResult(GeocoderResult $result)
    {
        $this->results[] = $result;
    }

    /**
     * Gets the geocoder results status.
     *
     * @return string The geocoder results status.
     */
    public function getStatus()
    {
        return $this->status;
    }

    /**
     * Sets the geocoder results status.
     *
     * @param string $status The geocoder result status.
     *
     * @throws \Ivory\GoogleMap\Exception\GeocodingException If the status is not valid.
     */
    public function setStatus($status)
    {
        if (!in_array($status, GeocoderStatus::getGeocoderStatus())) {
            throw GeocodingException::invalidGeocoderResponseStatus();
        }

        $this->status = $status;
    }
}


<?php
namespace Perry\Representation\Eve\v1;

use \Perry\Representation\Reference as Reference;
use \Perry\Representation\Uri as Uri;
use \Perry\Representation\Base as Base;

class TournamentStaticSceneData extends Base
{
    public $globalObjects = [];

    public $ships = [];

    public $nebulaName;

    // by Warringer\Types\ArrayType
    public function setGlobalObjects($globalObjects)
    {
        // by Warringer\Types\Dict
        $converters = [];
        $converters['name'] = function ($value) { return $value; };
        $converters['planetOrMoonInfo'] = function ($value) { return $value; };
        $converters['y'] = function ($value) { return $value; };
        $converters['x'] = function ($value) { return $value; };
        $converters['z'] = function ($value) { return $value; };
        $converters['type'] = function ($value) { return new Reference($value); };

        $func = function ($value) use($converters) {
            $return = new \ArrayObject($value, \ArrayObject::ARRAY_AS_PROPS);
            $return['name'] = isset($value->{'name'}) ? $converters['name']($value->{'name'}) : null;
            $return['planetOrMoonInfo'] = isset($value->{'planetOrMoonInfo'}) ? $converters['planetOrMoonInfo']($value->{'planetOrMoonInfo'}) : null;
            $return['y'] = isset($value->{'y'}) ? $converters['y']($value->{'y'}) : null;
            $return['x'] = isset($value->{'x'}) ? $converters['x']($value->{'x'}) : null;
            $return['z'] = isset($value->{'z'}) ? $converters['z']($value->{'z'}) : null;
            $return['type'] = isset($value->{'type'}) ? $converters['type']($value->{'type'}) : null;
            return $return;
        };

        foreach ($globalObjects as $key => $value) {
            $this->globalObjects[$key] = $func($value);
        }
    }

    // by Warringer\Types\ArrayType
    public function setShips($ships)
    {
        // by Warringer\Types\Dict
        $converters = [];
        $converters['item'] = function ($value) { return new Reference($value); };
        $converters['points'] = function ($value) { return $value; };
        $converters['character'] = function ($value) { return new Reference($value); };
        $converters['turrets'] = function ($values) {
        // by Warringer\Types\Reference
        $func = function ($value) { return new Reference($value); };

            foreach ($values as $key => $value) {
                 $values[$key] = $func($value);
            }
           return $values;
        };

        $converters['type'] = function ($value) { return new Reference($value); };

        $func = function ($value) use($converters) {
            $return = new \ArrayObject($value, \ArrayObject::ARRAY_AS_PROPS);
            $return['item'] = isset($value->{'item'}) ? $converters['item']($value->{'item'}) : null;
            $return['points'] = isset($value->{'points'}) ? $converters['points']($value->{'points'}) : null;
            $return['character'] = isset($value->{'character'}) ? $converters['character']($value->{'character'}) : null;
            $return['turrets'] = isset($value->{'turrets'}) ? $converters['turrets']($value->{'turrets'}) : null;
            $return['type'] = isset($value->{'type'}) ? $converters['type']($value->{'type'}) : null;
            return $return;
        };

        foreach ($ships as $key => $value) {
            $this->ships[$key] = $func($value);
        }
    }

    // by Warringer\Types\String
    public function setNebulaName($nebulaName)
    {
        $this->nebulaName = $nebulaName;
    }

}


<?php
/**
 * UTF-8 utils.
 *
 * @author @jaswrks
 * @copyright WebSharks™
 */
declare (strict_types = 1);
namespace WebSharks\Core\Classes\Core\Utils;

use WebSharks\Core\Classes;
use WebSharks\Core\Interfaces;
use WebSharks\Core\Traits;
#
use WebSharks\Core\Classes\Core\Error;
use WebSharks\Core\Classes\Core\Base\Exception;
#
use function assert as debug;
use function get_defined_vars as vars;

/**
 * UTF-8 utils.
 *
 * @since 150424 Enhancing multibyte support.
 */
class Utf8 extends Classes\Core\Base\Core
{
    /**
     * Marker.
     *
     * @since 150424
     *
     * @var string
     */
    const BOM = "\xEF\xBB\xBF";

    /**
     * Is valid UTF-8?
     *
     * @since 150424 Enhancing multibyte support.
     *
     * @param string $string Input string to test.
     *
     * @return bool True if is valid UTF-8.
     */
    public function isValid(string $string): bool
    {
        if (!isset($string[0])) {
            return true; // Nothing to do.
        }
        return (bool) preg_match('/^./us', $string);
    }
}


<?php
/**
 * User-Agent utils.
 *
 * @author @jaswrks
 * @copyright WebSharks™
 */
declare(strict_types=1);
namespace WebSharks\Core\Classes\Core\Utils;

use WebSharks\Core\Classes;
use WebSharks\Core\Interfaces;
use WebSharks\Core\Traits;
#
use WebSharks\Core\Classes\Core\Error;
use WebSharks\Core\Classes\Core\Base\Exception;
#
use function assert as debug;
use function get_defined_vars as vars;

/**
 * User-Agent utils.
 *
 * @since 170413.34876 User-Agent utils.
 */
class UserAgent extends Classes\Core\Base\Core
{
    /**
     * Class constructor.
     *
     * @since 170413.34876 User-Agent utils.
     *
     * @param Classes\App $App Instance of App.
     */
    public function __construct(Classes\App $App)
    {
        parent::__construct($App);

        if ($this->c::isCli()) {
            throw $this->c::issue('Not possible in CLI mode.');
        }
    }

    /**
     * Is a browser engine.
     *
     * @since 170413.34876 User-Agent utils.
     *
     * @return bool True if is engine.
     *
     * @see https://jas.xyz/2p3VIbG
     */
    public function isEngine(): bool
    {
        if (($is = &$this->cacheKey(__FUNCTION__)) !== null) {
            return $is; // Cached this already.
        }
        $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';
        return $is  = $user_agent && preg_match('/(?:blink|gecko|konqueror|msie|opera|playstation|presto|trident|webkit)/ui', $user_agent);
    }
}


<?php
/**
 * Dir path utilities.
 *
 * @author @jaswrks
 * @copyright WebSharks™
 */
declare (strict_types = 1);
namespace WebSharks\Core\Classes\Core\Utils;

use WebSharks\Core\Classes;
use WebSharks\Core\Interfaces;
use WebSharks\Core\Traits;
#
use WebSharks\Core\Classes\Core\Error;
use WebSharks\Core\Classes\Core\Base\Exception;
#
use function assert as debug;
use function get_defined_vars as vars;

/**
 * Dir path utilities.
 *
 * @since 150424 Initial release.
 */
class DirPath extends Classes\Core\Base\Core implements Interfaces\FsConstants
{
    /**
     * Normalizes directory separators deeply.
     *
     * @since 150424 Initial release.
     *
     * @param mixed $value                Any input value.
     * @param bool  $allow_trailing_slash Optional; defaults to a FALSE value.
     *
     * @return string|array|object Normalized directory/file path.
     */
    public function normalize($value, bool $allow_trailing_slash = false)
    {
        if (is_array($value) || is_object($value)) {
            foreach ($value as $_key => &$_value) {
                $_value = $this->normalize($_value);
            } // unset($_key, $_value);
            return $value;
        }
        if (!($string = (string) $value)) {
            return $string; // Nothing to do.
        }
        $stream_wrapper_regex = '/^(?<stream_wrapper>'.$this::FS_REGEX_FRAG_STREAM_WRAPPER.')/uS';
        $drive_prefix_regex   = '/^(?<drive_letter>'.$this::FS_REGEX_FRAG_DRIVE_PREFIX.')/uS';

        if (mb_strpos($string, '://') !== false && preg_match($stream_wrapper_regex, $string, $stream_wrapper)) {
            $string = preg_replace($stream_wrapper_regex, '', $string);
        }
        if (mb_strpos($string, ':') !== false && preg_match($drive_prefix_regex, $stringm, $drive_prefix)) {
            $string = preg_replace($stream_wrapper_regex, '', $string);
        }
        $string = str_replace([DIRECTORY_SEPARATOR, '\\', '/'], '/', $string);
        $string = preg_replace('/\/+/u', '/', $string); // Remove extra slashes.
        $string = $allow_trailing_slash ? $string : $this->c::mbRTrim($string, '/');

        if (!empty($drive_prefix[0])) {
            $string = mb_strtoupper($drive_prefix[0]).$string;
        }
        if (!empty($stream_wrapper[0])) {
            $string = mb_strtolower($stream_wrapper[0]).$string;
        }
        return $string;
    }
}


<?php
/**
 * Paginator.
 *
 * @author @jaswrks
 * @copyright WebSharks™
 */
declare(strict_types=1);
namespace WebSharks\Core\Classes\Core;

use WebSharks\Core\Classes;
use WebSharks\Core\Interfaces;
use WebSharks\Core\Traits;
#
use WebSharks\Core\Classes\Core\Error;
use WebSharks\Core\Classes\Core\Base\Exception;
#
use function assert as debug;
use function get_defined_vars as vars;

/**
 * Paginator.
 *
 * @since 161006 Paginator.
 */
class Paginator extends Classes\Core\Base\Core
{
    /**
     * Class constructor.
     *
     * @since 161006 Paginator.
     *
     * @param Classes\App $App  Instance of App.
     * @param array       $args Pagination args.
     */
    public function __construct(Classes\App $App, array $args = [])
    {
        parent::__construct($App);

        $default_args = [
            'page'       => 1,
            'per_page'   => 25,

            'found_rows' => 0,
            'range'      => 2,

            'page_url_callback'     => null,
            'page_replacement_code' => '%%page%%',
            'page_url'              => '#%%page%%',

            'page_class'               => 'item',
            'page_icon_class'          => 'item',
            'page_active_class'        => 'active item',
            'page_disabled_class'      => 'disabled item',
            'page_icon_disabled_class' => 'disabled item',
            'pages_class'              => 'ui small pagination menu',

            'prev_page_text'  => __('Prev'),
            'prev_page_icon'  => '',
            'first_page_icon' => '',

            'last_page_icon'  => '',
            'next_page_icon'  => '',
            'next_page_text'  => __('Next'),

            'ellipsis_icon'  => '',
        ];
        $args = array_merge($default_args, $args);
        $args = array_intersect_key($args, $default_args);

        foreach ($args as $_key => &$_value) {
            if ($_key !== 'page_url_callback') {
                $_value = (string) $_value;
            }
        } // unset($_key, $_value); // Housekeeping.

        $args['page']       = max(1, (int) $args['page']);
        $args['per_page']   = max(1, (int) $args['per_page']);
        $args['found_rows'] = max(0, (int) $args['found_rows']);
        $args['range']      = max(1, (int) $args['range']);

        $this->overload((object) $args, true);
    }

    /**
     * Set found rows.
     *
     * @since 161006 Paginator.
     *
     * @param int $found_rows Found rows.
     */
    public function setFoundRows(int $found_rows)
    {
        $this->found_rows = max(0, $found_rows);
    }

    /**
     * Build pagination links.
     *
     * @since 161006 Paginator.
     *
     * @return string Pagination links.
     */
    public function links(): string
    {
        $first_page = 1; // Always `1` (first page).
        $last_page  = (int) ceil($this->found_rows / $this->per_page);

        // Note: `6` = Prev, [x], ..., ..., [x], Next.
        // Calculations below force a consistent menu width.
        // i.e., Always the same number of links in the menu.

        if ($last_page < ($this->range * 2) + 6) {
            $start_page = $first_page;
            $end_page   = $last_page;
        } elseif ($this->page < ($this->range * 2) + 1) {
            $start_page = $first_page;
            $end_page   = ($this->range * 2) + 3;
        } elseif ($this->page > $last_page - ($this->range * 2)) {
            $start_page = $last_page - ($this->range * 2) - 2;
            $end_page   = $last_page;
        } else {
            $start_page = $this->page - $this->range;
            $end_page   = $this->page + $this->range;
        }
        $start_page = max($first_page, $start_page);
        $end_page   = min($last_page, $end_page);

        $links = '
pages_class.'">';

        $links .= 'c::escAttr($this->page === $first_page ? $this->page_icon_disabled_class : $this->page_icon_class).'"'.
                    ' href="'.$this->c::escUrl($this->page === $first_page ? '#' : $this->pageUrl($this->page - 1)).'">';
        $links .= $this->prev_page_icon.' '.$this->c::escHtml($this->prev_page_text);
        $links .= '';

        if ($start_page > $first_page) {
            $links .= 'c::escAttr($this->page_class).'"'.
                        ' href="'.$this->c::escUrl($this->pageUrl($first_page)).'">';
            $links .= $this->first_page_icon.' '.$first_page;
            $links .= '';

            $links .= 'c::escAttr($this->page_icon_disabled_class).'">';
            $links .= $this->ellipsis_icon;
            $links .= '';
        }
        for ($_page = $start_page; $_page <= $end_page; ++$_page) {
            $links .= 'c::escAttr($_page === $this->page ? $this->page_active_class : $this->page_class).'"'.
                        ' href="'.$this->c::escUrl($_page === $this->page ? '#' : $this->pageUrl($_page)).'">';
            $links .= $_page;
            $links .= '';
        }
        if ($end_page < $last_page) {
            $links .= 'c::escAttr($this->page_icon_disabled_class).'">';
            $links .= $this->ellipsis_icon;
            $links .= '';

            $links .= 'c::escAttr($this->page_class).'"'.
                        ' href="'.$this->c::escUrl($this->pageUrl($last_page)).'">';
            $links .= $last_page.' '.$this->last_page_icon;
            $links .= '';
        }
        $links .= 'c::escAttr($this->page === $last_page ? $this->page_icon_disabled_class : $this->page_icon_class).'"'.
                    ' href="'.$this->c::escUrl($this->page === $last_page ? '#' : $this->pageUrl($this->page + 1)).'">';
        $links .= $this->c::escHtml($this->next_page_text).' '.$this->next_page_icon;
        $links .= '';

        $links .= '
';

        return $links;
    }

    /**
     * Get page URL.
     *
     * @since 170117 Paginator.
     *
     * @param int $page Page number.
     *
     * @return string Page URL.
     */
    protected function pageUrl(int $page): string
    {
        if ($this->page_url_callback && is_callable($this->page_url_callback)) {
            return str_replace($this->page_replacement_code, $page, (string) $this->page_url_callback($page));
        }
        return str_replace($this->page_replacement_code, $page, $this->page_url);
    }
}


<?php

/*
 * This file is part of the Ivory Google Map package.
 *
 * (c) Eric GELOEN <geloen.eric@gmail.com>
 *
 * For the full copyright and license information, please read the LICENSE
 * file that was distributed with this source code.
 */

namespace Ivory\GoogleMap\Services\DistanceMatrix;

use Ivory\GoogleMap\Base\Coordinate;
use Ivory\GoogleMap\Exception\DistanceMatrixException;
use Ivory\GoogleMap\Services\Base\TravelMode;
use Ivory\GoogleMap\Services\Base\UnitSystem;

/**
 * DistanceMatrixRequest represents a google map distance matrix query.
 *
 * @see http://code.google.com/apis/maps/documentation/javascript/reference.html#DistanceMatrixRequest
 * @author GeLo <geloen.eric@gmail.com>
 * @author Tyler Sommer <sommertm@gmail.com>
 */
class DistanceMatrixRequest
{
    /** @var boolean */
    protected $avoidHighways;

    /** @var boolean */
    protected $avoidTolls;

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

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

    /** @var string */
    protected $region;

    /** @var string */
    protected $language;

    /** @var string */
    protected $travelMode;

    /** @var string */
    protected $unitSystem;

    /** @var boolean */
    protected $sensor;

    /**
     * Creates a distance matrix request.
     */
    public function __construct()
    {
        $this->origins = array();
        $this->destinations = array();
        $this->sensor = false;
    }

    /**
     * Checks if the distance matrix request has an avoid hightways flag.
     *
     * @return boolean TRUE if the distance matrix request has an avoid hightways flag else FALSE.
     */
    public function hasAvoidHighways()
    {
        return $this->avoidHighways !== null;
    }

    /**
     * Checks if the distance matrix request avoid hightways.
     *
     * @return boolean TRUE if the distance matrix request avoids hightways else FALSE.
     */
    public function getAvoidHighways()
    {
        return $this->avoidHighways;
    }

    /**
     * Sets if the the distance matrix request avoids hightways.
     *
     * @param boolean $avoidHighways TRUE if the distance matrix request avoids hightways else FALSE.
     *
     * @throws \Ivory\GoogleMap\Exception\DistanceMatrixException If the avoid highways flag is not valid.
     */
    public function setAvoidHighways($avoidHighways = null)
    {
        if (!is_bool($avoidHighways) && ($avoidHighways !== null)) {
            throw DistanceMatrixException::invalidDistanceMatrixRequestAvoidHighways();
        }

        $this->avoidHighways = $avoidHighways;
    }

    /**
     * Checks if the distance matrix request has an avoid tolls flag.
     *
     * @return boolean TRUE if the distance matrix request has an avoid tolls flag else FALSE.
     */
    public function hasAvoidTolls()
    {
        return $this->avoidTolls !== null;
    }

    /**
     * Checks if the distance matrix request avoid tolls.
     *
     * @return boolean TRUE if the distance matrix request avoids tolls else FALSE.
     */
    public function getAvoidTolls()
    {
        return $this->avoidTolls;
    }

    /**
     * Sets if the the distance matrix request avoids tolls.
     *
     * @param boolean $avoidTolls TRUE if the distance matrix request avoids tolls else FALSE.
     *
     * @throws \Ivory\GoogleMap\Exception\DistanceMatrixException If the avoid tolls flag is not valid.
     */
    public function setAvoidTolls($avoidTolls = null)
    {
        if (!is_bool($avoidTolls) && ($avoidTolls !== null)) {
            throw DistanceMatrixException::invalidDistanceMatrixRequestAvoidTolls();
        }

        $this->avoidTolls = $avoidTolls;
    }

    /**
     * Checks if the distance matrix request has destinations.
     *
     * @return boolean TRUE if the distance matrix request has a destination else FALSE.
     */
    public function hasDestinations()
    {
        return !empty($this->destinations);
    }

    /**
     * Gets the distance matrix request destinations
     *
     * @return array The distance matrix request destination.
     */
    public function getDestinations()
    {
        return $this->destinations;
    }

    /**
     * Sets the request destinations.
     *
     * @param array $destinations The distance matrix request destinations.
     */
    public function setDestinations(array $destinations = array())
    {
        $this->destinations = array();

        foreach ($destinations as $destination) {
            $this->addDestination($destination);
        }
    }

    /**
     * Adds a destination to the request.
     *
     * Available prototypes:
     * - function addDestination(string $destination)
     * - function addDestination(Ivory\GoogleMap\Base\Coordinate $destination)
     * - function addDestination(double $latitude, double $longitude, boolean $noWrap)
     *
     * @throws \Ivory\GoogleMap\Exception\DistanceMatrixException If the destination is not valid (prototypes).
     */
    public function addDestination()
    {
        $args = func_get_args();

        if (isset($args[0]) && is_string($args[0])) {
            $this->destinations[] = $args[0];
        } elseif (isset($args[0]) && ($args[0] instanceof Coordinate)) {
            $this->destinations[] = $args[0];
        } elseif ((isset($args[0]) && is_numeric($args[0])) && (isset($args[1]) && is_numeric($args[1]))) {
            $destination = new Coordinate();
            $destination->setLatitude($args[0]);
            $destination->setLongitude($args[1]);

            if (isset($args[2]) && is_bool($args[2])) {
                $destination->setNoWrap($args[2]);
            }

            $this->destinations[] = $destination;
        } else {
            throw DistanceMatrixException::invalidDistanceMatrixRequestDestination();
        }
    }

    /**
     * Checks if the distance matrix request has origins.
     *
     * @return boolean TRUE if the distance matrix request has origins else FALSE.
     */
    public function hasOrigins()
    {
        return !empty($this->origins);
    }

    /**
     * Gets the distance matrix request origin.
     *
     * @return array The distance matrix request origin.
     */
    public function getOrigins()
    {
        return $this->origins;
    }

    /**
     * Sets the request origins.
     *
     * @param array $origins The distance matrix request origins.
     */
    public function setOrigins(array $origins = array())
    {
        $this->origins = array();

        foreach ($origins as $origin) {
            $this->addOrigin($origin);
        }
    }

    /**
     * Adds an origin to the request.
     *
     * Available prototypes:
     * - function addOrigin(string $destination)
     * - function addOrigin(Ivory\GoogleMap\Base\Coordinate $destination)
     * - function addOrigin(double $latitude, double $longitude, boolean $noWrap)
     *
     * @throws \Ivory\GoogleMap\Exception\DistanceMatrixException If the origin is not valid (prototypes).
     */
    public function addOrigin()
    {
        $args = func_get_args();

        if (isset($args[0]) && is_string($args[0])) {
            $this->origins[] = $args[0];
        } elseif (isset($args[0]) && ($args[0] instanceof Coordinate)) {
            $this->origins[] = $args[0];
        } elseif ((isset($args[0]) && is_numeric($args[0])) && (isset($args[1]) && is_numeric($args[1]))) {
            $origin = new Coordinate();
            $origin->setLatitude($args[0]);
            $origin->setLongitude($args[1]);

            if (isset($args[2]) && is_bool($args[2])) {
                $origin->setNoWrap($args[2]);
            }

            $this->origins[] = $origin;
        } else {
            throw DistanceMatrixException::invalidDistanceMatrixRequestOrigin();
        }
    }

    /**
     * Checks if the distance matrix request has a region.
     *
     * @return boolean TRUE if the distance matrix request has a region else FALSE.
     */
    public function hasRegion()
    {
        return $this->region !== null;
    }

    /**
     * Gets the distance matrix request region.
     *
     * @return string The direction request region.
     */
    public function getRegion()
    {
        return $this->region;
    }

    /**
     * Sets the distance matrix request region.
     *
     * @param string $region The distance matrix request region.
     *
     * @throws \Ivory\GoogleMap\Exception\DistanceMatrixException If the region is not valid.
     */
    public function setRegion($region = null)
    {
        if ((!is_string($region) || (strlen($region) !== 2)) && ($region !== null)) {
            throw DistanceMatrixException::invalidDistanceMatrixRequestRegion();
        }

        $this->region = $region;
    }

    /**
     * Checks if the distance matrix request has a language.
     *
     * @return boolean TRUE if the distance matrix request has a language else FALSE.
     */
    public function hasLanguage()
    {
        return $this->language !== null;
    }

    /**
     * Gets the distance matrix request language.
     *
     * @return string The direction request language.
     */
    public function getLanguage()
    {
        return $this->language;
    }

    /**
     * Sets the distance matrix request language.
     *
     * @param string $language The distance matrix request language.
     *
     * @throws \Ivory\GoogleMap\Exception\DistanceMatrixException If the language is not valid.
     */
    public function setLanguage($language = null)
    {
        if ((!is_string($language) || ((strlen($language) !== 2) && (strlen($language) !== 5))) && ($language !== null)) {
            throw DistanceMatrixException::invalidDistanceMatrixRequestLanguage();
        }

        $this->language = $language;
    }

    /**
     * Checks if the distance matrix request has a travel mode.
     *
     * @return boolean TRUE if the distance matrix request has a travel mode else FALSE.
     */
    public function hasTravelMode()
    {
        return $this->travelMode !== null;
    }

    /**
     * Gets the distance matrix request travel mode.
     *
     * @return string The distance matrix request travel mode.
     */
    public function getTravelMode()
    {
        return $this->travelMode;
    }

    /**
     * Sets the distance matrix request travel mode.
     *
     * @param string $travelMode The distance matrix request travel mode.
     *
     * @throws \Ivory\GoogleMap\Exception\DistanceMatrixException If the travel mode is not valid.
     */
    public function setTravelMode($travelMode = null)
    {
        $travelModes = array_diff(TravelMode::getTravelModes(), array(TravelMode::TRANSIT));

        if (!in_array($travelMode, $travelModes) && ($travelMode !== null)) {
            throw DistanceMatrixException::invalidDistanceMatrixRequestTravelMode();
        }

        $this->travelMode = $travelMode;
    }

    /**
     * Checks if the distance matrix request has a unit system.
     *
     * @return boolean TRUE if the distance matrix request has a unit system else FALSE.
     */
    public function hasUnitSystem()
    {
        return $this->unitSystem !== null;
    }

    /**
     * Gets the distance matrix request unit system.
     *
     * @return string The distance matrix request unit system.
     */
    public function getUnitSystem()
    {
        return $this->unitSystem;
    }

    /**
     * Sets  the distance matrix request unit system.
     *
     * @param string $unitSystem The distance matrix request unit system.
     *
     * @throws \Ivory\GoogleMap\Exception\DistanceMatrixException If the unit system is not valid.
     */
    public function setUnitSystem($unitSystem = null)
    {
        if (!in_array($unitSystem, UnitSystem::getUnitSystems()) && ($unitSystem !== null)) {
            throw DistanceMatrixException::invalidDistanceMatrixRequestUnitSystem();
        }

        $this->unitSystem = $unitSystem;
    }

    /**
     * Checks if the distance matrix request has a sensor.
     *
     * @return boolean TRUE if the distance matrix request has a sensor else FALSE.
     */
    public function hasSensor()
    {
        return $this->sensor;
    }

    /**
     * Sets the distance matrix request sensor.
     *
     * @param boolean $sensor TRUE if the distance matrix request has a sensor else FALSE.
     *
     * @throws \Ivory\GoogleMap\Exception\DistanceMatrixException If the sensor flag is not valid.
     */
    public function setSensor($sensor)
    {
        if (!is_bool($sensor)) {
            throw DistanceMatrixException::invalidDistanceMatrixRequestSensor();
        }

        $this->sensor = $sensor;
    }

    /**
     * Checks if the distance matrix request is valid.
     *
     * @return boolean TRUE if the distance matrix request is valid else FALSE.
     */
    public function isValid()
    {
        return $this->hasDestinations() && $this->hasOrigins();
    }
}


<?php

/*
 * This file is part of the Ivory Google Map package.
 *
 * (c) Eric GELOEN <geloen.eric@gmail.com>
 *
 * For the full copyright and license information, please read the LICENSE
 * file that was distributed with this source code.
 */

namespace Ivory\GoogleMap\Controls;

/**
 * Control position which describes a google map control position.
 *
 * @see http://code.google.com/apis/maps/documentation/javascript/reference.html#ControlPosition
 * @author GeLo <geloen.eric@gmail.com>
 */
class ControlPosition
{
    const BOTTOM_CENTER = 'bottom_center';
    const BOTTOM_LEFT = 'bottom_left';
    const BOTTOM_RIGHT = 'bottom_right';
    const LEFT_BOTTOM = 'left_bottom';
    const LEFT_CENTER = 'left_center';
    const LEFT_TOP = 'left_top';
    const RIGHT_BOTTOM = 'right_bottom';
    const RIGHT_CENTER = 'right_center';
    const RIGHT_TOP = 'right_top';
    const TOP_CENTER = 'top_center';
    const TOP_LEFT = 'top_left';
    const TOP_RIGHT = 'top_right';

    /**
     * Disabled constructor.
     *
     * @codeCoverageIgnore
     */
    final private function __construct()
    {

    }

    /**
     * Gets the available control positions.
     *
     * @return array The control positions.
     */
    public static function getControlPositions()
    {
        return array(
            self::BOTTOM_CENTER,
            self::BOTTOM_LEFT,
            self::BOTTOM_RIGHT,
            self::LEFT_BOTTOM,
            self::LEFT_CENTER,
            self::LEFT_TOP,
            self::RIGHT_BOTTOM,
            self::RIGHT_CENTER,
            self::RIGHT_TOP,
            self::TOP_CENTER,
            self::TOP_LEFT,
            self::TOP_RIGHT,
        );
    }
}