<?php
/**
 * Trim (multibyte-safe).
 *
 * @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;

/**
 * Trim (multibyte-safe).
 *
 * @since 150424 Initial release.
 */
class Trim extends Classes\Core\Base\Core
{
    /**
     * Trim (multibyte-safe).
     *
     * @since 150424 Initial release.
     *
     * @param mixed  $value       Any input value.
     * @param string $chars       Defaults to: " \r\n\t\0\x0B".
     * @param string $extra_chars Additional chars to trim.
     * @param string $side        Optional; one of `l` or `r`.
     *
     * @return string|array|object Trimmed value.
     */
    public function __invoke($value, string $chars = '', string $extra_chars = '', string $side = '')
    {
        if (is_array($value) || is_object($value)) {
            foreach ($value as $_key => &$_value) {
                $_value = $this->__invoke($_value, $chars, $extra_chars, $side);
            } // unset($_key, $_value); // Housekeeping.
            return $value;
        }
        $string = (string) $value;

        if (!isset($string[0])) {
            return $string; // Nothing to do.
        }
        $chars = isset($chars[0]) ? $chars : " \r\n\t\0\x0B";
        $chars = $this->c::escRegex($chars.$extra_chars);

        switch ($side) {
            case 'l': // Left trim.
                return preg_replace('/^['.$chars.']+/u', '', $string);

            case 'r': // Right trim.
                return preg_replace('/['.$chars.']+$/u', '', $string);

            default: // Both sides.
                return preg_replace('/^['.$chars.']+|['.$chars.']+$/u', '', $string);
        }
    }

    /**
     * Trim (multibyte-safe) on left.
     *
     * @since 150424 Initial release.
     *
     * @param mixed  $value       Any input value.
     * @param string $chars       Defaults to: " \r\n\t\0\x0B".
     * @param string $extra_chars Additional chars to trim.
     *
     * @return string|array|object Trimmed value.
     */
    public function l($value, string $chars = '', string $extra_chars = '')
    {
        return $this->__invoke($value, $chars, $extra_chars, 'l');
    }

    /**
     * Trim (multibyte-safe) on right.
     *
     * @since 150424 Initial release.
     *
     * @param mixed  $value       Any input value.
     * @param string $chars       Defaults to: " \r\n\t\0\x0B".
     * @param string $extra_chars Additional chars to trim.
     *
     * @return string|array|object Trimmed value.
     */
    public function r($value, string $chars = '', string $extra_chars = '')
    {
        return $this->__invoke($value, $chars, $extra_chars, 'r');
    }
}


<?php
namespace Perry\Fetcher;

use GuzzleHttp\Client;
use Perry\Cache\CacheManager;
use Perry\Perry;
use Perry\Response;
use Perry\Setup;
use Perry\Tool;

class GuzzleFetcher implements CanFetch
{
    private $guzzle;

    public function __construct()
    {
        $this->guzzle = new Client();
    }

    /**
     * form the opts array
     *
     * @param string $representation
     * @return array
     */
    private function getOpts($representation)
    {
        $headers = [
            "Accept-language" => "en",
            'User-Agent' => 'Perry/' . Perry::$version . ' ' .Setup::$userAgent
        ];

        if (!is_null($representation)) {
            $headers["Accept"] = "application/$representation+json";
        }

        $config =[];

        if ("0.0.0.0:0" != Setup::$bindToIp) {
            $config['curl'] = [CURLOPT_INTERFACE => Setup::$bindToIp];
        }

        $options = [
            "headers" => $headers,
            "config" => $config
        ];

        // merge in the ons from the options array
        $options = array_merge_recursive(Setup::$fetcherOptions, $options);

        return $options;
    }

    /**
     * @param string $url
     * @param string $representation
     * @throws \Exception
     * @return \Perry\Response
     */
    public function doGetRequest($url, $representation)
    {

        if ($data = CacheManager::getInstance()->load($url)) {
            return new Response($data['value'], $data['representation']);
        }

        $response = $this->guzzle->get($url, $this->getOpts($representation));

        $data = $response->getBody();
        $data = (String) $data;

        if ($response->hasHeader("Content-Type")) {
            if (false !== ($retrep = Tool::parseContentTypeToRepresentation($response->getHeader("Content-Type")))) {
                $representation = $retrep;
            }
        }

        CacheManager::getInstance()->save($url, ["representation" => $representation, "value" => $data]);

        return new Response($data, $representation);
    }
}


<?php
/**
 * OAuth access token entity.
 *
 * @author @jaswrks
 * @copyright WebSharks™
 */
declare(strict_types=1);
namespace WebSharks\Core\Classes\Core\OAuth\Server\Entities;

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 Lcobucci\JWT\Builder;
use Lcobucci\JWT\Signer\Key;
use Lcobucci\JWT\Signer\Rsa\Sha256;
#
use League\OAuth2\Server\CryptKey;
use League\OAuth2\Server\Entities\ClientEntityInterface;
use League\OAuth2\Server\Entities\ScopeEntityInterface;
use League\OAuth2\Server\Entities\AccessTokenEntityInterface;

/**
 * OAuth access token entity.
 *
 * @since 17xxxx
 */
class AccessTokenEntity extends Entity implements AccessTokenEntityInterface
{
    /**
     * Client entity.
     *
     * @since 17xxxx
     *
     * @type ClientEntity|null
     */
    protected $ClientEntity;

    /**
     * User identifier.
     *
     * @since 17xxxx
     *
     * @type string
     */
    protected $user_identifier;

    /**
     * Scopes.
     *
     * @since 17xxxx
     *
     * @type array
     */
    protected $scopes;

    /**
     * Expiry date/time.
     *
     * @since 17xxxx
     *
     * @type \DateTime|null
     */
    protected $expiryDateTime;

    /**
     * Class constructor.
     *
     * @since 17xxxx OAuth utils.
     *
     * @param Classes\App       $App             App.
     * @param string            $identifier      Identifier.
     * @param ClientEntity|null $ClientEntity    Client entity.
     * @param string|int        $user_identifier User identifier.
     * @param ScopeEntity[]     $scopes          Scope entity array.
     * @param \DateTime         $expiryDateTime  Expiry date/time.
     */
    public function __construct(
        Classes\App $App,
        string $identifier = '',
        ClientEntity $ClientEntity = null,
        string $user_identifier = '',
        array $scopes = [],
        \DateTime $expiryDateTime = null
    ) {
        parent::__construct($App, $identifier);

        $this->ClientEntity    = $ClientEntity;
        $this->user_identifier = $user_identifier;
        $this->scopes          = $scopes;
        $this->expiryDateTime  = $expiryDateTime;
    }

    /**
     * Get client entity.
     *
     * @since 17xxxx OAuth utils.
     *
     * @return ClientEntityInterface|null Client entity.
     */
    public function getClient()
    {
        return $this->ClientEntity;
    }

    /**
     * Set client entity.
     *
     * @since 17xxxx OAuth utils.
     *
     * @param ClientEntityInterface $ClientEntity Client entity.
     */
    public function setClient(ClientEntityInterface $ClientEntity)
    {
        $this->ClientEntity = $ClientEntity;
    }

    /**
     * Get user identifier.
     *
     * @since 17xxxx OAuth utils.
     *
     * @return string User identifier.
     */
    public function getUserIdentifier()
    {
        return $this->user_identifier;
    }

    /**
     * Set user identifier.
     *
     * @since 17xxxx OAuth utils.
     *
     * @param string $user_identifier User identifier.
     */
    public function setUserIdentifier($user_identifier)
    {
        $this->user_identifier = $user_identifier;
    }

    /**
     * Get scope entities.
     *
     * @since 17xxxx OAuth utils.
     *
     * @return ScopeEntityInterface[] Scopes.
     */
    public function getScopes()
    {
        return array_values($this->scopes);
    }

    /**
     * Add a scope entity.
     *
     * @since 17xxxx OAuth utils.
     *
     * @param ScopeEntityInterface $ScopeEntity Scope entity.
     */
    public function addScope(ScopeEntityInterface $ScopeEntity)
    {
        $this->scopes[$ScopeEntity->getIdentifier()] = $ScopeEntity;
    }

    /**
     * Remove a scope entity.
     *
     * @since 17xxxx OAuth utils.
     *
     * @param string $scope_identifier Scope identifier.
     */
    public function removeScope($scope_identifier)
    {
        unset($this->scopes[$scope_identifier]);
    }

    /**
     * Get expiry date/time.
     *
     * @since 17xxxx OAuth utils.
     *
     * @return \DateTime|null Expiry date/time.
     */
    public function getExpiryDateTime()
    {
        return $this->expiryDateTime;
    }

    /**
     * Set expiry date/time.
     *
     * @since 17xxxx OAuth utils.
     *
     * @param \DateTime $DateTime Expiry date/time.
     */
    public function setExpiryDateTime(\DateTime $DateTime)
    {
        $this->expiryDateTime = $DateTime;
    }

    /**
     * Convert to JWT (token).
     *
     * @param CryptKey $CryptKey Private key.
     *
     * @return string JWT (token).
     */
    public function convertToJWT(CryptKey $CryptKey)
    {
        return (new Builder())
            ->setAudience($this->getClient()->getIdentifier())
            ->setId($this->getIdentifier(), true)
            ->setIssuedAt(time())
            ->setNotBefore(time())
            ->setExpiration($this->getExpiryDateTime()->getTimestamp())
            ->setSubject($this->getUserIdentifier())
            ->set('scopes', $this->getScopes())
            ->sign(new Sha256(), new Key($CryptKey->getKeyPath(), $CryptKey->getPassPhrase()))
            ->getToken();
    }
}


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

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

class Api extends Base
{
    public $motd;

    public $crestEndpoint;

    public $corporationRoles;

    public $itemGroups;

    public $channels;

    public $corporations;

    public $alliances;

    public $itemTypes;

    public $decode;

    public $battleTheatres;

    public $marketPrices;

    public $itemCategories;

    public $regions;

    public $bloodlines;

    public $marketGroups;

    public $sovereignty;

    public $tournaments;

    public $map;

    public $virtualGoodStore;

    public $serverVersion;

    public $wars;

    public $incursions;

    public $races;

    public $authEndpoint;

    public $serviceStatus;

    public $userCounts;

    public $industry;

    public $clients;

    public $time;

    public $marketTypes;

    public $serverName;

    // by Warringer\Types\Dict
    public function setMotd($motd)
    {
        // by Warringer\Types\Dict
        $converters = [];
        $converters['dust'] = function ($value) { return new Reference($value); };
        $converters['eve'] = function ($value) { return new Reference($value); };
        $converters['server'] = function ($value) { return new Reference($value); };

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    // by Warringer\Types\Dict
    public function setSovereignty($sovereignty)
    {
        // by Warringer\Types\Dict
        $converters = [];
        $converters['campaigns'] = function ($value) { return new Reference($value); };
        $converters['structures'] = function ($value) { return new Reference($value); };

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

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

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

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

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

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

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

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

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

    // by Warringer\Types\Dict
    public function setServiceStatus($serviceStatus)
    {
        // by Warringer\Types\Dict
        $converters = [];
        $converters['dust'] = function ($value) { return $value; };
        $converters['eve'] = function ($value) { return $value; };
        $converters['server'] = function ($value) { return $value; };

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

    // by Warringer\Types\Dict
    public function setUserCounts($userCounts)
    {
        // by Warringer\Types\Dict
        $converters = [];
        $converters['dust'] = function ($value) { return $value; };
        $converters['eve'] = function ($value) { return $value; };

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

    // by Warringer\Types\Dict
    public function setIndustry($industry)
    {
        // by Warringer\Types\Dict
        $converters = [];
        $converters['facilities'] = function ($value) { return new Reference($value); };
        $converters['systems'] = function ($value) { return new Reference($value); };

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

    // by Warringer\Types\Dict
    public function setClients($clients)
    {
        // by Warringer\Types\Dict
        $converters = [];
        $converters['dust'] = function ($value) { return new Reference($value); };
        $converters['eve'] = function ($value) { return new Reference($value); };

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

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

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

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

}


<?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 Constellation extends Base
{
    public $position;

    public $region;

    public $systems = [];

    public $name;

    // 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 setRegion($region)
    {
        $this->region = new Reference($region);
    }

    // by Warringer\Types\ArrayType
    public function setSystems($systems)
    {
        // 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 ($systems as $key => $value) {
            $this->systems[$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\Services\DistanceMatrix;

use Ivory\GoogleMap\Services\AbstractService;
use Ivory\GoogleMap\Exception\DistanceMatrixException;
use Ivory\GoogleMap\Services\Base\Distance;
use Ivory\GoogleMap\Services\Base\Duration;
use Widop\HttpAdapter\HttpAdapterInterface;

/**
 * DistanceMatrix service.
 *
 * @author GeLo <geloen.eric@gmail.com>
 * @author Tyler Sommer <sommertm@gmail.com>
 */
class DistanceMatrix extends AbstractService
{
    /**
     * Creates a distance matrix service.
     *
     * @param \Widop\HttpAdapter\HttpAdapterInterface $httpAdapter The http adapter.
     */
    public function __construct(HttpAdapterInterface $httpAdapter)
    {
        parent::__construct($httpAdapter, 'http://maps.googleapis.com/maps/api/distancematrix');
    }

    /**
     * Processes the given request.
     *
     * Available prototypes:
     * - function process(array $origins, array $destinations)
     * - function process(Ivory\GoogleMap\Services\DistanceMatrix\DistanceMatrixRequest $request)
     *
     * @throws \Ivory\GoogleMap\Exception\DistanceMatrixException If the request is not valid (prototypes).
     */
    public function process()
    {
        $args = func_get_args();

        if (isset($args[0]) && ($args[0] instanceof DistanceMatrixRequest)) {
            $distanceMatrixRequest = $args[0];
        } elseif ((isset($args[0]) && is_array($args[0])) && (isset($args[1]) && is_array($args[1]))) {
            $distanceMatrixRequest = new DistanceMatrixRequest();

            $distanceMatrixRequest->setOrigins($args[0]);
            $distanceMatrixRequest->setDestinations($args[1]);
        } else {
            throw DistanceMatrixException::invalidDistanceMatrixRequestParameters();
        }

        if (!$distanceMatrixRequest->isValid()) {
            throw DistanceMatrixException::invalidDistanceMatrixRequest();
        }

        $response = $this->send($this->generateUrl($distanceMatrixRequest));
        $distanceMatrixResponse = $this->buildDistanceMatrixResponse($this->parse($response->getBody()));

        return $distanceMatrixResponse;
    }

    /**
     * Generates distance matrix URL API according to the request.
     *
     * @param \Ivory\GoogleMap\Services\DistanceMatrix\DistanceMatrixRequest $distanceMatrixRequest The distance matrix request.
     *
     * @return string The generated URL.
     */
    protected function generateUrl(DistanceMatrixRequest $distanceMatrixRequest)
    {
        $httpQuery = array(
            'origins'      => array(),
            'destinations' => array(),
        );

        foreach ($distanceMatrixRequest->getOrigins() as $origin) {
            if (is_string($origin)) {
                $httpQuery['origins'][] = $origin;
            } else {
                $httpQuery['origins'][] = sprintf(
                    '%s,%s',
                    $origin->getLatitude(),
                    $origin->getLongitude()
                );
            }
        }

        foreach ($distanceMatrixRequest->getDestinations() as $destination) {
            if (is_string($destination)) {
                $httpQuery['destinations'][] = $destination;
            } else {
                $httpQuery['destinations'][] = sprintf(
                    '%s,%s',
                    $destination->getLatitude(),
                    $destination->getLongitude()
                );
            }
        }

        $httpQuery['origins'] = implode('|', $httpQuery['origins']);
        $httpQuery['destinations'] = implode('|', $httpQuery['destinations']);

        if ($distanceMatrixRequest->hasTravelMode()) {
            $httpQuery['mode'] = strtolower($distanceMatrixRequest->getTravelMode());
        }

        if ($distanceMatrixRequest->hasAvoidTolls() && $distanceMatrixRequest->getAvoidTolls()) {
            $httpQuery['avoidTolls'] = true;
        }

        if ($distanceMatrixRequest->hasAvoidHighways() && $distanceMatrixRequest->getAvoidHighways()) {
            $httpQuery['avoidHighways'] = true;
        }

        if ($distanceMatrixRequest->hasUnitSystem()) {
            $httpQuery['units'] = strtolower($distanceMatrixRequest->getUnitSystem());
        }

        if ($distanceMatrixRequest->hasRegion()) {
            $httpQuery['region'] = $distanceMatrixRequest->getRegion();
        }

        if ($distanceMatrixRequest->hasLanguage()) {
            $httpQuery['language'] = $distanceMatrixRequest->getLanguage();
        }

        $httpQuery['sensor'] = $distanceMatrixRequest->hasSensor() ? 'true' : 'false';

        $url = sprintf('%s/%s?%s', $this->getUrl(), $this->getFormat(), http_build_query($httpQuery));

        return $this->signUrl($url);
    }

    /**
     * Parses & normalizes the distance matrix API result response.
     *
     * @param string $response The distance matrix API response.
     *
     * @return \stdClass The parsed & normalized distance matrix response.
     */
    protected function parse($response)
    {
        if ($this->format === 'json') {
            return $this->parseJSON($response);
        }

        return $this->parseXML($response);
    }

    /**
     * Parses & normalizes a JSON distance matrix API result response.
     *
     * @param string $response The distance matrix API JSON response.
     *
     * @return \stdClass The parsed & normalized distance matrix response.
     */
    protected function parseJSON($response)
    {
        return json_decode($response);
    }

    /**
     * Parses & normalizes an XML distance matrix API result response.
     *
     * @param string $response The distance matrix API XML response.
     *
     * @return \stdClass The parsed & normalized distance matrix response.
     */
    protected function parseXML($response)
    {
        $rules = array(
            'destination_address' => 'destination_addresses',
            'element'             => 'elements',
            'origin_address'      => 'origin_addresses',
            'row'                 => 'rows',
        );

        return $this->xmlParser->parse($response, $rules);
    }

    /**
     * Builds the distance matrix response according to the normalized distance matrix API results.
     *
     * @param \stdClass $distanceMatrixResponse The normalized distance matrix response.
     *
     * @return \Ivory\GoogleMap\Services\DistanceMatrix\DistanceMatrixResponse The built distance matrix response.
     */
    protected function buildDistanceMatrixResponse(\stdClass $distanceMatrixResponse)
    {
        $status = $distanceMatrixResponse->status;
        $destinations = $distanceMatrixResponse->destination_addresses;
        $origins = $distanceMatrixResponse->origin_addresses;
        $rows = $this->buildDistanceMatrixRows($distanceMatrixResponse->rows);

        return new DistanceMatrixResponse($status, $origins, $destinations, $rows);
    }

    /**
     * Builds the distance matrix response rows according to the normalized distance matrix API results.
     *
     * @param array $rows The normalized distance matrix response rows.
     *
     * @return array The built distance matrix response rows.
     */
    protected function buildDistanceMatrixRows($rows)
    {
        $results = array();

        foreach ($rows as $row) {
            $results[] = $this->buildDistanceMatrixRow($row);
        }

        return $results;
    }

    /**
     * Builds a distance matrix response row according to the normalized distance matrix API response row.
     *
     * @param \stdClass $row The normalized distance matrix response row.
     *
     * @return \Ivory\GoogleMap\Services\DistanceMatrix\DistanceMatrixResponseRow The built distance matrix response row.
     */
    protected function buildDistanceMatrixRow($row)
    {
        $elements = array();

        foreach ($row->elements as $element) {
            $elements[] = $this->buildDistanceMatrixResponseElement($element);
        }

        return new DistanceMatrixResponseRow($elements);
    }

    /**
     * Builds a distance matrix response element according to the normalized distance matrix API response elements.
     *
     * @param \stdClass $element The normalized distance matrix response element.
     *
     * @return \Ivory\GoogleMap\Services\DistanceMatrix\DistanceMatrixResponseElement The built distance matrix response element.
     */
    protected function buildDistanceMatrixResponseElement($element)
    {
        $status = $element->status;
        $distance = null;
        $duration = null;

        if ($element->status === DistanceMatrixElementStatus::OK) {
            $distance = new Distance($element->distance->text, $element->distance->value);
            $duration = new Duration($element->duration->text, $element->duration->value);
        }

        return new DistanceMatrixResponseElement($status, $distance, $duration);
    }
}


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

use Ivory\GoogleMap\Base\Point;

/**
 * Point helper.
 *
 * @author GeLo <geloen.eric@gmail.com>
 */
class PointHelper
{
    /**
     * Renders a point.
     *
     * @param \Ivory\GoogleMap\Base\Point $point The point.
     *
     * @return string The JS output.
     */
    public function render(Point $point)
    {
        return sprintf(
            '%s = new google.maps.Point(%s, %s);'.PHP_EOL,
            $point->getJavascriptVariable(),
            $point->getX(),
            $point->getY()
        );
    }
}


<?php
//------------------------
//· email类
//---------------------
namespace denha;

class Smtp
{
    public $host_name;
    public $log_file; //日志文件
    public $relay_host; //SMTP服务器
    public $smtp_port; //SMTP服务器端口
    public $user; //SMTP账户
    public $pass; //SMTP密码
    public $debug = false; //是否开启调试信息
    public $time_out; //链接超时时间
    public $auth;
    public $sock;
    public $from;

    public function __construct($group = 0)
    {

        $this->init($group);

    }

    public function init($group)
    {
        $smtp = config(null, 'smtp'); //获取stmp配置信息

        $this->debug      = false;
        $this->smtp_port  = $smtp[$group]['smtp_port'];
        $this->relay_host = $smtp[$group]['smtp_host'];
        $this->time_out   = 30;
        $this->auth       = true;
        $this->user       = $smtp[$group]['smtp_user'];
        $this->pass       = $smtp[$group]['smtp_password'];
        $this->from       = $smtp[$group]['smtp_mail'] ? $smtp[$group]['smtp_mail'] : $smtp[$group]['smtp_user'];

        $this->host_name = 'localhost';
        $this->log_file  = '';
        $this->sock      = false;

    }

    protected function smtp($relay_host = '', $smtp_port = 25, $auth = false, $user, $pass)
    {
        $this->debug      = false;
        $this->smtp_port  = $smtp_port;
        $this->relay_host = $relay_host;
        $this->time_out   = 30;
        $this->auth       = $auth;
        $this->user       = $user;
        $this->pass       = $pass;

        $this->host_name = 'localhost';
        $this->log_file  = '';
        $this->sock      = false;

    }

    /** debug测试 */
    protected function testDebug()
    {

        $this->debug      = true;
        $this->smtp_port  = 25;
        $this->relay_host = 'smtp.163.com'; //服务器地址
        $this->time_out   = 30;
        $this->auth       = true;
        $this->user       = 'senddebug'; //账户
        $this->pass       = 'uVqe2aZ0Wc0DiAVo'; //密码
        $this->from       = 'senddebug@163.com'; //发送邮箱名

        $this->host_name = 'localhost';
        $this->log_file  = '';
        $this->sock      = false;

        $this->sendmail('cheng6251@163.com', '测试邮箱', '测邮箱信息能否通过', 'HTML');
    }

    /**
     * [sendmail description]
     * @date   2017-10-27T14:32:38+0800
     * @author ChenMingjiang
     * @param  [type]                   $to                 [接收邮箱 多个逗号分隔]
     * @param  string                   $subject            [邮件标题]
     * @param  string                   $body               [邮件内容]
     * @param  [type]                   $mailtype           [description]
     * @param  string                   $cc                 [抄送邮箱 多个逗号分隔]
     * @param  string                   $bcc                [description]
     * @param  string                   $additional_headers [邮件格式（HTML/TXT）,TXT为文本邮件]
     * @return [type]                                       [description]
     */
    protected function sendmail($to, $subject = '', $body = '', $mailtype = 'HTML', $cc = '', $bcc = '', $additional_headers = '')
    {

        //获取发件邮箱名称
        $from      = $this->from;
        $mail_from = $this->get_address($this->strip_comment($from));
        $body      = preg_replace('/(^|(\r\n))(\\.)/', "$1.$3", $body);
        $header    = 'MIME-Version:1.0\r\n';
        if ($mailtype == 'HTML') {
            $header .= 'Content-Type:text/html' . PHP_EOL;
        }
        $header .= 'To: ' . $to . PHP_EOL;
        if ($cc != '') {
            $header .= "Cc: " . $cc . PHP_EOL;
        }
        $header .= 'From: $from<' . $from . '>' . PHP_EOL;
        $header .= 'Subject: ' . $subject . PHP_EOL;
        $header .= $additional_headers;
        $header .= 'Date: ' . date('r') . PHP_EOL;
        $header .= 'X-Mailer:By Redhat (PHP/' . phpversion() . ')' . PHP_EOL;
        list($msec, $sec) = explode(' ', microtime());
        $header .= 'Message-ID: <' . date('YmdHis', $sec) . '.' . ($msec * 1000000) . '.' . $mail_from . '>' . PHP_EOL;
        $TO = explode(',', $this->strip_comment($to));

        if ($cc != '') {
            $TO = array_merge($TO, explode(',', $this->strip_comment($cc)));
        }
        if ($bcc != '') {
            $TO = array_merge($TO, explode(',', $this->strip_comment($bcc)));
        }

        $sent = true;
        foreach ($TO as $rcpt_to) {
            $rcpt_to = $this->get_address($rcpt_to);
            if (!$this->smtp_sockopen($rcpt_to)) {
                $this->log_write('Error: Cannot send email to ' . $rcpt_to . PHP_EOL);
                $sent = false;
                continue;
            }
            if ($this->smtp_send($this->host_name, $mail_from, $rcpt_to, $header, $body)) {
                $this->log_write('E-mail has been sent to <' . $rcpt_to . ' > ' . PHP_EOL);
            } else {
                $this->log_write('Error: Cannot send email to <' . $rcpt_to . '>' . PHP_EOL);
                $sent = false;
            }
            fclose($this->sock);
            $this->log_write('Disconnected from remote host' . PHP_EOL);
        }
        //echo "
";
        //echo $header;
        return $sent;
    }

    public function smtp_send($helo, $from, $to, $header, $body = "")
    {
        if (!$this->smtp_putcmd("HELO", $helo)) {
            return $this->smtp_error("sending HELO command");
        }

        if ($this->auth) {
            if (!$this->smtp_putcmd("AUTH LOGIN", base64_encode($this->user))) {
                return $this->smtp_error("sending HELO command");
            }

            if (!$this->smtp_putcmd('', base64_encode($this->pass))) {
                return $this->smtp_error('sending HELO command');
            }
        }

        if (!$this->smtp_putcmd('MAIL', 'FROM:<' . $from . '>')) {
            return $this->smtp_error('sending MAIL FROM command');
        }

        if (!$this->smtp_putcmd('RCPT', 'TO:<' . $to . '>')) {
            return $this->smtp_error('sending RCPT TO command');
        }

        if (!$this->smtp_putcmd('DATA')) {
            return $this->smtp_error('sending DATA command');
        }

        if (!$this->smtp_message($header, $body)) {
            return $this->smtp_error('sending message');
        }

        if (!$this->smtp_eom()) {
            return $this->smtp_error('sending <CR><LF>.<CR><LF> [EOM]');
        }

        if (!$this->smtp_putcmd('QUIT')) {
            return $this->smtp_error('sending QUIT command');
        }

        return true;
    }

    public function smtp_sockopen($address)
    {
        if ($this->relay_host == '') {
            return $this->smtp_sockopen_mx($address);
        } else {
            return $this->smtp_sockopen_relay();
        }
    }

    public function smtp_sockopen_relay()
    {
        $this->log_write('Trying to ' . $this->relay_host . ':' . $this->smtp_port . PHP_EOL);
        $this->sock = @fsockopen($this->relay_host, $this->smtp_port, $errno, $errstr, $this->time_out);
        if (!($this->sock && $this->smtp_ok())) {
            $this->log_write('Error: Cannot connenct to relay host ' . $this->relay_host . PHP_EOL);
            $this->log_write('Error: ' . $errstr . ' (' . $errno . ')' . PHP_EOL);
            return false;
        }
        $this->log_write('Connected to relay host ' . $this->relay_host . PHP_EOL);
        return true;
    }

    public function smtp_sockopen_mx($address)
    {
        $domain = preg_replace('/^.+@([^@]+)$/', '$1', $address);
        if (!@getmxrr($domain, $MXHOSTS)) {
            $this->log_write("Error: Cannot resolve MX \"" . $domain . "\"" . PHP_EOL);
            return false;
        }
        foreach ($MXHOSTS as $host) {
            $this->log_write('Trying to ' . $host . ':' . $this->smtp_port . PHP_EOL);
            $this->sock = @fsockopen($host, $this->smtp_port, $errno, $errstr, $this->time_out);
            if (!($this->sock && $this->smtp_ok())) {
                $this->log_write('Warning: Cannot connect to mx host ' . $host . PHP_EOL);
                $this->log_write("Error: " . $errstr . " (" . $errno . ")" . PHP_EOL);
                continue;
            }
            $this->log_write('Connected to mx host ' . $host . PHP_EOL);
            return true;
        }
        $this->log_write('Error: Cannot connect to any mx hosts (' . implode(', ', $MXHOSTS) . ')' . PHP_EOL);
        return false;
    }

    public function smtp_message($header, $body)
    {
        fputs($this->sock, $header . PHP_EOL . $body);
        $this->smtp_debug("> " . str_replace(PHP_EOL, "\n" . "> ", $header . "\n> " . $body . "\n> "));

        return true;
    }

    public function smtp_eom()
    {
        fputs($this->sock, "\r\n.\r\n");
        $this->smtp_debug(". [EOM]\n");

        return $this->smtp_ok();
    }

    public function smtp_ok()
    {
        $response = str_replace(PHP_EOL, "", fgets($this->sock, 512));
        $this->smtp_debug($response . PHP_EOL);

        if (!preg_match("/^[23]/", $response)) {
            fputs($this->sock, "QUIT\r\n");
            fgets($this->sock, 512);
            $this->log_write("Error: Remote host returned " . $response . PHP_EOL);
            return false;
        }
        return true;
    }

    public function smtp_putcmd($cmd, $arg = "")
    {
        if ($arg != "") {
            if ($cmd == "") {
                $cmd = $arg;
            } else {
                $cmd = $cmd . " " . $arg;
            }

        }

        fputs($this->sock, $cmd . PHP_EOL);
        $this->smtp_debug("> " . $cmd . PHP_EOL);

        return $this->smtp_ok();
    }

    public function smtp_error($string)
    {
        $this->log_write('Error: Error occurred while ' . $string . '.' . PHP_EOL);
        return false;
    }

    public function log_write($message)
    {
        $this->smtp_debug($message);

        if ($this->log_file == '') {
            return true;
        }

        $message = date('M d H:i:s ') . get_current_user() . '[' . getmypid() . ']: ' . $message;
        if (!@file_exists($this->log_file) || !($fp = @fopen($this->log_file, 'a'))) {
            $this->smtp_debug("Warning: Cannot open log file \"" . $this->log_file . "\"" . PHP_EOL);
            return false;
        }
        flock($fp, LOCK_EX);
        fputs($fp, $message);
        fclose($fp);

        return true;
    }

    public function strip_comment($address)
    {
        $comment = "/\\([^()]*\\)/";
        while (preg_match($comment, $address)) {
            $address = ereg_replace($comment, "", $address);
        }

        return $address;
    }

    public function get_address($address)
    {
        $address = preg_replace("/([ \t\r\n])+/", "", $address);
        $address = preg_replace("/^.*<(.+)>.*$/", "$1", $address);

        return $address;
    }

    public function smtp_debug($message)
    {
        if ($this->debug) {
            echo $message . "
";
        }
    }

    public function get_attach_type($image_tag)
    {
        //

        $filedata = array();

        $img_file_con = fopen($image_tag, "r");
        unset($image_data);
        while ($tem_buffer = AddSlashes(fread($img_file_con, filesize($image_tag)))) {
            $image_data .= $tem_buffer;
        }

        fclose($img_file_con);

        $filedata['context']  = $image_data;
        $filedata['filename'] = basename($image_tag);
        $extension            = substr($image_tag, strrpos($image_tag, "."), strlen($image_tag) - strrpos($image_tag, "."));
        switch ($extension) {
            case '.gif':
                $filedata['type'] = 'image/gif';
                break;
            case '.gz':
                $filedata['type'] = 'application/x-gzip';
                break;
            case '.htm':
                $filedata['type'] = 'text/html';
                break;
            case '.html':
                $filedata['type'] = 'text/html';
                break;
            case '.jpg':
                $filedata['type'] = 'image/jpeg';
                break;
            case '.tar':
                $filedata['type'] = 'application/x-tar';
                break;
            case '.txt':
                $filedata['type'] = 'text/plain';
                break;
            case '.zip':
                $filedata['type'] = 'application/zip';
                break;
            default:
                $filedata['type'] = 'application/octet-stream';
                break;
        }

        return $filedata;
    }
}


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

use Illuminate\Foundation\AliasLoader;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Bootstrap\BootProviders;
use Illuminate\Support\ServiceProvider;
use Illuminate\View\Compilers\BladeCompiler;
use Illuminate\View\Factory as ViewFactory;
use Illuminate\View\View;
use RabbitCMS\Modules\Console\DisableCommand;
use RabbitCMS\Modules\Console\EnableCommand;
use RabbitCMS\Modules\Console\ListCommand;
use RabbitCMS\Modules\Console\ScanCommand;
use RabbitCMS\Modules\Managers\Modules;
use RabbitCMS\Modules\Support\Facade\Modules as ModulesFacade;

/**
 * Class ModulesServiceProvider.
 * @package RabbitCMS\Modules
 * @property Application $app
 */
class ModulesServiceProvider extends ServiceProvider
{
    /**
     * @param Modules $modules
     */
    public function boot(Modules $modules)
    {
        if ($this->app->routesAreCached()) {
            $this->loadCachedRoutes();
        } else {
            $this->loadRoutes($modules);

            $this->app->booted(function () {
                $this->app->make('router')->getRoutes()->refreshNameLookups();
            });
        }
    }

    /**
     * Load the cached routes for the application.
     *
     * @return void
     */
    protected function loadCachedRoutes()
    {
        $this->app->booted(function () {
            require $this->app->getCachedRoutesPath();
        });
    }

    /**
     * Load the application routes.
     *
     * @param Modules $modules
     */
    protected function loadRoutes(Modules $modules)
    {
        $modules->loadRoutes('web');
    }

    /**
     * Register the service provider.
     */
    public function register()
    {
        AliasLoader::getInstance(['Modules' => ModulesFacade::class,]);

        $this->registerConfig();
        $this->registerServices();
        $this->registerCommands();
        $this->registerModules();

        $this->app->afterResolving('view', function (ViewFactory $view) {
            $view->composer('*', function (View $view) {
                $name = explode('::', $view->getName(), 2);
                if (count($name) > 1) {
                    $view->with('module_name', $name[0]);
                }
            });
        });

        $this->app->afterResolving('blade.compiler', function (BladeCompiler $compiler) {
            $compiler->directive('mlang', function ($expression) {
                return "<?php echo trans(\$module_name.'::'.{$expression}); ?>";
            });
            $compiler->directive('masset', function ($expression) {
                return "<?php echo module_asset(\$module_name, {$expression}); ?>";
            });
        });
    }

    /**
     * Register config.
     */
    protected function registerConfig()
    {
        $path = realpath(__DIR__ . '/../../config/config.php');

        $this->mergeConfigFrom($path, "modules");

        $this->publishes([$path => config_path('modules.php')]);
    }

    /**
     * Register the service provider.
     */
    protected function registerServices()
    {
        $this->app->singleton(Modules::class, function ($app) {
            return new Modules($app);
        });
    }

    public function registerCommands()
    {
        $this->app->singleton('modules.commands.scan', function () {
            return new ScanCommand($this->app->make(Modules::class));
        });

        $this->app->singleton('modules.commands.enable', function () {
            return new EnableCommand($this->app->make(Modules::class));
        });

        $this->app->singleton('modules.commands.disable', function () {
            return new DisableCommand($this->app->make(Modules::class));
        });

        $this->app->singleton('modules.commands.list', function () {
            return new ListCommand($this->app->make(Modules::class));
        });

        $this->commands([
            'modules.commands.scan',
            'modules.commands.enable',
            'modules.commands.disable',
            'modules.commands.list',
        ]);
    }

    public function registerModules()
    {
        $this->app->beforeBootstrapping(BootProviders::class, function (Application $app) {
            $app->make(Modules::class)->register($app);
        });
    }
}


<?php
/**
 * Copyright (C) php-fn. See LICENSE file for license details.
 */

namespace fn;

use ArrayAccess;
use Countable;
use IteratorAggregate;

/**
 * @property-read array $keys
 * @property-read array $traverse
 * @property-read array $values
 * @property-read array $tree
 * @property-read array $leaves
 * @property-read array $flatten
 * @property-read string $string
 * @property-read bool $every
 * @property-read bool $some
 */
class Map implements IteratorAggregate, Countable, ArrayAccess
{
    /**
     * @var iterable
     */
    private $iterable;

    /**
     * @var callable
     */
    private $mappers;

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

    /**
     * @var Map\Tree
     */
    private $inner;

    /**
     * @param iterable $iterable
     * @param callable ...$mappers
     */
    public function __construct($iterable = null, callable ...$mappers)
    {
        $this->iterable = $iterable;
        $this->mappers  = $mappers;
    }

    /**
     * @param string $property
     * @return mixed
     */
    public function __get($property)
    {
        switch($property) {
            case 'keys':
                return traverse($this->keys());
            case 'traverse':
                return is_array($this->compiled) ? $this->compiled : traverse($this);
            case 'values':
                return _\toValues(is_array($this->compiled) ? $this->compiled : $this);
            case 'tree':
                return _\toValues($this->tree());
            case 'leaves':
                return _\toValues($this->leaves());
            case 'flatten':
                return traverse($this->flatten());
            case 'string':
                return $this->string();
            case 'every':
                return $this->every(function($value) {return $value;});
            case 'some':
                return $this->some(function($value) {return $value;});
            default:
                fail\logic($property);
        }
        return null;
    }

    /**
     * @param string|callable|array $delimiter
     *
     * @param array $replacements
     *
     * @return string
     */
    public function string($delimiter = PHP_EOL, ...$replacements): string
    {
        $string = '';
        if (!isCallable($delimiter)) {
            if (is_array($delimiter)) {
                array_unshift($replacements, $delimiter);
                $delimiter = PHP_EOL;
            }
            $delimiter = function($counter) use($delimiter) {
                return $counter ? $delimiter : '';
            };
        }
        traverse($this->leaves(function($value, Map\Path $iterator) use ($delimiter, &$string) {
            static $counter = 0;
            $string .= $delimiter(...[$counter++, $iterator->getDepth(), $iterator]) . $value;

        }));
        return $replacements ? str($string, ...$replacements) : $string;
    }

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

    /**
     * @param string $property
     * @return bool
     */
    public function __isset($property): bool
    {
        return hasValue($property, ['keys', 'traverse', 'map', 'values', 'tree', 'leaves', 'string', 'every', 'some']);
    }

    /**
     * @inheritdoc
     */
    public function __set($property, $value): void
    {
        fail\logic($property);
    }

    /**
     * @inheritdoc
     */
    public function __unset($property): void
    {
        fail\logic($property);
    }

    /**
     * @inheritdoc
     */
    public function getIterator(): \Traversable
    {
        if (!$this->inner) {
            if (is_array($this->compiled)) {
                $this->inner = new Map\Tree($this->compiled);
            } else {
                $this->inner = new Map\Tree($this->iterable ?: [], ...$this->mappers);
            }
        }
        return $this->inner;
    }

    /**
     * @inheritdoc
     */
    public function count(): int
    {
        return $this->getIterator()->count();
    }

    /**
     * @return bool
     */
    public function isLast(): bool
    {
        return $this->getIterator()->isLast();
    }

    /**
     * @return array
     */
    private function compile(): array
    {
        if (!is_array($this->compiled)) {
            $this->compiled = traverse($this);
            $this->inner = null;
            $this->mappers = [];
        }
        return $this->compiled;
    }

    /**
     * @param mixed $value
     * @param bool $strict
     * @return bool
     */
    public function has($value, $strict = true): bool
    {
        return hasValue($value, $this->compile(), $strict);
    }

    /**
     * @param string $key
     * @param mixed $default
     * @return mixed|null
     */
    public function get($key, $default = null)
    {
        return $this->offsetExists($key) ? $this->offsetGet($key) : $default;
    }

    /**
     * @inheritdoc
     */
    public function offsetExists($offset): bool
    {
        return hasKey($offset, $this->compile());
    }

    /**
     * @inheritdoc
     */
    public function offsetGet($offset)
    {
        $this->offsetExists($offset) ?: fail\argument($offset);
        return $this->compiled[$offset];
    }

    /**
     * @inheritdoc
     */
    public function offsetSet($offset, $value): void
    {
        $this->compile();
        $this->compiled[$offset] = $value;
    }

    /**
     * @inheritdoc
     */
    public function offsetUnset($offset): void
    {
        $this->compile();
        unset($this->compiled[$offset]);
    }

    /**
     * @param callable ...$mappers
     * @return static
     */
    public function then(callable ...$mappers): self
    {
        return new static(
            is_array($this->compiled) ? $this->compiled : $this->iterable,
            ...$this->mappers, ...$mappers
        );
    }

    /**
     * @param callable|int $strategy callable or SORT_ constants
     * @param int $flags SORT_ constants
     * @return static
     */
    public function sort($strategy = null, $flags = null): self
    {
        return new static(new Map\Sort($this, $strategy, $flags));
    }

    /**
     * @param callable ...$mappers
     * @return static
     */
    public function keys(callable ...$mappers): self
    {
        return $this->then(function ($value, $key)  {
            static $counter = 0;
            return mapValue($key)->andKey($counter++);
        }, ...$mappers);
    }

    /**
     * @param callable ...$mappers
     * @return static
     */
    public function values(callable ...$mappers): self
    {
        return $this->then(function ($value)  {
            static $counter = 0;
            return mapValue($value)->andKey($counter++);
        }, ...$mappers);
    }

    /**
     * @param callable $function
     * @param array ...$iterables
     * @return \Closure
     */
    private static function variadic($function, ...$iterables): \Closure
    {
        return function () use ($function, $iterables) {
            return $function(...traverse($iterables, function ($iterable) {
                return _\toArray($iterable);
            }));
        };
    }

    /**
     * @param iterable ...$iterables
     * @return static
     */
    public function merge(...$iterables): self
    {
        return new static(new Map\Lazy(self::variadic('array_merge', $this, ...$iterables)));
    }

    /**
     * @param iterable ...$iterables
     * @return static
     */
    public function replace(...$iterables): self
    {
        return new static(new Map\Lazy(self::variadic('array_replace', $this, ...$iterables)));
    }

    /**
     * @param iterable ...$iterables
     * @return static
     */
    public function diff(...$iterables): self
    {
        return new static(new Map\Lazy(self::variadic('array_diff', $this, ...$iterables)));
    }

    /**
     * @param int $start
     * @param int $length
     * @return static
     */
    public function sub($start, $length = null): self
    {
        return new static(new Map\Lazy(function () use($start, $length) {
            return sub($this, $start, $length);
        }));
    }

    /**
     * @param mixed $needle
     * @param bool $strict
     * @return false|int|string
     */
    public function search($needle, $strict = true)
    {
        return array_search($needle, $this->compile(), $strict);
    }

    /**
     * @param callable $mapper
     *
     * @return static|\Traversable
     */
    public function tree(callable $mapper = null): self
    {
        return _\recursive($this, false, $mapper);
    }

    /**
     * @param callable $mapper
     *
     * @return static|iterable
     */
    public function leaves(callable $mapper = null): self
    {
        return _\recursive($this, true, $mapper);
    }

    /**
     * @param callable $mapper
     * @param string $glue
     *
     * @return static
     */
    public function flatten(callable $mapper = null, string $glue = '/'): self
    {
        return $this->tree(function(Map\Path $it, $value) use($glue, $mapper) {
            $key = implode($glue, $it->keys);
            $mapper && $value = $mapper(...[$value, &$key, $it]);
            if ($value instanceof Map\Value) {
                return $value->key === null ? $value->andKey($key) : $value;
            }
            return $value === null ? $value : mapKey($key)->andValue($value);
        });
    }

    /**
     * @param callable       $check
     * @param callable|mixed $true
     * @param callable|mixed $false
     *
     * @return bool|mixed
     */
    public function every(callable $check, $true = true, $false = false)
    {
        foreach ($this as $key => $value) {
            if (!$check($value, $key, $this)) {
                return isCallable($false) ? $false($this) : $false;
            }
        }
        return isCallable($true) ? $true($this) : $true;
    }

    /**
     * @param callable       $check
     * @param callable|mixed $true
     * @param callable|mixed $false
     *
     * @return bool|mixed
     */
    public function some(callable $check, $true = true, $false = false)
    {
        foreach ($this as $key => $value) {
            if ($check($value, $key, $this)) {
                return isCallable($true) ? $true($this) : $true;
            }
        }
        return isCallable($false) ? $false($this) : $false;
    }

    /**
     * @param int $limit
     * @param int $offset
     *
     * @return static
     */
    public function limit($limit, $offset = 0): self
    {
        $from = max($offset, 0);
        $to   = $from + max($limit, 0);
        return $this->then(function($value) use($from, $to) {
            static $count = 0;
            if ($count < $from) {
                $value = null;
            } else if ($to > 0 && $count >= $to) {
                $value = mapBreak();
            }
            $count++;
            return $value;
        });
    }
}


<?php

namespace webignition\InternetMediaType\Parser;

use webignition\InternetMediaType\InternetMediaType;
use webignition\InternetMediaType\Parameter\Parser\AttributeParserException;
use webignition\InternetMediaType\Parameter\Parser\Parser as ParameterParser;
use webignition\InternetMediaTypeInterface\InternetMediaTypeInterface;
use webignition\InternetMediaTypeInterface\ParameterInterface;

/**
 * Parses a string representation of an Internet media type into an
 * InternetMediaTypeInterface object
 */
class Parser
{
    const TYPE_SUBTYPE_SEPARATOR = '/';
    const TYPE_PARAMETER_SEPARATOR = ';';

    /**
     * @var TypeParser
     */
    private $typeParser = null;

    /**
     * @var SubtypeParser
     */
    private $subtypeParser = null;

    /**
     * @var ParameterParser
     */
    private $parameterParser = null;

    /**
     * @var Configuration
     */
    private $configuration;

    public function __construct()
    {
        $this->configuration = new Configuration();
        $this->typeParser = new TypeParser();

        $this->subtypeParser = new SubtypeParser();
        $this->subtypeParser->setConfiguration($this->configuration);

        $this->parameterParser = new ParameterParser();
        $this->parameterParser->setConfiguration($this->configuration);
    }

    /**
     * @param string $internetMediaTypeString
     *
     * @return InternetMediaTypeInterface|null
     *
     * @throws ParseException
     */
    public function parse(string $internetMediaTypeString): ?InternetMediaTypeInterface
    {
        $inputString = trim($internetMediaTypeString);

        $internetMediaType = new InternetMediaType();

        try {
            $internetMediaType->setType($this->typeParser->parse($inputString));
            $internetMediaType->setSubtype($this->subtypeParser->parse($inputString));

            $parameterString = $this->createParameterString(
                $inputString,
                $internetMediaType->getType(),
                $internetMediaType->getSubtype()
            );
            $parameterStrings = $this->getParameterStrings($parameterString);

            $parameters = $this->getParameters($parameterStrings);

            foreach ($parameters as $parameter) {
                $internetMediaType->addParameter($parameter);
            }

            return $internetMediaType;
        } catch (TypeParserException $typeParserException) {
            throw new ParseException(
                $typeParserException->getMessage(),
                $typeParserException->getCode(),
                $inputString,
                $typeParserException
            );
        } catch (SubtypeParserException $subtypeParserException) {
            throw new ParseException(
                $subtypeParserException->getMessage(),
                $subtypeParserException->getCode(),
                $inputString,
                $subtypeParserException
            );
        } catch (AttributeParserException $attributeParserException) {
            throw new ParseException(
                $attributeParserException->getMessage(),
                $attributeParserException->getCode(),
                $inputString,
                $attributeParserException
            );
        }
    }

    /**
     * @param string $inputString
     * @param string $type
     * @param string $subtype
     *
     * @return string
     */
    private function createParameterString(string $inputString, string $type, string $subtype): string
    {
        $parts = explode(self::TYPE_PARAMETER_SEPARATOR, $inputString, 2);

        if (count($parts) === 1) {
            return trim(str_replace($type . self::TYPE_SUBTYPE_SEPARATOR . $subtype, '', $inputString));
        }

        return trim($parts[1]);
    }

    /**
     * Get collection of string representations of each parameter
     *
     * @param string $parameterString
     *
     * @return string[]
     */
    private function getParameterStrings(string $parameterString): array
    {
        $rawParameterStrings = explode(self::TYPE_PARAMETER_SEPARATOR, $parameterString);
        $parameterStrings = array();

        foreach ($rawParameterStrings as $rawParameterString) {
            if ($rawParameterString != '') {
                $parameterStrings[] = trim($rawParameterString);
            }
        }

        return $parameterStrings;
    }

    /**
     * Get a collection of Parameter objects from a collection of string
     * representations of the same
     *
     * @param array $parameterStrings
     *
     * @return ParameterInterface[]
     *
     * @throws AttributeParserException
     */
    private function getParameters($parameterStrings): array
    {
        $parameters = array();
        foreach ($parameterStrings as $parameterString) {
            $parameters[] = $this->parameterParser->parse($parameterString);
        }

        return $parameters;
    }

    public function setConfiguration(Configuration  $configuration)
    {
        $this->configuration = $configuration;
        $this->subtypeParser->setConfiguration($configuration);
        $this->parameterParser->setConfiguration($configuration);
    }

    public function getConfiguration(): Configuration
    {
        return $this->configuration;
    }

    public function setIgnoreInvalidAttributes(bool $ignoreInvalidAttributes)
    {
        if (filter_var($ignoreInvalidAttributes, FILTER_VALIDATE_BOOLEAN)) {
            $this->getConfiguration()->enableIgnoreInvalidAttributes();
        } else {
            $this->getConfiguration()->disableIgnoreInvalidAttributes();
        }
    }

    public function setAttemptToRecoverFromInvalidInternalCharacter(bool $attemptToRecoverFromInvalidInternalCharacter)
    {
        if (filter_var($attemptToRecoverFromInvalidInternalCharacter, FILTER_VALIDATE_BOOLEAN)) {
            $this->getConfiguration()->enableAttemptToRecoverFromInvalidInternalCharacter();
        } else {
            $this->getConfiguration()->disableAttemptToRecoverFromInvalidInternalCharacter();
        }
    }
}


<?php
/**
 * Header 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;

/**
 * Header utilities.
 *
 * @since 151121 Header utilities.
 */
class Headers extends Classes\Core\Base\Core implements Interfaces\HttpStatusConstants, Interfaces\SecondConstants
{
    /**
     * Current request headers.
     *
     * @since 170824.30708 Current request headers.
     *
     * @return array Unique/associative array of all headers.
     */
    public function current(): array
    {
        if (($headers = &$this->cacheKey(__FUNCTION__)) !== null) {
            return $headers; // Cached this already.
        }
        $headers = []; // Initialize.

        foreach ($_SERVER as $_header => $_value) {
            if (mb_stripos($_header, 'HTTP_') === 0) {
                $_header                          = preg_replace('/^HTTP_/ui', '', $_header);
                $_header                          = str_replace('_', '-', $_header);
                $headers[mb_strtolower($_header)] = $_value;
            }
        } // unset($_header, $_value); // Housekeeping.

        return $headers;
    }

    /**
     * Yes-cache headers.
     *
     * @since 17xxxx Yes-cache headers.
     *
     * @param int $expires_after Expires after (seconds).
     *
     * @return array Yes-cache headers.
     */
    public function yesCache(int $expires_after = self::SECONDS_IN_YEAR): array
    {
        return [
            'pragma'        => 'public',
            'expires'       => gmdate('D, d M Y H:i:s T', time() + $expires_after),
            'cache-control' => 'public, immutable, max-age='.$expires_after,
        ];
    }

    /**
     * No-cache headers.
     *
     * @since 17xxxx No-cache headers.
     *
     * @return array No-cache headers.
     */
    public function noCache(): array
    {
        return [
            'pragma'        => 'no-cache',
            'expires'       => gmdate('D, d M Y H:i:s T', time() - $this::SECONDS_IN_YEAR),
            'cache-control' => 'no-cache, must-revalidate, max-age=0',
        ];
    }

    /**
     * Send yes-cache headers.
     *
     * @since 17xxxx Yes-cache headers.
     *
     * @param int $expires_after Expires after (seconds).
     */
    public function yesCacheSend(int $expires_after = self::SECONDS_IN_YEAR)
    {
        if (headers_sent()) {
            throw $this->c::issue('Headers already sent.');
        }
        header_remove('last-modified');

        foreach ($this->yesCache() as $_header => $_value) {
            header($_header.': '.$_value);
        } // unset($_header, $_value);
    }

    /**
     * Send no-cache headers.
     *
     * @since 17xxxx No-cache headers.
     */
    public function noCacheSend()
    {
        if (headers_sent()) {
            throw $this->c::issue('Headers already sent.');
        }
        header_remove('last-modified');

        foreach ($this->noCache() as $_header => $_value) {
            header($_header.': '.$_value);
        } // unset($_header, $_value);
    }

    /**
     * Get slug for status code.
     *
     * @since 170824.30708 Adding status slug utility.
     *
     * @param int $status The HTTP status code.
     *
     * @return string Status slug for code.
     */
    public function getStatusSlug(int $status): string
    {
        return $this->c::nameToSlug($this->getStatusTitle($status));
    }

    /**
     * Get title for status code.
     *
     * @since 17xxxx Status title utility.
     *
     * @param int $status The HTTP status code.
     *
     * @return string Status title for code.
     */
    public function getStatusTitle(int $status): string
    {
        return $this::HTTP_STATUSES[$status] ?? 'Bad Request';
    }

    /**
     * Get message for status code.
     *
     * @since 17xxxx Status message utility.
     *
     * @param int $status The HTTP status code.
     *
     * @return string Status message for code.
     */
    public function getStatusMessage(int $status): string
    {
        return $this->c::mbUcFirst(mb_strtolower($this->getStatusTitle($status))).'.';
    }

    /**
     * Status header.
     *
     * @since 151121 Header utilities.
     *
     * @param int    $status   Status code.
     * @param string $protocol Protocol.
     */
    public function sendStatus(int $status, string $protocol = '')
    {
        if (headers_sent()) {
            throw $this->c::issue('Headers already sent.');
        }
        if (!$protocol && !($protocol = $_SERVER['SERVER_PROTOCOL'] ?? '')) {
            $protocol = 'HTTP/1.1'; // Default fallback.
        }
        header($protocol.' '.$status.' '.$this->getStatusTitle($status), true, $status);
    }

    /**
     * Parses headers.
     *
     * @since 151121 Header utilities.
     *
     * @param mixed $value Input value w/ headers.
     *
     * @return array Unique/associative array of all headers.
     */
    public function parse($value): array
    {
        $headers = []; // Initialize.

        if (is_array($value) || is_object($value)) {
            foreach ($value as $_key => $_value) {
                if ($_key && is_string($_key) && is_string($_value)) {
                    $headers = array_merge($headers, $this->parse($_key.': '.$_value));
                } else {
                    $headers = array_merge($headers, $this->parse($_value));
                }
            } // unset($_key, $_value);
            return $headers; // All done here.
        }
        $string = (string) $value; // Force string.

        foreach (explode("\r\n", $string) as $_rn_delimited_header) {
            if (mb_strpos($_rn_delimited_header, ':') === false) {
                continue; // Invalid header.
            }
            list($_header, $_value) = $this->c::mbTrim(explode(':', $_rn_delimited_header, 2));

            if (!$_header || !isset($_value[0])) {
                continue; // Invalid header.
            }
            $headers[mb_strtolower($_header)] = $_value;
        } // unset($_rn_delimited_header, $_header, $_value);

        return $headers;
    }
}


<?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 Region extends Base
{
    public $description;

    public $marketBuyOrders;

    public $name;

    public $constellations = [];

    public $marketSellOrders;

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

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

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

    // by Warringer\Types\ArrayType
    public function setConstellations($constellations)
    {
        // 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 ($constellations as $key => $value) {
            $this->constellations[$key] = $func($value);
        }
    }

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

}


<?php
/**
 * PHP strip 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;

/**
 * PHP strip utilities.
 *
 * @since 150424 Initial release.
 */
class PhpStrip extends Classes\Core\Base\Core
{
    /**
     * Strips PHP tags.
     *
     * @since 150424 Initial release.
     *
     * @param mixed $value Any input value.
     *
     * @return string|array|object Output value.
     */
    public function tags($value)
    {
        if (is_array($value) || is_object($value)) {
            foreach ($value as $_key => &$_value) {
                $_value = $this->tags($_value);
            } // unset($_key, $_value);
            return $value;
        }
        if (!($string = (string) $value)) {
            return $string; // Empty.
        }
        $regex = // Search for PHP tags.
            '/'.// Open pattern delimiter.
            '(?:'.// Any of these.

                '\<\?php.*?\?\>|\<\?\=.*?\?\>|\<\?.*?\?\>|\<%.*?%\>'.
                '|\<script\s+[^>]*?language\s*\=\s*(["\'])?php\\1[^>]*\>.*?\<\s*\/\s*script\s*\>'.

            ')'.// Close 'any of these'.
            '/uis'; // End pattern.
        return preg_replace($regex, '', $string);
    }
}


<?php
declare(strict_types=1);

namespace RabbitCMS\Modules;

use Illuminate\Contracts\Foundation\Application;
use Illuminate\Support\ServiceProvider as IlluminateServiceProvider;
use RabbitCMS\Modules\Concerns\BelongsToModule;
use RabbitCMS\Modules\Managers\Modules;

/**
 * Class ModuleProvider.
 *
 * @package RabbitCMS\Modules
 */
abstract class ModuleProvider extends IlluminateServiceProvider
{
    use BelongsToModule;

    /**
     * @var Module
     */
    protected $module;

    /**
     * @var Modules
     * @deprecated
     */
    protected $modulesManager;

    /**
     * ModuleProvider constructor.
     *
     * @param Application $app
     */
    public function __construct(Application $app)
    {
        parent::__construct($app);
        $this->modulesManager = $this->app->make(Modules::class);
        $this->module = static::module();
    }

    /**
     * Fetch module name
     *
     * @return string
     */
    protected function name(): string
    {
        return static::module()->getName();
    }

    /**
     * Register the service provider.
     */
    public function register()
    {
        $this->registerConfig();
        $this->registerTrans();
        $this->registerViews();
        $this->registerMigrations();
    }

    /**
     * Register migrations.
     */
    protected function registerMigrations()
    {
        if (is_dir($dir = $this->module->getPath('src/Database/Migrations'))
            || is_dir($dir = $this->module->getPath('database/migrations'))
        ) {
            $this->loadMigrationsFrom($dir);
        }
    }

    /**
     * Register config.
     */
    protected function registerConfig()
    {
        $path = $this->module->getPath('config/config.php');

        if (is_file($path)) {
            $this->mergeConfigFrom($path, "module.{$this->module->getName()}");

            $this->publishes([$path => config_path("module/{$this->module->getName()}.php")]);
        }
    }

    /**
     * Register translations.
     */
    protected function registerTrans()
    {
        $path = base_path("resources/lang/modules/{$this->module->getName()}");

        if (is_dir($path)) {
            $this->loadTranslationsFrom($path, $this->module->getName());
        } else {
            $this->loadTranslationsFrom($this->module->getPath('resources/lang'), $this->module->getName());
        }
    }

    /**
     * Register views.
     */
    protected function registerViews()
    {
        if (is_dir($source = $this->module->getPath('resources/views'))) {
            $this->loadViewsFrom($source, $this->module->getName());
        }
    }

    /**
     * @param callable $loader
     */
    protected function loadRoutes(callable $loader)
    {
        if (!$this->app->routesAreCached()) {
            $this->app->call($loader);
        }
    }

    /**
     * Get the specified configuration value.
     *
     * @deprecated use Module::config()
     *
     * @param  string $key
     * @param  mixed  $default
     *
     * @return mixed
     */
    protected function config(string $key, $default = null)
    {
        return static::module()->config($key, $default);
    }
}


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

use Ivory\GoogleMap\Assets\AbstractOptionsAsset;
use Ivory\GoogleMap\Base\Coordinate;
use Ivory\GoogleMap\Base\Size;
use Ivory\GoogleMap\Events\MouseEvent;
use Ivory\GoogleMap\Exception\OverlayException;

/**
 * Info window which describes a google map info window.
 *
 * @see http://code.google.com/apis/maps/documentation/javascript/reference.html#InfoWindow
 * @author GeLo <geloen.eric@gmail.com>
 */
class InfoWindow extends AbstractOptionsAsset implements ExtendableInterface
{
    /** @var string */
    protected $content;

    /** @var \Ivory\GoogleMap\Base\Coordinate */
    protected $position;

    /** @var \Ivory\GoogleMap\Base\Size */
    protected $pixedOffset;

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

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

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

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

    /**
     * Creates an info window.
     *
     * @param string                           $content     The info window content.
     * @param \Ivory\GoogleMap\Base\Coordinate $position    The info window position.
     * @param \Ivory\GoogleMap\Base\Size       $pixelOffset The info window pixel offset.
     * @param boolean                          $open        The info window open flag.
     * @param string                           $openEvent   The info window open event.
     * @param boolean                          $autoOpen    The info window auto open flag.
     * @param boolean                          $autoClose   The info window auto close flag
     */
    public function __construct(
        $content = '
Default content
',
        Coordinate $position = null,
        Size $pixelOffset = null,
        $open = false,
        $openEvent = MouseEvent::CLICK,
        $autoOpen = true,
        $autoClose = false
    ) {
        parent::__construct();

        $this->setPrefixJavascriptVariable('info_window_');

        $this->setContent($content);

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

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

        $this->setOpen($open);
        $this->setOpenEvent($openEvent);

        $this->setAutoOpen($autoOpen);
        $this->setAutoClose($autoClose);
    }

    /**
     * Gets the infow window position.
     *
     * @return \Ivory\GoogleMap\Base\Coordinate The info window position.
     */
    public function getPosition()
    {
        return $this->position;
    }

    /**
     * Sets the info window position
     *
     * Available prototypes:
     *  - function setPosition(Ivory\GoogleMap\Base\Coordinate $position = null)
     *  - function setPosition(double $latitude, double $longitude, boolean $noWrap = true)
     *
     * @throws \Ivory\GoogleMap\Exception\OverlayException If the position is not valid.
     */
    public function setPosition()
    {
        $args = func_get_args();

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

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

            if (isset($args[2]) && is_bool($args[2])) {
                $this->position->setNoWrap($args[2]);
            }
        } elseif (!isset($args[0])) {
            $this->position = null;
        } else {
            throw OverlayException::invalidInfoWindowPosition();
        }
    }

    /**
     * Checks if the info window has a pixel offset.
     *
     * @return boolean TRUE if the info window has a pixel offset else FALSE.
     */
    public function hasPixelOffset()
    {
        return $this->pixedOffset !== null;
    }

    /**
     * Gets the pixel offset.
     *
     * @return \Ivory\GoogleMap\Base\Size The pixel offset.
     */
    public function getPixelOffset()
    {
        return $this->pixedOffset;
    }

    /**
     * Sets the pixel offset.
     *
     * Available prototypes:
     *  - function setPixelOffset(Ivory\GoogleMap\Base\Size $scaledSize)
     *  - function setPixelOffset(double $width, double $height, string $widthUnit = null, string $heightUnit = null)
     *
     * @throws \Ivory\GoogleMap\Exception\OverlayException If the pixel offset is not valid (prototypes).
     */
    public function setPixelOffset()
    {
        $args = func_get_args();

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

            $this->pixedOffset->setWidth($args[0]);
            $this->pixedOffset->setHeight($args[1]);

            if (isset($args[2]) && is_string($args[2])) {
                $this->pixedOffset->setWidthUnit($args[2]);
            }

            if (isset($args[3]) && is_string($args[3])) {
                $this->pixedOffset->setHeightUnit($args[3]);
            }
        } elseif (!isset($args[0])) {
            $this->pixedOffset = null;
        } else {
            throw OverlayException::invalidInfoWindowPixelOffset();
        }
    }

    /**
     * Gets the info window content.
     *
     * @return string The info window content.
     */
    public function getContent()
    {
        return $this->content;
    }

    /**
     * Sets the info window content
     *
     * @param string $content The info window content.
     *
     * @throws \Ivory\GoogleMap\Exception\OverlayException If the content is not valid.
     */
    public function setContent($content)
    {
        if (!is_string($content)) {
            throw OverlayException::invalidInfoWindowContent();
        }

        $this->content = $content;
    }

    /**
     * Checks if the info window is open.
     *
     * @return boolean TRUE if the info window is open else FALSE.
     */
    public function isOpen()
    {
        return $this->open;
    }

    /**
     * Sets if the info window is open.
     *
     * @param boolean $open TRUE if the info window is open else FALSE.
     *
     * @throws \Ivory\GoogleMap\Exception\OverlayException If the info window open flag is not valid.
     */
    public function setOpen($open)
    {
        if (!is_bool($open)) {
            throw OverlayException::invalidInfoWindowOpen();
        }

        $this->open = $open;
    }

    /**
     * Checks if the info window auto open.
     *
     * @return boolean TRUE if the info window auto open on event else FALSE.
     */
    public function isAutoOpen()
    {
        return $this->autoOpen;
    }

    /**
     * Sets if the info window auto open.
     *
     * @param boolean $autoOpen TRUE if the info window auto open on event else FALSE.
     *
     * @throws \Ivory\GoogleMap\Exception\OverlayException If the auto open flag is not valid.
     */
    public function setAutoOpen($autoOpen)
    {
        if (!is_bool($autoOpen)) {
            throw OverlayException::invalidInfoWindowAutoOpen();
        }

        $this->autoOpen = $autoOpen;
    }

    /**
     * Gets the info window open event.
     *
     * @return string The info window open event.
     */
    public function getOpenEvent()
    {
        return $this->openEvent;
    }

    /**
     * Sets the info window open event.
     *
     * @param string $openEvent The info window open event.
     *
     * @throws \Ivory\GoogleMap\Exception\OverlayException If the open event is not valid.
     */
    public function setOpenEvent($openEvent)
    {
        if (!in_array($openEvent, MouseEvent::getMouseEvents())) {
            throw OverlayException::invalidInfoWindowOpenEvent();
        }

        $this->openEvent = $openEvent;
    }

    /**
     * Gets the auto close flag.
     *
     * @return boolean TRUE if all opened info windows close when one is opened else FALSE.
     */
    public function isAutoClose()
    {
        return $this->autoClose;
    }

    /**
     * Sets the auto close flag.
     *
     * @param boolean $autoClose TRUE if all opened info windows close when one is opened else FALSE.
     *
     * @throws \Ivory\GoogleMap\Exception\OverlayException If the auto close flag is not valid.
     */
    public function setAutoClose($autoClose)
    {
        if (!is_bool($autoClose)) {
            throw OverlayException::invalidInfoWindowAutoClose();
        }

        $this->autoClose = $autoClose;
    }
}


<?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\PanControl;
use Ivory\GoogleMap\Helper\AbstractHelper;

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

    /**
     * Creates a pan 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 pan control.
     *
     * @param \Ivory\GoogleMap\Controls\PanControl $panControl The pan control.
     *
     * @return string The JS output.
     */
    public function render(PanControl $panControl)
    {
        return $this->jsonBuilder
            ->reset()
            ->setValue('[position]', $this->controlPositionHelper->render($panControl->getControlPosition()), false)
            ->build();
    }
}


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

/**
 * Mouse event describes the google map mouse event.
 *
 * @author GeLo <geloen.eric@gmail.com>
 */
class MouseEvent
{
    const CLICK = 'click';
    const DBLCLICK = 'dblclick';
    const MOUSEUP = 'mouseup';
    const MOUSEDOWN = 'mousedown';
    const MOUSEOVER = 'mouseover';
    const MOUSEOUT = 'mouseout';

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

    }

    /**
     * Gets the available mouse events.
     *
     * @return array The mouse events.
     */
    public static function getMouseEvents()
    {
        return array(
            self::CLICK,
            self::DBLCLICK,
            self::MOUSEUP,
            self::MOUSEDOWN,
            self::MOUSEOVER,
            self::MOUSEOUT,
        );
    }
}


<?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;
use Ivory\GoogleMap\MapTypeId;

/**
 * Map type control options describes a google map type control options.
 *
 * @see http://code.google.com/apis/maps/documentation/javascript/reference.html#MapTypeControlOptions
 * @author GeLo <geloen.eric@gmail.com>
 */
class MapTypeControl
{
    /** @var array */
    protected $mapTypeIds;

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

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

    /**
     * Create a map type control.
     *
     * @param array  $mapTypeIds          The map type IDs.
     * @param string $controlPosition     The control position.
     * @param string $mapTypeControlStyle The map type control style.
     */
    public function __construct(
        array $mapTypeIds = array(MapTypeId::ROADMAP, MapTypeId::SATELLITE),
        $controlPosition = ControlPosition::TOP_RIGHT,
        $mapTypeControlStyle = MapTypeControlStyle::DEFAULT_
    ) {
        $this->setMapTypeIds($mapTypeIds);
        $this->setControlPosition($controlPosition);
        $this->setMapTypeControlStyle($mapTypeControlStyle);
    }

    /**
     * Gets the map type IDs.
     *
     * @return array The map type IDs.
     */
    public function getMapTypeIds()
    {
        return $this->mapTypeIds;
    }

    /**
     * Sets the map type IDs.
     *
     * @param array $mapTypeIds The map type IDs.
     */
    public function setMapTypeIds($mapTypeIds)
    {
        $this->mapTypeIds = array();

        foreach ($mapTypeIds as $mapTypeId) {
            $this->addMapTypeId($mapTypeId);
        }
    }

    /**
     * Add a map type ID.
     *
     * @param string $mapTypeId The map type ID to add.
     *
     * @throws \Ivory\GoogleMap\Exception\ControlException If the map type ID is not valid.
     */
    public function addMapTypeId($mapTypeId)
    {
        if (!in_array($mapTypeId, MapTypeId::getMapTypeIds())) {
            throw ControlException::invalidMapTypeId();
        }

        if (!in_array($mapTypeId, $this->mapTypeIds)) {
            $this->mapTypeIds[] = $mapTypeId;
        }
    }

    /**
     * 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 map type control style.
     *
     * @return string The map type control style.
     */
    public function getMapTypeControlStyle()
    {
        return $this->mapTypeControlStyle;
    }

    /**
     * Sets the map type control style.
     *
     * @param type $mapTypeControlStyle The map type control style.
     *
     * @throws \Ivory\GoogleMap\Exception\ControlException If the map type control style is not valid.
     */
    public function setMapTypeControlStyle($mapTypeControlStyle)
    {
        if (!in_array($mapTypeControlStyle, MapTypeControlStyle::getMapTypeControlStyles())) {
            throw ControlException::invalidMapTypeControlStyle();
        }

        $this->mapTypeControlStyle = $mapTypeControlStyle;
    }
}


<?php
/**
 * Cookie 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;

/**
 * Cookie utilities.
 *
 * @since 150424 Initial release.
 */
class Cookie extends Classes\Core\Base\Core
{
    /**
     * Class constructor.
     *
     * @since 150424 Initial release.
     *
     * @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.');
        }
    }

    /**
     * Sets a cookie.
     *
     * @param string      $name          Name of the cookie.
     * @param string      $value         Cookie value (empty to delete).
     * @param int|null    $expires_after Time (in seconds) this cookie should last for.
     * @param string|null $path          Path to set the cookie for.
     * @param string|null $domain        Domain name to set the cookie for.
     * @param bool|null   $secure        Over SSL access only?
     * @param bool|null   $http_only     HTTP only access?
     * @param string|null $key           Encryption key.
     */
    public function set(
        string $name,
        string $value,
        int $expires_after = null,
        string $path = null,
        string $domain = null,
        bool $secure = null,
        bool $http_only = null,
        string $key = null
    ) {
        if (!$name) { // Must have a cookie name!
            throw $this->c::issue('Missing cookie name.');
            //
        } elseif (!$key && !($key = $this->App->Config->©cookies['©encryption_key'])) {
            throw $this->c::issue('Missing cookie encryption key.');
        }
        if (isset($value[0])) { // If not empty.
            $value = $this->c::encrypt($value, $key);
        }
        $expires_after = max(0, $expires_after ?? 31556926);
        $expires       = $expires_after ? time() + $expires_after : 0;

        $path   = $path ?? '/'; // Entire site.
        $domain = $domain ?? $this->c::currentHost(false);
        $domain = $domain === 'root' ? '.'.$this->c::currentRootHost(false) : $domain;

        $secure    = $secure ?? $this->c::isSsl();
        $http_only = $http_only ?? true;

        if (headers_sent()) {
            throw $this->c::issue('Headers already sent.');
        }
        setcookie($name, $value, $expires, $path, $domain, $secure, $http_only);

        if (mb_stripos($name, '_test_') === false) {
            $_COOKIE[$name] = $value;
        }
    }

    /**
     * Sets an unencrypted cookie.
     *
     * @param string      $name          Name of the cookie.
     * @param string      $value         Cookie value (empty to delete).
     * @param int|null    $expires_after Time (in seconds) this cookie should last for.
     * @param string|null $path          Path to set the cookie for.
     * @param string|null $domain        Domain name to set the cookie for.
     * @param bool|null   $secure        Over SSL access only?
     * @param bool|null   $http_only     HTTP only access?
     */
    public function setUe(
        string $name,
        string $value,
        int $expires_after = null,
        string $path = null,
        string $domain = null,
        bool $secure = null,
        bool $http_only = null
    ) {
        if (!$name) { // Must have a cookie name!
            throw $this->c::issue('Missing cookie name.');
        }
        $expires_after = max(0, $expires_after ?? 31556926);
        $expires       = $expires_after ? time() + $expires_after : 0;

        $path   = $path ?? '/'; // Entire site.
        $domain = $domain ?? $this->c::currentHost(false);
        $domain = $domain === 'root' ? '.'.$this->c::currentRootHost(false) : $domain;

        $secure    = $secure ?? $this->c::isSsl();
        $http_only = $http_only ?? true;

        if (headers_sent()) {
            throw $this->c::issue('Headers already sent.');
        }
        setcookie($name, $value, $expires, $path, $domain, $secure, $http_only);

        if (mb_stripos($name, '_test_') === false) {
            $_COOKIE[$name] = $value;
        }
    }

    /**
     * Gets an encrypted cookie value.
     *
     * @param string      $name Name of the cookie.
     * @param string|null $key  Encryption key.
     *
     * @return string Cookie value (decrypted).
     */
    public function get(string $name, string $key = null): string
    {
        if (!$name) { // Must have a cookie name!
            throw $this->c::issue('Missing cookie name.');
            //
        } elseif (!$key && !($key = $this->App->Config->©cookies['©encryption_key'])) {
            throw $this->c::issue('Missing cookie encryption key.');
        }
        if (isset($_COOKIE[$name]) && is_string($_COOKIE[$name])) {
            return $this->c::decrypt($_COOKIE[$name], $key);
        }
        return ''; // Missing cookie.
    }

    /**
     * Gets an unencrypted cookie value.
     *
     * @param string $name Name of the cookie.
     *
     * @return string Cookie value.
     */
    public function getUe(string $name): string
    {
        if (!$name) { // Must have a cookie name!
            throw $this->c::issue('Missing cookie name.');
        }
        if (isset($_COOKIE[$name]) && is_string($_COOKIE[$name])) {
            return $_COOKIE[$name];
        }
        return ''; // Missing cookie.
    }
}