<?php
/**
 * This file is part of the PHP Generics package.
 *
 * @package Generics
 */
namespace Generics\Client;

use Generics\Streams\InputOutputStream;
use Generics\Streams\InputStream;
use Generics\Streams\MemoryStream;
use Generics\Socket\Endpoint;
use Generics\Socket\SocketException;

/**
 * This trait provides common http(s) client functionality
 *
 * @author Maik Greubel <greubel@nkey.de>
 */
trait HttpClientTrait
{
    use HttpHeadersTrait;

    /**
     * The query string
     *
     * @var string
     */
    private $queryString;

    /**
     * The payload
     *
     * @var MemoryStream
     */
    private $payload;

    /**
     * The HTTP protocol version
     *
     * @var string
     */
    private $protocol;

    /**
     * Path to file on server (excluding endpoint address)
     *
     * @var string
     */
    private $path;

    /**
     * When the connection times out (in seconds)
     *
     * @var int
     */
    private $timeout;

    /**
     * Load headers from remote and return it
     *
     * @return array
     */
    public function retrieveHeaders(): array
    {
        $this->setHeader('Connection', 'close');
        $this->setHeader('Accept', '');
        $this->setHeader('Accept-Language', '');
        $this->setHeader('User-Agent', '');

        $savedProto = $this->protocol;
        $this->protocol = 'HTTP/1.0';
        $this->request('HEAD');
        $this->protocol = $savedProto;

        return $this->getHeaders();
    }

    /**
     *
     * {@inheritdoc}
     * @see \Generics\Streams\HttpStream::appendPayload()
     */
    public function appendPayload(InputStream $payload)
    {
        while ($payload->ready()) {
            $this->payload->write($payload->read(1024));
        }
    }

    /**
     *
     * {@inheritdoc}
     * @see \Generics\Streams\HttpStream::getPayload()
     */
    public function getPayload(): InputOutputStream
    {
        return $this->payload;
    }

    /**
     * Set connection timeout in seconds
     *
     * @param int $timeout
     */
    public function setTimeout($timeout)
    {
        $timeout = intval($timeout);
        if ($timeout < 1 || $timeout > 60) {
            $timeout = 5;
        }
        $this->timeout = $timeout;
    }

    /**
     *
     * {@inheritdoc}
     * @see \Generics\Resettable::reset()
     */
    public function reset()
    {
        if (null == $this->payload) {
            $this->payload = new MemoryStream();
        }
        $this->payload->reset();
    }

    /**
     * Prepare the request buffer
     *
     * @param string $requestType
     * @return \Generics\Streams\MemoryStream
     * @throws \Generics\Streams\StreamException
     */
    private function prepareRequest($requestType): MemoryStream
    {
        $ms = new MemoryStream();

        // First send the request type
        $ms->interpolate("{rqtype} {path}{query} {proto}\r\n", array(
            'rqtype' => $requestType,
            'path' => $this->path,
            'proto' => $this->protocol,
            'query' => (strlen($this->queryString) ? '?' . $this->queryString : '')
        ));

        // Add the host part
        $ms->interpolate("Host: {host}\r\n", array(
            'host' => $this->getEndpoint()
                ->getAddress()
        ));

        $this->adjustHeaders($requestType);

        // Add all existing headers
        foreach ($this->getHeaders() as $headerName => $headerValue) {
            if (isset($headerValue) && strlen($headerValue) > 0) {
                $ms->interpolate("{headerName}: {headerValue}\r\n", array(
                    'headerName' => $headerName,
                    'headerValue' => $headerValue
                ));
            }
        }

        $ms->write("\r\n");

        return $ms;
    }

    /**
     * Set the query string
     *
     * @param string $queryString
     */
    public function setQueryString(string $queryString)
    {
        $this->queryString = $queryString;
    }

    /**
     * Retrieve and parse the response
     *
     * @param string $requestType
     * @throws \Generics\Client\HttpException
     * @throws \Generics\Socket\SocketException
     * @throws \Generics\Streams\StreamException
     */
    private function retrieveAndParseResponse($requestType)
    {
        $this->payload = new MemoryStream();
        $this->headers = array();

        $delimiterFound = false;

        $tmp = "";
        $numBytes = 1;
        $start = time();
        while (true) {
            if (! $this->checkConnection($start)) {
                continue;
            }

            $c = $this->read($numBytes);

            if ($c == null) {
                break;
            }

            $start = time(); // we have readen something => adjust timeout start point
            $tmp .= $c;

            if (! $delimiterFound) {
                $this->handleHeader($delimiterFound, $numBytes, $tmp);
            }

            if ($delimiterFound) {
                if ($requestType == 'HEAD') {
                    // Header readen, in type HEAD it is now time to leave
                    break;
                }

                // delimiter already found, append to payload
                $this->payload->write($tmp);
                $tmp = "";

                if ($this->checkContentLengthExceeded()) {
                    break;
                }
            }
        }

        $size = $this->payload->count();
        if ($size == 0) {
            return;
        }
        // Set pointer to start
        $this->payload->reset();

        $mayCompressed = $this->payload->read($size);
        switch ($this->getContentEncoding()) {
            case 'gzip':
                $uncompressed = gzdecode(strstr($mayCompressed, "\x1f\x8b"));
                $this->payload->flush();
                $this->payload->write($uncompressed);
                break;

            case 'deflate':
                $uncompressed = gzuncompress($mayCompressed);
                $this->payload->flush();
                $this->payload->write($uncompressed);
                break;

            default:
                // nothing
                break;
        }
        $this->payload->reset();
    }

    /**
     * Append the payload buffer to the request buffer
     *
     * @param MemoryStream $ms
     * @return MemoryStream
     * @throws \Generics\Streams\StreamException
     * @throws \Generics\ResetException
     */
    private function appendPayloadToRequest(MemoryStream $ms): MemoryStream
    {
        $this->payload->reset();

        while ($this->payload->ready()) {
            $ms->write($this->payload->read(1024));
        }

        $ms->reset();

        return $ms;
    }

    /**
     * Handle a header line
     *
     * All parameters by reference, which means the the values can be
     * modified during execution of this method.
     *
     * @param boolean $delimiterFound
     *            Whether the delimiter for end of header section was found
     * @param int $numBytes
     *            The number of bytes to read from remote
     * @param string $tmp
     *            The current readen line
     */
    private function handleHeader(&$delimiterFound, &$numBytes, &$tmp)
    {
        if ($tmp == "\r\n") {
            $numBytes = $this->adjustNumbytes($numBytes);
            $delimiterFound = true;
            $tmp = "";
            return;
        }

        if (substr($tmp, - 2, 2) == "\r\n") {
            $this->addParsedHeader($tmp);
            $tmp = "";
        }
    }

    /**
     * Perform the request
     *
     * @param string $requestType
     */
    private function requestImpl(string $requestType)
    {
        if ($requestType == 'HEAD') {
            $this->setTimeout(1); // Don't wait too long on simple head
        }

        $ms = $this->prepareRequest($requestType);

        $ms = $this->appendPayloadToRequest($ms);

        if (! $this->isConnected()) {
            $this->connect();
        }

        while ($ms->ready()) {
            $this->write($ms->read(1024));
        }

        $this->retrieveAndParseResponse($requestType);

        if ($this->getHeader('Connection') == 'close') {
            $this->disconnect();
        }
    }

    /**
     * Check the connection availability
     *
     * @param int $start
     *            Timestamp when read request attempt starts
     * @throws HttpException
     * @return bool
     */
    private function checkConnection($start): bool
    {
        if (! $this->ready()) {
            if (time() - $start > $this->timeout) {
                $this->disconnect();
                throw new HttpException("Connection timed out!");
            }

            return false;
        }

        return true;
    }

    /**
     * Check whether the readen bytes amount has reached the
     * content length amount
     *
     * @return bool
     */
    private function checkContentLengthExceeded(): bool
    {
        if (isset($this->headers['Content-Length'])) {
            if ($this->payload->count() >= $this->headers['Content-Length']) {
                return true;
            }
        }
        return false;
    }

    /**
     * Set the used protocol
     *
     * @param string $protocol
     */
    private function setProtocol(string $protocol)
    {
        $this->protocol = $protocol;
    }

    /**
     * Set the path on remote server
     *
     * @param string $path
     */
    private function setPath(string $path)
    {
        $this->path = $path;
    }

    /**
     *
     * {@inheritdoc}
     * @see \Generics\Streams\HttpStream::request()
     */
    abstract public function request(string $requestType);

    /**
     * Get the socket endpoint
     *
     * @return \Generics\Socket\Endpoint
     */
    abstract public function getEndpoint(): Endpoint;

    /**
     *
     * {@inheritdoc}
     * @see \Generics\Streams\InputStream::read()
     */
    abstract public function read($length = 1, $offset = null): string;

    /**
     * Whether the client is connected
     *
     * @return bool
     */
    abstract public function isConnected(): bool;

    /**
     * Connect to remote endpoint
     *
     * @throws SocketException
     */
    abstract public function connect();

    /**
     * Disconnects the socket
     *
     * @throws SocketException
     */
    abstract public function disconnect();

    /**
     *
     * {@inheritdoc}
     * @see \Generics\Streams\OutputStream::write()
     */
    abstract public function write($buffer);

    /**
     *
     * {@inheritdoc}
     * @see \Generics\Streams\Stream::ready()
     */
    abstract public function ready(): bool;
}


<?php
/**
 * This file is part of the PHP Generics package.
 *
 * @package Generics
 */
namespace Generics\Streams;

use Generics\Streams\Interceptor\StreamInterceptor;
use Countable;

/**
 * This class provides a stream for standard output
 *
 * @author Maik Greubel <greubel@nkey.de>
 */
class StandardOutputStream implements OutputStream
{

    /**
     * Interceptor
     *
     * @var StreamInterceptor
     */
    private $interceptor;

    /**
     * The standard out channel
     *
     * @var resource
     */
    private $stdout;

    /**
     * Create a new instance of StandardOutputStream
     */
    public function __construct()
    {
        $this->open();
    }

    /**
     * Opens a new standard output channel
     */
    private function open()
    {
        $this->stdout = fopen("php://stdout", "w");
    }

    /**
     *
     * {@inheritdoc}
     * @see \Generics\Streams\Stream::isOpen()
     */
    public function isOpen(): bool
    {
        return is_resource($this->stdout);
    }

    /**
     *
     * {@inheritdoc}
     * @see \Generics\Streams\OutputStream::flush()
     */
    public function flush()
    {
        if ($this->isOpen()) {
            fflush($this->stdout);
        }
        if ($this->interceptor instanceof StreamInterceptor) {
            $this->interceptor->reset();
        }
    }

    /**
     *
     * {@inheritdoc}
     * @see \Generics\Streams\Stream::ready()
     */
    public function ready(): bool
    {
        return $this->isOpen();
    }

    /**
     *
     * {@inheritdoc}
     * @see Countable::count()
     */
    public function count()
    {
        return 0;
    }

    /**
     *
     * {@inheritdoc}
     * @see \Generics\Resettable::reset()
     */
    public function reset()
    {
        $this->close();
        $this->open();

        if ($this->interceptor instanceof StreamInterceptor) {
            $this->interceptor->reset();
            $this->setInterceptor($this->interceptor);
        }
    }

    /**
     *
     * {@inheritdoc}
     * @see \Generics\Streams\OutputStream::write()
     */
    public function write($buffer)
    {
        if ($this->isWriteable()) {
            fwrite($this->stdout, $buffer);
        }
    }

    /**
     *
     * {@inheritdoc}
     * @see \Generics\Streams\Stream::close()
     */
    public function close()
    {
        if ($this->isOpen()) {
            fclose($this->stdout);
            $this->stdout = null;
        }
    }

    /**
     *
     * {@inheritdoc}
     * @see \Generics\Streams\OutputStream::isWriteable()
     */
    public function isWriteable(): bool
    {
        return $this->isOpen();
    }

    /**
     * Apply a stream interceptor
     *
     * @param StreamInterceptor $interceptor
     */
    public function setInterceptor(StreamInterceptor $interceptor)
    {
        $this->interceptor = $interceptor;
        stream_filter_append($this->stdout, $interceptor->getFilterName());
    }
}


<?php

namespace Creads\Api2Symfony;

/**
 * @author Quentin <q.pautrat@creads.org>
 */
class SymfonyAction
{
    /**
     * Name
     *
     * @var string
     */
    private $name;

    /**
     * Description
     *
     * @var string
     */
    private $description;

    /**
     * Route
     *
     * @var SymfonyActionRoute
     */
    private $route;

    /**
     * Method
     *
     * @var string
     */
    private $method;

    /**
     * Parameters
     *
     * @var array
     */
    private $parameters;

    /**
     * Responses
     *
     * @var array
     */
    private $responses;

    /**
     * Constructor
     *
     * @param string             $name
     * @param SymfonyActionRoute $route
     * @param string             $method
     * @param string             $description
     *
     * @todo Checks if name ends with 'Action'
     */
    public function __construct($name, SymfonyRoute $route, $method, $description = '')
    {
        if (!$name || empty($name)) {
            throw new \Exception("You must provide a action's name");
        }

        if (!$method || empty($method)) {
            throw new \Exception("You must provide a action's method");
        }

        $this->name = $name;
        $this->route = $route;
        $this->method = $method;
        $this->description = str_replace(array("\r\n", "\n", "\r", "\t", "  "), '', $description);
        $this->parameters = array();
        $this->responses = array();
    }

    /**
     * Factory method for chainability
     *
     * @param  string       $name
     * @param  SymfonyRoute $route
     * @param  string       $method
     * @param  string       $description
     * @return SymonyAction
     */
    public static function create($name, SymfonyRoute $route, $method, $description = '')
    {
        return new static($name, $route, $method, $description);
    }

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

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

    /**
     * Gets route
     *
     * @return SymfonyActionRoute
     */
    public function getRoute()
    {
        return $this->route;
    }

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

    /**
     * Adds parameter
     *
     * @param string $parameter
     * @return SymfonyAction Fluent method
     */
    public function addParameter($parameter)
    {
        $this->parameters[] = $parameter;

        return $this;
    }

    /**
     * Gets parameters
     *
     * @return array
     */
    public function getParameters()
    {
        return $this->parameters;
    }

    /**
     * Add response
     * @param SymfonyResponse $response
     * @return  SymfonyAction Fluent interface
     */
    public function addResponse(SymfonyResponse $response)
    {
        $this->responses[] = $response;

        return $this;
    }

    /**
     * Gets responses
     *
     * @return array
     */
    public function getResponses()
    {
        return $this->responses;
    }
}


<?php
namespace WMS\Library\BusinessRulesEngine\Loader;

use Symfony\Component\Config\Loader\FileLoader;
use Symfony\Component\Config\Resource\FileResource;
use Symfony\Component\Yaml\Parser as YamlParser;
use WMS\Library\BusinessRulesEngine\Rule;
use WMS\Library\BusinessRulesEngine\RuleCollection;

class YamlFileLoader extends FileLoader
{
    private static $availableKeys = array(
        'resource',
        'type',
        'expression',
        'tags'
    );
    private $yamlParser;

    /**
     * Loads a resource.
     *
     * @param mixed  $file The resource
     * @param string $type The resource type
     *
     * @throws \InvalidArgumentException
     * @return \WMS\Library\BusinessRulesEngine\RuleCollection
     */
    public function load($file, $type = null)
    {
        $path = $this->locator->locate($file);

        if (!stream_is_local($path)) {
            throw new \InvalidArgumentException(sprintf('This is not a local file "%s".', $path));
        }

        if (!file_exists($path)) {
            throw new \InvalidArgumentException(sprintf('File "%s" not found.', $path));
        }

        if (null === $this->yamlParser) {
            $this->yamlParser = new YamlParser();
        }

        $config = $this->yamlParser->parse(file_get_contents($path));

        $collection = new RuleCollection();
        $collection->addResource(new FileResource($path));

        // empty file
        if (null === $config) {
            return $collection;
        }

        // not an array
        if (!is_array($config)) {
            throw new \InvalidArgumentException(sprintf('The file "%s" must contain a YAML array.', $path));
        }

        foreach ($config as $name => $subConfig) {
            $this->validate($subConfig, $name, $path);

            if (isset($subConfig['resource'])) {
                $this->parseImport($collection, $subConfig, $path, $file);
            } else {
                $this->parseRule($collection, $name, $subConfig, $path);
            }
        }

        return $collection;
    }

    /**
     * Returns true if this class supports the given resource.
     *
     * @param mixed  $resource A resource
     * @param string $type     The resource type
     *
     * @return Boolean true if this class supports the given resource, false otherwise
     */
    public function supports($resource, $type = null)
    {
        return is_string($resource) && 'yml' === pathinfo($resource, PATHINFO_EXTENSION) && (!$type || 'yaml' === $type);
    }

    /**
     * Parses a rule and adds it to the RuleCollection.
     *
     * @param RuleCollection $collection A RouteCollection instance
     * @param string         $name       Rule name
     * @param array          $config     Rule definition
     * @param string         $path       Full path of the YAML file being processed
     */
    protected function parseRule(RuleCollection $collection, $name, array $config, $path)
    {
        $expression = isset($config['expression']) ? $config['expression'] : null;
        $tags = isset($config['tags']) ? $this->parseTags($config['tags']) : array();

        $rule = new Rule($expression);

        foreach ($tags as $tagName => $tagAttr) {
            $rule->addTag($tagName, $tagAttr);
        }

        $collection->add($name, $rule);
    }

    /**
     * Parses an import and adds the rules in the resource to the RuleCollection.
     *
     * @param RuleCollection $collection A RuleCollection instance
     * @param array          $config     Rule definition
     * @param string         $path       Full path of the YAML file being processed
     * @param string         $file       Loaded file name
     */
    protected function parseImport(RuleCollection $collection, array $config, $path, $file)
    {
        $type = isset($config['type']) ? $config['type'] : null;
        $tags = isset($config['tags']) ? $this->parseTags($config['tags']) : array();
        $this->setCurrentDir(dirname($path));

        $subCollection = $this->import($config['resource'], $type, false, $file);
        /* @var $subCollection RuleCollection */

        foreach ($tags as $tagName => $tagAttr) {
            $subCollection->addTag($tagName, $tagAttr);
        }

        $collection->addCollection($subCollection);
    }

    protected function parseTags($tags)
    {
        $properTags = array();

        foreach ($tags as $tag) {
            $name = $tag['name'];
            unset($tag['name']);

            $properTags[$name] = $tag ? : array();
        }

        return $properTags;
    }

    /**
     * Validates the rule configuration.
     *
     * @param array  $config A resource config
     * @param string $name   The config key
     * @param string $path   The loaded file path
     *
     * @throws \InvalidArgumentException If one of the provided config keys is not supported,
     *                                   something is missing or the combination is nonsense
     */
    protected function validate($config, $name, $path)
    {
        if (!is_array($config)) {
            throw new \InvalidArgumentException(sprintf('The definition of "%s" in "%s" must be a YAML array.', $name, $path));
        }
        if ($extraKeys = array_diff(array_keys($config), self::$availableKeys)) {
            throw new \InvalidArgumentException(sprintf(
                'The routing file "%s" contains unsupported keys for "%s": "%s". Expected one of: "%s".',
                $path,
                $name,
                implode('", "', $extraKeys),
                implode('", "', self::$availableKeys)
            ));
        }
        if (isset($config['resource']) && isset($config['expression'])) {
            throw new \InvalidArgumentException(sprintf(
                'The business rule file "%s" must not specify both the "resource" key and the "expression" key for "%s". Choose between an import and a rule definition.',
                $path,
                $name
            ));
        }
        if (!isset($config['resource']) && isset($config['type'])) {
            throw new \InvalidArgumentException(sprintf(
                'The "type" key for the rule definition "%s" in "%s" is unsupported. It is only available for imports in combination with the "resource" key.',
                $name,
                $path
            ));
        }
        if (!isset($config['resource']) && !isset($config['expression'])) {
            throw new \InvalidArgumentException(sprintf(
                'You must define an "expression" for the rule "%s" in file "%s".',
                $name,
                $path
            ));
        }
        if (isset($config['tags']) && !is_array($config['tags'])) {
            throw new \InvalidArgumentException(sprintf(
                'The "tags" key for the rule definition "%s" in "%s" contains unsupported data. Each tag defined must be an array with at least the "name" element set to a string.',
                $name,
                $path
            ));
        } elseif (isset($config['tags'])) {
            foreach ($config['tags'] as $tag) {
                if (!isset($tag['name'])) {
                    throw new \InvalidArgumentException(sprintf(
                        'The "tags" key for the rule definition "%s" in "%s" contains unsupported data. Each tag defined must be an array with at least the "name" element set to a string.',
                        $name,
                        $path
                    ));
                }
            }
        }
    }
}


<?php

namespace Unite\UnisysApi\Http\Controllers;

use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
use Spatie\MediaLibrary\Models\Media;
use Unite\UnisysApi\Http\Resources\MediaResource;
use Unite\UnisysApi\QueryBuilder\QueryBuilder;
use Unite\UnisysApi\QueryBuilder\QueryBuilderRequest;
use Unite\UnisysApi\Repositories\MediaRepository;

/**
 * @resource Media
 *
 * Media handler
 */
class MediaController extends Controller
{
    protected $repository;

    public function __construct(MediaRepository $repository)
    {
        $this->repository = $repository;

        $this->setResourceClass(MediaResource::class);

        $this->setResponse();

        $this->middleware('cache')->only(['list', 'show']);
    }

    /**
     * List
     *
     * @param QueryBuilderRequest $request
     * @return AnonymousResourceCollection|MediaResource[]
     */
    public function list(QueryBuilderRequest $request)
    {
        $this->authorize('hasPermission', $this->prefix('update'));

        $object = QueryBuilder::for($this->resource, $request)->paginate();

        return $this->response->collection($object);
    }

    /**
     * Stream
     *
     * @param Media $model
     * @return mixed
     */
    public function stream(Media $model)
    {
        return response()->stream(function() use ($model) {
            $stream = $model->stream();

            fpassthru($stream);

            if (is_resource($stream)) {
                fclose($stream);
            }
        });
    }

    /**
     * Download
     *
     * @param Media $model
     * @return \Symfony\Component\HttpFoundation\BinaryFileResponse
     */
    public function download(Media $model)
    {
        return response()->download($model->getPath(), $model->name);
    }

    /**
     * Show
     *
     * @param Media $model
     *
     * @return Resource|MediaResource
     */
    public function show(Media $model)
    {
        return $this->response->resource($model);
    }

    /**
     * Delete
     *
     * @param Media $model
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function delete(Media $model)
    {
        try {
            $model->delete();
        } catch (\Exception $e) {
            abort(409, 'Cannot delete record');
        }

        \Cache::tags('response')->flush();

        return $this->successJsonResponse();
    }
}


<?php

namespace Unite\UnisysApi\Http\Controllers;

/**
 * @resource Home
 *
 * Home handler
 */
class HomeController extends Controller
{
    /**
     * About
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function index()
    {
        return response()->json([
            'name' => env('APP_NAME'),
            'url' => env('APP_URL'),
            'env' => env('APP_ENV'),
            'version' => env('APP_VERSION', null),
            'database' => env('DB_DATABASE').'@'.env('DB_HOST'),
        ]);
    }
}


<?php
namespace Nkey\Caribu\Mvc\Router;

use Nkey\Caribu\Mvc\Controller\AbstractController;
use Nkey\Caribu\Mvc\Controller\Request;
use Nkey\Caribu\Mvc\Application;

abstract class AbstractRouter {

	/**
	 * Application instance
	 *
	 * @var Application
	 */
	private $application;

	public function setApplication(Application $application)
	{
		$this->application = $application;
		foreach($this->routes as $routeName => $controller) {
			$this->application->registerController($controller, $routeName);
		}
	}

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

	public function addRoute(string $name, AbstractController $controller)
	{
		$this->routes[$name] = $controller;
	}

	/**
	 * Checks wether a route exists
	 *
	 * @param string $name
	 * @return bool
	 */
	public function hasRoute(string $name)
	{
		return key_exists($name, $this->routes);
	}

	/**
	 *
	 * @param string $name
	 * @throws RouterException
	 * @return AbstractController
	 */
	private function getRoute(string $name)
	{
		if(!$this->hasRoute($name)) {
			throw new RouterException("Router {$router} is not registered");
		}

		return $this->routes[$name];
	}

	/**
	 * Route the existing request into a new controller
	 *
	 * @param string $name The name of route
	 * @param Request $request The existing request instance
	 * @return \Nkey\Caribu\Mvc\Controller\AbstractController
	 */
	public function route(string $name, Request $request)
	{
		$parts = \explode('/', $request->getOrigin());
		$found = false;
		for($i = 0; $i < count($parts); $i++) {
			if($parts[$i] === $name && isset($parts[$i+1])) {
				$action = $parts[$i+1];
				if(strpos($action, "?")) {
					$action = strstr($action, "?", true);
				}

				$request->setAction($action);
				$found = true;
			}
		}
		if(!$found) {
			$request->setAction("index");
		}
		$controller = $this->getRoute($name);
		$request->setController($controller->getControllerSimpleName());

		return $controller;
	}
}


<?php

namespace Zf2Forum\Service;

use Zend\ServiceManager\ServiceManager;
use Zend\ServiceManager\ServiceManagerAwareInterface;
use Zf2Forum\Model\Category\CategoryInterface;
use Zf2Forum\Model\Category\CategoryMapperInterface;
use Zf2Forum\Model\Message\MessageInterface;
use Zf2Forum\Model\Message\MessageMapperInterface;
use Zf2Forum\Model\Topic\TopicInterface;
use Zf2Forum\Model\Topic\TopicMapperInterface;
use Zf2Forum\Model\Visit\VisitInterface;
use Zf2Forum\Model\Visit\VisitMapperInterface;
use ZfcBase\EventManager\EventProvider;

class Discuss extends EventProvider implements ServiceManagerAwareInterface
{
    /**
     * @var ServiceManager
     */
    protected $serviceManager;

    /**
     * @var TopicMapperInterface
     */
    protected $topicMapper;

    /**
     * @var MessageMapperInterface
     */
    protected $messageMapper;

    /**
     * @var CategoryMapperInterface
     */
    protected $categoryMapper;

    /**
     * Retrieve service manager instance
     *
     * @return ServiceManager
     */
    public function getServiceManager()
    {
        return $this->serviceManager;
    }

    /**
     * Set service manager instance
     *
     * @param ServiceManager $serviceManager
     * @return Discuss
     */
    public function setServiceManager(ServiceManager $serviceManager)
    {
        $this->serviceManager = $serviceManager;
        return $this;
    }

    /**
     * getLatestThreads
     *
     * @param int $limit
     * @param int $offset
     * @param int $tagId
     * @return array
     */
    public function getLatestThreads($limit = 25, $offset = 0, $tagId = false)
    {
        return $this->topicMapper->getLatestTopics($limit, $offset, $tagId);
    }

    /**
     * getMessagesByThread
     *
     * @param ThreadInterface $thread
     * @param int $limit
     * @param int $offset
     * @return array
     */
    public function getMessagesByThread(TopicInterface $thread, $limit = 25, $offset = 0)
    {
        $messages = $this->messageMapper->getMessagesByTopic($thread->getThreadId(), $limit, $offset);
        $messagesRet = array();
        foreach ($messages as $message) {
            $sender = $this->getServiceManager()->get("Zf2Forum_user_mapper")->findById($message->getUserId());
            /**
             * @return \Zd2Forum\Options\ModuleOptions
             */
            $options = $this->getServiceManager()->get('Zf2Forum\ModuleOptions');
            $funcName = "get" . $options->getUserColumn();
            $message->user = $sender->$funcName();
            $messagesRet[] = $message;
        }

        return $messagesRet;
    }

    /**
     * createThread
     *
     * @param CategoryInterface $tag
     * @param ThreadInterface $thread
     * @return ThreadInterface
     */
    public function createThread(CategoryInterface $tag, TopicInterface $thread)
    {
        $thread->setForumCategoryId($tag->getid());
        $thread->setTimestampCreated(date("Y-m-d H:i:s"));
        $thread->setUserId($this->getServiceManager()->get('zfcuser_auth_service')->getIdentity()->getId());

        $this->getEventManager()->trigger(
            __FUNCTION__,
            $thread,
            array(
                'thread'  => $thread,
            )
        );

        $thread = $this->topicMapper->persist($thread);

        $this->getEventManager()->trigger(
            __FUNCTION__ . '.post',
            $thread,
            array(
                'thread'  => $thread,
            )
        );

        return $thread;
    }

    /**
     * updateThread
     *
     * @param ThreadInterface $thread
     * @return ThreadInterface
     */
    public function updateThread(TopicMapperInterface $thread)
    {
        return $this->threadMapper->persist($thread);
    }

    /**
     * createMessage
     *
     * @param MessageInterface $message
     * @return MessageInterface
     */
    public function createMessage(MessageInterface $message)
    {
        // Set post time and persist message.
        $message->setUserId($this->getServiceManager()->get('zfcuser_auth_service')->getIdentity()->getId());
        $message->setTimestampCreated(new \DateTime);

        $this->getEventManager()->trigger(
            __FUNCTION__,
            $message,
            array(
                'message' => $message,
            )
        );

        $message = $this->messageMapper->persist($message);

        $this->getEventManager()->trigger(
            __FUNCTION__ . '.post',
            $message,
            array(
                'message' => $message,
            )
        );
        return $message;
    }

    /**
     * updateMessage
     *
     * @param MessageInterface $message
     * @return MessageInterface
     */
    public function updateMessage(MessageInterface $message)
    {
        $message->setPostTime(new \DateTime);
        return $this->messageMapper->persist($message);
    }

    /**
     * getTagById
     *
     * @param int $id
     * @return CategoryInterface
     */
    public function getCategoryById($id)
    {
        return $this->categoryMapper->getCategoryById($id);
    }

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

    /**
     * getThreadById
     *
     * @param int $threadId
     * @return ThreadInterface
     */
    public function getTopicById($threadId)
    {
        return $this->topicMapper->getTopicById($threadId);
    }

    /**
     * getMessageById
     *
     * @param int $messageId
     * @return MessageInterface
     */
    public function getMessageById($messageId)
    {
        return $this->messageMapper->getMessageById($messageId);
    }

    /**
     * getThreadMapper
     *
     * @return ThreadMapperInterface
     */
    public function getThreadMapper()
    {
        return $this->threadMapper;
    }

    /**
     * setThreadMapper
     *
     * @param ThreadMapperInterface $threadMapper
     * @return Discuss
     */
    public function setTopicMapper($topicMapper)
    {
        $this->topicMapper = $topicMapper;
        return $this;
    }

    /**
     * getMessageMapper
     *
     * @return MessageMapperInterface
     */
    public function getMessageMapper()
    {
        return $this->messageMapper;
    }

    /**
     * setMessageMapper
     *
     * @param MessageMapperInterface $messageMapper
     * @return Discuss
     */
    public function setMessageMapper($messageMapper)
    {
        $this->messageMapper = $messageMapper;
        return $this;
    }

    /**
     * Get categoryMapper.
     *
     * @return categoryMapper
     */
    public function getCategoryMapper()
    {
        return $this->categoryMapper;
    }

    /**
     * Set categoryMapper.
     *
     * @param CategoryMapperInterface $categoryMapper the value to be set
     */
    public function setCategoryMapper(CategoryMapperInterface $categoryMapper)
    {
        $this->categoryMapper = $categoryMapper;
        return $this;
    }

    /**
     * Set Visit Mapper
     *
     * Enter description here ...
     * @param VisitMapperInterface $visitMapper
     */
    public function setVisitMapper(VisitMapperInterface $visitMapper)
    {
        $this->visitMapper = $visitMapper;
        return $this;
    }

    /**
     * Get Vist Mapper.
     *
     * Enter description here ...
     */
    public function getVisitMapper()
    {
        return $this->visitMapper;
    }

    /**
     * storeVisitIfUnique - records the visit if it is unuiqe.
     * @param VisitInterface $vist
     * @return \Zf2Forum\Service\Discuss
     */
    public function storeVisitIfUnique(VisitInterface $visit)
    {
        $this->getVisitMapper()->storeVisitIfUnique($visit);
        return $this;
    }
}


<?php
namespace Zf2Forum\Model\Topic;

use Zf2Forum\Model\Topic\TopicInterface;
use DateTime;

class Topic implements TopicInterface
{

    /**
     *
     * @var int
     */
    private $_id;

    /**
     *
     * @var string
     */
    private $_title;

    private $_text;

    private $_lastPost;

    /**
     *
     * @var integer
     */
    private $_messageCount;

    /**
     *
     * @var integer
     */
    private $_visitCount;

    /**
     *
     * @var DateTime
     */
    private $_timestampCreated;

    /**
     *
     * @var integer
     */
    private $_userId;

    /**
     *
     * @var integer
     */
    private $_forumCategoryId;

    /**
     *
     * @return the $timestampCreated
     */
    public function getTimestampCreated()
    {
        return $this->_timestampCreated;
    }

    /**
     *
     * @param
     *            $timestampCreated
     */
    public function setTimestampCreated($postTime)
    {
        $this->_timestampCreated = $postTime;
        return $this;
    }

    /**
     *
     * @return the $_id
     */
    public function getId()
    {
        return $this->_id;
    }

    /**
     *
     * @return the $_title
     */
    public function getTitle()
    {
        return $this->_title;
    }

    /**
     *
     * @return the $_text
     */
    public function getText()
    {
        return $this->_text;
    }

    /**
     *
     * @param number $_id
     */
    public function setId($_id)
    {
        $this->_id = $_id;
    }

    /**
     *
     * @param string $_title
     */
    public function setTitle($_title)
    {
        $this->_title = $_title;
    }

    /**
     *
     * @param field_type $_text
     */
    public function setText($_text)
    {
        $this->_text = $_text;
    }

    public function getUserId()
    {
        return $this->_userId;
    }

    public function setUserId($_userId)
    {
        $this->_userId = $_userId;
        return $this;
    }

    public function getForumCategoryId()
    {
        return $this->_forumCategoryId;
    }

    public function setForumCategoryId($_forumCategoryId)
    {
        $this->_forumCategoryId = $_forumCategoryId;
        return $this;
    }

    public function getMessageCount()
    {
        return $this->_messageCount;
    }

    public function setMessageCount($_messageCount)
    {
        $this->_messageCount = $_messageCount;
        return $this;
    }

    public function getVisitCount()
    {
        return $this->_visitCount;
    }

    public function setVisitCount($_visitCount)
    {
        $this->_visitCount = $_visitCount;
        return $this;
    }

    /**
     * Set Last Post
     *
     * @param Date $lastPost
     */
    public function setLastPost($lastPost)
    {
        if ($lastPost == 0) {
            $this->_lastPost = "";
        } elseif ($lastPost !== "" and $lastPost !== "NULL" and $lastPost !== null) {
            if ($lastPost instanceof DateTime) {
                $this->_lastPost = $lastPost;
            } else {
                $this->_lastPost = new DateTime($lastPost);
            }
        }
        return $this;
    }

    /**
     * Get Last Post.
     *
     * @return Date
     */
    public function getLastPost()
    {
        return $this->_lastPost;
    }
}


<?php

/**
 * This file is part of the PHP Generics package.
 *
 * @package Generics
 */
namespace Generics\Util;

use Generics\Socket\InvalidUrlException;
use Generics\Socket\Url;

/**
 * This class provides a parser to retrieve Url objects out of arbitrary URIs
 *
 * @author Maik Greubel <greubel@nkey.de>
 */
class UrlParser
{

    /**
     * Parse a URI into a Url
     *
     * @param string $url
     * @throws InvalidUrlException
     * @return \Generics\Socket\Url
     */
    public static function parseUrl($url): Url
    {
        $parts = parse_url($url);

        if (false === $parts || false === Arrays::hasElement($parts, 'host') || false === Arrays::hasElement($parts, 'scheme')) {
            throw new InvalidUrlException('The URL {url} does not contain necessary parts', array('url' => $url));
        }

        $address = $parts['host'];
        $scheme = $parts['scheme'];
        $query = (isset($parts['query']) ? $parts['query'] : '');
        $port = 0;
        $path = "/";

        if (isset($parts['port'])) {
            $port = intval($parts['port']);
        }

        if ($port == 0) {
            $port = self::getPortByScheme($scheme);
        }

        if (isset($parts['path'])) {
            $path = $parts['path'];
        }

        return new Url($address, $port, $path, $scheme, $query);
    }

    /**
     * Get port number by scheme name.
     * The port will be the default which is defined by
     * http://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers
     *
     * @param string $scheme
     *            The scheme.
     * @throws InvalidUrlException
     * @return int
     */
    public static function getPortByScheme($scheme): int
    {
        switch ($scheme) {
            case 'http':
                return 80;

            case 'https':
                return 443;

            case 'ftp':
                return 21;

            default:
                throw new InvalidUrlException("Scheme {scheme} is not handled!", array(
                    'scheme' => $scheme
                ));
        }
    }
}


<?php

namespace ThemeManager;

use Symfony\Component\Yaml\Yaml;
use ThemeManager\Exceptions\EmptyThemeName;
use ThemeManager\Exceptions\MissingRequiredFields;
use ThemeManager\Exceptions\NoThemeData;
use ThemeManager\Exceptions\NoThemeName;

class Theme
{
    /**
     * @var null|string
     */
    private $autoload = null;

    /**
     * @var string
     */
    protected $autoloadPath = 'vendor';

    /**
     * @var string
     */
    private $basePath;

    /**
     * @var bool
     */
    private $error = false;

    /**
     * @var string
     */
    private $errorType = 'Unknown';

    /**
     * @var string
     */
    protected $fileName = 'theme';

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

    /**
     * @var array
     */
    private $missingRequiredFields = [];

    /**
     * @var string
     */
    private $name;

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

    /**
     * @var string
     */
    private $locationType;

    /**
     * @var string
     */
    private $ymlFileExtension;

    /**
     * @var string
     */
    private $yml;

    /**
     * @param         $path
     * @param array   $requiredFields
     * @param bool $yaml
     * @param bool $isSecondary
     */
    public function __construct($path, array $requiredFields = [], $yaml = false, $isSecondary = false)
    {
        $this->basePath = $path;
        $this->locationType = ($isSecondary) ? 'Secondary' : 'Primary';
        $this->requiredFields = $requiredFields;
        $this->ymlFileExtension = $yaml ? '.yaml' : '.yml';

        $this->setThemeYmlPath()
            ->setAutoloadPath()
            ->setInfo()
            ->setName()
            ->checkRequiredFields();
    }

    /**
     * @return $this
     */
    protected function setThemeYmlPath()
    {
        $this->yml = $this->basePath($this->fileName . $this->ymlExtension());

        return $this;
    }

    /**
     * @return $this
     */
    protected function setAutoloadPath()
    {
        if (file_exists($this->basePath(rtrim($this->autoloadPath, '/') . '/autoload.php'))) {
            $this->autoload = $this->basePath(rtrim($this->autoloadPath, '/') . '/autoload.php');
        }

        return $this;
    }

    /**
     * @return $this
     */
    protected function setInfo()
    {
        $this->info = Yaml::parse($this->yml);

        return $this;
    }

    /**
     * @throws \ThemeManager\Exceptions\NoThemeData When theme.yml is empty
     * @throws \ThemeManager\Exceptions\NoThemeName When themes name isn't defined
     * @throws \ThemeManager\Exceptions\EmptyThemeName When themes name is empty
     *
     * @return $this
     */
    protected function setName()
    {
        $info = $this->getInfo();

        if (! is_array($info)) {
            $this->setError('No Theme Data');
            throw new NoThemeData($this->getYmlPath(), $this);
        } elseif (! array_key_exists('name', $info)) {
            $this->setError();
            throw new NoThemeName($this->getYmlPath(), $this);
        } elseif (empty($info['name'])) {
            $this->setError('Empty Theme Name');
            throw new EmptyThemeName($this->getYmlPath(), $this);
        }
        $this->name = $info['name'];

        return $this;
    }

    /**
     * @throws \ThemeManager\Exceptions\MissingRequiredFields When required field is empty
     *
     * @return $this
     */
    protected function checkRequiredFields()
    {
        if (! empty($this->requiredFields)) {
            foreach ($this->requiredFields as $field) {
                if (is_string($field) && ($this->getInfoByKey($field) === false ||
                        ! isset($this->info[$field]))
                ) {
                    $this->missingRequiredFields[] = $field;
                }
            }

            if (! empty($this->missingRequiredFields)) {
                $this->setError('Missing Required Field(s)');
                throw new MissingRequiredFields($this->getYmlPath(), $this);
            }
        }

        return $this;
    }

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

    /**
     * @return int
     */
    public function countMissingRequiredFields()
    {
        return count($this->missingRequiredFields);
    }

    /**
     * @param string $type
     *
     * @return $this
     */
    protected function setError($type = 'No Name')
    {
        $this->error = true;
        $this->errorType = $type;

        return $this;
    }

    /**
     * @return null|string
     */
    protected function getAutoloadPath()
    {
        return $this->autoload;
    }

    /**
     * @return bool
     */
    public function hasError()
    {
        return $this->error;
    }

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

    /**
     * @return string
     */
    public function getYmlPath()
    {
        return realpath($this->yml) ?: '{path undefined}';
    }

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

    /**
     * @return $this
     */
    public function registerAutoload()
    {
        if (! is_null($this->getAutoloadPath())) {
            require_once "{$this->getAutoloadPath()}";
        }

        return $this;
    }

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

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

    /**
     * @param $key
     *
     * @return bool|mixed
     */
    public function getInfoByKey($key)
    {
        if (array_has($this->getInfo(), $key)) {
            return array_get($this->getInfo(), $key);
        }

        return false;
    }

    /**
     * @param $key
     *
     * @return bool|mixed
     */
    public function __get($key)
    {
        return $this->getInfoByKey($key);
    }

    /**
     * @return string
     */
    public function getName()
    {
        return $this->name ?: '{empty}';
    }

    /**
     * @param null $path
     *
     * @return string
     */
    public function basePath($path = null)
    {
        return $this->basePath . ($path ? DIRECTORY_SEPARATOR . $path : $path);
    }
}


<?php

namespace Unite\UnisysApi\Commands;

use Illuminate\Console\Command;
use Illuminate\Routing\Router;
use Unite\Contacts\CountryRepository;
use Unite\Contacts\Models\Country;
use Unite\UnisysApi\Services\SettingService;

class SetCompanyProfile extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'unisys-api:set-company-profile';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Set Basic company profile if is not exists';

    /**
     * The router instance.
     *
     * @var \Illuminate\Routing\Router
     */
    protected $router;

    /**
     * An array of all the registered routes.
     *
     * @var \Illuminate\Routing\RouteCollection
     */
    protected $routes;

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct(Router $router)
    {
        parent::__construct();

        $this->router = $router;
        $this->routes = $router->getRoutes();
    }

    /*
     * Execute the console command.
     */
    public function handle(SettingService $settingService, CountryRepository $countryRepository)
    {
        if(app('companyProfile')) {
            $this->info('Company profile already exist');

            if (!$this->confirm('Do you wish to continue and rewrite it?')) {
                return;
            }
        }

        $this->info('Set Company information');

        $contactData['name'] = $this->validate(function() {
            return $this->ask('Contact name *');
        }, 'required|string|max:40');

        $contactData['company'] = $this->validate(function() {
            return $this->ask('Company name *');
        }, 'required|string|max:40');

        $contactData['street'] = $this->validate(function() {
            return $this->ask('Street');
        }, 'nullable|string|max:40');

        $contactData['zip'] = $this->validate(function() {
            return $this->ask('Zip');
        }, 'nullable|string|max:10');

        $contactData['city'] = $this->validate(function() {
            return $this->ask('City');
        }, 'nullable|string|max:20');

        $countryName = $this->validate(function() use ($countryRepository) {
            return $this->choice('Country', $countryRepository->getListForSelect(), Country::DEFAULT_COUNTRY_ID);
        }, 'string');

        if($countryName && $country = $countryRepository->getByName($countryName)) {
            $contactData['country_id'] = $country->id;
        }

        $contactData['reg_no'] = $this->validate(function() {
            return $this->ask('Registration number');
        }, 'nullable|string|max:20');

        $contactData['tax_no'] = $this->validate(function() {
            return $this->ask('Tax number');
        }, 'nullable|string|max:20');

        $contactData['vat_no'] = $this->validate(function() {
            return $this->ask('Vat number');
        }, 'nullable|string|max:20');

        $contactData['email'] = $this->validate(function() {
            return $this->ask('Email *');
        }, 'required|email');

        $contactData['telephone'] = $this->validate(function() {
            return $this->ask('Phone number');
        }, 'nullable|string|max:20');

        $settingService->saveCompanyProfile($contactData);

        $this->info('Company profile is set');
    }

    private function validate(\Closure $closure, string $validates)
    {
        do {
            $value = $closure();

            $validator = \Validator::make(['input' => $value], ['input' => $validates]);

            if ($validator->fails()) {
                $this->error( $validator->errors()->first() );
            }
        } while ($validator->fails());

        return $value;
    }
}


<?php
namespace WMS\Library\BusinessRulesEngine;

/**
 * Class used to represent a configured business rule
 *
 * @author Andrew Moore <me@andrewmoore.ca>
 */
class Rule
{
    /** @var string */
    private $expression;

    /** @var array */
    private $tags = array();

    /**
     * @param string $expression Rule's expression
     */
    function __construct($expression)
    {
        $this->setExpression($expression);
    }

    /**
     * @return string The rule's expression
     */
    public function getExpression()
    {
        return $this->expression;
    }

    /**
     * @param string $expression The rule's expression
     *
     * @return Rule The current instance
     */
    public function setExpression($expression)
    {
        $this->expression = $expression;
        return $this;
    }

    /**
     * Gets all tags.
     *
     * @return array An array of tags
     */
    public function getTags()
    {
        return $this->tags;
    }

    /**
     * Gets a tag by name.
     *
     * @param string $name The tag name
     *
     * @return array An array of attributes
     */
    public function getTag($name)
    {
        return isset($this->tags[$name]) ? $this->tags[$name] : array();
    }

    /**
     * Adds a tag for this definition.
     *
     * @param string $name       The tag name
     * @param array  $attributes An array of attributes
     *
     * @return Rule The current instance
     *
     * @api
     */
    public function addTag($name, array $attributes = array())
    {
        $this->tags[$name][] = $attributes;

        return $this;
    }

    /**
     * Whether this rule has a tag with the given name
     *
     * @param string $name
     *
     * @return Boolean
     */
    public function hasTag($name)
    {
        return isset($this->tags[$name]);
    }

    /**
     * Clears all tags for a given name.
     *
     * @param string $name The tag name
     *
     * @return Rule
     */
    public function clearTag($name)
    {
        if (isset($this->tags[$name])) {
            unset($this->tags[$name]);
        }

        return $this;
    }

    /**
     * Clears the tags for this rule.
     *
     * @return Rule The current instance
     *
     * @api
     */
    public function clearTags()
    {
        $this->tags = array();

        return $this;
    }
}


<?php
namespace Nkey\Caribu\Mvc\View;

use \Nkey\Caribu\Mvc\Controller\Response;
use \Nkey\Caribu\Mvc\Controller\Request;
use \Nkey\Caribu\Mvc\View\AbstractView;

/**
 * This is the default view class
 *
 *
 * It provides the lowest level of view rending possible.
 * The render function determines the output type and either
 * renders html or let the body content untouched.
 *
 * @applyTo(controller=any,action=any)
 *
 * @author Maik Greubel <greubel@nkey.de>
 *
 *         This file is part of Caribu MVC package
 */
class DefaultView extends AbstractView
{

    /**
     * (non-PHPdoc)
     *
     * @see \Nkey\Caribu\Mvc\View\AbstractView::getOrder()
     */
    public function getOrder()
    {
        return 0;
    }

    /**
     * (non-PHPdoc)
     *
     * @see \Nkey\Caribu\Mvc\View\AbstractView::render()
     */
    public function render(Response &$response, Request $request, $parameters = array())
    {
        if ($response->getType() == 'text/html') {
            $html = sprintf("
<!DOCTYPE html>
<html>
<head>
<title>%s</title>
</head>

<body>
%s
</body>

</html>", $response->getTitle(), $response->getBody());

            $response->setBody($html);
        }
    }
}


<?php

declare(strict_types=1);

namespace Chiron\Container;

use Chiron\Container\Annotations\Alias;
use Chiron\Container\Exception\CannotFindParameterException;
use Chiron\Container\Exception\CannotResolveException;
use Chiron\Container\Exception\ContainerException;
use Chiron\Container\Exception\EntityNotFoundException;
use Chiron\Container\Reflection\ReflectionCallable;
use Closure;
use InvalidArgumentException;
use Psr\Container\ContainerInterface;
use ReflectionClass;
use ReflectionException;
use ReflectionFunction;
use ReflectionFunctionAbstract;
use ReflectionMethod;
use ReflectionObject;

// https://github.com/thephpleague/container/blob/master/src/Container.php#L92
//https://github.com/mrferos/di/blob/master/src/Container.php#L99

// TODO : améliorer le Circular exception avec le code : https://github.com/symfony/dependency-injection/blob/master/Container.php#L236

// TODO : classe à renommer en DefinitionResolver
class ReflectionResolver
{
    protected $container;

    /**
     * Array of entries being resolved. Used to avoid circular dependencies and infinite loops.
     *
     * @var array
     */
    protected $entriesBeingResolved = [];

    // TODO : mettre la valeur par défaut du paramétre à null pour rendre facultatif la présence du container.
    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    // $concrete c'est un mixed
    public function resolve($concrete, array $args = [])
    {
        $instance = $concrete;

        if (is_callable($concrete)) {
            //$concrete = $this->resolveCallable($concrete);
            $instance = $this->call($concrete, $args);
        }

        if (is_string($concrete) && class_exists($concrete)) {
            //$concrete = $this->resolveClass($concrete);
            $instance = $this->build($concrete, $args);
        }

        return $instance;
    }

    // TODO : ajouter la signature dans l'interface
    // TODO : regarder aussi ici : https://github.com/mrferos/di/blob/master/src/Definition/AbstractDefinition.php#L75
    // TODO : regarder ici pour utiliser le arobase @    https://github.com/slince/di/blob/master/DefinitionResolver.php#L210
    public function resolveArguments(array $arguments): array
    {
        foreach ($arguments as &$arg) {
            if (! is_string($arg)) {
                continue;
            }

            //if (! is_null($this->container) && $this->container->has($arg)) {
            if ($this->container->has($arg)) {
                $arg = $this->container->get($arg);

                continue;
            }
        }

        return $arguments;
    }

    // TODO : améliorer le code regarder ici   =>   https://github.com/illuminate/container/blob/master/Container.php#L778
    // TODO : améliorer le code et regarder ici => https://github.com/thephpleague/container/blob/68c148e932ef9959af371590940b4217549b5b65/src/Definition/Definition.php#L225
    // TODO : attention on ne gére pas les alias, alors que cela pourrait servir si on veut builder une classe en utilisant l'alias qui est présent dans le container. Réfléchir si ce cas peut arriver.
    // TODO : renommer en buildClass() ????
    // TODO : améliorer le Circular exception avec le code : https://github.com/symfony/dependency-injection/blob/master/Container.php#L236
    // TODO : renommer la fonction en "make()"
    public function build(string $className, array $arguments = [])
    {
        $arguments = $this->resolveArguments($arguments);

        $class = $this->reflectClass($className);

        // Check if we are already getting this entry -> circular dependency
        if (isset($this->entriesBeingResolved[$className])) {
            throw new ContainerException(sprintf(
                'Circular dependency detected while trying to resolve entry "%s"',
                $className
            ));
        }
        $this->entriesBeingResolved[$className] = true;

        // TODO : améliorer ce bout de code, on fait 2 fois un new class, alors qu'on pourrait en faire qu'un !!! https://github.com/illuminate/container/blob/master/Container.php#L815
        if ($constructor = $class->getConstructor()) {
            $arguments = $this->getParameters($constructor, $arguments);

            unset($this->entriesBeingResolved[$className]);

            return new $className(...$arguments);
        }

        unset($this->entriesBeingResolved[$className]);

        //$reflection->newInstanceArgs($resolved);
        return new $className();
    }

    private function reflectClass(string $className): ReflectionClass
    {
        if (! class_exists($className)) {
            throw new InvalidArgumentException("Entry '{$className}' cannot be resolved");
        }

        // TODO : vérifier que le constructeur est public !!!! => https://github.com/PHP-DI/PHP-DI/blob/cdcf21d2a8a60605e81ec269342d48b544d0dfc7/src/Definition/Source/ReflectionBasedAutowiring.php#L31
        // TODO : déplacer ce bout de code dans une méthode "reflectClass()"
        $class = new ReflectionClass($className);

        // Prevent error if you try to instanciate an abstract class or a class with a private constructor.
        if (! $class->isInstantiable()) {
            throw new ContainerException(sprintf(
                'Entry "%s" cannot be resolved: the class is not instantiable',
                $className
            ));
        }

        return $class;
    }

    // TODO : regarder ici le code qui permet d'executer aussi les callables ajoutés dans le container   => https://github.com/mrferos/di/blob/master/src/Container.php#L173
    // grosso modo le typehint de $callee peut être une string présente dans le tableau des closure =>  $this->closure[$calleeName]
    // TODO : méthode à virer !!!!
    /*
    public function call_old(callable $callee, array $arguments = [])
    {
        try {
            return call_user_func_array(
                $callee,
                $this->getParameters(new ReflectionCallable($callee), $arguments)
            );
        } catch (CannotFindParameterException $e) {
            throw new CannotResolveException($callee, $e->getParameter());
        }
    }*/

    /*
        public function call2($callback, array $parameters = [], ?string $defaultMethod = null)
        {
            if ($this->isCallableWithAtSign($callback) || $defaultMethod) {
                return $this->callClass($callback, $parameters, $defaultMethod);
            }

            if (! is_callable($callback)) {
                throw new InvalidArgumentException(sprintf(
                    '(%s) is not resolvable.',
                    is_array($callback) || is_object($callback) || is_null($callback) ? json_encode($callback) : $callback
                ));
            }

            try {
                return call_user_func_array(
                    $callback,
                    $this->getParameters(new ReflectionCallable($callback), $parameters)
                );
            } catch (CannotFindParameterException $e) {
                throw new CannotResolveException($callback, $e->getParameter());
            }
        }
    */

    /**
     * Invoke a callable and inject its dependencies.
     *
     * @param callable $callable
     * @param array    $args
     *
     * @return mixed
     */
    public function call(callable $callable, array $args = [])
    {
        $args = $this->resolveArguments($args);

        $reflection = $this->reflectCallable($callable);

        return call_user_func_array(
                $callable,
                $this->getParameters($reflection, $args)
            );
    }

    private function reflectCallable(callable $callee): ReflectionFunctionAbstract
    {
        // closure, or function name,
        if ($callee instanceof Closure) {
            return new ReflectionFunction($callee);
        } elseif (is_string($callee) && strpos($callee, '::') === false) {
            return new ReflectionFunction($callee);
        }
        if (is_string($callee)) {
            $callee = explode('::', $callee);
        } elseif (is_object($callee)) {
            $callee = [$callee, '__invoke'];
        }
        if (is_object($callee[0])) {
            $reflection = new ReflectionObject($callee[0]);
            if ($reflection->hasMethod($callee[1])) {
                return $reflection->getMethod($callee[1]);
            }
            //magicMethod
            return $reflection->getMethod('__call');
        }

        $reflection = new ReflectionClass($callee[0]);
        if ($reflection->hasMethod($callee[1])) {
            return $reflection->getMethod($callee[1]);
        }
        //magicMethod
        return $reflection->getMethod('__callStatic');
    }

    /*
        public function call_save(callable $callable, array $args = [])
        {

            if (is_string($callable) && strpos($callable, '::') !== false) {
                $callable = explode('::', $callable);
            }
            if (is_array($callable)) {
                if (is_string($callable[0])) {
                    $callable[0] = $this->container->get($callable[0]);
                }
                $reflection = new ReflectionMethod($callable[0], $callable[1]);
                if ($reflection->isStatic()) {
                    $callable[0] = null;
                }
                return $reflection->invokeArgs($callable[0], $this->getParameters($reflection, $args));
            }
            if (is_object($callable)) {
                $reflection = new ReflectionMethod($callable, '__invoke');
                return $reflection->invokeArgs($callable, $this->getParameters($reflection, $args));
            }
            $reflection = new ReflectionFunction($callable);

            return $reflection->invokeArgs($this->getParameters($reflection, $args));
        }
    */

    /**
     * @param \ReflectionFunctionAbstract $reflection
     * @param array                       $arguments
     *
     * @return array
     */
    // TODO : renommer en getMethodDependencies() ou plutot en reflectArguments(ReflectionFunctionAbstract $method, array $args = []) : array ou alors en resolveFunctionArguments()
    protected function getParameters(ReflectionFunctionAbstract $reflection, array $arguments = []): array
    {
        // TODO : améliorer ce bout de code ******************
        $parametersToReturn = static::getSeqArray($arguments); // utiliser plutot ce bout de code pour éviter d'initialiser un tableau lorsque les clés sont numeriques => https://github.com/illuminate/container/blob/master/BoundMethod.php#L119

        $reflectionParameters = array_slice($reflection->getParameters(), count($parametersToReturn));

        if (! count($reflectionParameters)) {
            return $parametersToReturn;
        }
        // TODO END ******************************************

        /* @var \ReflectionParameter $param */
        foreach ($reflectionParameters as $param) {
            /*
             * #1. search in arguments by parameter name
             * #1.1. search in arguments by class name
             * #2. if parameter has type hint
             * #2.1. search in container by class name
             * #3. if has default value, insert default value.
             * #4. exception
             */
            $paramName = $param->getName();

            try {
                if (array_key_exists($paramName, $arguments)) { // #1.
                    $parametersToReturn[] = $arguments[$paramName];

                    continue;
                }

                $paramClass = $param->getClass();

                if ($paramClass) { // #2.
                    $paramClassName = $paramClass->getName();

                    if (array_key_exists($paramClassName, $arguments)) {
                        $parametersToReturn[] = $arguments[$paramClassName];

                        continue;
                    } else { // #2.1.
                        try {
                            // TODO : on devrait pas créer une méthode make() qui soit un alias de get ? => https://github.com/illuminate/container/blob/master/Container.php#L616
                            // TODO : https://github.com/illuminate/container/blob/master/Container.php#L925
                            // TODO : ajouter des tests dans le cas ou la classe passée en parameter est optionnelle (cad avec une valeur par défaut), il faudrait aussi faire un test avec "?ClassObject" voir si on passe null par défaut ou si on léve une exception car la classe n'existe pas !!!! => https://github.com/illuminate/container/blob/master/Container.php#L935
                            $parametersToReturn[] = $this->container->get($paramClassName);

                            continue;
                        } catch (EntityNotFoundException $e) {
                        }
                    }
                }
                if ($param->isDefaultValueAvailable()) { // #3.
                    $parametersToReturn[] = $param->getDefaultValue();

                    continue;
                }

                throw new ContainerException("Parameter '{$paramName}' cannot be resolved"); // #4.
            } catch (ReflectionException $e) {
                // ReflectionException is thrown when the class doesn't exist.
                throw new ContainerException("Parameter '{$paramName}' cannot be resolved");
            }
        }

        return $parametersToReturn;
    }

    /**
     * @param array $array
     *
     * @return array
     */
    // TODO : essayer ce bout de code pour améliorer les choses : https://github.com/slince/di/blob/master/DefinitionResolver.php#L159
    protected static function getSeqArray(array $array): array
    {
        $arrayToReturn = [];
        foreach ($array as $key => $item) {
            if (is_int($key)) {
                $arrayToReturn[] = $item;
            }
        }

        return $arrayToReturn;
    }
}


<?php

namespace Monospice\SpicyIdentifiers\Tools;

use Monospice\SpicyIdentifiers\Tools\Interfaces;

/**
 * Formats an array of identifier parts into a string
 *
 * @author Cy Rossignol <cy.rossignol@yahoo.com>
 */
class Formatter implements Interfaces\Formatter
{

    // Inherit Doc from Interfaces\Formatter
    public static function format(array $parts, $format)
    {
        $formatFunction = 'format' . $format;

        return static::$formatFunction($parts);
    }

    // Inherit Doc from Interfaces\Formatter
    public static function formatUppercase(array $parts)
    {
        return strtoupper(implode('', $parts));
    }

    // Inherit Doc from Interfaces\Formatter
    public static function formatLowercase(array $parts)
    {
        return strtolower(implode('', $parts));
    }

    // Inherit Doc from Interfaces\Formatter
    public static function formatCamelCase(array $parts)
    {
        return lcfirst(
            implode('', array_map(function($p) {
                return static::ucfirstAndLower($p);
            }, $parts))
        );
    }

    // Inherit Doc from Interfaces\Formatter
    public static function formatUpperCamelCase(array $parts)
    {
        return implode('', array_map(function($p) {
            return static::ucfirstAndLower($p);
        }, $parts));
    }

    // Inherit Doc from Interfaces\Formatter
    public static function formatCamelCaseWithAcronyms(array $parts)
    {
        $camelCase = array_map(function($p) {
            return static::ucfirstAndLowerNonAcronym($p);
        }, $parts);

        if (static::isAcronym($camelCase[0])) {
            return implode('', $camelCase);
        }

        return lcfirst(implode('', $camelCase));
    }

    // Inherit Doc from Interfaces\Formatter
    public static function formatUpperCamelCaseWithAcronyms(array $parts)
    {
        return implode('', array_map(function($p) {
            return static::ucfirstAndLowerNonAcronym($p);
        }, $parts));
    }

    // Inherit Doc from Interfaces\Formatter
    public static function formatUnderscore(array $parts)
    {
        return implode('_', array_map('strtolower', $parts));
    }

    // Inherit Doc from Interfaces\Formatter
    public static function formatUpperUnderscore(array $parts)
    {
        return implode('_', array_map(function($p) {
            return static::ucfirstAndLower($p);
        }, $parts));
    }

    // Inherit Doc from Interfaces\Formatter
    public static function formatCapsUnderscore(array $parts)
    {
        return implode('_', array_map('strtoupper', $parts));
    }

    // Inherit Doc from Interfaces\Formatter
    public static function formatUnderscoreWithAcronyms(array $parts)
    {
        return implode('_', array_map(function($p) {
            return static::lowerNonAcronym($p);
        }, $parts));
    }

    // Inherit Doc from Interfaces\Formatter
    public static function formatUpperUnderscoreWithAcronyms(array $parts)
    {
        return implode('_', array_map(function($p) {
            return static::ucfirstAndLowerNonAcronym($p);
        }, $parts));
    }

    // Inherit Doc from Interfaces\Formatter
    public static function formatHyphen(array $parts)
    {
        return implode('-', array_map('strtolower', $parts));
    }

    // Inherit Doc from Interfaces\Formatter
    public static function formatUpperHyphen(array $parts)
    {
        return implode('-', array_map(function($p) {
            return static::ucfirstAndLower($p);
        }, $parts));
    }

    // Inherit Doc from Interfaces\Formatter
    public static function formatCapsHyphen(array $parts)
    {
        return implode('-', array_map('strtoupper', $parts));
    }

    // Inherit Doc from Interfaces\Formatter
    public static function formatHyphenWithAcronyms(array $parts)
    {
        return implode('-', array_map(function($p) {
            return static::lowerNonAcronym($p);
        }, $parts));
    }

    // Inherit Doc from Interfaces\Formatter
    public static function formatUpperHyphenWithAcronyms(array $parts)
    {
        return implode('-', array_map(function($p) {
            return static::ucfirstAndLowerNonAcronym($p);
        }, $parts));
    }

    /**
     * Determine if a string is an acronym (all caps)
     *
     * @param string $string The input string
     *
     * @return bool True if the string is all caps
     */
    protected static function isAcronym($string)
    {
        return strtoupper($string) === $string;
    }

    /**
     * Convert a string into a format with the first character capitalized and
     * the remaining characters lowercased
     *
     * @param string $string The input string
     *
     * @return string The converted string
     */
    protected static function ucfirstAndLower($string)
    {
        return ucfirst(strtolower($string));
    }

    /**
     * Convert a non-acronym (not all caps) string to lowercase
     *
     * @param string $string The input string
     *
     * @return string The converted string
     */
    protected static function lowerNonAcronym($string)
    {
        if (static::isAcronym($string)) {
            return $string;
        }

        return strtolower($string);
    }

    /**
     * Convert a non-acronym (not all caps) string to a lowercase string with
     * the first character uppercased
     *
     * @param string $string The input string
     *
     * @return string The converted string
     */
    protected static function ucfirstAndLowerNonAcronym($string)
    {
        if (static::isAcronym($string)) {
            return $string;
        }

        return static::ucfirstAndLower($string);
    }
}


<?php
namespace Nkey\Caribu\Mvc\Controller;

use \Generics\Socket\InvalidUrlException;

/**
 * The request is encapsulated in this class
 *
 * @author Maik Greubel <greubel@nkey.de>
 *
 *         This file is part of Caribu MVC package
 */
class Request
{
    use \Nkey\Caribu\Mvc\Util\RequestParser;

    /**
     * Address of remote host
     *
     * @var string
     */
    private $remoteHost;

    /**
     * Original request uri
     *
     * @var string
     */
    private $origin = null;

    /**
     * Controller requested
     *
     * @var string
     */
    private $controller = null;

    /**
     * Action requested
     *
     * @var string
     */
    private $action = null;

    /**
     * Parameters of the request
     *
     * @var array
     */
    private $params = array();

    /**
     * Prefix of the uri inside application context
     *
     * @var string
     */
    private $contextPrefix = null;

    /**
     * An occured exception
     *
     * @var \Exception
     */
    private $exception;

    /**
     * Create a new instance of request
     *
     * @param string $defaultController
     *            The name of default controller of nothing is provided
     * @param string $defaultAction
     *            The name of default action if nothing is provided
     */
    private function __construct($defaultController, $defaultAction)
    {
        $this->controller = $defaultController;
        $this->action = $defaultAction;
    }

    /**
     * Parse an uri into its request parts
     *
     * @param string $uri
     *            The uri to parse
     *
     * @param array $serverVars
     *            The variables provided by sapi
     *
     * @param string $defaultController
     *            The name of the default controller if nothing else is requested
     *
     * @param string $defaultAction
     *            The name of the default action if nothing else is requested
     *
     * @return \Nkey\Caribu\Mvc\Controller\Request The new created request
     */
    public static function parse($uri, $serverVars = array(), $defaultController = 'Index', $defaultAction = 'index')
    {
        $req = new self($defaultController, $defaultAction);
        $req->origin = $uri;

        self::parseRemoteHost($req, $serverVars);

        self::parseGetPostSessionCookie($req);

        // Save the request parameters for later usage and rewrite the uri
        $savedRequestParams = array();
        if (strpos($uri, '?')) {
            parse_str(substr($uri, strpos($uri, '?') + 1), $savedRequestParams);
            $uri = substr($uri, 0, strpos($uri, '?'));
        }

        self::parseContextPrefix($req, $serverVars);

        $parts = self::parseUri($req, $uri, $defaultController, $defaultAction);

        // Walk over all parameters and put them into container
        $numParts = count($parts);
        for ($i = 0; $i < $numParts; $i = $i + 2) {
            $paramName = trim($parts[$i]);
            $paramValue = isset($parts[$i + 1]) ? trim($parts[$i + 1]) : '';
            if ($paramName && $paramValue) {
                $req->params[$paramName] = $paramValue;
            }
        }

        $req->params = array_merge($req->params, $savedRequestParams);

        self::parseParameters($req, $serverVars);

        // Et'voila
        return $req;
    }

    /**
     * Parse uri directly from request uri
     *
     * @param array $serverVars
     *            The server variables provided by sapi
     * @param string $defaultController The
     *            name of the default controller
     * @param string $defaultAction The
     *            name of the default action
     *
     * @return \Nkey\Caribu\Mvc\Controller\Request
     *
     * @throws InvalidUrlException If no uri exists (e.g. sapi = cli)
     */
    public static function parseFromServerRequest($serverVars, $defaultController = 'Index', $defaultAction = 'index')
    {
        if (! isset($serverVars['REQUEST_URI'])) {
            throw new InvalidUrlException("No such uri provided");
        }
        return self::parse($serverVars['REQUEST_URI'], $serverVars, $defaultController, $defaultAction);
    }

    /**
     * The origin uri
     *
     * @return string The original request string
     */
    public function getOrigin()
    {
        return $this->origin;
    }

    /**
     * The requested controller
     *
     * @return string The controller
     */
    public function getController()
    {
        return $this->controller;
    }

    /**
     * Set controller property
     *
     * @param string $controller
     */
    public function setController($controller)
    {
    	$this->controller = strval($controller);
    }

    /**
     * The requested action
     *
     * @return string The action
     */
    public function getAction()
    {
        return $this->action;
    }

    /**
     * Set action property
     *
     * @param string $action
     */
    public function setAction($action)
    {
    	$this->action = $action;
    }

    /**
     * Retrieve the request parameters
     *
     * @return array The request parameters
     */
    public function getParams()
    {
        return $this->params;
    }

    /**
     * Retrieve the context prefix
     *
     * @return string The context prefix
     */
    public function getContextPrefix()
    {
        return $this->contextPrefix;
    }

    /**
     * Set context prefix property
     *
     * @param string $prefix
     */
    public function setContextPrefix($prefix)
    {
    	$this->contextPrefix = strval($prefix);
    }

    /**
     * Retrieve the remote host
     *
     * @return string The remote host address
     */
    public function getRemoteHost()
    {
        return $this->remoteHost;
    }

    /**
     * Check whether a given parameter exists
     *
     * @param string $name
     *            The name of the parameter
     * @return boolean true in case of it exists, false otherwise
     */
    public function hasParam($name)
    {
        return isset($this->params[$name]);
    }

    /**
     * Get value of particular parameter
     *
     * @param string $name
     *            The name of parameters
     * @param string $typeOf
     *            The type expected parameter value
     * @return mixed Depending on $typeOf the value as requested type and escaped
     */
    public function getParam($name, $typeOf = 'string')
    {
        $result = $this->hasParam($name) ? $this->params[$name] : null;

        switch ($typeOf) {
            case 'bool':
            case 'boolean':
                $result = function_exists('boolval') ? boolval($result) : (bool) $result;
                break;

            case 'double':
            case 'float':
                $result = doubleval($result);
                break;

            case 'int':
                $result = intval($result);
                break;

            case 'string':
            default:
                $result = htmlentities(strval($result));
                break;
        }

        return $result;
    }

    /**
     * To override a given parameter
     *
     * @param string $name
     *            The parameter name to override
     * @param string $value
     *            The value to override
     *
     * @return Request the current request as fluent interface
     */
    public function setParam($name, $value)
    {
        $this->params[$name] = $value;
        return $this;
    }

    /**
     * Set the exception occured
     *
     * @param \Exception $ex
     *
     * @return Request the current request instance
     */
    public function setException(\Exception $ex)
    {
        $this->exception = $ex;
        return $this;
    }

    /**
     * Get the exception occured
     *
     * @return \Exception
     */
    public function getException()
    {
        return $this->exception;
    }
}


<?php

/**
 * TechDivision\Import\Configuration\Jms\Configuration\ParamsTrait
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Open Software License (OSL 3.0)
 * that is available through the world-wide-web at this URL:
 * http://opensource.org/licenses/osl-3.0.php
 *
 * PHP version 5
 *
 * @author    Tim Wagner <t.wagner@techdivision.com>
 * @copyright 2016 TechDivision GmbH <info@techdivision.com>
 * @license   http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
 * @link      https://github.com/techdivision/import-configuration-jms
 * @link      http://www.techdivision.com
 */

namespace TechDivision\Import\Configuration\Jms\Configuration;

use JMS\Serializer\Annotation\Type;
use JMS\Serializer\Annotation\SerializedName;

/**
 * A trait implementation that provides parameter handling.
 *
 * @author    Tim Wagner <t.wagner@techdivision.com>
 * @copyright 2016 TechDivision GmbH <info@techdivision.com>
 * @license   http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
 * @link      https://github.com/techdivision/import-configuration-jms
 * @link      http://www.techdivision.com
 */
trait ParamsTrait
{

    /**
     * The array with the formatter's params.
     *
     * @var array
     * @Type("array")
     */
    protected $params = array();

    /**
     * The delimiter for the params that should be converted into an array.
     *
     * @var string
     * @Type("string")
     * @SerializedName("param-delimiter")
     */
    protected $paramDelimiter = ',';

    /**
     * Return's the parameter delimiter.
     *
     * @return string The delimiter
     */
    public function getParamDelimiter()
    {
        return $this->paramDelimiter;
    }

    /**
     * Return's the array with the params.
     *
     * @return array The params
     */
    public function getParams()
    {

        // initialize the array for the params
        $params = array();

        // prepare the params, e. g. explode them into an array
        if ($paramsAvailable = reset($this->params)) {
            foreach (array_keys($paramsAvailable) as $paramKey) {
                $params[$paramKey] = $this->getParam($paramKey);
            }
        }

        // return the params
        return $params;
    }

    /**
     * Query whether or not the param with the passed name exists.
     *
     * @param string $name The name of the param to be queried
     *
     * @return boolean TRUE if the requested param exists, else FALSE
     */
    public function hasParam($name)
    {
        return array_key_exists($name, $this->getParams());
    }

    /**
     * Return's the param with the passed name.
     *
     * @param string $name         The name of the param to return
     * @param mixed  $defaultValue The default value if the param doesn't exists
     *
     * @return string The requested param
     * @throws \Exception Is thrown, if the requested param is not available
     */
    public function getParam($name, $defaultValue = null)
    {

        // load the params
        $params = reset($this->params);

        // query whether or not, the param with the passed name is set
        if (is_array($params) && isset($params[$name])) {
            // load the value from the array
            $value = $params[$name];
            // query whether or not, the value contains a comma => if yes, we explode it into an array
            if (is_string($value) && stripos($value, $delimiter = $this->getParamDelimiter())) {
                $value = explode($delimiter, $value);
            }

            // return the found value
            return $value;
        }

        // if not, query we query if a default value has been passed
        if ($defaultValue != null) {
            return $defaultValue;
        }

        // throw an exception if neither the param exists or a default value has been passed
        throw new \Exception(sprintf('Requested param %s not available', $name));
    }
}


<?php
/**
 * This file is part of the PHP Generics package.
 *
 * @package Generics
 */
namespace Generics\Util;

/**
 * This utility class helps to generate a random string
 *
 * @author Maik Greubel <greubel@nkey.de>
 *
 */
class RandomString
{

    /**
     * ISO Characters
     *
     * @final
     *
     */
    const ISO = 1;

    /**
     * ASCII Characters
     *
     * @final
     *
     */
    const ASCII = 2;

    /**
     * Generate a random string with specific length
     *
     * @param number $length
     *            The length of string to generate
     * @param int $allowed
     *            Type of allowed characters
     * @param boolean $repeatable
     *            Whether a character may be reused
     *
     * @return string The generated string
     */
    public static function generate($length = 8, $allowed = RandomString::ASCII, $repeatable = true): string
    {
        $allowedChars = array();

        $currentLocale = setlocale(LC_ALL, "0");
        if ($allowed == RandomString::ASCII) {
            setlocale(LC_ALL, "C");
        }

        for ($i = 32; $i < 256; $i ++) {
            if (($allowed == RandomString::ASCII && ! ctype_alnum(chr($i))) || (! ctype_print(chr($i)))) {
                continue;
            }
            $allowedChars[] = $i;
        }

        self::resetLocaleTo($currentLocale);

        $used = array();

        $string = "";
        $i = $length;
        while ($i > 0) {
            $index = mt_rand(0, count($allowedChars) - 1);
            if (! $repeatable && in_array($index, $used)) {
                continue;
            }
            $string .= chr($allowedChars[$index]);
            $used[] = $i;
            $i --;
        }

        return $string;
    }

    /**
     * Reset the locale settings back to saved vars
     *
     * @param string $localeSaved
     *            String containing the locale infos obtained using setlocale(LC_ALL, '');
     */
    private static function resetLocaleTo($localeSaved)
    {
        $localeData = explode(';', $localeSaved);

        foreach ($localeData as $identifier) {
            if (! strchr($identifier, '=')) {
                continue;
            }
            $type = $value = null;
            sscanf($identifier, "%s=%s", $type, $value);
            switch ($type) {
                case 'LC_ALL':
                    setlocale(LC_ALL, $value);
                    break;

                case 'LC_COLLATE':
                    setlocale(LC_COLLATE, $value);
                    break;

                case 'LC_CTYPE':
                    setlocale(LC_CTYPE, $value);
                    break;

                case 'LC_MONETARY':
                    setlocale(LC_MONETARY, $value);
                    break;

                case 'LC_NUMERIC':
                    setlocale(LC_NUMERIC, $value);
                    break;

                case 'LC_TIME':
                    setlocale(LC_TIME, $value);
                    break;

                case 'LC_MESSAGES':
                    setlocale(LC_MESSAGES, $value);
                    break;

                default:
                    ;
                    break;
            }
        }
    }
}


<?php

/**
 * This file is part of the PHP Generics package.
 *
 * @package Generics
 */
namespace Generics\Client;

/**
 * This class provides session provider
 *
 * @author Maik Greubel <greubel@nkey.de>
 *
 */
class Session
{

    private $sessionId;

    /**
     * Session variable container
     * @var array
     */
    private $sessionContainer;

    /**
     * Create a new session provider
     */
    public function __construct(array &$container)
    {
        $this->sessionContainer = &$container;
    }

    /**
     * Create session
     */
    public function create()
    {
        session_start();
        $this->sessionId = session_id();
    }

    /**
     * Destroy session
     */
    public function destroy()
    {
        session_destroy();
    }

    /**
     * Add a new identifier with corresponding value to session storage
     *
     * @param string $key
     * @param string $value
     */
    public function put($key, $value)
    {
        $this->sessionContainer[$key] = $value;
    }

    /**
     * Retrieve value from session storage for corresponding key
     *
     * @param string $key
     * @return NULL|string
     */
    public function get($key)
    {
        if (! isset($this->sessionContainer[$key])) {
            return null;
        }

        return $this->sessionContainer[$key];
    }
}


<?php

/**
 * This file is part of the PHP Generics package.
 *
 * @package Generics
 */
namespace Generics\Socket;

use Generics\Streams\SocketStream;
use Generics\ResetException;
use Exception;

/**
 * This abstract class provides basic socket functionality
 *
 * @author Maik Greubel <greubel@nkey.de>
 */
abstract class Socket implements SocketStream
{

    /**
     * The socket handle
     *
     * @var resource
     */
    protected $handle;

    /**
     * The socket endpoint
     *
     * @var Endpoint
     */
    protected $endpoint;

    /**
     * Create a new socket
     *
     * @param Endpoint $endpoint
     *            The endpoint for the socket
     */
    public function __construct(Endpoint $endpoint)
    {
        $this->endpoint = $endpoint;
        $this->open();
    }

    /**
     * Opens a socket
     *
     * @throws SocketException
     */
    private function open()
    {
        $this->handle = @socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

        if (! is_resource($this->handle)) {
            $code = socket_last_error();
            throw new SocketException(socket_strerror($code), array(), $code);
        }
    }

    /**
     * Clean up
     */
    public function __destruct()
    {
        $this->close();
    }

    /**
     *
     * {@inheritdoc}
     * @see \Generics\Streams\Stream::close()
     */
    public function close()
    {
        if (is_resource($this->handle)) {
            socket_close($this->handle);
            $this->handle = null;
        }
    }

    /**
     *
     * {@inheritdoc}
     * @see \Generics\Streams\Stream::ready()
     */
    public function ready(): bool
    {
        if (! is_resource($this->handle)) {
            return false;
        }

        $read = array(
            $this->handle
        );
        $write = null;
        $except = null;

        $num = @socket_select($read, $write, $except, 0);

        if ($num === false) {
            $code = socket_last_error($this->handle);
            throw new SocketException(socket_strerror($code), array(), $code);
        }

        if ($num < 1) {
            return false;
        }

        if (! in_array($this->handle, $read)) {
            return false;
        }

        return true;
    }

    /**
     *
     * {@inheritdoc}
     * @see \Generics\Streams\OutputStream::isWriteable()
     */
    public function isWriteable(): bool
    {
        if (! is_resource($this->handle)) {
            return false;
        }

        $read = null;
        $write = array(
            $this->handle
        );
        $except = null;

        $num = @socket_select($read, $write, $except, 0, 0);

        if ($num === false) {
            $code = socket_last_error($this->handle);
            throw new SocketException(socket_strerror($code), array(), $code);
        }

        if ($num < 1) {
            return false;
        }

        if (! in_array($this->handle, $write)) {
            return false;
        }

        return true;
    }

    /**
     *
     * {@inheritdoc}
     * @see \Countable::count()
     */
    public function count()
    {
        throw new SocketException("Cannot count elements of socket");
    }

    /**
     *
     * {@inheritdoc}
     * @see \Generics\Streams\InputStream::read()
     */
    public function read($length = 1, $offset = null): string
    {
        if (($buf = @socket_read($this->handle, $length)) === false) {
            $buf = "";
            $code = socket_last_error();
            if ($code != 0) {
                if ($code != 10053) {
                    throw new SocketException(socket_strerror($code), array(), $code);
                } else {
                    $this->handle = null;
                }
            }
        }

        return $buf;
    }

    /**
     *
     * {@inheritdoc}
     * @see \Generics\Streams\OutputStream::write()
     */
    public function write($buffer)
    {
        if (($written = @socket_write($this->handle, "{$buffer}")) === false) {
            $code = socket_last_error();
            throw new SocketException(socket_strerror($code), array(), $code);
        }

        if ($written != strlen($buffer)) {
            throw new SocketException("Could not write all {bytes} bytes to socket ({written} written)", array(
                'bytes' => strlen($buffer),
                'written' => $written
            ));
        }
    }

    /**
     * Get the socket endpoint
     *
     * @return \Generics\Socket\Endpoint
     */
    public function getEndpoint(): Endpoint
    {
        return $this->endpoint;
    }

    /**
     *
     * {@inheritdoc}
     * @see \Generics\Streams\OutputStream::flush()
     */
    public function flush()
    {
        // There is no function to flush a socket. This is only possible for file descriptors.
    }

    /**
     *
     * {@inheritdoc}
     * @see \Generics\Streams\Stream::isOpen()
     */
    public function isOpen(): bool
    {
        return is_resource($this->handle);
    }

    /**
     *
     * {@inheritdoc}
     * @see \Generics\Resettable::reset()
     */
    public function reset()
    {
        try {
            $this->close();
            $this->open();
        } catch (Exception $ex) {
            throw new ResetException($ex->getMessage(), array(), $ex->getCode(), $ex);
        }
    }
}


<?php

namespace Zf2Forum\Model\Message;

use Zend\Stdlib\Hydrator\ClassMethods;
use Zf2Forum\Model\Message\MessageInterface;

class MessageHydrator extends ClassMethods
{
    /**
     * Extract values from an object
     *
     * @param  object $object
     * @return array
     * @throws Exception\InvalidArgumentException
     */
    public function extract($object)
    {
        if (!$object instanceof MessageInterface) {
            throw new Exception\InvalidArgumentException('$object must be an instance of Zf2Forum\Model\Message\MessageInterface');
        }
        $data = parent::extract($object);

        $thread = $object->getThread();
        $data['forum_topic_id'] = (int)$thread->getId();
        unset($data['topic']);
        $data['timestamp_created'] = $data['timestamp_created']->format('Y-m-d H:i:s');
        return $data;
    }

    /**
     * Hydrate $object with the provided $data.
     *
     * @param  array $data
     * @param  object $object
     * @return MessageInterface
     * @throws Exception\InvalidArgumentException
     */
    public function hydrate(array $data, $object)
    {
        if (!$object instanceof MessageEntityInterface) {
            throw new Exception\InvalidArgumentException('$object must be an instance of Zf2Forum\Model\Message\MessageInterface');
        }

        // example of mapping a field
        $data = $this->mapField('user_id', 'id', $data);

        return parent::hydrate($data, $object);
    }

    protected function mapField($keyFrom, $keyTo, array $array)
    {
        $array[$keyTo] = $array[$keyFrom];
        unset($array[$keyFrom]);
        return $array;
    }
}