<?php
namespace SGH\PdfBox;

/**
 * PDF converter implemention with PdfBox
 *
 * @author Fabian Schmengler <fschmengler@sgh-it.eu>
 * @copyright SGH informationstechnologie UGmbh 2011-2014
 * @category SGH
 * @package PdfBox
 *
 */
class PdfBox implements PdfConverter
{
    /**
     * @var string
     */
    protected $_pathToPdfBox = 'pdfbox-app-1.6.0.jar';
    /**
     * @var Options
     */
    protected $_options;
    /**
     * @var string
     */
    protected $_pdfFile;

    /* (non-PHPdoc)
     * @see SGH\PdfBox.PdfConverter::domFromPdfFile()
     */
    public function domFromPdfFile($filename, $saveToFile = null)
    {
        $dom = new \DOMDocument();
        $dom->loadHTML($this->htmlFromPdfFile($filename, $saveToFile));
        return $dom;
    }

    /* (non-PHPdoc)
     * @see SGH\PdfBox.PdfConverter::domFromPdfStream()
     */
    public function domFromPdfStream($content, $saveToFile = null)
    {
        $dom = new \DOMDocument();
        $dom->loadHTML($this->htmlFromPdfStream($content, $saveToFile));
        return $dom;
    }

    /* (non-PHPdoc)
     * @see SGH\PdfBox.PdfConverter::htmlFromPdfFile()
     */
    public function htmlFromPdfFile($filename, $saveToFile = null)
    {
        $command = $this->prepareCommand($filename, $saveToFile);
        $command->setAsHtml(true);
        return $this->execute($command);
    }

    /* (non-PHPdoc)
     * @see SGH\PdfBox.PdfConverter::htmlFromPdfStream()
     */
    public function htmlFromPdfStream($content, $saveToFile = null)
    {
        $temp = tempnam(sys_get_temp_dir(), 'pdfbox');
        file_put_contents($temp, $content);
        $command = $this->prepareCommand($temp, $saveToFile, true);
        $command->setAsHtml(true);
        return $this->execute($command);
    }

    /* (non-PHPdoc)
     * @see SGH\PdfBox.PdfConverter::textFromPdfFile()
     */
    public function textFromPdfFile($filename, $saveToFile = null)
    {
        $command = $this->prepareCommand($filename, $saveToFile);
        return $this->execute($command);
    }

    /* (non-PHPdoc)
     * @see SGH\PdfBox.PdfConverter::textFromPdfStream()
     */
    public function textFromPdfStream($content, $saveToFile = null)
    {
        $temp = tempnam(sys_get_temp_dir(), 'pdfbox');
        file_put_contents($temp, $content);
        $command = $this->prepareCommand($temp, $saveToFile, true);
        return $this->execute($command);
    }
    /**
     * Constructor
     */
    public function __construct()
    {
        $this->resetOptions();
    }
    /**
     * Reset advanced options to default values
     *
     * @return \SGH\PdfBox\PdfBox
     */
    public function resetOptions()
    {
        $this->_options = new Options();
        return $this;
    }
    /**
     * Factory method for Command object
     *
     * @param string $filename   Path to input file
     * @param string $saveToFile Path to output file or null if file should not be saved
     * @param bool   $pdfIsTemp  True if given PDF is a temporary file. Default: false
     * @return \SGH\PdfBox\Command
     */
    protected function prepareCommand($filename, $saveToFile, $pdfIsTemp = false)
    {
        $resultIsTemp = false;
        $command = new Command();
        $command->setPdfFile($filename, $pdfIsTemp);
        if ($saveToFile === null) {
            $saveToFile = tempnam(sys_get_temp_dir(), 'pdfbox');
            $resultIsTemp = true;
        }
        $command->setTextFile($saveToFile, $resultIsTemp);
        return $command;
    }
    /**
     * Execute given Command object.
     *
     * @param Command $command
     * @throws \RuntimeException If PdfBox returns error exit code
     * @return string            The converted text or HTML as string
     */
    protected function execute(Command $command)
    {
        $command->setJar($this->getPathToPdfBox());
        $command->setOptions($this->_options);
        exec((string) $command . ' 2>&1', $stdErr, $exitCode);
        if ($command->getPdfFileIsTemp()) {
            unlink($command->getPdfFile());
        }
        if ($exitCode > 0) {
            throw new \RuntimeException(join("\n", $stdErr), $exitCode);
        }
        $resultFile = $command->getTextFile();
        $result = file_get_contents($resultFile);
        if ($command->getTextFileIsTemp()) {
            unlink($resultFile);
        }
        return $result;
    }
    /**
     * Return configuration object
     *
     * @return \SGH\PdfBox\Options
     */
    public function getOptions()
    {
        return $this->_options;
    }
    /**
     * Return full path to PdfBox jar file
     *
     * @return string $_pathToPdfBox
     */
    public function getPathToPdfBox()
    {
        return $this->_pathToPdfBox;
    }

    /**
     * Set full path to PdfBox jar file
     *
     * @param string $_pathToPdfBox
     */
    public function setPathToPdfBox($_pathToPdfBox)
    {
        $this->_pathToPdfBox = $_pathToPdfBox;
    }

}


<?php
declare(strict_types=1);

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

namespace Ytake\PrestoClient;

use GuzzleHttp\Psr7\Uri;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Psr7\UriNormalizer;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Exception\RequestException;
use Fig\Http\Message\StatusCodeInterface;
use Fig\Http\Message\RequestMethodInterface;
use Psr\Http\Message\ResponseInterface;
use Ytake\PrestoClient\Exception\QueryErrorException;
use Ytake\PrestoClient\Exception\RequestFailedException;
use Ytake\PrestoClient\Session\Property;

/**
 * Class StatementClient
 *
 * @author Yuuki Takezawa <yuuki.takezawa@comnect.jp.net>
 */
class StatementClient
{
    const STATEMENT_URI = '/v1/statement';

    /** @var ClientInterface */
    private $client;

    /** @var ClientSession */
    private $session;

    /** @var QueryResult */
    protected $queryResult;

    /** @var array<string, string> */
    protected $headers = [];

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

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

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

    /** @var bool */
    private $valid = true;

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

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

    /** @var int */
    protected $nanoseconds = 5000000000;

    /**
     * PrestoClient constructor.
     *
     * @param ClientSession        $session
     * @param string               $query
     * @param ClientInterface|null $client
     */
    public function __construct(ClientSession $session, string $query, ClientInterface $client = null)
    {
        $this->session = $session;
        $this->query = $query;
        $this->client = (is_null($client)) ? new Client : $client;
        $this->queryResult = new QueryResult();
        $this->prepareRequest();
    }

    private function prepareRequest()
    {
        $this->headers = [
            PrestoHeaders::PRESTO_USER => $this->session->getUser(),
            'User-Agent'               => $this->session->getSource() . '/' . PrestoHeaders::VERSION,
        ];
    }

    /**
     * @param Request $request
     *
     * @return Request
     */
    protected function buildQueryRequest(Request $request): Request
    {
        $sessionTransaction = $this->session->getTransactionId();
        $transactionId = is_null($sessionTransaction) ? 'NONE' : $sessionTransaction->toString();
        $request = $request->withAddedHeader(PrestoHeaders::PRESTO_CATALOG, $this->session->getCatalog())
            ->withAddedHeader(PrestoHeaders::PRESTO_SCHEMA, $this->session->getSchema())
            ->withAddedHeader(PrestoHeaders::PRESTO_SOURCE, $this->session->getSource())
            ->withAddedHeader(PrestoHeaders::PRESTO_TRANSACTION_ID, $transactionId);
        $sessionProperty = $this->session->getProperty();
        if (count($sessionProperty)) {
            $sessions = [];
            /** @var Property $property */
            foreach ($sessionProperty as $property) {
                $sessions[] = $property->getKey() . '=' . $property->getValue();
            }
            $request = $request->withAddedHeader(
                PrestoHeaders::PRESTO_SESSION,
                implode(',', $sessions)
            );
        }
        $preparedStatements = $this->session->getPreparedStatement();
        if (count($preparedStatements)) {
            $statements = [];
            foreach ($preparedStatements as $preparedStatement) {
                $statements[] = urlencode($preparedStatement->getKey())
                    . '=' . urlencode($preparedStatement->getValue());
            }
            $request = $request->withAddedHeader(
                PrestoHeaders::PRESTO_PREPARED_STATEMENT,
                implode(',', $statements)
            );
        }

        return $request;
    }

    /**
     * @param int  $timeout
     * @param bool $debug
     *
     * @return void
     * @throws QueryErrorException
     */
    public function execute(int $timeout = 500000, bool $debug = false)
    {
        $normalize = UriNormalizer::normalize(
            new Uri($this->session->getHost() . StatementClient::STATEMENT_URI),
            UriNormalizer::REMOVE_DUPLICATE_SLASHES
        );
        $request = new Request(RequestMethodInterface::METHOD_POST, $normalize, $this->headers);
        try {
            $response = $this->client->send($this->buildQueryRequest($request), [
                'timeout' => $timeout,
                'body'    => $this->query,
                'debug'   => $debug,
            ]);
            if ($response->getStatusCode() === StatusCodeInterface::STATUS_OK) {
                $this->queryResult->set($response->getBody()->getContents());
            }
        } catch (ClientException $e) {
            throw new QueryErrorException($e->getMessage(), $e->getCode(), $e);
        }
    }

    /**
     * @return QueryResult
     * @throws QueryErrorException
     */
    public function current(): QueryResult
    {
        return $this->queryResult;
    }

    /**
     * @return bool
     */
    public function advance(): bool
    {
        $nextUri = $this->current()->getNextUri();
        if (is_null($nextUri) || $this->isClosed()) {
            $this->valid = false;

            return false;
        }
        $this->prepareRequest();

        return $this->detectResponse($nextUri);
    }

    /**
     * @param int  $timeout
     * @param bool $debug
     *
     * @return bool
     */
    public function cancelLeafStage(int $timeout = 500000, bool $debug = false): bool
    {
        if (!$this->isClosed()) {
            $cancelUri = $this->current()->getPartialCancelUri();
            if (is_null($cancelUri)) {
                return false;
            }
            $promise = $this->client->deleteAsync($cancelUri, [
                'timeout' => $timeout,
                'debug'   => $debug,
            ]);
            $promise->then(function (ResponseInterface $response) {
                $this->fulfilled = (StatusCodeInterface::STATUS_NO_CONTENT === $response->getStatusCode());
            }, function (RequestException $e) {
                throw new RequestFailedException($e->getMessage(), $e->getCode(), $e);
            });
            $promise->wait();
        }

        return $this->fulfilled;
    }

    /**
     * @param int $nanoseconds
     */
    public function setNanoseconds(int $nanoseconds)
    {
        $this->nanoseconds = $nanoseconds;
    }

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

    /**
     * @return bool
     */
    public function isFailed(): bool
    {
        return $this->queryResult->getError() !== null;
    }

    /**
     * @return bool
     */
    public function isValid(): bool
    {
        return $this->valid && (!$this->isGone()) && (!$this->isClosed());
    }

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

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

    /**
     * close
     * HTTP method DELETE
     */
    public function close()
    {
        $uri = $this->current()->getNextUri();
        if (!is_null($uri)) {
            $this->client->deleteAsync($uri)->wait();
        }
        $this->closed = true;
    }

    /**
     * @param string                 $message
     * @param string                 $uri
     * @param ResponseInterface|null $response
     *
     * @return RequestFailedException
     */
    private function requestFailedException(
        string $message,
        string $uri,
        ResponseInterface $response = null
    ): RequestFailedException {
        $this->gone = true;
        if ($response) {
            if (!$response->getBody()->getSize()) {
                return new RequestFailedException(
                    sprintf(
                        "Error %s at %s returned an invalid response: %s [Error: %s]",
                        $message,
                        $uri,
                        $response->getStatusCode(),
                        $response->getBody()->getContents()
                    )
                );
            }

            return new RequestFailedException(
                sprintf(
                    "Error %s at %s returned %s: %s",
                    $message,
                    $uri,
                    $response->getStatusCode(),
                    $response->getBody()->getContents()
                )
            );
        }

        return new RequestFailedException('server error.');
    }

    /**
     * @param string $nextUri
     *
     * @return bool
     */
    private function detectResponse(string $nextUri): bool
    {
        $start = microtime(true);
        $cause = null;
        $attempts = 0;
        do {
            if ($attempts > 0) {
                usleep($attempts * 100);
            }
            $attempts++;
            try {
                $response = $this->client->get($nextUri);
                if ($response->getStatusCode() === StatusCodeInterface::STATUS_OK) {
                    $this->queryResult->set($response->getBody()->getContents());

                    return true;
                }
            } catch (ClientException $e) {
                $cause = $e;
                if ($e->getCode() != StatusCodeInterface::STATUS_SERVICE_UNAVAILABLE) {
                    throw $this->requestFailedException("fetching next", $nextUri, $e->getResponse());
                }
            }
        } while (((microtime(true) - $start) < $this->nanoseconds) && !$this->isClosed());

        $this->gone = true;
        throw new \RuntimeException('Error fetching next', 0, $cause);
    }
}


<?php
/**
 * @link http://2amigos.us
 * @copyright Copyright (c) 2013 2amigOS! Consulting Group LLC
 * @license http://www.opensource.org/licenses/bsd-license.php New BSD License
 */
namespace dosamigos\resourcemanager;

use Aws\S3\Enum\CannedAcl;
use Aws\S3\S3Client;
use Guzzle\Http\Exception\ClientErrorResponseException;
use Guzzle\Service\Client;
use yii\base\Component;
use yii\base\InvalidConfigException;
use yii\helpers\ArrayHelper;
use Yii;

/**
 *
 * AmazonS3ResourceManager handles resources to upload/uploaded to Amazon AWS
 *
 * @author Antonio Ramirez <amigo.cobos@gmail.com>
 * @link http://www.ramirezcobos.com/
 * @link http://www.2amigos.us/
 */
class AmazonS3ResourceManager extends Component implements ResourceManagerInterface
{

	/**
	 * @var string Amazon access key
	 */
	public $key;
	/**
	 * @var string Amazon secret access key
	 */
	public $secret;
	/**
	 * @var string Amazon Bucket
	 */
	public $bucket;
	/**
	 * @var \Aws\S3\S3Client
	 */
	private $_client;

	/**
	 * @var boolean V4 signature
	 */
	public $enableV4=false;

	/**
	 * @inheritdoc
	 */
	public function init()
	{
		foreach (['key', 'secret', 'bucket'] as $attribute) {
			if ($this->$attribute === null) {
				throw new InvalidConfigException(strtr('"{class}::{attribute}" cannot be empty.', [
					'{class}' => static::className(),
					'{attribute}' => '$' . $attribute
				]));
			}
		}
		parent::init();
	}

	/**
	 * Saves a file
	 * @param \yii\web\UploadedFile $file the file uploaded. The [[UploadedFile::$tempName]] will be used as the source
	 * file.
	 * @param string $name the name of the file
	 * @param array $options extra options for the object to save on the bucket. For more information, please visit
	 * [[http://docs.aws.amazon.com/aws-sdk-php/latest/class-Aws.S3.S3Client.html#_putObject]]
	 * @return \Guzzle\Service\Resource\Model
	 */
	public function save($file, $name, $options = [])
	{
		$options = ArrayHelper::merge([
			'Bucket' => $this->bucket,
			'Key' => $name,
			'SourceFile' => $file->tempName,
			'ACL' => CannedAcl::PUBLIC_READ // default to ACL public read
		], $options);

		return $this->getClient()->putObject($options);
	}

	/**
	 * Removes a file
	 * @param string $name the name of the file to remove
	 * @return boolean
	 */
	public function delete($name)
	{
		$result = $this->getClient()->deleteObject([
			'Bucket' => $this->bucket,
			'Key' => $name
		]);

		return $result['DeleteMarker'];
	}

	/**
	 * Checks whether a file exists or not. This method only works for public resources, private resources will throw
	 * a 403 error exception.
	 * @param string $name the name of the file
	 * @return boolean
	 */
	public function fileExists($name)
	{
		$http = new \Guzzle\Http\Client();
		try {
			$response = $http->get($this->getUrl($name))->send();
		} catch(ClientErrorResponseException $e) {
			return false;
		}
		return $response->isSuccessful();
	}

	/**
	 * Returns the url of the file or empty string if the file does not exists.
	 * @param string $name the key name of the file to access
	 * @param mixed $expires The time at which the URL should expire
	 * @return string
	 */
	public function getUrl($name, $expires = NULL)
	{
		return $this->getClient()->getObjectUrl($this->bucket, $name, $expires);
	}

	/**
	 * Delete all objects that match a specific key prefix.
	 * @param string $prefix delete only objects under this key prefix
	 * @return type
	 */
	public function deleteMatchingObjects($prefix) {
		return $this->getClient()->deleteMatchingObjects($this->bucket, $prefix);
	}

	/**
	 * Return the full path a file names only (no directories) within s3 virtual "directory" by treating s3 keys as path names.
	 * @param string $directory the prefix of keys to find
	 * @return array of ['path' => string, 'name' => string, 'type' => string, 'size' => int]
	 */
	public function listFiles($directory) {
		$files = [];

		$iterator = $this->getClient()->getIterator('ListObjects', [
			'Bucket' => $this->bucket,
			'Prefix' => $directory,
		]);

		foreach ($iterator as $object) {
			// don't return directories
			if(substr($object['Key'], -1) != '/') {
				$file = [
					'path' => $object['Key'],
					'name' => substr($object['Key'], strrpos($object['Key'], '/' ) + 1),
					'type' => $object['StorageClass'],
					'size' => (int)$object['Size'],
				];
				$files[] = $file;
			}
		}

		return $files;
	}

	/**
	 * Returns a S3Client instance
	 * @return \Aws\S3\S3Client
	 */
	public function getClient()
	{
		if ($this->_client === null) {
			$settings=[
				'key' => $this->key,
				'secret' => $this->secret
			];
			if($this->enableV4)
				$settings['signature']='v4';

			$this->_client = S3Client::factory($settings);
		}
		return $this->_client;
	}
}


<?php
declare(strict_types=1);

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

namespace Ytake\PrestoClient;

/**
 * Class QueryResult
 *
 * @author Yuuki Takezawa <yuuki.takezawa@comnect.jp.net>
 */
final class QueryResult
{
    /** @var string */
    private $id;

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

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

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

    /** @var \stdClass[] */
    private $columns = [];

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

    /** @var StatementStats|null */
    private $stats;

    /** @var QueryError|null */
    private $error;

    /**
     * QueryResult constructor.
     *
     * @param string $content
     */
    public function set(string $content)
    {
        $parsed = $this->parseContent($content);
        $this->id = $parsed->id;
        $this->infoUri = $parsed->infoUri;
        $this->partialCancelUri = $parsed->partialCancelUri ?? null;
        $this->nextUri = $parsed->nextUri ?? null;
        $this->columns = [];
        if (isset($parsed->columns)) {
            $this->columnTransfer($parsed->columns);
        }
        $this->data = $parsed->data ?? [];
        $this->stats = isset($parsed->stats) ? $this->statsTransfer($parsed->stats) : null;
        $this->error = isset($parsed->error) ? $this->errorTransfer($parsed->error) : null;
    }

    /**
     * @return string|null
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @return string|null
     */
    public function getInfoUri()
    {
        return $this->infoUri;
    }

    /**
     * @return string|null
     */
    public function getNextUri()
    {
        return $this->nextUri;
    }

    /**
     * @return QueryError|null
     */
    public function getError()
    {
        return $this->error;
    }

    /**
     * @return string|null
     */
    public function getPartialCancelUri()
    {
        return $this->partialCancelUri;
    }

    /**
     * @return \Generator
     */
    public function yieldData(): \Generator
    {
        if (!count($this->data)) {
            yield;
        }
        $column = $this->getColumns();
        $columnCount = count($column);
        foreach ($this->data as $data) {
            $fixData = new FixData();
            for ($i = 0; $i < $columnCount; $i++) {
                $fixData->add($column[$i]->getName(), $data[$i]);
            }
            yield $fixData;
        }
    }

    /**
     * @return \Generator
     */
    public function yieldDataArray(): \Generator
    {
        if (!count($this->data)) {
            yield;
        }
        $columns = array_map(function (Column $item) {
            return $item->getName();
        }, $this->getColumns());
        foreach ($this->data as $data) {
            yield array_combine($columns, $data);
        }
    }

    /**
     * @param string $fetchClassName
     *
     * @return \Generator
     */
    public function yieldObject(string $fetchClassName)
    {
        if (!count($this->data)) {
            yield;
        }
        $column = $this->getColumns();
        $columnCount = count($column);
        foreach ($this->data as $data) {
            $reflectionClass = new \ReflectionClass($fetchClassName);
            $newInstance = $reflectionClass->newInstanceWithoutConstructor();
            for ($i = 0; $i < $columnCount; $i++) {
                if ($reflectionClass->hasProperty($column[$i]->getName())) {
                    $property = $reflectionClass->getProperty($column[$i]->getName());
                    $property->setAccessible(true);
                    $property->setValue($newInstance, $data[$i]);
                }
            }
            yield $newInstance;
        }
    }

    /**
     * @param string $content
     *
     * @return \stdClass
     */
    private function parseContent(string $content): \stdClass
    {
        $parsed = json_decode($content);
        if ($parsed === null && json_last_error() !== JSON_ERROR_NONE) {
            throw new \RuntimeException;
        }

        return $parsed;
    }

    /**
     * @param \stdClass $jsonContent
     *
     * @return StatementStats
     */
    private function statsTransfer(\stdClass $jsonContent): StatementStats
    {
        return new StatementStats($jsonContent);
    }

    /**
     * @param \stdClass $jsonContent
     *
     * @return QueryError
     */
    private function errorTransfer(\stdClass $jsonContent): QueryError
    {
        return new QueryError($jsonContent);
    }

    /**
     * @param array $columns
     */
    private function columnTransfer(array $columns)
    {
        foreach ($columns as $column) {
            $this->columns[] = new Column($column);
        }
    }

    /**
     * @return StatementStats|null
     */
    public function getStats()
    {
        return $this->stats;
    }

    /**
     * @return Column[]
     */
    public function getColumns(): array
    {
        return $this->columns;
    }
}


<?php

namespace RocketChatPhp;

use GuzzleHttp\Client as GuzzleClient;

class Client
{

    const HOOK_URI = '/hooks';

    /**
     * @var string The server to connect to.
     */
    private $server;

    /**
     * @var string The token for the webhook.
     */
    private $token;

    /**
     * Client constructor.
     * @param string $server
     * @param string $token
     */
    public function __construct($server, $token)
    {
        $this->server = $server;
        $this->token = $token;
    }

    /**
     * Sends a payload to the server.
     * @param array $payload
     */
    public function payload(array $payload)
    {
        $client = new GuzzleClient([
            'base_uri' => $this->server
        ]);
        $client->request('POST', $this->getUri(), [
            'form_params' => [
                'payload' => json_encode($payload)
            ]
        ]);
    }

    /**
     * Returns the webhook URI.
     * @return string
     */
    private function getUri()
    {
        return sprintf('%s/%s', self::HOOK_URI, $this->token);
    }
}


<?php
declare(strict_types=1);

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

namespace Ytake\PrestoClient;

use GuzzleHttp\Client;
use GuzzleHttp\Middleware;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\MessageFormatter;
use Psr\Log\LoggerInterface;

/**
 * Class LoggerClient
 *
 * @author Yuuki Takezawa <yuuki.takezawa@comnect.jp.net>
 */
class LoggerClient
{
    /** @var LoggerInterface */
    protected $logger;

    /** @var string */
    protected $template = '{date_common_log} {uri} {req_headers} {req_body} {res_headers}';

    /**
     * LoggerClient constructor.
     *
     * @param LoggerInterface $logger
     */
    public function __construct(LoggerInterface $logger)
    {
        $this->logger = $logger;
    }

    /**
     * @param callable|null $handler
     *
     * @return ClientInterface
     */
    public function client(callable $handler = null): ClientInterface
    {
        $handlerStack = HandlerStack::create($handler);
        $handlerStack->push(
            Middleware::log($this->logger, new MessageFormatter($this->template))
        );
        return new Client([
            'handler' => $handlerStack,
        ]);
    }

    /**
     * @codeCoverageIgnore
     * @param string $template
     */
    public function setTemplate(string $template)
    {
        $this->template = $template;
    }
}


<?php
/**
 * @link http://2amigos.us
 * @copyright Copyright (c) 2013 2amigOS! Consulting Group LLC
 * @license http://www.opensource.org/licenses/bsd-license.php New BSD License
 */
namespace dosamigos\resourcemanager;

use yii\helpers\ArrayHelper;
use yii\base\Component;
use Yii;

/**
 *
 * FileSystemResourceManager handles resource to upload/uploaded to a server folder.
 *
 * @author Antonio Ramirez <amigo.cobos@gmail.com>
 * @link http://www.ramirezcobos.com/
 * @link http://www.2amigos.us/
 */
class FileSystemResourceManager extends Component implements ResourceManagerInterface
{
	private $_basePath = '@webroot/uploads';
	private $_baseUrl = '@web/uploads';

	/**
	 * Saves a file
	 * @param \yii\web\UploadedFile $file the file uploaded
	 * @param string $name the name of the file. If empty, it will be set to the name of the uploaded file
	 * @param array $options to save the file. The options can be any of the following:
	 *  - `folder` : whether we should create a subfolder where to save the file
	 *  - `override` : whether we allow rewriting a existing file
	 * @return boolean
	 */
	public function save($file, $name, $options = [])
	{
		$name = ltrim($name, DIRECTORY_SEPARATOR);

		if ($folder = trim(ArrayHelper::getValue($options, 'folder'), DIRECTORY_SEPARATOR)) {
			$name = $folder . DIRECTORY_SEPARATOR . $name;
		}

		if (!ArrayHelper::getValue($options, 'override', true) && $this->fileExists($name)) {
			return false;
		}

		$path = $this->getBasePath() . DIRECTORY_SEPARATOR . $name;
		@mkdir(dirname($path), 0777, true);

		return $file->saveAs($path);
	}

	/**
	 * Removes a file
	 * @param string $name the name of the file to remove
	 * @return boolean
	 */
	public function delete($name)
	{
		return $this->fileExists($name) ? @unlink($this->getBasePath() . DIRECTORY_SEPARATOR . $name) : false;
	}

	/**
	 * Checks whether a file exists or not
	 * @param string $name the name of the file
	 * @return boolean
	 */
	public function fileExists($name)
	{
		return file_exists($this->getBasePath() . DIRECTORY_SEPARATOR . $name);
	}

	/**
	 * Returns the url of the file or empty string if the file doesn't exist.
	 * @param string $name the name of the file
	 * @return string
	 */
	public function getUrl($name)
	{
		return $this->getBaseUrl() . '/' . $name;
	}

	/**
	 * Returns the upload directory path
	 * @return string
	 */
	public function getBasePath()
	{
		return Yii::getAlias($this->_basePath);
	}

	/**
	 * Sets the upload directory path
	 * @param $value
	 */
	public function setBasePath($value)
	{
		$this->_basePath = rtrim($value, DIRECTORY_SEPARATOR);
	}

	/**
	 * Returns the base url
	 * @return string the url pointing to the directory where we saved the files
	 */
	public function getBaseUrl()
	{
		return Yii::getAlias($this->_baseUrl);
	}

	/**
	 * Sets the base url
	 * @param string $value the url pointing to the directory where to get the files
	 */
	public function setBaseUrl($value)
	{
		$this->_baseUrl = rtrim($value, '/');
	}
}


<?php

namespace RocketChatPhp;

class Attachment
{

    /**
     * @var array An array of fields.
     */
    private $fields;

    /**
     * @var string The fallback text, if attachment could not be displayed.
     */
    private $fallback;

    /**
     * @var string The color of the left bar in hex.
     */
    private $color;

    /**
     * Attachments constructor.
     * @param string $fallback
     * @param string $color
     */
    public function __construct($fallback, $color)
    {
        $this->fallback = $fallback;
        $this->color = $color;
    }

    /**
     * Add a field to the attachment list.
     * @param $title
     * @param $value
     * @param bool $short
     */
    public function addField($title, $value, $short = false)
    {
        $this->fields[] = [
            'title' => $title,
            'value' => $value,
            'short' => $short
        ];
    }

    /**
     * Return the array of data for the attachment.
     * @return array
     */
    public function toArray()
    {
        return [
            'fallback' => $this->fallback,
            'color' => $this->color,
            'fields' => $this->fields
        ];
    }

}


<?php
/**
 * A simple Object wrapper arround the semaphore functions
 */

namespace QXS\WorkerPool;

/**
 * Semaphore Class
 *
 * <code>
 * $t=new Semaphore();
 * $t->create(Semaphore::SEM_FTOK_KEY);
 * // acquire &&  release
 * $t->acquire();
 * echo "We are in the sem\n";
 * $t->release();
 * // acquire && release (aliases)
 * $t->synchronizedBegin();
 * echo "We are in the sem\n";
 * $t->synchronizedEnd();
 *
 * $t->destroy();
 * </code>
 */
class Semaphore {

	/** generate a random key */
	const SEM_RAND_KEY = 'rand';

	/** generate a key based on ftok */
	const SEM_FTOK_KEY = 'ftok';

	/** minimum semaphore int */
	const SEM_MIN_INT=-2147483647;

	/** maximum semaphore int */
	const SEM_MAX_INT=2147483647;

	/** @var resource the semaphore resource */
	protected $semaphore = NULL;

	/** @var int the key that is used to access the semaphore */
	protected $semKey = NULL;

	/**
	 * Returns the key, that can be used to access the semaphore
	 * @return int the key of the semaphore
	 */
	public function getSemaphoreKey() {
		return $this->semKey;
	}

	/**
	 * Create a semaphore
	 * @param string $semKey the key of the semaphore - use a specific number or Semaphore::SEM_RAND_KEY or Semaphore::SEM_FTOK_KEY
	 * @param int $maxAcquire the maximum number of processes, that can acquire the semaphore
	 * @param int $perms the unix permissions for (user,group,others) - valid range from 0 to 0777
	 * @throws SemaphoreException
	 * @return \QXS\WorkerPool\Semaphore the current object
	 */
	public function create($semKey = Semaphore::SEM_FTOK_KEY, $maxAcquire = 1, $perms=0666) {
		if (is_resource($this->semaphore)) {
			throw new SemaphoreException('Semaphore has already been created.');
		}

		if (!is_int($maxAcquire)) {
			$maxAcquire = 1;
		}
		$perms=(int)$perms;
		if ($perms < 0 || $perms > 0777) {
			$perms = 0666;
		}

		// randomly generate semaphore, without collision
		if ($semKey == Semaphore::SEM_RAND_KEY) {
			$retries = 5;
			mt_srand((int)(microtime(true)*10000));
		} else {
			$retries = 1;
		}
		// try to generate a semaphore
		while (!is_resource($this->semaphore) && $retries > 0) {
			$retries--;
			// generate a semKey
			if (!is_int($semKey)) {
				if ($semKey == Semaphore::SEM_RAND_KEY) {
					$this->semKey = mt_rand(Semaphore::SEM_MIN_INT, Semaphore::SEM_MAX_INT);
				} else {
					$this->semKey = ftok(__FILE__, 's');
				}
			} else {
				$this->semKey = $semKey;
			}
			// check the range
			if($this->semKey < Semaphore::SEM_MIN_INT || $this->semKey > Semaphore::SEM_MAX_INT) {
				$this->semKey = ftok(__FILE__, 's');
			}
			$this->semaphore = sem_get($this->semKey, $maxAcquire, $perms, 0);
		}
		if (!is_resource($this->semaphore)) {
			$this->semaphore = NULL;
			$this->semKey = NULL;
			throw new SemaphoreException('Cannot create the semaphore.');
		}

		return $this;
	}

	/**
	 * Acquire the semaphore
	 * @throws SemaphoreException in case of an error
	 * @return \QXS\WorkerPool\Semaphore the current object
	 */
	public function acquire() {
		if (!sem_acquire($this->semaphore)) {
			throw new SemaphoreException('Cannot acquire the semaphore.');
		}
		return $this;
	}

	/**
	 * Releases the semaphore
	 * @throws SemaphoreException in case of an error
	 * @return \QXS\WorkerPool\Semaphore the current object
	 */
	public function release() {
		if (!sem_release($this->semaphore)) {
			throw new SemaphoreException('Cannot release the semaphore.');
		}
		return $this;
	}

	/**
	 * Acquire the semaphore
	 * @throws SemaphoreException in case of an error
	 * @return \QXS\WorkerPool\Semaphore the current object
	 * @see \QXS\WorkerPool\Semaphore::acquire()
	 */
	public function synchronizedBegin() {
		return $this->acquire();
	}

	/**
	 * Releases the semaphore
	 * @throws SemaphoreException in case of an error
	 * @return \QXS\WorkerPool\Semaphore the current object
	 * @see \QXS\WorkerPool\Semaphore::release()
	 */
	public function synchronizedEnd() {
		return $this->release();
	}

	/**
	 * Run something synchronized
	 * @param \Closure $closure the closure, that should be run synchronized
	 * @throws SemaphoreException in case of an error
	 * @return \QXS\WorkerPool\Semaphore the current object
	 */
	public function synchronize(\Closure $closure) {
		$this->acquire();
		call_user_func($closure);
		$this->release();
		return $this;
	}

	/**
	 * Has the semaphore been created?
	 * @return bool true in case the semaphore has been created
	 */
	public function isCreated() {
		return is_resource($this->semaphore);
	}

	/**
	 * Destroys the semaphore
	 * @throws SemaphoreException in case of an error
	 * @return \QXS\WorkerPool\Semaphore the current object
	 */
	public function destroy() {
		if (!is_resource($this->semaphore)) {
			throw new SemaphoreException('Semaphore hasn\'t yet been created.');
		}
		if (!sem_remove($this->semaphore)) {
			throw new SemaphoreException('Cannot remove the semaphore.');
		}

		$this->semaphore = NULL;
		$this->semKey = NULL;
		return $this;
	}
}


<?php
require_once(__DIR__ . '/../autoload.php');

use QXS\WorkerPool\WorkerPool;
use QXS\WorkerPool\WorkerInterface;
use QXS\WorkerPool\Semaphore;

/**
 * The PI Worker
 */
class PiWorker implements WorkerInterface {
	/** @var int the number of steps */
	protected $num_steps;
	/** @var float the step */
	protected $step;

	/**
	 * The constructor
	 */
	public function __construct($num_steps, $step) {
		$this->num_steps = (int) $num_steps;
		$this->step = (string) $step;

	}

	/**
	 * After the worker has been forked into another process
	 *
	 * @param \QXS\WorkerPool\Semaphore $semaphore the semaphore to run synchronized tasks
	 * @throws \Exception in case of a processing Error an Exception will be thrown
	 */
	public function onProcessCreate(Semaphore $semaphore) { }

	/**
	 * Before the worker process is getting destroyed
	 *
	 * @throws \Exception in case of a processing Error an Exception will be thrown
	 */
	public function onProcessDestroy() { }

	/**
	 * run the work
	 *
	 * @param \Serializable $input the data, that the worker should process
	 * @return \Serializable Returns the result
	 * @throws \Exception in case of a processing Error an Exception will be thrown
	 */
	public function run($input) {
		list($part_number, $part_step) = $input;
		$sum='0';
		for ($i = $part_number; $i < $this->num_steps; $i += $part_step) {
			//$x = ($i + 0.5) * $this->step;
			//$sum += 4.0 / (1.0 + $x * $x);
			$x = bcmul(bcadd($i, '0.5'), $this->step);
			$sum = bcadd($sum, bcdiv('4.0', bcadd('1.0', bcmul($x, $x))));
		}
		return $sum;
	}

}

bcscale(100); // sets the scale
$num_steps = 1000000; // setps - sets the calculation detail
$part_step = 8; // parallelization degree set to number of cores

$step = bcdiv('1.0', (string)$num_steps);

$wp=new WorkerPool();
$wp->setWorkerPoolSize($part_step)
   ->create(new PiWorker($num_steps, $step));

for($i = 0; $i < $part_step; $i++) {
	$wp->run(array($i, $part_step));
}

$wp->waitForAllWorkers(); // wait for all workers

$sum='0';
foreach($wp as $result) {
	$sum=bcadd($sum, $result['data']);
}

$pi = bcmul($step, $sum);

echo "PI is $pi\n";


<?php
/**
 * The Process Details Collection
 */

namespace QXS\WorkerPool;

/**
 * The Process Details Collection Class
 */
class ProcessDetailsCollection implements \IteratorAggregate {

	/** @var ProcessDetails[] the details */
	public $processDetails = array();

	/** @var array the free process ids */
	protected $freeProcessIds = array();

	/** @var SimpleSocket[] all sockets */
	protected $sockets = array();

	/**
	 * Adds the ProcessDetails to the list and registers it as a free one.
	 *
	 * @param ProcessDetails $processDetails
	 * @return ProcessDetailsCollection
	 */
	public function addFree(ProcessDetails $processDetails) {
		$pid = $processDetails->getPid();
		$this->processDetails[$pid] = $processDetails;
		$this->sockets[$pid] = $processDetails->getSocket();
		$this->registerFreeProcess($processDetails);
		return $this;
	}

	/**
	 * Removes the ProcessDetails from the list.
	 *
	 * @param ProcessDetails $processDetails
	 * @throws \InvalidArgumentException
	 * @return ProcessDetailsCollection
	 */
	public function remove(ProcessDetails $processDetails) {
		$pid = $processDetails->getPid();

		if ($this->hasProcess($pid) === FALSE) {
			throw new \InvalidArgumentException(sprintf('Could not remove process. Process (%d) not in list.', $processDetails->getPid()), 1400761297);
		}

		if (isset($this->freeProcessIds[$pid])) {
			unset($this->freeProcessIds[$pid]);
		}

		if (isset($this->sockets[$pid])) {
			unset($this->sockets[$pid]);
		}

		unset($this->processDetails[$pid]);

		return $this;
	}

	/**
	 * Sends the kill signal to all processes and removes them from the list.
	 *
	 * @return void
	 */
	public function killAllProcesses() {
		foreach ($this->processDetails as $pid => $processDetails) {
			$this->remove($processDetails);
			posix_kill($pid, SIGKILL);
		}
	}

	/**
	 * Register a ProcessDetails as free
	 *
	 * @param ProcessDetails $processDetails
	 * @throws \InvalidArgumentException
	 * @return ProcessDetailsCollection
	 */
	public function registerFreeProcess(ProcessDetails $processDetails) {
		$pid = $processDetails->getPid();
		if ($this->hasProcess($pid) === FALSE) {
			throw new \InvalidArgumentException(sprintf('Could not register free process. Process (%d) not in list.', $processDetails->getPid()), 1400761296);
		}
		$this->freeProcessIds[$pid] = $pid;

		return $this;
	}

	/**
	 * Register the ProcessDetails with the given PID as free.
	 *
	 * @param int $pid
	 * @return ProcessDetailsCollection
	 */
	public function registerFreeProcessId($pid) {
		$processDetails = $this->getProcessDetails($pid);
		if ($processDetails !== NULL) {
			$this->registerFreeProcess($processDetails);
		}

		return $this;
	}

	/**
	 * Get all ProcessDetails by reference
	 *
	 * @return ProcessDetails[]
	 */
	public function &getAllProcesssDetails() {
		return $this->processDetails;
	}

	/**
	 * Takes one ProcessDetails from the list of free ProcessDetails. Returns NULL if no free process is available.
	 *
	 * @return ProcessDetails
	 */
	public function takeFreeProcess() {
		if ($this->getFreeProcessesCount() === 0) {
			return NULL;
		}
		$freePid = array_shift($this->freeProcessIds);
		if ($freePid === NULL) {
			return NULL;
		}
		return $this->getProcessDetails($freePid);
	}

	/**
	 * Checks if the ProcessDetails with given PID is in the list.
	 *
	 * @param int $pid
	 * @return bool
	 */
	public function hasProcess($pid) {
		return isset($this->processDetails[$pid]);
	}

	/**
	 * Get the count of free processes
	 *
	 * @return int
	 */
	public function getFreeProcessesCount() {
		return count($this->freeProcessIds);
	}

	/**
	 * Get the count of processes
	 *
	 * @return int
	 */
	public function getProcessesCount() {
		return count($this->processDetails);
	}

	/**
	 * Returns the associated sockets of all processes in the list.
	 *
	 * @return \QXS\WorkerPool\SimpleSocket[]
	 */
	public function &getSockets() {
		return $this->sockets;
	}

	/**
	 * Get a ProcessDetails of the given PID
	 *
	 * @param int $pid
	 * @return ProcessDetails
	 */
	public function getProcessDetails($pid) {
		if ($this->hasProcess($pid) === FALSE) {
			return NULL;
		}

		return $this->processDetails[$pid];
	}

	/**
	 * @inheritdoc
	 */
	public function getIterator() {
		return new \ArrayIterator($this->processDetails);
	}
}


<?php

namespace Todstoychev\CalendarEvents\Validator;

use Illuminate\Validation\Validator;

/**
 * Calendar events custom validation rules
 *
 * @package Todstoychev\CalendarEvents\Validator
 * @author Todor Todorov <todstoychev@gmail.com>
 */
class CalendarEventsValidator
{
    /**
     * Validate time
     *
     * @param string $attribute
     * @param string $value
     * @param array $parameters
     * @param Validator $validator
     *
     * @return bool
     */
    public function validateTime($attribute, $value, array $parameters, Validator $validator)
    {
        return (bool)preg_match('/([01]?[0-9]|2[0-3]):[0-5][0-9](:[0-5][0-9])?/', $value);
    }

    /**
     * Validate array of dates
     *
     * @param string $attribute
     * @param mixed $value
     * @param array $parameters
     * @param Validator $validator
     *
     * @return bool
     */
    public function validateDatesArray($attribute, $value, array $parameters, Validator $validator)
    {
        foreach ($value as $date) {
            if (false === strtotime($date) || empty($date)) {
                return false;
            }
        }

        return true;
    }
}


<?php namespace CanGelis\L4pdf;

use Response;
use View;
use File;

class PDF extends \CanGelis\PDF\PDF {

	/**
	 * Loads the Input Content from the view
	 *
	 * @param string $viewName
	 * @param array  $data
	 * @param array  $mergeData
	 *
	 * @return $this
	 */
	public function loadView($viewName, $data = array(), $mergeData = array())
	{
		$this->htmlContent = View::make($viewName, $data, $mergeData);

		return $this;
	}

	/**
	 * Get the PDF Content as an attachment
	 *
	 * @param string $as
	 *
	 * @return \Illuminate\Http\Response
	 */
	public function download($as = null)
	{
		return $this->createResponse()->header('Content-Disposition', 'attachment; ' . $this->getAs($as));
	}

	/**
	 * Display the PDF Document in the browser window
	 *
	 * @param string $as
	 *
	 * @return \Illuminate\Http\Response
	 */
	public function stream($as = null)
	{
		return $this->createResponse()->header('Content-Disposition', 'inline; ' . $this->getAs($as));
	}

	/**
	 * Creates a response object with proper Content-type for PDF Doc.
	 *
	 * @return \Illuminate\Http\Response
	 */
	protected function createResponse()
	{
		return Response::make($this->get(), 200)->header('Content-type', 'application/pdf');
	}

	/**
	 * Gets the attachment name for the Response
	 *
	 * @param string $as
	 *
	 * @return string
	 */
	protected function getAs($as = null)
	{
		if (!is_null($as))
		{
			return 'filename="' . $as . '"';
		}

		return "";
	}

}


<?php

namespace Krenor\LdapAuth\Objects;

use Illuminate\Contracts\Auth\Authenticatable as UserContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Krenor\LdapAuth\Contracts\UserInterface as LdapUserContract;
use Illuminate\Foundation\Auth\Access\Authorizable;

class LdapUser implements UserContract, AuthorizableContract, LdapUserContract
{

    use Authorizable;

    /**
     * Most of the ldap user's attributes.
     *
     * @var array
     */
    protected $attributes;

    /**
     * Build an LdapUser object from the LDAP entry
     *
     * @param array $entry
     *
     * @return void
     */
    public function build(array $entry)
    {
        $this->buildAttributesFromLdap($entry);
    }

    /**
     * Get the name of the unique identifier for the user.
     *
     * @return string
     */
    public function getAuthIdentifierName()
    {
        return 'samaccountname';
    }

    /**
     * Get the unique identifier for the user.
     *
     * @return mixed
     */
    public function getAuthIdentifier()
    {
        return $this->attributes[$this->getAuthIdentifierName()];
    }

    /**
     * Get the password for the user.
     *
     * @return string
     */
    public function getAuthPassword()
    {
        // this shouldn't be needed as you cannot directly access the password
    }

    /**
     * Get the column name for the "remember me" token.
     *
     * @return string
     */
    public function getRememberTokenName()
    {
        // this shouldn't be needed as user / password is in ldap
    }

    /**
     * Get the token value for the "remember me" session.
     *
     * @return string
     */
    public function getRememberToken()
    {
        // this shouldn't be needed as user / password is in ldap
    }

    /**
     * Set the token value for the "remember me" session.
     *
     * @param  string $value
     *
     * @return void
     */
    public function setRememberToken($value)
    {
        // this shouldn't be needed as user / password is in ldap
    }

    /**
     * Dynamically access the user's attributes.
     *
     * @param  string $key
     *
     * @return mixed
     */
    public function __get($key)
    {
        return $this->attributes[$key];
    }

    /**
     * Dynamically set an attribute on the user.
     *
     * @param  string $key
     * @param  mixed  $value
     *
     * @return void
     */
    public function __set($key, $value)
    {
        $this->attributes[$key] = $value;
    }

    /**
     * Dynamically check if a value is set on the user.
     *
     * @param  string $key
     *
     * @return bool
     */
    public function __isset($key)
    {
        return isset( $this->attributes[$key] );
    }

    /**
     * Setting of the LdapUser attributes
     *
     * @param array $entry
     */
    private function buildAttributesFromLdap($entry)
    {
        $this->attributes['dn']   = $entry['dn'];

        // Set the attributes accordingly to the search fields given
        foreach($entry as $index => $key){
            if(array_key_exists($index, config('ldap.search_fields'))){
                $this->attributes[$key] = isset($entry[$key][1]) ? $entry[$key] : $entry[$key][0];
            }
        };
    }

    /**
     * Check if the LdapUser is a member of requested group
     *
     * @param string $group
     *
     * @return bool
     */
    public function isMemberOf($group)
    {
        foreach ($this->attributes['member_of'] as $groups) {
            if (preg_match('/^CN=' . $group . '/', $groups)) {
                return true;
            }
        }

        return false;
    }

}


<?php
require_once(__DIR__ . '/../autoload.php');

use QXS\WorkerPool\WorkerPool;
use QXS\WorkerPool\WorkerInterface;
use QXS\WorkerPool\Semaphore;

/**
 * The PI Worker
 */
class PiWorker implements WorkerInterface {
	/** @var int the number of steps */
	protected $num_steps;
	/** @var float the step */
	protected $step;

	/**
	 * The constructor
	 */
	public function __construct($num_steps, $step) {
		$this->num_steps = (int) $num_steps;
		$this->step = (float) $step;

	}

	/**
	 * After the worker has been forked into another process
	 *
	 * @param \QXS\WorkerPool\Semaphore $semaphore the semaphore to run synchronized tasks
	 * @throws \Exception in case of a processing Error an Exception will be thrown
	 */
	public function onProcessCreate(Semaphore $semaphore) { }

	/**
	 * Before the worker process is getting destroyed
	 *
	 * @throws \Exception in case of a processing Error an Exception will be thrown
	 */
	public function onProcessDestroy() { }

	/**
	 * run the work
	 *
	 * @param \Serializable $input the data, that the worker should process
	 * @return \Serializable Returns the result
	 * @throws \Exception in case of a processing Error an Exception will be thrown
	 */
	public function run($input) {
		list($part_number, $part_step) = $input;
		$x=0.0;
		$sum=0.0;
		for ($i = $part_number; $i < $this->num_steps; $i += $part_step) {
			$x = ($i + 0.5) * $this->step;
			$sum += 4.0 / (1.0 + $x * $x);
		}
		return $sum;
	}

}

$num_steps = 1000000; // setps - sets the calculation detail
$part_step = 8; // parallelization degree set to number of cores

$step = 1.0 / $num_steps;

$wp=new WorkerPool();
$wp->setWorkerPoolSize($part_step)
   ->create(new PiWorker($num_steps, $step));

for($i = 0; $i < $part_step; $i++) {
	$wp->run(array($i, $part_step));
}

$wp->waitForAllWorkers(); // wait for all workers

$sum=0;
foreach($wp as $result) {
	$sum+=$result['data'];
}

$pi = $step * $sum;

echo "PI is $pi\n";


<?php
/*
 * This file is part of the ShortCode project.
 *
 * (c) Anis Uddin Ahmad <anis.programmer@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace ShortCode;

use ShortCode\Exception\InputIsTooLarge;
use ShortCode\Exception\UnexpectedCodeLength;

/**
 * Reversible
 *
 * Generate reversible codes from numbers and revert them to original number
 *
 * @author Anis Uddin Ahmad <anis.programmer@gmail.com>
 */
class Reversible extends Code
{

    /**
     * Get a code created from a number
     *
     * @param $input
     * @param string $outputFormat One of Code::FORMAT_* constants. Default Code::FORMAT_ALNUM
     * @param null $minLength
     *
     * @return string
     */
    public static function convert($input, $outputFormat = Code::FORMAT_ALNUM, $minLength = null)
    {
        if(is_int($minLength)) {
            $input += self::getMinForlength($outputFormat, $minLength);
        }

        static::throwUnlessAcceptable($outputFormat, $input);

        return self::convertBase($input, self::FORMAT_NUMBER, $outputFormat);
    }

    /**
     * Revert a code to it's original number
     *
     * @param $input
     * @param string $inputFormat
     * @param null $minLength
     *
     * @return int
     */
    public static function revert($input, $inputFormat = Code::FORMAT_ALNUM, $minLength = null)
    {
        $number = self::convertBase($input, $inputFormat, Code::FORMAT_NUMBER);

        if (is_int($minLength)) {
            $number -= self::getMinForlength($inputFormat, $minLength);
        }

        return $number;
    }

    private static function throwUnlessAcceptable($type, $input)
    {
        if(false !== strpos("$input", 'E+')) {
            throw new InputIsTooLarge("Input is too large to process.");
        }

        if($input < 0) {
            throw new UnexpectedCodeLength("Negative numbers are not acceptable for conversion.");
        }
    }

    /**
     * @param $outputFormat
     * @param $minLength
     *
     * @return int|string
     */
    private static function getMinForlength($outputFormat, $minLength)
    {
        $offset         = str_pad($outputFormat[1], $minLength, $outputFormat[0]);
        $offsetAsNumber = \ShortCode\Code::convertBase($offset, $outputFormat, \ShortCode\Code::FORMAT_NUMBER);
        return $offsetAsNumber;
    }

}


<?php

namespace Krenor\LdapAuth\Objects;

use Krenor\LdapAuth\Connections\LdapConnection;
use Krenor\LdapAuth\Contracts\ConnectionInterface;
use Krenor\LdapAuth\Exceptions\EmptySearchResultException;
use Krenor\LdapAuth\Exceptions\MissingConfigurationException;

class Ldap
{

    /**
     * The current LDAP Connection.
     *
     * @var LdapConnection
     */
    protected $ldap;

    /**
     * The account suffix for the domain.
     *
     * @var string
     */
    protected $suffix;

    /**
     * The base distinguished name for the domain.
     *
     * @var string
     */
    protected $base_dn;

    /**
     * The filter to execute a search query on.
     *
     * @var string
     */
    private $search_filter;

    /**
     * The fields to fetch from a search result.
     *
     * @var array
     */
    protected $search_fields = [ ];

    /**
     * User with permissions for preventing anonymous bindings.
     *
     * @var string
     */
    private $admin_user;

    /**
     * Password of the user with permissions for preventing anonymous bindings.
     *
     * @var string
     */
    private $admin_pass;

    /**
     * Tries to connect and bind to the LDAP
     *
     * @param array $options
     *
     * @throws MissingConfigurationException
     */
    public function __construct($options)
    {
        $config = $this->bindConfig($options);

        // Build Common Name from Config file and append to base DN
        $this->admin_user = 'CN=' . $this->admin_user . ',' . $this->base_dn;

        $this->ldap = new LdapConnection($config);
        $this->connect($this->ldap);
    }

    /**
     * Initializes the connecting parameters.
     * The actual connect happens with $this->ldap->bind()
     *
     * @param ConnectionInterface $connection
     *
     * @throws Exceptions\ConnectionException
     */
    protected function connect(ConnectionInterface $connection)
    {
        $this->ldap->connect();

        $this->ldap->option(LDAP_OPT_PROTOCOL_VERSION, $connection::VERSION);
        $this->ldap->option(LDAP_OPT_REFERRALS, $connection::REFERRALS);
        $this->ldap->option(LDAP_OPT_TIMELIMIT, $connection::TIMELIMIT);
        $this->ldap->option(LDAP_OPT_NETWORK_TIMEOUT, $connection::TIMELIMIT);

        // For debug purposes only.
        // $this->ldap->option(LDAP_OPT_DEBUG_LEVEL, 7);

        $this->ldap->bind($this->admin_user, $this->admin_pass);
    }

    /**
     * Execute a search query in the LDAP Base DN.
     *
     * @param string $identifier msdn.microsoft.com/En-US/library/aa746475.aspx
     * @param array  $fields     specific attributes to be returned
     *
     * @return array $entry
     * @throws EmptySearchResultException
     */
    public function find($identifier, array $fields = [ ])
    {
        // Get all result entries
        $results = $this->ldap->search(
            $this->base_dn,
            $this->search_filter . '=' . $identifier,
            ( $fields ?: $this->search_fields )
        );

        if (count($results) > 0) {
            $entry = $this->ldap->entry($results);

            // Returning a single LDAP entry
            if (isset( $entry[0] ) && ! empty( $entry[0] )) {
                return $entry[0];
            }
        }

        throw new EmptySearchResultException;
    }

    /**
     * Rebinds with a given DN and Password
     *
     * @param string $username
     * @param string $password
     *
     * @return bool
     *
     * @throws Exceptions\ConnectionException
     */
    public function auth($username, $password)
    {
        return $this->ldap->bind($username, $password);
    }

    /**
     * Bind configuration file to class properties
     * as long as these already exist
     *
     * @param array $config Complete config
     *
     * @return array $config Striped config
     */
    private function bindConfig(array $config)
    {
        foreach ($config as $key => $value) {
            if (property_exists($this, $key)) {
                $this->{$key} = $value;
                // Remove config key
                unset( $config[$key] );
            }
        }

        // Every non-property key is left over and returned
        return $config;
    }

}


<?php

namespace Todstoychev\CalendarEvents\Engine;

use Carbon\Carbon;
use Todstoychev\CalendarEvents\Exceptions\DateDifferenceException;
use Todstoychev\CalendarEvents\Exceptions\InvalidDateStringException;

/**
 * Calendar events engine. Calculates repeat dates and event length.
 *
 * @package Todstoychev\CalendarEvents\Engine
 * @author Todor Todorov <todstoychev@gmail.com>
 */
class CalendarEventsEngine
{
    /**
     * @var Carbon
     */
    protected $carbon;

    /**
     * CalendarEventsEngine constructor.
     *
     * @param Carbon $carbon
     */
    public function __construct(Carbon $carbon)
    {
        $this->carbon = $carbon;
    }

    /**
     * Builds event data
     *
     * @param array $data
     *
     * @return array
     */
    public function buildEventData(array $data)
    {
        $start = strtotime($data['start']['date'] . ' ' . $data['start']['time']);
        $start = date('Y-m-d H:i:s', $start);
        $end = null;

        if (array_key_exists('end', $data)) {
            $end = strtotime($data['end']['date'] . ' ' . $data['end']['time']);
            $end = date('Y-m-d H:i:s', $end);

            if (strtotime($end) < strtotime($start)) {
                throw new DateDifferenceException('Start date bigger then end date!');
            }
        }

        $event = [
            'title' => $data['title'],
            'description' => $data['description'],
            'start' => $start,
            'end' => $end,
            'all_day' => array_key_exists('all_day', $data),
            'border_color' => $data['border_color'],
            'background_color' => $data['background_color'],
            'text_color' => $data['text_color'],
        ];

        return $event;
    }

    /**
     * Builds event dates array
     *
     * @param array $data
     *
     * @return array
     */
    public function buildEventDates(array $data)
    {
        $dates = [];
        $eventLength = $this->calculateEventLength($data);
        $allDay = array_key_exists('all_day', $data);

        foreach ($data['repeat_dates'] as $date) {
            if (strlen($date) > 0) {
                $date = strtotime($date . ' ' . $data['start']['time']);

                if (false === $date) {
                    throw new InvalidDateStringException('Invalid date string!');
                }

                $eventStart = $this->carbon->copy()->setTimestamp($date);
                $eventEnds = $allDay ? null : $eventStart->copy()->addSeconds($eventLength);
                $dates[] = [
                    'start' => $eventStart->toDateTimeString(),
                    'end' => (null !== $eventEnds) ? $eventEnds->toDateTimeString() : null,
                ];
            }
        }

        return $dates;
    }

    /**
     * Creates JSON string from events collection
     *
     * @param array $calendarEvents
     *
     * @return array
     */
    public function formatEventsToJson(array $calendarEvents)
    {
        $array = [];

        foreach ($calendarEvents as $event) {
            $start = $this->carbon
                ->copy()
                ->setTimestamp(strtotime($event->start))
                ->toIso8601String();
            $end = $this->carbon
                ->copy()
                ->setTimestamp(strtotime($event->end))
                ->toIso8601String();
            $allDay = $event->all_day == 1;

            $data = [
                'title' => $event->title,
                'description' => $event->description,
                'start' => $start,
                'end' => $end,
                'allDay' => $allDay,
                'borderColor' => $event->border_color,
                'textColor' => $event->text_color,
                'backgroundColor' => $event->background_color,
            ];

            $array[] = $data;

            if ($event->calendarEventRepeatDates()->count() > 0) {
                foreach ($event->calendarEventRepeatDates()->get() as $repeatDate) {
                    $start = $this->carbon
                        ->copy()
                        ->setTimestamp(strtotime($repeatDate->start))
                        ->toIso8601String();
                    $end = $this->carbon
                        ->copy()
                        ->setTimestamp(strtotime($repeatDate->end))
                        ->toIso8601String();

                    $data['start'] = $start;
                    $data['end'] = $end;

                    $array[] = $data;
                }
            }
        }

        return $array;
    }

    /**
     * Calculate event length in seconds
     *
     * @param array $data
     *
     * @return int
     */
    protected function calculateEventLength(array $data)
    {
        $start = $this->carbon->copy()->setTimestamp(strtotime($data['start']['date'] . ' ' . $data['start']['time']));

        if (array_key_exists('all_day', $data)) {
            $end = $this->carbon->copy()->setTimestamp(strtotime($data['start']['date'] . ' 23:59:59'));
        } else {
            $end = $this->carbon->copy()->setTimestamp(strtotime($data['start']['date'] . ' ' . $data['end']['time']));
        }

        return $start->diffInSeconds($end);
    }
}


<?php
/**
 * Super Closure Worker Class
 */

namespace QXS\WorkerPool;

use DomainException;

/**
 * The Super Closure Worker Class
 */
class SuperClosureWorker implements WorkerInterface {

	/** @var \Closure Closure that runs the task */
	protected $create;

	/** @var \Closure Closure that will be used before a worker is getting destroyed */
	protected $destroy;

	/** @var \ArrayObject persistent storage container for the working process */
	protected $storage;

	/** @var \QXS\WorkerPool\Semaphore $semaphore the semaphore to run synchronized tasks */
	protected $semaphore;

	/**
	 * The constructor
	 * @param \Closure $create Closure that can be used when a worker has been forked
	 * @param \Closure $destroy Closure that can be used before a worker is getting destroyed
	 */
	public function __construct(\Closure $create = NULL, \Closure $destroy = NULL) {
		$this->storage = new \ArrayObject();
		if(is_null($create)) {
			$create=function($semaphore, $storage) { };
		}
		if(is_null($destroy)) {
			$destroy=function($semaphore, $storage) { };
		}
		$this->create = $create;
		$this->destroy = $destroy;
	}

	/**
	 * After the worker has been forked into another process
	 *
	 * @param \QXS\WorkerPool\Semaphore $semaphore the semaphore to run synchronized tasks
	 * @throws \Exception in case of a processing Error an Exception will be thrown
	 */
	public function onProcessCreate(Semaphore $semaphore) {
		$this->semaphore = $semaphore;
		$this->create->__invoke($this->semaphore, $this->storage);
	}

	/**
	 * Before the worker process is getting destroyed
	 *
	 * @throws \Exception in case of a processing Error an Exception will be thrown
	 */
	public function onProcessDestroy() {
		$this->destroy->__invoke($this->semaphore, $this->storage);
	}

	/**
	 * run the work
	 *
	 * @param \Serializable $input the data, that the worker should process
	 * @return \Serializable Returns the result
	 * @throws \Exception in case of a processing Error an Exception will be thrown
	 */
	public function run($input) {
		if(!($input instanceof SerializableWorkerClosure)) {
			throw new DomainException('No SerializableClosureWorker was specified');
		}

		$c = $input->getSerializableClosure();
		return $c($input->getInput(), $this->semaphore, $this->storage);
	}
}


<?php
/**
 * The Process Details
 */

namespace QXS\WorkerPool;

/**
 * The Process Details Class
 */
class ProcessDetails {

	/** @var int process id pid */
	protected $pid;

	/** @var SimpleSocket the socket */
	protected $socket;

	/**
	 * The constructor
	 * @param int $pid
	 * @param SimpleSocket $socket
	 */
	public function __construct($pid, SimpleSocket $socket) {
		$this->pid = $pid;
		$this->socket = $socket;
		$this->socket->annotation['pid'] = $pid;
	}

	/**
	 * Sanitizes the process title format string
	 * @param string $string the process title
	 * @return string the process sanitized title
	 * @throws \DomainException in case the $string value is not within the permitted range
	 */
	public static function sanitizeProcessTitleFormat($string) {
		$string = preg_replace(
			'/[^a-z0-9-_.:% \\\\\\]\\[]/i',
			'',
			$string
		);
		$string = trim($string);
		return $string;
	}

	/**
	 * Sets the proccess title
	 *
	 * This function call requires php5.5+ or the proctitle extension!
	 * Empty title strings won't be set.
	 * @param string $title the new process title
	 * @param array $replacements an associative array of replacment values
	 * @return void
	 */
	public static function setProcessTitle($title, array $replacements = array()) {
		// skip when empty title names or running on MacOS
		if (trim($title) == '' || PHP_OS == 'Darwin') {
			return;
		}
		// 1. replace the values
		$title = preg_replace_callback(
			'/\%([a-z0-9]+)\%/i',
			function ($match) use ($replacements) {
				if (isset($replacements[$match[1]])) {
					return $replacements[$match[1]];
				}
				return $match[0];
			},
			$title
		);
		// 2. remove forbidden chars
		$title = preg_replace(
			'/[^a-z0-9-_.: \\\\\\]\\[]/i',
			'',
			$title
		);
		// 3. set the title
		if (function_exists('cli_set_process_title')) {
			cli_set_process_title($title); // PHP 5.5+ has a builtin function
		} elseif (function_exists('setproctitle')) {
			setproctitle($title); // pecl proctitle extension
		}
	}

	/**
	 * Get the pid
	 * @return int
	 */
	public function getPid() {
		return $this->pid;
	}

	/**
	 * Get the socket
	 * @return \QXS\WorkerPool\SimpleSocket
	 */
	public function getSocket() {
		return $this->socket;
	}
}


<?php
/**
 * A simple object wrapper arround the socket functions
 */

namespace QXS\WorkerPool;

/**
 * Socket Class for IPC
 */
class SimpleSocket {

	/** @var resource the connection socket, that is used for IPC */
	protected $socket = NULL;
	/**
	 * This Variable can be used to attack custom information to the socket
	 * @var array of custom annotations
	 */
	public $annotation = array();

	/**
	 * The constructor
	 * @param resource $socket a valid socket resource
	 * @throws \InvalidArgumentException
	 */
	public function __construct($socket) {
		if (!is_resource($socket) && strtolower(@get_resource_type($socket)) != 'socket') {
			throw new \InvalidArgumentException('Socket resource is required!');
		}
		$this->socket = $socket;
	}

	/**
	 * The destructor
	 */
	public function __destruct() {
		socket_close($this->socket);
	}

	/**
	 * Selects active sockets with a timeout
	 * @param SimpleSocket[] $readSockets Array of \QXS\WorkerPool\SimpleSocket Objects, that should be monitored for read activity
	 * @param SimpleSocket[] $writeSockets Array of \QXS\WorkerPool\SimpleSocket Objects, that should be monitored for write activity
	 * @param SimpleSocket[] $exceptSockets Array of \QXS\WorkerPool\SimpleSocket Objects, that should be monitored for except activity
	 * @param int $sec seconds to wait until a timeout is reached
	 * @param int $usec microseconds to wait a timeout is reached
	 * @return array Associative Array of \QXS\WorkerPool\SimpleSocket Objects, that matched the monitoring, with the following keys 'read', 'write', 'except'
	 */
	public static function select(array $readSockets = array(), array $writeSockets = array(), array $exceptSockets = array(), $sec = 0, $usec = 0) {
		$out = array();
		$out['read'] = array();
		$out['write'] = array();
		$out['except'] = array();

		if(count($readSockets) === 0){
			return $out;
		}

		$readSocketsResources = array();
		$writeSocketsResources = array();
		$exceptSocketsResources = array();
		$readSockets = self::createSocketsIndex($readSockets, $readSocketsResources);
		$writeSockets = self::createSocketsIndex($writeSockets, $writeSocketsResources);
		$exceptSockets = self::createSocketsIndex($exceptSockets, $exceptSocketsResources);

		$socketsSelected = @socket_select($readSocketsResources, $writeSocketsResources, $exceptSocketsResources, $sec, $usec);
		if ($socketsSelected === FALSE) {
			$socketError = socket_last_error();
			// 1 more retry https://stackoverflow.com/questions/2933343/php-can-pcntl-alarm-and-socket-select-peacefully-exist-in-the-same-thread/2938156#2938156
			if ($socketError === SOCKET_EINTR) {
				socket_clear_error();

				$socketsSelected = socket_select($readSocketsResources, $writeSocketsResources, $exceptSocketsResources, $sec, $usec);
				if ($socketsSelected === FALSE) {
					return $out;
				}
			} else {
				trigger_error(
					sprintf('socket_select(): unable to select [%d]: %s', $socketError, socket_strerror($socketError)),
					E_USER_WARNING
				);
				return $out;
			}
		}

		foreach ($readSocketsResources as $socketResource) {
			$out['read'][] = $readSockets[intval($socketResource)];
		}
		foreach ($writeSocketsResources as $socketResource) {
			$out['write'][] = $writeSockets[intval($socketResource)];
		}
		foreach ($exceptSocketsResources as $socketResource) {
			$out['except'][] = $exceptSockets[intval($socketResource)];
		}

		return $out;
	}

	/**
	 * @param SimpleSocket[] $sockets
	 * @param array $socketsResources
	 * @return SimpleSocket[]
	 */
	protected static function createSocketsIndex($sockets, &$socketsResources) {
		$socketsIndex = array();
		foreach ($sockets as $socket) {
			if (!$socket instanceof SimpleSocket) {
				continue;
			}
			$resourceId = $socket->getResourceId();
			$socketsIndex[$resourceId] = $socket;
			$socketsResources[$resourceId] = $socket->getSocket();
		}

		return $socketsIndex;
	}

	/**
	 * Get the id of the socket resource
	 * @return int the id of the socket resource
	 */
	public function getResourceId() {
		return intval($this->socket);
	}

	/**
	 * Get the socket resource
	 * @return resource the socket resource
	 */
	public function getSocket() {
		return $this->socket;
	}

	/**
	 * Check if there is any data available
	 * @param int $sec seconds to wait until a timeout is reached
	 * @param int $usec microseconds to wait a timeout is reached
	 * @return bool true, in case there is data, that can be red
	 */
	public function hasData($sec = 0, $usec = 0) {
		$sec = (int)$sec;
		$usec = (int)$usec;
		if ($sec < 0) {
			$sec = 0;
		}
		if ($usec < 0) {
			$usec = 0;
		}

		$read = array($this->socket);
		$write = array();
		$except = array();
		$sockets = socket_select($read, $write, $except, $sec, $usec);

		if ($sockets === FALSE) {
			return FALSE;
		}
		return $sockets > 0;
	}

	/**
	 * Write the data to the socket in a predetermined format
	 * @param mixed $data the data, that should be sent
	 * @throws \QXS\WorkerPool\SimpleSocketException in case of an error
	 */
	public function send($data) {
		$serialized = serialize($data);
		$hdr = pack('N', strlen($serialized)); // 4 byte length
		$buffer = $hdr . $serialized;
		unset($serialized);
		unset($hdr);
		$total = strlen($buffer);
		while ($total > 0) {
			$sent = socket_write($this->socket, $buffer);
			if ($sent === FALSE) {
				throw new SimpleSocketException('Sending failed with: ' . socket_strerror(socket_last_error($this->socket)));
			}
			$total -= $sent;
			$buffer = substr($buffer, $sent);
		}
	}

	/**
	 * Read a data packet from the socket in a predetermined format.
	 * @throws \QXS\WorkerPool\SimpleSocketException in case of an error
	 * @return mixed the data, that has been received
	 */
	public function receive() {
		// read 4 byte length first
		$hdr = '';
		do {
			$read = socket_read($this->socket, 4 - strlen($hdr));
			if ($read === FALSE) {
				throw new SimpleSocketException('Reception failed with: ' . socket_strerror(socket_last_error($this->socket)));
			}
			elseif ($read === '' || $read === NULL) {
				return NULL;
			}
			$hdr .= $read;
		} while (strlen($hdr) < 4);

		list($len) = array_values(unpack("N", $hdr));

		// read the full buffer
		$buffer = '';
		do {
			$read = socket_read($this->socket, $len - strlen($buffer));
			if ($read === FALSE || $read == '') {
				throw new SimpleSocketException('Reception failed with: ' . socket_strerror(socket_last_error($this->socket)));
			}
			elseif ($read == '') {
				return NULL;
			}
			$buffer .= $read;
		} while (strlen($buffer) < $len);

		$data = unserialize($buffer);
		return $data;
	}
}


<?php
/**
 * Closure Worker Class
 */

namespace QXS\WorkerPool;

/**
 * The Closure Worker Class
 */
class ClosureWorker implements WorkerInterface {

	/** @var \Closure Closure that runs the task */
	protected $create;

	/** @var \Closure Closure that will be used when a worker has been forked */
	protected $run;

	/** @var \Closure Closure that will be used before a worker is getting destroyed */
	protected $destroy;

	/** @var \ArrayObject persistent storage container for the working process */
	protected $storage;

	/** @var \QXS\WorkerPool\Semaphore $semaphore the semaphore to run synchronized tasks */
	protected $semaphore;

	/**
	 * The constructor
	 * @param \Closure $run Closure that runs the task
	 * @param \Closure $create Closure that can be used when a worker has been forked
	 * @param \Closure $destroy Closure that can be used before a worker is getting destroyed
	 */
	public function __construct(\Closure $run, \Closure $create = NULL, \Closure $destroy = NULL) {
		$this->storage = new \ArrayObject();
		if(is_null($create)) {
			$create=function($semaphore, $storage) { };
		}
		if(is_null($destroy)) {
			$destroy=function($semaphore, $storage) { };
		}
		$this->create = $create;
		$this->run = $run;
		$this->destroy = $destroy;
	}

	/**
	 * After the worker has been forked into another process
	 *
	 * @param \QXS\WorkerPool\Semaphore $semaphore the semaphore to run synchronized tasks
	 * @throws \Exception in case of a processing Error an Exception will be thrown
	 */
	public function onProcessCreate(Semaphore $semaphore) {
		$this->semaphore = $semaphore;
		$this->create->__invoke($this->semaphore, $this->storage);
	}

	/**
	 * Before the worker process is getting destroyed
	 *
	 * @throws \Exception in case of a processing Error an Exception will be thrown
	 */
	public function onProcessDestroy() {
		$this->destroy->__invoke($this->semaphore, $this->storage);
	}

	/**
	 * run the work
	 *
	 * @param \Serializable $input the data, that the worker should process
	 * @return \Serializable Returns the result
	 * @throws \Exception in case of a processing Error an Exception will be thrown
	 */
	public function run($input) {
		return $this->run->__invoke($input, $this->semaphore, $this->storage);
	}
}


<?php
/**
 * A simple Object wrapper arround the semaphore functions
 */

namespace QXS\WorkerPool;

/**
 * No Semaphore Class
 *
 * Disables the semaphore! Just pass it to the Workerpool setSemaphore method before creating the pool.
 * Attention: You will lose the possibility to synchronize worker processes
 */
class NoSemaphore extends Semaphore {

	/**
	 * Returns the key, that can be used to access the semaphore
	 * @return int the key of the semaphore
	 */
	public function getSemaphoreKey() {
		return $this->semKey;
	}

	/**
	 * Create a semaphore
	 * @param string $semKey the key of the semaphore - use a specific number or Semaphore::SEM_RAND_KEY or Semaphore::SEM_FTOK_KEY
	 * @param int $maxAcquire the maximum number of processes, that can acquire the semaphore
	 * @param int $perms the unix permissions for (user,group,others) - valid range from 0 to 0777
	 * @throws SemaphoreException
	 * @return \QXS\WorkerPool\Semaphore the current object
	 */
	public function create($semKey = Semaphore::SEM_FTOK_KEY, $maxAcquire = 1, $perms=0666) {
		$this->semaphore = NULL;
		$this->semKey = 1;

		return $this;
	}

	/**
	 * Acquire the semaphore
	 * @throws SemaphoreException in case of an error
	 * @return \QXS\WorkerPool\Semaphore the current object
	 */
	public function acquire() {
		return $this;
	}

	/**
	 * Releases the semaphore
	 * @throws SemaphoreException in case of an error
	 * @return \QXS\WorkerPool\Semaphore the current object
	 */
	public function release() {
		return $this;
	}

	/**
	 * Has the semaphore been created?
	 * @return bool true in case the semaphore has been created
	 */
	public function isCreated() {
		return $this->semKey!==NULL;
	}

	/**
	 * Destroys the semaphore
	 * @throws SemaphoreException in case of an error
	 * @return \QXS\WorkerPool\Semaphore the current object
	 */
	public function destroy() {
		$this->semaphore = NULL;
		$this->semKey = NULL;
		return $this;
	}
}


<?php

namespace Todstoychev\CalendarEvents\Services;

use Illuminate\Support\Facades\Cache;
use Todstoychev\CalendarEvents\Engine\CalendarEventsEngine;
use Todstoychev\CalendarEvents\Models;
use Todstoychev\CalendarEvents\Models\EventLocation;

/**
 * Calendar events service
 *
 * @package Todstoychev\CalendarEvents\Services
 * @author Todor Todorov <todstoychev@gmail.com>
 */
class CalendarEventsService
{
    /**
     * @var CalendarEventsEngine
     */
    protected $calendarEventsEngine;

    /**
     * @var Models\CalendarEvent
     */
    protected $calendarEvent;

    /**
     * @var Models\CalendarEventRepeatDate
     */
    protected $calendarEventRepeatDate;

    /**
     * @var Cache
     */
    protected $cache;

    /**
     * Cache key
     */
    const CACHE_KEY = 'calendar_event_';

    /**
     * All calendar events cache key
     */
    const ALL_EVENTS_KEY = 'all_calendar_events';

    /**
     * All calendar events json string cache key
     */
    const ALL_EVENTS_TO_JSON_KEY = 'all_calendar_events_json';

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

    /**
     * @var Models\EventLocation
     */
    protected $eventLocation;

    /**
     * CalendarEventsService constructor.
     *
     * @param CalendarEventsEngine $calendarEventsEngine
     * @param Models\CalendarEvent $calendarEvent
     * @param Models\CalendarEventRepeatDate $calendarEventRepeatDate
     * @param Models\EventLocation $eventLocation
     * @param Cache $cache
     * @param int $cacheTimeToLive
     */
    public function __construct(
        CalendarEventsEngine $calendarEventsEngine,
        Models\CalendarEvent $calendarEvent,
        Models\CalendarEventRepeatDate $calendarEventRepeatDate,
        EventLocation $eventLocation,
        Cache $cache,
        $cacheTimeToLive = 10
    ) {
        $this->calendarEventsEngine = $calendarEventsEngine;
        $this->calendarEvent = $calendarEvent;
        $this->calendarEventRepeatDate = $calendarEventRepeatDate;
        $this->eventLocation = $eventLocation;
        $this->cache = $cache;
        $this->cacheTimeToLive = $cacheTimeToLive;
    }

    /**
     * @param int $cacheTimeToLive
     *
     * @return $this
     */
    public function setCacheTimeToLive($cacheTimeToLive)
    {
        $this->cacheTimeToLive = $cacheTimeToLive;

        return $this;
    }

    /**
     * Creates calendar event
     *
     * @param array $data
     *
     * @return bool
     */
    public function createCalendarEvent(array $data)
    {
        $eventData = $this->calendarEventsEngine->buildEventData($data);
        $eventDates = $this->calendarEventsEngine->buildEventDates($data);
        $cache = $this->cache;
        $calendarEvent = $this->calendarEvent->create($eventData);
        $this->handleEventLocation($data, $calendarEvent);

        foreach ($eventDates as $date) {
            $calendarEventRepeatDate = clone $this->calendarEventRepeatDate;
            $calendarEventRepeatDate->start = $date['start'];
            $calendarEventRepeatDate->end = $date['end'];
            $calendarEventRepeatDate->calendarEvent()
                                    ->associate($calendarEvent)
            ;
            $calendarEventRepeatDate->save();
            unset($calendarEventRepeatDate);
        }

        $cache::put(self::CACHE_KEY.$calendarEvent->id, $calendarEvent, $this->cacheTimeToLive);
        $allEvents = $this->getAllEvents();
        $allEvents[$calendarEvent->id] = $calendarEvent;
        $cache::put(self::ALL_EVENTS_KEY, $allEvents, $this->cacheTimeToLive);

        return true;
    }

    /**
     * Gets an calendar event based on id
     *
     * @param int $id
     *
     * @return Models\CalendarEvent
     */
    public function getCalendarEvent($id)
    {
        /** @var Models\CalendarEvent $calendarEvent */
        $calendarEvent = null;

        $cache = $this->cache;

        if ($cache::has(self::CACHE_KEY.$id)) {
            return $cache::get(self::CACHE_KEY.$id);
        }

        $calendarEvent = $this->calendarEvent
            ->with(['calendarEventRepeatDates'])
            ->where('id', $id)
            ->firstOrFail()
        ;

        $cache::put(self::CACHE_KEY.$id, $calendarEvent, $this->cacheTimeToLive);

        return $calendarEvent;
    }

    /**
     * Gets all calendar events
     *
     * @return \Illuminate\Database\Eloquent\Collection|null|static[]
     */
    public function getAllEvents(): array
    {
        $calendarEvents = null;
        $cache = $this->cache;

        if ($cache::has(self::ALL_EVENTS_KEY)) {
            return $cache::get(self::ALL_EVENTS_KEY);
        }

        $allEvents = $this->calendarEvent
            ->with(['calendarEventRepeatDates'])
            ->get()
        ;
        $calendarEvents = $allEvents->keyBy('id')
                                    ->toArray()
        ;

        $cache::put(self::ALL_EVENTS_KEY, $calendarEvents, $this->cacheTimeToLive);

        return $calendarEvents;
    }

    /**
     * Get all events JSON
     *
     * @return string
     */
    public function getAllEventsAsJson()
    {
        $cache = $this->cache;

        if ($cache::has(self::ALL_EVENTS_TO_JSON_KEY)) {
            return $cache::get(self::ALL_EVENTS_TO_JSON_KEY);
        }

        $allEvents = $this->calendarEventsEngine
            ->formatEventsToJson($this->getAllEvents());
        $allEventsToJson = json_encode($allEvents);
        $cache::put(self::ALL_EVENTS_TO_JSON_KEY, $allEventsToJson, $this->cacheTimeToLive);

        return $allEventsToJson;

    }

    /**
     * Deletes an calendar event and rebuilds the cache.
     *
     * @param int $id
     *
     * @return bool
     */
    public function deleteCalendarEvent($id)
    {
        $cache = $this->cache;

        $this->calendarEvent->destroy($id);

        $allEvents = $this->getAllEvents();
        unset($allEvents[$id]);
        $cache::put(self::ALL_EVENTS_KEY, $allEvents, $this->cacheTimeToLive);

        return true;
    }

    /**
     * Updates an calendar event
     *
     * @param int $id
     * @param array $data
     *
     * @return bool
     */
    public function updateCalendarEvent($id, array $data)
    {
        $eventData = $this->calendarEventsEngine->buildEventData($data);
        $eventDates = $this->calendarEventsEngine->buildEventDates($data);
        $cache = $this->cache;
        $calendarEventRepeatDate = clone $this->calendarEventRepeatDate;
        $calendarEventRepeatDate
            ->where('calendar_event_id', $id)
            ->delete()
        ;
        $this->calendarEvent
            ->where('id', $id)
            ->update($eventData)
        ;

        // This is necessary due to in some Laravel 5.1 versions there is no model hydration after update
        $calendarEvent = $this->calendarEvent
            ->where('id', $id)
            ->firstOrFail()
        ;
        $this->handleEventLocation($data, $calendarEvent);

        foreach ($eventDates as $date) {
            $calendarEventRepeatDate = clone $this->calendarEventRepeatDate;
            $calendarEventRepeatDate->start = $date['start'];
            $calendarEventRepeatDate->end = $date['end'];
            $calendarEventRepeatDate->calendarEvent()
                                    ->associate($calendarEvent)
            ;
            $calendarEventRepeatDate->save();
            unset($calendarEventRepeatDate);
        }

        $cache::put(self::CACHE_KEY.$calendarEvent->id, $calendarEvent, $this->cacheTimeToLive);
        $allEvents = $this->getAllEvents();
        $allEvents->put($calendarEvent->id, $calendarEvent);
        $cache::put(self::ALL_EVENTS_KEY, $allEvents, $this->cacheTimeToLive);

        return true;
    }

    /**
     * Handles EventLocation save/update
     *
     * @param array $data
     *
     * @param \Todstoychev\CalendarEvents\Models\CalendarEvent $calendarEvent
     *
     * @return null|\Todstoychev\CalendarEvents\Models\EventLocation
     */
    protected function handleEventLocation(array $data, Models\CalendarEvent $calendarEvent)
    {
        if (array_key_exists('longitude', $data) && !empty($data['longitude'])) {
            $this->eventLocation->longitude = $data['longitude'];
        }

        if (array_key_exists('latitude', $data) && !empty($data['latitude'])) {
            $this->eventLocation->latitude = $data['latitude'];
        }

        if (array_key_exists('address', $data) && !empty($data['address'])) {
            $this->eventLocation->address = $data['address'];
        }

        if (
            (!empty($this->eventLocation->longitude) && !empty($this->eventLocation->latitude)) ||
            !empty($this->eventLocation->address)
        ) {
            $this->eventLocation->calendarEvent()
                                ->associate($calendarEvent)
            ;
            $this->eventLocation->save();

            return $this->eventLocation;
        }

        return null;
    }
}


<?php
/*
 * This file is part of the ShortCode project.
 *
 * (c) Anis Uddin Ahmad <anis.programmer@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace ShortCode;

use ShortCode\Exception\UnexpectedCodeLength;

/**
 * Random
 *
 * Generate Random code string of desired length and format
 *
 * @author Anis Uddin Ahmad <anis.programmer@gmail.com>
 */
class Random extends Code
{

    /**
     * Get a random code of fixed length.
     *
     * @param int $length  length of code, default 8
     * @param string $outputFormat One of Code::FORMAT_* constants. Default Code::FORMAT_ALNUM
     *
     * @return string
     */
    public static function get($length = 8, $outputFormat = Code::FORMAT_ALNUM)
    {
        static::throwUnlessAcceptable($outputFormat, $length);

        $number = rand(100, 900) . str_replace('.', '', microtime(true));
        $output = self::convertBase($number, self::FORMAT_NUMBER, $outputFormat);

        if(strlen($output) < $length) {
            $output .= substr(str_shuffle($outputFormat.$outputFormat), 0, ($length - strlen($output)));
        }
        if(strlen($output) > $length) {
            $output = substr($output, 0, $length);
        }

        return $output;
    }

    private static function throwUnlessAcceptable($type, $length)
    {
        if($length > 20) {
            $typeName = self::getTypeName($type);
            throw new UnexpectedCodeLength("Code length $length is not acceptable for $typeName");
        }
    }

}


<?php namespace CanGelis\L4pdf;

use Illuminate\Support\ServiceProvider as IlluminateServiceProvider;
use Config;

class ServiceProvider extends IlluminateServiceProvider {

	/**
	 * Indicates if loading of the provider is deferred.
	 *
	 * @var bool
	 */
	protected $defer = false;

	/**
	 * Bootstrap the application events.
	 *
	 * @return void
	 */
	public function boot()
	{
		$this->package('cangelis/l4pdf');
	}

	/**
	 * Register the service provider.
	 *
	 * @return void
	 */
	public function register()
	{
		$this->app['pdf'] = $this->app->share(function($app)
		{
			return new PDF(Config::get('l4pdf::executable'), storage_path());
		});
	}

	/**
	 * Get the services provided by the provider.
	 *
	 * @return array
	 */
	public function provides()
	{
		return array('pdf');
	}

}


<?php

namespace Krenor\LdapAuth;

use Illuminate\Support\Facades\Auth;
use Illuminate\Support\ServiceProvider;
use Krenor\LdapAuth\Exceptions\MissingConfigurationException;
use Krenor\LdapAuth\Objects\Ldap;

class LdapAuthServiceProvider extends ServiceProvider
{

    /**
     * Indicates if loading of the provider is deferred.
     *
     * @var bool
     */
    protected $defer = false;

    /**
     * Perform post-registration booting of services.
     *
     * @return void
     */
    public function boot()
    {
        $config = __DIR__ . '/config/ldap.php';

        // Add publishable configuration
        $this->publishes([
            $config => config_path('ldap.php'),
        ], 'ldap');
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        // Register 'ldap' as authentication method
        Auth::provider('ldap', function ($app) {

            $model = $app['config']['auth']['providers']['ldap-users']['model'];

            // Create a new LDAP connection
            $connection = new Ldap($this->getLdapConfig());

            return new LdapAuthUserProvider($connection, $model);
        });
    }

    /**
     * Get the services provided by the provider.
     *
     * @return array
     */
    public function provides()
    {
        return [ 'auth' ];
    }

    /**
     * @return array
     *
     * @throws MissingConfigurationException
     */
    private function getLdapConfig()
    {
        if (is_array($this->app['config']['ldap'])) {
            return $this->app['config']['ldap'];
        }

        throw new MissingConfigurationException();
    }

}