<?php

namespace QCharts\ApiBundle\Controller;

use QCharts\ApiBundle\Exception\InvalidCredentialsException;
use QCharts\CoreBundle\Exception\InstanceNotFoundException;
use QCharts\CoreBundle\Exception\OverlappingException;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;

/**
 * Class FavoriteController
 * @package QCharts\ApiBundle\Controller
 */
class FavoriteController extends Controller
{

    /**
     * ApiDoc(
     *     description="Returns the favorite Query from the current user",
     *     statusCodes = {
     *          200 = "Returns the favorites from the current user"
     *     }
     * )
     * @return JsonResponse
     * @throws \QCharts\ApiBundle\Exception\InvalidCredentialsException
     */
    public function getFavoritesAction()
    {
        $roles = $this->getParameter("qcharts.user_roles");
        $authService = $this->get("security.authorization_checker");
        $favService = $this->get("qcharts.core.favorite_service");

        $options = [];

        try
        {
            ApiController::checkCredentials($authService, $roles, "user");

            $user = $this->getUser();
            $favorites = $favService->getFavourites($user);
            $options = [
                "status" => 200,
                "textStatus" => "favorites returned",
                "favorites" => $favorites,
                "count" => count($favorites)
            ];
        }
        catch (InvalidCredentialsException $e)
        {
            $options = [
                "status" => $e->getCode(),
                "textStatus" => $e->getMessage()
            ];
        }
        finally
        {
            return new JsonResponse($options);
        }

    }

    /**
     *
     * ApiDoc(
     *     description = "Adds the given Query as a favorite of the current user",
     *     parameters = {
     *          {
     *              "name" = "q",
     *              "required" = true,
     *              "dataType" = "integer",
     *              "description" = "The Id from the query request to favorite"
     *          }
     *     },
     *     statusCodes = {
     *          201 = "Description of the favorites returned",
     *          402 = "Invalid credentials",
     *          500 = "Error while attempting to add the favorite to the user",
     *          555 = "The given query is already in the same context"
     *
     *     }
     * )
     *
     * @param Request $request
     * @return JsonResponse
     * @throws \Exception
     */
    public function registerFavoriteAction(Request $request)
    {
        $roles = $this->getParameter("qcharts.user_roles");
        $authService = $this->get("security.authorization_checker");
        $favService = $this->get("qcharts.core.favorite_service");
        $queryService = $this->get("qcharts.query");

        $options = [];

        try
        {
            ApiController::checkCredentials($authService, $roles, ApiController::USER);

            $user = $this->getUser();
            $queryId = $request->request->get("q", null);
            // query request to add to favorite!
            $queryRequest = $queryService->getQueryRequestById($queryId);
            $favService->addFavourite($user, $queryRequest);
            $options = [
                "status" => 201,
                "textStatus" => "The query was added to the favorites"
            ];
        }
        catch (InvalidCredentialsException $e)
        {
            $options = [
                "status" => $e->getCode(),
                "textStatus" => "To add to favorites valid credentials are required. {$e->getMessage()}"
            ];
        }
        catch (InstanceNotFoundException $e)
        {
            $options = [
                "status" => $e->getCode(),
                "textStatus" => $e->getMessage()
            ];
        }
        catch (OverlappingException $e)
        {
            $options = [
                "status" => $e->getCode(),
                "textStatus" => $e->getMessage()
            ];
        }
        finally
        {
            return new JsonResponse($options);
        }
    }

    /**
     * ApiDoc(
     *     description = "Removes the given query request from the favorites list of the user",
     *     parameters = {
     *          {
     *              "name" = "q",
     *              "required" = true,
     *              "dataType" = "integer",
     *              "description" = "The query Id to remove from the user's list"
     *          }
     *     },
     *     statusCodes = {
     *          202 = "The query was removed from the user's favorite list",
     *          500 = "Error while attempting to remove the query form the user's favorite list"
     *     }
     * )
     * @param Request $request
     * @return JsonResponse
     */
    public function removeFavoriteAction(Request $request)
    {
        $roles = $this->getParameter("qcharts.user_roles");
        $authService = $this->get("security.authorization_checker");

        $options = [];

        try
        {
            ApiController::checkCredentials($authService, $roles, "user");
            $user = $this->getUser();
            $queryId = $request->request->get("q", null);
            $queryService = $this->get("qcharts.query");
            $favService = $this->get("qcharts.core.favorite_service");

            $queryRequest = $queryService->getQueryRequestById($queryId);
            $favService->removeFavourite($user, $queryRequest);

            $options = [
                "status" => 202,
                "textStatus" => "The favorite was removed from the user's list"
            ];

        }
        catch (InstanceNotFoundException $e)
        {
            $options = [
                "status" => $e->getCode(),
                "textStatus" => $e->getMessage()
            ];
        }
        finally
        {
            return new JsonResponse($options);
        }
    }

}


<?php

declare(strict_types=1);

namespace Psi\Bridge\ObjectAgent\Doctrine\Orm;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Persistence\Mapping\MappingException;
use Doctrine\Common\Util\ClassUtils;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\QueryBuilder;
use Psi\Component\ObjectAgent\AgentInterface;
use Psi\Component\ObjectAgent\Capabilities;
use Psi\Component\ObjectAgent\Exception\BadMethodCallException;
use Psi\Component\ObjectAgent\Exception\ObjectNotFoundException;
use Psi\Component\ObjectAgent\Query\Comparison;
use Psi\Component\ObjectAgent\Query\Query;

class OrmAgent implements AgentInterface
{
    /**
     * @var EntityManagerInterface
     */
    private $entityManager;

    /**
     * @var PsiToOrmQueryBuilderConverter
     */
    private $queryConverter;

    public function __construct(
        EntityManagerInterface $entityManager,
        PsiToOrmQueryBuilderConverter $queryConverter = null
    ) {
        $this->entityManager = $entityManager;
        $this->queryConverter = $queryConverter ?: new PsiToOrmQueryBuilderConverter($entityManager);
    }

    /**
     * {@inheritdoc}
     */
    public function getCapabilities(): Capabilities
    {
        return Capabilities::create([
            'can_query_join' => true,
            'can_query_select' => true,
            'can_set_parent' => false,
            'can_query_count' => true,
            'supported_comparators' => [
                Comparison::EQUALS,
                Comparison::NOT_EQUALS,
                Comparison::LESS_THAN,
                Comparison::LESS_THAN_EQUAL,
                Comparison::GREATER_THAN,
                Comparison::GREATER_THAN_EQUAL,
                Comparison::IN,
                Comparison::NOT_IN,
                Comparison::CONTAINS,
                Comparison::NOT_CONTAINS,
                Comparison::NULL,
                Comparison::NOT_NULL,
            ],
        ]);
    }

    /**
     * {@inheritdoc}
     */
    public function find($identifier, string $class = null)
    {
        if (null === $class) {
            throw BadMethodCallException::classArgumentIsMandatory(__CLASS__);
        }

        $object = $this->entityManager->find($class, $identifier);

        if (null === $object) {
            throw ObjectNotFoundException::forClassAndIdentifier($class, $identifier);
        }

        return $object;
    }

    /**
     * {@inheritdoc}
     */
    public function findMany(array $identifiers, string $class = null)
    {
        if (null === $class) {
            throw BadMethodCallException::classArgumentIsMandatory(__CLASS__);
        }

        $classMetadata = $this->entityManager->getMetadataFactory()->getMetadataFor($class);

        $idFields = $classMetadata->getIdentifier();

        if (count($idFields) > 1) {
            throw new \RuntimeException(sprintf(
                'Only objects with a single primary key are supported. Class: "%s", primary key fields: "%s"',
                $class, implode('", "', $idFields)
            ));
        }

        $idField = reset($idFields);

        $queryBuilder = $this->entityManager->getRepository($class)->createQueryBuilder('a');
        $queryBuilder->where($queryBuilder->expr()->in('a.' . $idField, ':identifiers'));
        $queryBuilder->setParameter('identifiers', $identifiers);

        return $queryBuilder->getQuery()->execute();
    }

    /**
     * {@inheritdoc}
     */
    public function persist($object)
    {
        $this->entityManager->persist($object);
    }

    /**
     * {@inheritdoc}
     */
    public function remove($object)
    {
        $this->entityManager->remove($object);
    }

    /**
     * {@inheritdoc}
     */
    public function flush()
    {
        $this->entityManager->flush();
    }

    /**
     * {@inheritdoc}
     */
    public function getIdentifier($object)
    {
        $objectFqn = ClassUtils::getRealClass(get_class($object));
        $metadata = $this->entityManager->getClassMetadata($objectFqn);
        $ids = $metadata->getIdentifierValues($object);

        if (count($ids) !== 1) {
            throw new \RuntimeException(sprintf(
                'Object agent does not support ORM objects with composite IDs (for class "%s")',
                $objectFqn
            ));
        }

        return reset($ids);
    }

    /**
     * {@inheritdoc}
     */
    public function getCanonicalClassFqn(string $classFqn): string
    {
        return ClassUtils::getRealClass($classFqn);
    }

    /**
     * {@inheritdoc}
     */
    public function setParent($object, $parent)
    {
        throw new \BadMethodCallException(
            'Doctrine ORM is not a hierarhical storage system, cannot set parent.'
        );
    }

    /**
     * {@inheritdoc}
     */
    public function supports(string $class): bool
    {
        $metadataFactory = $this->entityManager->getMetadataFactory();

        $supports = false;
        try {
            $metadataFactory->getMetadataFor(ClassUtils::getRealClass($class));
            $supports = true;
        } catch (MappingException $exception) {
            // no metadata - class is not known to the ORM
        }

        return $supports;
    }

    /**
     * {@inheritdoc}
     */
    public function query(Query $query): \Traversable
    {
        $queryBuilder = $this->getQueryBuilder($query);

        return new ArrayCollection(
            $queryBuilder->getQuery()->execute()
        );
    }

    public function queryCount(Query $query): int
    {
        $metadata = $this->entityManager->getMetadataFactory()->getMetadataFor(
            ClassUtils::getRealClass($query->getClassFqn())
        );

        $identifierFields = $metadata->getIdentifier();

        $idField = reset($identifierFields);

        $query = $query->cloneWith([
            'selects' => ['count(distinct ' . PsiToOrmQueryBuilderConverter::FROM_ALIAS . '.' . $idField . ')'],
            'firstResult' => null,
            'maxResults' => null,
        ]);

        $queryBuilder = $this->getQueryBuilder($query);
        $count = (int) $queryBuilder->getQuery()->getSingleScalarResult();

        return $count;
    }

    /**
     * Return the entity manager instance (for use in events).
     */
    public function getEntityManager(): EntityManagerInterface
    {
        return $this->entityManager;
    }

    private function getQueryBuilder(Query $query): QueryBuilder
    {
        return $this->queryConverter->convert($query);
    }
}


<?php
/**
 * Поле типа «integer» для MySQL
 *
 * @version ${product.version}
 *
 * @copyright 2013, Михаил Красильников <m.krasilnikov@yandex.ru>
 * @license http://www.gnu.org/licenses/gpl.txt	GPL License 3
 * @author Михаил Красильников <m.krasilnikov@yandex.ru>
 *
 * Данная программа является свободным программным обеспечением. Вы
 * вправе распространять ее и/или модифицировать в соответствии с
 * условиями версии 3 либо (по вашему выбору) с условиями более поздней
 * версии Стандартной Общественной Лицензии GNU, опубликованной Free
 * Software Foundation.
 *
 * Мы распространяем эту программу в надежде на то, что она будет вам
 * полезной, однако НЕ ПРЕДОСТАВЛЯЕМ НА НЕЕ НИКАКИХ ГАРАНТИЙ, в том
 * числе ГАРАНТИИ ТОВАРНОГО СОСТОЯНИЯ ПРИ ПРОДАЖЕ и ПРИГОДНОСТИ ДЛЯ
 * ИСПОЛЬЗОВАНИЯ В КОНКРЕТНЫХ ЦЕЛЯХ. Для получения более подробной
 * информации ознакомьтесь со Стандартной Общественной Лицензией GNU.
 *
 * Вы должны были получить копию Стандартной Общественной Лицензии
 * GNU с этой программой. Если Вы ее не получили, смотрите документ на
 * <http://www.gnu.org/licenses/>
 *
 * @package ORM
 */

/**
 * Поле типа «integer» для MySQL
 *
 * @package ORM
 * @since 3.00
 */
class ORM_Driver_MySQL_Integer extends ORM_Driver_SQL_Field
{
    /**
     * Возвращает выражение SQL для описания поля при создании таблицы
     *
     * @return string
     */
    public function getSqlFieldDefinition()
    {
        $sql = $this->field->getName() . ' INT';
        $length = $this->field->hasParam('length') ? $this->field->getParam('length') : 10;
        $sql .= '(' . $length . ')';
        if ($this->field->getParam('unsigned'))
        {
            $sql .= ' UNSIGNED';
        }
        if ($this->field->hasParam('autoincrement'))
        {
            $sql .= ' AUTO_INCREMENT';
        }
        return $sql;
    }
}


<?php

/*
 * This file is part of the Valkyrja framework.
 *
 * (c) Melech Mizrachi
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Valkyrja\Http;

use Valkyrja\Application;
use Valkyrja\Support\Providers\Provides;

/**
 * Class JsonResponse.
 *
 * @author Melech Mizrachi
 */
class NativeJsonResponse extends NativeResponse implements JsonResponse
{
    use Provides;

    /**
     * @constant
     *
     * Encode <, >, ', &, and " characters in the JSON, making it also safe to
     * be embedded into HTML.
     * 15 === JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT
     */
    public const DEFAULT_ENCODING_OPTIONS = 15;

    /**
     * Json data.
     *
     * @var string
     */
    protected $data;

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

    /**
     * Json encoding options.
     *
     * @var int
     */
    protected $encodingOptions = self::DEFAULT_ENCODING_OPTIONS;

    /**
     * JsonResponse constructor.
     *
     * @param string $content [optional] The response content, see setContent()
     * @param int    $status  [optional] The response status code
     * @param array  $headers [optional] An array of response headers
     * @param array  $data    [optional] An array of data
     *
     * @throws \InvalidArgumentException
     */
    public function __construct(
        string $content = '',
        int $status = StatusCode::OK,
        array $headers = [],
        array $data = []
    ) {
        parent::__construct($content, $status, $headers);

        // Set the json data
        $this->setData($data);
    }

    /**
     * Create a new json response.
     *
     * @param string $content [optional] The response content, see setContent()
     * @param int    $status  [optional] The response status code
     * @param array  $headers [optional] An array of response headers
     * @param array  $data    [optional] An array of data
     *
     * @throws \InvalidArgumentException
     *
     * @return \Valkyrja\Http\JsonResponse
     */
    public static function createJson(
        string $content = '',
        int $status = StatusCode::OK,
        array $headers = [],
        array $data = []
    ): JsonResponse {
        return new static($content, $status, $headers, $data);
    }

    /**
     * Sets the JSONP callback.
     *
     * @param string $callback [optional] The JSONP callback or null to use none
     *
     * @throws \InvalidArgumentException When the callback name is not valid
     *
     * @return \Valkyrja\Http\JsonResponse
     */
    public function setCallback(string $callback = null): JsonResponse
    {
        if (null !== $callback) {
            // taken from http://www.geekality.net/2011/08/03/valid-javascript-identifier/
            $pattern = '/^[$_\p{L}][$_\p{L}\p{Mn}\p{Mc}\p{Nd}\p{Pc}\x{200C}\x{200D}]*+$/u';
            $parts   = explode('.', $callback);

            foreach ($parts as $part) {
                if (! preg_match($pattern, $part)) {
                    throw new \InvalidArgumentException(
                        'The callback name is not valid.'
                    );
                }
            }
        }

        $this->callback = $callback;

        return $this->update();
    }

    /**
     * Sets a raw string containing a JSON document to be sent.
     *
     * @param string $json The json to set
     *
     * @throws \InvalidArgumentException
     *
     * @return \Valkyrja\Http\JsonResponse
     */
    public function setJson(string $json): JsonResponse
    {
        $this->data = $json;

        return $this->update();
    }

    /**
     * Sets the data to be sent as JSON.
     *
     * @param array $data [optional] The data to set
     *
     * @throws \InvalidArgumentException
     *
     * @return \Valkyrja\Http\JsonResponse
     */
    public function setData(array $data = []): JsonResponse
    {
        $content = json_encode($data, $this->encodingOptions);

        if (JSON_ERROR_NONE !== json_last_error()) {
            throw new \InvalidArgumentException(json_last_error_msg());
        }

        return $this->setJson($content);
    }

    /**
     * Returns options used while encoding data to JSON.
     *
     * @return int
     */
    public function getEncodingOptions(): int
    {
        return $this->encodingOptions;
    }

    /**
     * Sets options used while encoding data to JSON.
     *
     * @param int $encodingOptions The encoding options to set
     *
     * @throws \InvalidArgumentException
     *
     * @return \Valkyrja\Http\JsonResponse
     */
    public function setEncodingOptions(int $encodingOptions): JsonResponse
    {
        $this->encodingOptions = $encodingOptions;

        return $this->setData(json_decode($this->data));
    }

    /**
     * Updates the content and headers according to the JSON data and callback.
     *
     * @return \Valkyrja\Http\JsonResponse
     */
    protected function update(): JsonResponse
    {
        if (null !== $this->callback) {
            // Not using application/javascript for compatibility reasons with older browsers.
            $this->headers()->get('Content-Type', 'text/javascript');

            $this->setContent(
                sprintf('/**/%s(%s);', $this->callback, $this->data)
            );

            return $this;
        }

        // Only set the header when there is none or when it equals 'text/javascript' (from a previous update with callback)
        // in order to not overwrite a custom definition.
        if (
            ! $this->headers()->has('Content-Type')
            || 'text/javascript' === $this->headers()->get('Content-Type')
        ) {
            $this->headers()->set('Content-Type', 'application/json');
        }

        $this->setContent($this->data);

        return $this;
    }

    /**
     * The items provided by this provider.
     *
     * @return array
     */
    public static function provides(): array
    {
        return [
            JsonResponse::class,
        ];
    }

    /**
     * Publish the provider.
     *
     * @param Application $app The application
     *
     * @throws \InvalidArgumentException
     *
     * @return void
     */
    public static function publish(Application $app): void
    {
        $app->container()->singleton(
            JsonResponse::class,
            new static()
        );
    }
}


<?php

/**
 * MvcCore
 *
 * This source file is subject to the BSD 3 License
 * For the full copyright and license information, please view
 * the LICENSE.md file that are distributed with this source code.
 *
 * @copyright	Copyright (c) 2016 Tom Flídr (https://github.com/mvccore/mvccore)
 * @license		https://mvccore.github.io/docs/mvccore/4.0.0/LICENCE.md
 */

namespace MvcCore\Ext\Routers\MediaAndLocalization;

trait UrlByRoute
{
	/**
	 * Complete non-absolute, localized or non-localized URL with special media
	 * type prefix or without the prefix by route instance reverse info.
	 * If there is key `media_version` in `$params`, unset this param before
	 * route URL completing and choose by this param URL prefix to prepend
	 * completed URL string.
	 * If there is key `localization` in `$params`, unset this param before
	 * route url completing and place this param as url prefix to prepend
	 * completed url string and to prepend media site version prefix.
	 * Example:
	 *	Input (`\MvcCore\Route::$reverse`):
	 *		`"/products-list/<name>/<color>"`
	 *	Input ($params):
	 *		`array(
	 *			"name"			=> "cool-product-name",
	 *			"color"			=> "red",
	 *			"variant"		=> ["L", "XL"],
	 *			"media_version"	=> "mobile",
	 *			"localization"	=> "en-US",
	 *		);`
	 *	Output:
	 *		`/application/base-bath/m/en-US/products-list/cool-product-name/blue?variant[]=L&variant[]=XL"`
	 * @param \MvcCore\Route|\MvcCore\IRoute &$route
	 * @param array $params
	 * @param string $urlParamRouteName
	 * @return string
	 */
	public function UrlByRoute (\MvcCore\IRoute & $route, array & $params = [], $urlParamRouteName = NULL) {
		// get domain with base path url section,
		// path with query string url section
		// and system params for url prefixes
		list($urlBaseSection, $urlPathWithQuerySection, $systemParams) = $this->urlByRouteSections(
			$route, $params, $urlParamRouteName
		);

		// remove localization prefix for non localized routes or
		// remove localization prefix if url targets top homepage `/` on default language version
		$localizedRoute = $route instanceof \MvcCore\Ext\Routers\Localizations\Route;
		$localizationParamName = static::URL_PARAM_LOCALIZATION;
		$urlPathWithQueryIsHome = NULL;
		if (isset($systemParams[$localizationParamName])) {
			if (!$localizedRoute) {
				unset($systemParams[$localizationParamName]);
			} else {
				// Get `TRUE` if path with query string target homepage - `/` (or `/index.php` - request script name)
				$urlPathWithQueryIsHome = $this->urlIsHomePath($urlPathWithQuerySection);
				if (
					$urlPathWithQueryIsHome &&
					$systemParams[$localizationParamName] === $this->defaultLocalizationStr
				) {
					unset($systemParams[$localizationParamName]);
				}
			}
		}

		// create prefixed url
		return $this->urlByRoutePrefixSystemParams(
			$urlBaseSection, $urlPathWithQuerySection, $systemParams, $urlPathWithQueryIsHome
		);
	}
}


<?php
/**
 * This source file is part of Xloit project.
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the MIT License that is bundled with this package in the file LICENSE.
 * It is also available through the world-wide-web at this URL:
 * <http://www.opensource.org/licenses/mit-license.php>
 * If you did not receive a copy of the license and are unable to obtain it through the world-wide-web,
 * please send an email to <license@xloit.com> so we can send you a copy immediately.
 *
 * @license   MIT
 * @link      http://xloit.com
 * @copyright Copyright (c) 2016, Xloit. All rights reserved.
 */

namespace Xloit\Bridge\Zend\Session\SaveHandler\Database\Adapter;

use Closure;

/**
 * A {@link TableGateaway} class.
 *
 * @package Xloit\Bridge\Zend\Session\SaveHandler\Database\Adapter
 */
class TableGateaway extends AbstractAdapter
{
    /**
     * Select all entities.
     *
     * @return array
     */
    public function selectAll()
    {
        return $this->selectBy();
    }

    /**
     * Select entities by a set of criteria.
     *
     * @param Closure|string|array $criteria
     *
     * @return array
     */
    public function selectBy($criteria = null)
    {
        return $this->storageManager->select($criteria);
    }

    /**
     * Select entity by a set of criteria.
     *
     * @param Closure|string|array $criteria
     *
     * @return mixed
     */
    public function select($criteria)
    {
        return current($this->selectBy($criteria));
    }

    /**
     * Insert a new record.
     *
     * @param array $data
     *
     * @return mixed
     */
    public function insert($data)
    {
        return $this->storageManager->insert($data);
    }

    /**
     * Update a record.
     *
     * @param mixed $sessionEntity
     * @param array $data
     *
     * @return mixed
     */
    public function update($sessionEntity, $data)
    {
        return $this->storageManager->update(
            $data,
            [
                $this->options->getIdColumn()   => $this->getIdValue($sessionEntity),
                $this->options->getNameColumn() => $this->getNameValue($sessionEntity)
            ]
        );
    }

    /**
     * Returns the session id.
     *
     * @param mixed $sessionEntity
     *
     * @return string|int
     */
    public function getIdValue($sessionEntity)
    {
        return $sessionEntity->{$this->getOptions()->getIdColumn()};
    }

    /**
     * Returns the session name.
     *
     * @param mixed $sessionEntity
     *
     * @return string
     */
    public function getNameValue($sessionEntity)
    {
        return $sessionEntity->{$this->getOptions()->getNameColumn()};
    }

    /**
     * Garbage Collection - remove old session data older than $maxlifetime (in seconds).
     *
     * @param int $maxlifetime
     *
     * @return bool
     */
    public function gc($maxlifetime)
    {
        $sessions = $this->selectBy(
            sprintf(
                '%s < %d',
                $this->options->getModifiedColumn(),
                time() - $maxlifetime
            )
        );

        foreach ($sessions as $session) {
            $this->delete($session);
        }

        return true;
    }

    /**
     * Delete a record.
     *
     * @param mixed $sessionEntity
     *
     * @return mixed
     */
    public function delete($sessionEntity)
    {
        return (bool) $this->storageManager->delete(
            [
                $this->options->getIdColumn()   => $this->getIdValue($sessionEntity),
                $this->options->getNameColumn() => $this->getNameValue($sessionEntity)
            ]
        );
    }

    /**
     * Returns the session created Unix timestamp.
     *
     * @param mixed $sessionEntity
     *
     * @return int
     */
    public function getCreatedValue($sessionEntity)
    {
        return $sessionEntity->{$this->getOptions()->getCreatedColumn()};
    }

    /**
     * Returns the session data.
     *
     * @param mixed $sessionEntity
     *
     * @return string
     */
    public function getDataValue($sessionEntity)
    {
        return $sessionEntity->{$this->getOptions()->getDataColumn()};
    }

    /**
     * Returns the session lifetime.
     *
     * @param mixed $sessionEntity
     *
     * @return int
     */
    public function getLifetimeValue($sessionEntity)
    {
        return $sessionEntity->{$this->getOptions()->getLifetimeColumn()};
    }

    /**
     * Returns the session modified Unix timestamp.
     *
     * @param mixed $sessionEntity
     *
     * @return int
     */
    public function getModifiedValue($sessionEntity)
    {
        return $sessionEntity->{$this->getOptions()->getModifiedColumn()};
    }
}


<?php

/*
 * Plugin Manager for Yii2
 *
 * @link      https://github.com/hiqdev/yii2-pluginmanager
 * @package   yii2-pluginmanager
 * @license   BSD-3-Clause
 * @copyright Copyright (c) 2015, HiQDev (http://hiqdev.com/)
 */

namespace hiqdev\pluginmanager;

use hiqdev\php\collection\ArrayHelper;
use ReflectionClass;
use Yii;
use yii\base\BootstrapInterface;

/**
 * Plugin Manager.
 *
 * Usage, in config:
 * ~~~
 * 'pluginManager' => [
 *     'class' => 'hiqdev\pluginmanager\PluginManager',
 * ],
 * ~~~
 */
class PluginManager extends \hiqdev\yii2\collection\Object implements BootstrapInterface
{
    /**
     * @var int|bool the duration of caching in seconds, default 3600
     *               When false - caching is disabled.
     */
    public $cacheDuration = 3600;

    protected $_app;

    public function getApp()
    {
        return $this->_app;
    }

    /**
     * Adds given plugins. Doesn't delete old.
     */
    public function setPlugins(array $plugins)
    {
        $this->setItem('plugins', array_merge((array) $this->rawItem('plugins'), $plugins));
    }

    /**
     * @var bool is already bootstrapped.
     */
    protected $_isBootstrapped = false;

    /**
     * {@inheritdoc}
     */
    public function bootstrap($app)
    {
        if ($this->_isBootstrapped) {
            return;
        }
        $this->_isBootstrapped = true;
        $this->_app = $app;
        if ($this->cache) {
            Yii::trace('Bootstrap from cache', get_called_class() . '::bootstrap');
            $this->setItems($this->cache);
            // $this->toArray(); // TODO 2 SilverFire: check and remove this line
        } else {
            Yii::trace('Bootstrap plugins from the list of extensions', get_called_class() . '::bootstrap');
            foreach ($app->extensions as $name => $extension) {
                foreach ($extension['alias'] as $alias => $path) {
                    $class = strtr(substr($alias, 1) . '/' . 'Plugin', '/', '\\');
                    if (!class_exists($class)) {
                        continue;
                    }
                    $ref = new ReflectionClass($class);
                    if ($ref->isSubclassOf('hiqdev\pluginmanager\Plugin')) {
                        $plugin = Yii::createObject($class);
                        if ($plugin instanceof BootstrapInterface) {
                            $plugin->bootstrap($app);
                        }
                        //$this->setPlugins([$name => $plugin]);
                        $this->mergeItems($plugin->getItems());
                    }
                }
            }
            $this->saveCache($this->getItems());
        }
        if ($this->aliases) {
            $app->setAliases($this->aliases);
        }
        if ($this->modules) {
            $modules = ArrayHelper::getItems($app->modules, array_keys($this->modules));
            $this->modules = ArrayHelper::merge($this->modules, $modules);
            $app->setModules($this->modules);
        }
        if ($this->components) {
            $components = ArrayHelper::getItems($app->components, array_keys($this->components));
            $this->components = ArrayHelper::merge($this->components, $components);
            $app->setComponents($this->components);
        }
        if ($app->has('menuManager')) {
            $app->menuManager->bootstrap($app);
        }
        if ($app->has('themeManager')) {
            $app->themeManager->bootstrap($app);
        }
    }

    protected $_cache;

    public function getCache()
    {
        if ($this->_cache === null) {
            $this->_cache = $this->loadCache();
        }

        return $this->_cache;
    }

    /**
     * Loads items from the cache. The key is generated automatically using [[buildCacheKey()]].
     *
     * @return array
     *
     * @see buildCacheKey()
     */
    protected function loadCache()
    {
        if ($this->cacheDuration === false) {
            return [];
        }

        return $this->serializer->unpack($this->app->cache->get($this->buildCacheKey()));
    }

    /**
     * Saves the $value to the cache. The key is generated with [[buildCacheKey()]].
     *
     * @param $value mixed
     *
     * @return bool
     *
     * @see buildCacheKey()
     */
    protected function saveCache($value)
    {
        return $this->app->cache->set($this->buildCacheKey(), $this->serializer->pack($value), $this->cacheDuration);
    }

    protected $_serializer;

    public function getSerializer()
    {
        if ($this->_serializer === null) {
            $this->_serializer = new Serializer();
        }

        return $this->_serializer;
    }

    /**
     * @return array
     */
    protected function buildCacheKey()
    {
        return [
            'name'       => get_called_class(),
            'app'        => $this->app->className(),
            'lang'       => $this->app->language,
            'extensions' => $this->app->extensions,
        ];
    }
}


<?php

namespace Reaction\Run\Commands;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Helper\Table;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Process\PhpExecutableFinder;

/**
 * Trait ConfigPmTrait
 * @package Reaction\Run\Commands
 */
trait ConfigPmTrait
{

    protected $file = './pm.json';

    /**
     * Configure PM options
     * @param Command $command
     */
    protected function configurePMOptions(Command $command)
    {
        $iniMemLimit = ceil($this->getIniMemoryLimit() * 0.9);
        $command
            ->addOption('bridge', null, InputOption::VALUE_REQUIRED, 'Bridge for converting React Psr7 requests to target framework.', 'ReactionBridge')
            ->addOption('host', null, InputOption::VALUE_REQUIRED, 'Load-Balancer host. Default is 127.0.0.1', '127.0.0.1')
            ->addOption('port', null, InputOption::VALUE_REQUIRED, 'Load-Balancer port. Default is 8080', 8080)
            ->addOption('workers', null, InputOption::VALUE_REQUIRED, 'Worker count. Default is 8. Should be minimum equal to the number of CPU cores.', 8)
            ->addOption('app-env', null, InputOption::VALUE_REQUIRED, 'The environment that your application will use to bootstrap (if any)', 'dev')
            ->addOption('debug', null, InputOption::VALUE_REQUIRED, 'Enable/Disable debugging so that your application is more verbose, enables also hot-code reloading. 1|0', 0)
            ->addOption('logging', null, InputOption::VALUE_REQUIRED, 'Enable/Disable http logging to stdout. 1|0', 1)
            ->addOption('static-directory', null, InputOption::VALUE_REQUIRED, 'Static files root directory, if not provided static files will not be served', '')
            ->addOption('max-requests', null, InputOption::VALUE_REQUIRED, 'Max requests per worker until it will be restarted', 1000)
            ->addOption('ttl', null, InputOption::VALUE_REQUIRED, 'Time to live for a worker until it will be restarted', null)
            ->addOption('populate-server-var', null, InputOption::VALUE_REQUIRED, 'If a worker application uses $_SERVER var it needs to be populated by request data 1|0', 1)
            ->addOption('bootstrap', null, InputOption::VALUE_REQUIRED, 'Class responsible for bootstrapping the application', 'Reaction\PM\Bootstraps\ReactionBootstrap')
            ->addOption('cli-path', null, InputOption::VALUE_REQUIRED, 'Full path to the php-cli executable', false)
            ->addOption('socket-path', null, InputOption::VALUE_REQUIRED, 'Path to a folder where socket files will be placed. Relative to working-directory or cwd()', '.pm/run/')
            ->addOption('pidfile', null, InputOption::VALUE_REQUIRED, 'Path to a file where the pid of the master process is going to be stored', '.pm/pm.pid')
            ->addOption('reload-timeout', null, InputOption::VALUE_REQUIRED, 'The number of seconds to wait before force closing a worker during a reload, or -1 to disable. Default: 30', 30)
            ->addOption('max-memory-usage', null, InputOption::VALUE_REQUIRED, 'The number of slave memory usage in bytes until it will be restarted, or 0 to disable.', $iniMemLimit)
            ->addOption('config', 'c', InputOption::VALUE_REQUIRED, 'Path to config file', '');
    }

    /**
     * Get path of config file
     * @param InputInterface $input
     * @param bool $create
     * @return string
     * @throws \Exception
     */
    protected function getPmConfigPath(InputInterface $input, $create = false)
    {
        $configOption = $input->getOption('config');
        if ($configOption && !file_exists($configOption)) {
            if ($create) {
                file_put_contents($configOption, json_encode([]));
            } else {
                throw new \Exception(sprintf('Config file not found: "%s"', $configOption));
            }
        }
        $possiblePaths = [
            $configOption,
            $this->file,
            sprintf('%s/%s', dirname($GLOBALS['argv'][0]), $this->file)
        ];

        foreach ($possiblePaths as $path) {
            if (file_exists($path)) {
                return realpath($path);
            }
        }
        return '';
    }

    /**
     * Load config file content
     * @param InputInterface  $input
     * @param OutputInterface $output
     * @return array|mixed
     * @throws \Exception
     */
    protected function loadPmConfig(InputInterface $input, OutputInterface $output)
    {
        $config = [];

        if ($path = $this->getPmConfigPath($input)) {
            $content = file_get_contents($path);
            $config = json_decode($content, true);
        }

        $config['bridge'] = $this->optionOrConfigValue($input, $config, 'bridge');
        $config['host'] = $this->optionOrConfigValue($input, $config, 'host');
        $config['port'] = (int)$this->optionOrConfigValue($input, $config, 'port');
        $config['workers'] = (int)$this->optionOrConfigValue($input, $config, 'workers');
        $config['app-env'] = $this->optionOrConfigValue($input, $config, 'app-env');
        $config['debug'] = $this->optionOrConfigValue($input, $config, 'debug');
        $config['logging'] = $this->optionOrConfigValue($input, $config, 'logging');
        $config['static-directory'] = $this->optionOrConfigValue($input, $config, 'static-directory');
        $config['bootstrap'] = $this->optionOrConfigValue($input, $config, 'bootstrap');
        $config['max-requests'] = (int)$this->optionOrConfigValue($input, $config, 'max-requests');
        $config['ttl'] = (int)$this->optionOrConfigValue($input, $config, 'ttl');
        $config['populate-server-var'] = (boolean)$this->optionOrConfigValue($input, $config, 'populate-server-var');
        $config['socket-path'] = $this->optionOrConfigValue($input, $config, 'socket-path');
        $config['pidfile'] = $this->optionOrConfigValue($input, $config, 'pidfile');
        $config['reload-timeout'] = $this->optionOrConfigValue($input, $config, 'reload-timeout');
        $config['max-memory-usage'] = $this->optionOrConfigValue($input, $config, 'max-memory-usage');

        $config['cli-path'] = $this->optionOrConfigValue($input, $config, 'cli-path');

        if (false === $config['cli-path']) {
            //not set in config nor in command options -> autodetect path
            $executableFinder = new PhpExecutableFinder();
            $binary = $executableFinder->find();
            $config['cli-path'] = $binary;

            if (false === $config['cli-path']) {
                $output->writeln('<error>PPM could find a php-cli path. Please specify by --cli-path=</error>');
                exit(1);
            }
        }

        return $config;
    }

    /**
     * Init config.
     * Locate file, load it and check values
     * @param InputInterface  $input
     * @param OutputInterface $output
     * @param bool            $render
     * @return array
     */
    protected function initializePmConfig(InputInterface $input, OutputInterface $output, $render = true)
    {
        if ($workingDir = $input->getArgument('working-directory')) {
            chdir($workingDir);
        }
        $config = $this->loadPmConfig($input, $output);

        if ($path = $this->getPmConfigPath($input)) {
            $modified = '';
            $fileConfig = json_decode(file_get_contents($path), true);
            if (json_encode($fileConfig) !== json_encode($config)) {
                $modified = ', modified by command arguments';
            }
            $output->writeln(sprintf('<info>Read configuration %s%s.</info>', $path, $modified));
        }
        $output->writeln(sprintf('<info>%s</info>', getcwd()));

        if ($render) {
            $this->renderConfig($output, $config);
        }
        return $config;
    }

    /**
     * Get memory_limit directive in bytes
     * @return int
     */
    private function getIniMemoryLimit()
    {
        $iniMemLimit = ini_get('memory_limit');
        if (!is_numeric($iniMemLimit)) {
            $iniSuffix = strtoupper(substr($iniMemLimit, -1));
            $iniMemLimit = substr($iniMemLimit, 0, -1);
            $iniMultiplier = 1024; //K
            $iniMultiplier = $iniSuffix === 'M' ? $iniMultiplier * 1024 : $iniMultiplier * 1024 * 1024; //M || G
            $iniMemLimit *= $iniMultiplier;
        }
        return (int)$iniMemLimit;
    }
}


<?php

/*
 *	Copyright 2015 RhubarbPHP
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

namespace Rhubarb\Leaf\Crud\Leaves;

use Rhubarb\Crown\String\StringTools;
use Rhubarb\Leaf\Controls\Common\Checkbox\Checkbox;
use Rhubarb\Leaf\Controls\Common\DateTime\Date;
use Rhubarb\Leaf\Controls\Common\DateTime\DateTime;
use Rhubarb\Leaf\Controls\Common\SelectionControls\DropDown\DropDown;
use Rhubarb\Leaf\Controls\Common\Text\NumericTextBox;
use Rhubarb\Leaf\Controls\Common\Text\PasswordTextBox;
use Rhubarb\Leaf\Controls\Common\Text\TextArea;
use Rhubarb\Leaf\Controls\Common\Text\TextBox;
use Rhubarb\Leaf\Leaves\Leaf;
use Rhubarb\Stem\Collections\Collection;
use Rhubarb\Stem\Models\Model;
use Rhubarb\Stem\Repositories\MySql\Schema\Columns\MySqlEnumColumn;
use Rhubarb\Stem\Schema\Columns\BooleanColumn;
use Rhubarb\Stem\Schema\Columns\Column;
use Rhubarb\Stem\Schema\Columns\DateColumn;
use Rhubarb\Stem\Schema\Columns\DateTimeColumn;
use Rhubarb\Stem\Schema\Columns\DecimalColumn;
use Rhubarb\Stem\Schema\Columns\IntegerColumn;
use Rhubarb\Stem\Schema\Columns\LongStringColumn;
use Rhubarb\Stem\Schema\Columns\MoneyColumn;
use Rhubarb\Stem\Schema\Columns\StringColumn;
use Rhubarb\Stem\Schema\Columns\TimeColumn;
use Rhubarb\Stem\Schema\SolutionSchema;

abstract class ModelBoundLeaf extends Leaf
{
    /**
     * @var ModelBoundModel
     */
    protected $model;
    private $incomingRestModel;

    private $hasRestModelOrCollection = false;

    public function __construct($modelOrCollection = null)
    {
        $this->incomingRestModel = $modelOrCollection;

        parent::__construct("");
    }

    public function setRestModel(Model $restModel)
    {
        $this->model->restModel = $restModel;
        $this->hasRestModelOrCollection = true;
    }

    public function setRestCollection(Collection $restCollection)
    {
        $this->model->restCollection = $restCollection;
        $this->hasRestModelOrCollection = true;
    }

    /**
     * Provides an opportunity for extending classes to modify the model in some way when they themselves are not
     * directly responsible for the model creation.
     */
    protected function onModelCreated()
    {
        parent::onModelCreated();

        if ($this->incomingRestModel instanceof Model){
            $this->setRestModel($this->incomingRestModel);
        } elseif ($this->incomingRestModel instanceof Collection){
            $this->setRestCollection($this->incomingRestModel);
        }

        $this->model->createSubLeafFromNameEvent->attachHandler(function($leafName){

            if (!$this->hasRestModelOrCollection) {
                return null;
            }

            $restModel = $this->model->restModel;

            if ($restModel) {
                $class = $restModel->getModelName();
                $schema = $restModel->getSchema();
            } else {
                $restCollection = $this->model->restCollection;

                $class = $restCollection->getModelClassName();
                $schema = $restCollection->getModelSchema();
            }

            $leaf = $this->createLeafForLeafName($leafName);

            if ($leaf){
                return $leaf;
            }

            // See if the model has a relationship with this name.
            $relationships = SolutionSchema::getAllOneToOneRelationshipsForModelBySourceColumnName($class);

            $columnRelationships = false;

            if (isset($relationships[$leafName])) {
                $columnRelationships = $relationships[$leafName];
            } else {
                if ($leafName == $schema->uniqueIdentifierColumnName) {
                    if (isset($relationships[""])) {
                        $columnRelationships = $relationships[""];
                    }
                }
            }

            if ($columnRelationships) {
                $relationship = $relationships[$leafName];

                $collection = $relationship->getCollection();

                $dropDown = new DropDown($leafName);
                $dropDown->setSelectionItems(
                    [
                        ["", "Please Select"],
                        $collection
                    ]
                );

                $dropDown->setLabel(StringTools::wordifyStringByUpperCase($relationship->getNavigationPropertyName()));

                return $dropDown;
            }

            $columns = $schema->getColumns();

            if (!isset($columns[$leafName])) {
                return null;
            }

            $column = $columns[$leafName];

            return $this->createLeafFromColumn($column, $leafName);
        });
    }

    protected function createLeafForLeafName($leafName)
    {
        return null;
    }

    protected function createLeafFromColumn(Column $column, $leafName)
    {
        // Checkbox
        if ($column instanceof BooleanColumn) {
            return new Checkbox($leafName);
        }

        // DateTime
        if($column instanceof DateTimeColumn) {
            return new DateTime($leafName);
        }

        // Date
        if ($column instanceof DateColumn) {
            return new Date($leafName);
        }

        // Time
        if ($column instanceof TimeColumn) {
            //$textBox = new \Rhubarb\Leaf\Presenters\Controls\DateTime\Time($leafName);
            //return $textBox;
        }

        // Drop Downs
        if ($column instanceof MySqlEnumColumn) {
            $dropDown = new DropDown($leafName);
            $dropDown->setSelectionItems(
                [
                    ["", "Please Select"],
                    $column
                ]
            );

            return $dropDown;
        }

        // TextArea
        if ($column instanceof LongStringColumn) {
            $textArea = new TextArea($leafName);

            return $textArea;
        }

        // TextBoxes
        if ($column instanceof StringColumn) {
            if (stripos($leafName, "password") !== false) {
                return new PasswordTextBox($leafName);
            }

            $textBox = new TextBox($leafName);
            $textBox->setMaxLength($column->maximumLength);

            return $textBox;
        }

        // Decimal
        if ($column instanceof DecimalColumn || $column instanceof MoneyColumn) {
            $textBox = new NumericTextBox($leafName);

            return $textBox;
        }

        // Int
        if ($column instanceof IntegerColumn) {
            $textBox = new TextBox($leafName);
            //$textBox->setSize(5);

            return $textBox;
        }

        return null;
    }
}


<?php

namespace XM\FilterBundle\Form\DataTransformer;

use Symfony\Component\Form\DataTransformerInterface;
use XM\FilterBundle\Form\Type\BooleanType;

class BooleanTypeToBooleanTransformer implements DataTransformerInterface
{
    /**
     * {@inheritdoc}
     */
    public function transform($value)
    {
        if (true === $value || BooleanType::VALUE_TRUE === (int) $value) {
            return BooleanType::VALUE_TRUE;
        }

        return BooleanType::VALUE_FALSE;
    }

    /**
     * {@inheritdoc}
     */
    public function reverseTransform($value)
    {
        if (BooleanType::VALUE_TRUE === (int) $value) {
            return true;
        }

        return false;
    }
}


<?php
/**
 * This file is part of the CarteBlanche PHP framework.
 *
 * (c) Pierre Cassat <me@e-piwi.fr> and contributors
 *
 * License Apache-2.0 <http://github.com/php-carteblanche/carteblanche/blob/master/LICENSE>
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace CarteBlanche\Abstracts;

use \CarteBlanche\CarteBlanche;
use \CarteBlanche\App\Kernel;
use \CarteBlanche\App\FrontController;
use \Library\Helper\Directory as DirectoryHelper;
use \CarteBlanche\Exception\RuntimeException;

/**
 * Any tool class must extend this abstract one
 */
abstract class AbstractTool
{

    /**
     * @var string The views directory
     *
     * This must be a sub-directory of the tool directory
     */
    public $views_dir;

    /**
     * @var string The view file
     */
    public $view;

    /**
     * @var string The direct output (if no view is set or parse)
     */
    public $output;

    /**
     * @var array The views arguments
     */
    public $_args = array();

    /**
     * The constructor : overrides the tool options
     *
     * @param array $opts An array of the tool options
     */
    public function __construct($opts = array())
    {
        if (!empty($opts))
        foreach ($opts as $_opt_var=>$_opt_val) {
            if (property_exists($this, $_opt_var))
                $this->{$_opt_var} = $_opt_val;
            else
                $this->_args[$_opt_var] = $_opt_val;
        }
        if (empty($this->views_dir)) {
            $this->views_dir = \CarteBlanche\App\Locator::getToolPath( get_called_class() ).'/'
                .CarteBlanche::getPath('views_dir');
        }
    }

    /**
     * Direct rendering of the tool object
     *
     * It basically allows to directly write `echo $tool`
     *
     * @return string
     */
    public function __toString()
    {
        try {
            return $this->render();
        } catch( \Exception $e) {
            trigger_error( $e->getMessage(), E_USER_WARNING );
        }
    }

    /**
     * The final rendering of the tool
     *
     * @return string
     * @throws \CarteBlanche\Exception\RuntimeException if the rendering is empty
     */
    public function render()
    {
        $args = $this->buildViewParams();
        if (isset($args['output']))
            $this->output = $args['output'];

        if (!empty($this->view)) {
            return FrontController::getInstance()
                ->view( DirectoryHelper::slashDirname($this->views_dir).$this->view, $args );
        } elseif (isset($this->output)) {
            return $this->output;
        } else {
            throw new RuntimeException("Tool '".get_class($this)."' do not render anything !");
        }
    }

    /**
     * The tool logic : construction of the objects parameters passed to final view
     *
     * @return array
     */
    abstract function buildViewParams();

}

// Endfile


<?php
    /**
     * Bu Dosya AnonymFramework'e ait bir dosyadır.
     *
     * @author vahitserifsaglam <vahit.serif119@gmail.com>
     * @see http://gemframework.com
     *
     */

    namespace Anonym\Components\Crypt;
    use Exception;
    use InvalidArgumentException;
    use Anonym\Components\Crypt\CrypterEncodeableInterface;
    use Anonym\Components\Crypt\CrypterDecodeableInterface;
    /**
     * Class AnonymCrypt
     * @package Anonym\Components\Crypt
     */
    class AnonymCrypt implements CrypterDecodeableInterface,CrypterEncodeableInterface
    {

        /**
         * Güvenlik anahtarı
         *
         * @var string
         */
        private $securityKey;
        /**
         * Mcrypt şifreleme türü
         *
         * @var string
         */
        private $mode = MCRYPT_MODE_ECB;

        /**
         * Mcrypt şifreleme rastgele sayısı
         *
         * @var int
         */
        private $rand = MCRYPT_RAND;
        /**
         * Mcrypt Şifreleme aligoritması
         *
         * @var string
         */
        private $alogirtym = MCRYPT_RIJNDAEL_256;

        /**
         * Sınıfı başlatır
         *
         * @throws Exception
         */
        public function __construct()
        {
            if (!extension_loaded('mcrypt')) {
                throw new Exception('Sunucunuzda Mcrypt desteği bulunamadı.');
            }

            $this->setSecurityKey('AnonymCrypter');
        }

        /**
         * Metni şifreler
         *
         * @param string $value
         * @return string
         */
        public function encode($value = ''){
            $iv = mcrypt_create_iv($this->getIvSize(), $this->getRandomizer());
            $base = base64_encode(serialize($this->payloadCreator($this->encrypt($value, $iv), $iv)));
            return $base;
        }

        /**
         * @param string $value
         * @param        $iv
         * @return string
         * Şifrelenmiş metni hazırlar
         */
        private function encrypt($value = '', $iv)
        {
            $value = trim($value);
            try {
                $crypted = mcrypt_encrypt($this->getAlogirtym(), $this->getSecurityKey(), $value, $this->getMode(), $iv);
                return $crypted;
            } catch (Exception $e) {
                //
            }
        }

        /**
         * Value ve iv değerlerini kullanılmak için hazırlar
         *
         * @param $creypted
         * @param $iv
         * @return array
         */
        private function payloadCreator($creypted, $iv)
        {
            return [
                'value' => $creypted,
                'iv'    => $iv,
            ];
        }

        /**
         * Şifrelenmiş metni çözer
         *
         * @param string $value
         * @return string
         */
        public function decode($value = '')
        {
            if (is_string($value)) {
                $payload = $this->parsePayload($value);
                return $this->decrypt($payload);
            }
        }
        /**
         * @param $value
         * @return array
         * payload verisi parçalanır
         */
        private function parsePayload($value)
        {
            $based = unserialize(base64_decode($value));
            if (isset($based['value']) && isset($based['iv'])) {
                return $based;
            }else{
                return [];
            }
        }
        /**
         * Metnin şifresini çözer
         *
         * @param array $payload
         * @return string
         */
        private function decrypt(array $payload)
        {
            $iv = $payload['iv'];
            $value = $payload['value'];
            $value = trim($value);
            return mcrypt_decrypt($this->getAlogirtym(), $this->getSecurityKey(), $value, $this->getMode(), $iv);
        }

        /**
         * Randomizer i döndürür
         *
         * @return int
         */
        private function getRandomizer()
        {
            if ($this->getRand()) {
                return $this->getRand();
            }
        }

        /**
         * Iv uzunluÄŸunu DÃ¶ndÃ¼rÃ¼r
         *
         * @return int
         */
        private function getIvSize()
        {
            return mcrypt_get_iv_size($this->getAlogirtym(), $this->getMode());
        }

        /**
         * @return mixed
         */
        public function getSecurityKey()
        {
            return $this->securityKey;
        }

        /**
         * @param mixed $securityKey
         * @throws InvalidArgumentException
         * @return AnonymCrypt
         */
        public function setSecurityKey($securityKey)
        {

            if($securityKey instanceof SecurityKeyGeneratorInterface){
                $securityKey = $securityKey->create();
            }

            if(!is_string($securityKey)){
                throw new InvalidArgumentException('Güvenlik anahtarınız sadece string olabilir');
            }
            $this->securityKey = $securityKey;
            return $this;
        }

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

        /**
         * @param string $mode
         * @return AnonymCrypt
         */
        public function setMode($mode)
        {
            $this->mode = $mode;

            return $this;
        }

        /**
         * @return int
         */
        public function getRand()
        {
            return $this->rand;
        }

        /**
         * @param int $rand
         * @return AnonymCrypt
         */
        public function setRand($rand)
        {
            $this->rand = $rand;

            return $this;
        }

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

        /**
         * @param string $alogirtym
         * @return AnonymCrypt
         */
        public function setAlogirtym($alogirtym)
        {
            $this->alogirtym = $alogirtym;

            return $this;
        }

    }


<?php

namespace Dhii\Iterator;

use Dhii\Util\String\StringableInterface as Stringable;
use stdClass;
use Traversable;
use Exception as RootException;
use InvalidArgumentException;

trait PathSegmentsAwareTrait
{
    /**
     * A list of path segments.
     *
     * @since [*next-version*]
     *
     * @var string[]|Stringable[]|Traversable
     */
    protected $pathSegments;

    /**
     * Sets the path segments.
     *
     * @since [*next-version*]
     *
     * @param string[]|Stringable[]|Traversable|stdClass $segments A list of path segments.
     */
    protected function _setPathSegments($segments)
    {
        /*
         * `PathSegmentsAwareInterface#getPathSegments()` disallows `stdClass`.
         */
        if ($segments instanceof stdClass) {
            $segments = (array) $segments;
        }

        $segments = $this->_normalizeIterable($segments);

        $this->pathSegments = $segments;
    }

    /**
     * Retrieves the path segments.
     *
     * @since [*next-version*]
     *
     * @return string[]|Stringable[]|Traversable The list of segments.
     */
    protected function _getPathSegments()
    {
        return is_null($this->pathSegments)
            ? []
            : $this->pathSegments;
    }

    /**
     * Creates a new Invalid Argument exception.
     *
     * @since [*next-version*]
     *
     * @param string|Stringable|null $message  The error message, if any.
     * @param int|null               $code     The error code, if any.
     * @param RootException|null     $previous The inner exception for chaining, if any.
     * @param mixed|null             $argument The invalid argument, if any.
     *
     * @return InvalidArgumentException The new exception.
     */
    abstract protected function _createInvalidArgumentException(
        $message = null,
        $code = null,
        RootException $previous = null,
        $argument = null
    );

    /**
     * Normalizes an iterable.
     *
     * Makes sure that the return value can be iterated over.
     *
     * @since [*next-version*]
     *
     * @param mixed $iterable The iterable to normalize.
     *
     * @throws InvalidArgumentException If the iterable could not be normalized.
     *
     * @return array|Traversable|stdClass The normalized iterable.
     */
    abstract protected function _normalizeIterable($iterable);
}


<?php

namespace Simply\Container\Entry;

use Psr\Container\ContainerInterface;
use Simply\Container\Exception\ContainerException;

/**
 * Container entry that loads the value using a separate entry provider.
 *
 * @author Riikka Kalliomäki <riikka.kalliomaki@gmail.com>
 * @copyright Copyright (c) 2018 Riikka Kalliomäki
 * @license http://opensource.org/licenses/mit-license.php MIT License
 */
class ProviderEntry implements EntryInterface
{
    /** @var string The provider class used to load the value */
    private $provider;

    /** @var string The method called for the provider class to load the value */
    private $method;

    /**
     * ProviderEntry constructor.
     * @param callable $providerMethod The provider callable provided as an array
     */
    public function __construct(callable $providerMethod)
    {
        if (!\is_array($providerMethod)) {
            throw new \InvalidArgumentException('The provider entry callable must be provided as an array');
        }

        [$provider, $method] = $providerMethod;

        $this->setProvider($provider);
        $this->setMethod($method);
    }

    /**
     * Sets the provider class based on the given provider instance.
     * @param object $provider The provider instance
     */
    private function setProvider(object $provider): void
    {
        $this->provider = \get_class($provider);
    }

    /**
     * Sets the method to call for the provider instance.
     * @param string $method The method to call for the provider
     */
    private function setMethod(string $method): void
    {
        $this->method = $method;
    }

    /** {@inheritdoc} */
    public static function createFromCacheParameters(array $parameters): EntryInterface
    {
        /** @var ProviderEntry $entry */
        $entry = (new \ReflectionClass(static::class))->newInstanceWithoutConstructor();

        [
            $entry->provider,
            $entry->method,
        ] = $parameters;

        return $entry;
    }

    /** {@inheritdoc} */
    public function getCacheParameters(): array
    {
        return [
            $this->provider,
            $this->method,
        ];
    }

    /** {@inheritdoc} */
    public function isFactory(): bool
    {
        return false;
    }

    /** {@inheritdoc} */
    public function getValue(ContainerInterface $container)
    {
        $provider = $container->get($this->provider);

        if (!\is_object($provider)) {
            throw new ContainerException('Unexpected value returned for the provider object by the container');
        }

        return $provider->{$this->method}($container);
    }
}


<?php

namespace nb\composer;

use Composer\Installer\LibraryInstaller;
use Composer\Package\PackageInterface;
use Composer\Repository\InstalledRepositoryInterface;

class Framework extends LibraryInstaller {
    public function install(InstalledRepositoryInterface $repo, PackageInterface $package) {
        parent::install($repo, $package);
        if ($this->composer->getPackage()->getType() == 'project' && $package->getInstallationSource() != 'source') {
            //remove tests dir
            $this->filesystem->removeDirectory($this->getInstallPath($package) . DIRECTORY_SEPARATOR . 'tests');
        }
    }

    /**
     * {@inheritDoc}
     */
    public function getInstallPath(PackageInterface $package) {

        if ('nbcx/framework' !== $package->getPrettyName()) {
            throw new \InvalidArgumentException('Unable to install this library:'. $package->getPrettyName());
        }

        if ($this->composer->getPackage()->getType() !== 'project') {
            return parent::getInstallPath($package);
        }

        if ($this->composer->getPackage()) {
            $extra = $this->composer->getPackage()->getExtra();
            if (!empty($extra['nb-path'])) {
                return $extra['nb-path'];
            }
        }

        return 'nb';
    }

    public function update(InstalledRepositoryInterface $repo, PackageInterface $initial, PackageInterface $target) {
        parent::update($repo, $initial, $target);
        if ($this->composer->getPackage()->getType() == 'project' && $target->getInstallationSource() != 'source') {
            //remove tests dir
            $this->filesystem->removeDirectory($this->getInstallPath($target) . DIRECTORY_SEPARATOR . 'tests');
        }
    }

    /**
     * {@inheritDoc}
     */
    public function supports($packageType) {
        return 'nb-framework' === $packageType;
    }
}


<?php
/**
 * Class to create a proxy object to be used in a test szenario.
 *
 * Mainly the ProxyObjectBuilder provides a fluent interface for the ProxyObject.
 *
 * Copyright (c) 2010-2011, Bastian Feder <github@bastian-feder.de>.
 * All rights reserved.
 * @license    http://www.apache.org/licenses/LICENSE-2.0  Apache License Version 2.0, January 2004
 *             Licensed under the Apache License, Version 2.0 (the "License");
 *             you may not use this file except in compliance with the License.
 *             You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *
 * @copyright  2010-2011 Bastian Feder <github@bastian-feder.de>
 * @author     Bastian Feder <github@bastian-feder.de>
 * @license    http://www.apache.org/licenses/LICENSE-2.0
 * @link       https://github.com/lapistano/proxy-object
 * @package    Unittests
 * @subpackage ProxyObject
 */
namespace lapistano\ProxyObject;

/**
 * Implementation of the Builder pattern for Proxy objects.
 *
 * @copyright  2010-2011 Bastian Feder <github@bastian-feder.de>
 * @author     Bastian Feder <github@bastian-feder.de>
 * @license    http://www.apache.org/licenses/LICENSE-2.0
 * @link       https://github.com/lapistano/proxy-object
 * @package    Unittests
 * @subpackage ProxyObject
 */
class ProxyBuilder
{
    /**
     * @var string
     */
    protected $className;

    /**
     * @var array
     */
    protected $methods = array();

    /**
     * @var array
     */
    protected $properties = array();

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

    /**
     * @var array
     */
    protected $constructorArgs = array();

    /**
     * @var boolean
     */
    protected $autoload = true;

    /**
     * @var boolean
     */
    protected $invokeOriginalConstructor = true;

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

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

    /**
     * Creates a proxy object using a fluent interface.
     *
     * @return object Instance of the proxied class exposing the configured attributes and methods.
     */
    public function getProxy()
    {
        include_once(__DIR__ . '/Generator.php');

        $proxyClass = Generator::generate(
            $this->className, $this->methods, $this->properties, $this->proxyClassName, $this->autoload
        );

        $classname = $proxyClass['proxyClassName'];

        if (!empty($proxyClass['namespaceName'])) {
            $classname = $proxyClass['namespaceName'] . '\\' . $proxyClass['proxyClassName'];
        }

        if (!class_exists($classname, false)) {
            eval($proxyClass['code']);
        }

        if ($this->invokeOriginalConstructor && !interface_exists($this->className, $this->autoload)) {

            if (empty($this->constructorArgs)) {
                return new $classname();
            }

            $proxy = new \ReflectionClass($classname);

            return $proxy->newInstanceArgs($this->constructorArgs);
        }

        return $this->getInstanceOf($classname);
    }

    /**
     * Specifies the subset of methods to proxy. Default is to proxy all of them.
     *
     * @param  array $methods
     *
     * @return ProxyBuilder
     */
    public function setMethods(array $methods)
    {
        $this->methods = $methods;

        return $this;
    }

    /**
     * Specifies the subset of properties to expose. Default is to proxy all of them.
     *
     * @param  array $properties
     *
     * @return \lapistano\ProxyObject\ProxyBuilder
     */
    public function setProperties(array $properties)
    {
        $this->properties = $properties;

        return $this;
    }

    /**
     * Specifies the arguments for the constructor.
     *
     * @param  array $args
     *
     * @return \lapistano\ProxyObject\ProxyBuilder
     */
    public function setConstructorArgs(array $args)
    {
        $this->constructorArgs = $args;

        return $this;
    }

    /**
     * Specifies the name for the proxy class.
     *
     * @param string $name
     *
     * @return \lapistano\ProxyObject\ProxyBuilder
     */
    public function setProxyClassName($name)
    {
        $this->mockClassName = $name;

        return $this;
    }

    /**
     * Suppresses the invocation of the original constructor.
     *
     * @return \lapistano\ProxyObject\ProxyBuilder
     */
    public function disableOriginalConstructor()
    {
        $this->invokeOriginalConstructor = false;

        return $this;
    }

    /**
     * Suppresses the use of class autoloading while creating the proxy object.
     *
     * @return \lapistano\ProxyObject\ProxyBuilder
     */
    public function disableAutoload()
    {
        $this->autoload = false;

        return $this;
    }

    /**
     * Provides an instance of the given class without invoking it's constructor
     *
     * @param string $classname
     *
     * @return object
     */
    protected function getInstanceOf($classname)
    {
        // As of PHP5.4 the reflection api provides a way to get an instance
        // of a class without invoking the constructor.
        if (method_exists('ReflectionClass', 'newInstanceWithoutConstructor')) {
            $reflectedClass = new \ReflectionClass($classname);

            return $reflectedClass->newInstanceWithoutConstructor();
        }

        // Use a trick to create a new object of a class
        // without invoking its constructor.
        return unserialize(
            sprintf(
                'O:%d:"%s":0:{}', strlen($classname), $classname
            )
        );
    }
}


<?php

namespace BDK\AsyncEventDispatcher;

/**
 * AsyncEventDispatcher
 *
 * @copyright Bodaclick S.A
 * @author Eduardo Gulias Davis <eduardo.gulias@bodaclick.com>
 */
class AsyncEventDispatcher implements AsyncEventDispatcherInterface
{
    /**
     * events
     *
     * @var array
     */
    private $events = [];

    /**
     * drivers
     *
     * @var driver
     */
    private $drivers = [];

    /**
     * {@inherit}
     */
    public function dispatch(AsyncEventInterface $event)
    {
        if (!isset($this->events[$event->getName()])) {
            return $event;
        }

        foreach ($this->events[$event->getName()] as $driver) {
            $driver->publish($event);
        }

        return $event;
    }

    /**
     * {@inherit}
     */
    public function addDriver(AsyncEventDriverInterface $driver, $eventName = null)
    {
        $this->drivers[$driver->getName()] = $driver;
        if (null === $eventName) {
            foreach ($this->events as $name => $currentDriver) {
                $this->events[$name][$driver->getName()] = $driver;
            }
        }

        if (!isset($this->events[$eventName][$driver->getName()])) {
            $this->events[$eventName][$driver->getName()] = $driver;
        }
    }

    /**
     * {@inherit}
     */
    public function getDrivers()
    {
        return $this->drivers;
    }

    /**
     * {@inherit}
     */
    public function removeDriver(AsyncEventDriverInterface $driver, $eventName = null)
    {
        unset($this->drivers[$driver->getName()]);
        if (null === $eventName) {
            foreach ($this->events as $eventName => $currentDriver) {
                unset($this->events[$eventName][$driver->getName()]);
            }
        }
        unset($this->events[$eventName][$driver->getName()]);
    }

    /**
     * {@inherit}
     */
    public function hasDriver($driverName)
    {
        return isset($this->drivers[$driverName]);
    }

    /**
     * eventHasDrivers
     *
     * @param string $eventName
     *
     * @return Boolean
     */
    public function eventHasDrivers($eventName)
    {
        return (bool) count($this->events[$eventName]);
    }

    /**
     * get the registerd events
     *
     * @return array of events
     */
    public function getEvents()
    {
        return $this->events;
    }
}


<?php
/**
 * @author Serhii Nekhaienko <sergey.nekhaenko@gmail.com>
 * @license GPL
 * @copyright Serhii Nekhaienko &copy 2018
 * @version 4.0.0
 * @project endorphin-studio/browser-detector
 */

namespace EndorphinStudio\Detector\Detection;

use EndorphinStudio\Detector\Tools;

/**
 * Detector for robot
 * Class RobotDetector
 * @package EndorphinStudio\Detector\Detection
 */
class RobotDetector extends AbstractDetection
{
    /**
     * @var string Key in array
     */
    protected $configKey = 'robot';

    /** @var array List of objects */
    private $homepages;

    /**
     * Setup result object
     */
    protected function setupResultObject()
    {
        $this->homepages = $this->config['homepages'];
        $this->config = $this->config['types'];
        $object = $this->detectByConfig();
        foreach ($object as $key => $value) {
            Tools::runSetter($this->resultObject, $key, $value);
        }
        if (\array_key_exists('name', $object) && $object['name']) {
            $this->detector->getResultObject()->setIsRobot(true);
        }
        $this->additionalInfo = $object;
    }

    /**
     * @return array List with result
     */
    protected function detectByConfig(): array
    {
        foreach ($this->config as $type => $companyList) {
            $data = $this->detectByType($type);
            if ($data) {
                return \array_merge($data, ['homepage' => \array_key_exists($data['owner'], $this->homepages) ? $this->homepages[$data['owner']] : null, 'type' => $type]);
            }
        }
        return [];
    }

    /**
     * Detect by type
     * @param string $key
     * @return array
     */
    protected function detectByType($key = 'none'): array
    {
        foreach ($this->config[$key] as $companyName => $patternList) {
            $data = $this->detectByPattern($patternList);
            if ($data) {
                return \array_merge($data, ['owner' => $companyName]);
            }
        }
        return [];
    }

    /**
     * Detect by pattern
     * @param array $patternList
     * @return array|null
     */
    protected function detectByPattern(array $patternList)
    {
        foreach ($patternList as $name => $pattern) {
            $pattern = $this->getPattern($pattern);

            if (preg_match($pattern, $this->detector->getUserAgent())) {
                return ['name' => $name];
            }
        }
        return null;
    }

    /**
     * Get regex pattern
     * @param string $pattern
     * @return string
     */
    private function getPattern(string $pattern): string
    {
        return sprintf('/%s/', $pattern);
    }
}


<?php

namespace Oxygen\Data\Repository\Doctrine;

use DateTime;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\QueryBuilder;
use Doctrine\ORM\Query;
use InvalidArgumentException;
use Doctrine\ORM\NoResultException as DoctrineNoResultException;
use Oxygen\Data\Exception\NoResultException;
use Oxygen\Data\Repository\QueryParameters;
use Oxygen\Data\Behaviour\Searchable;
use Oxygen\Data\Repository\RepositoryInterface;
use Oxygen\Data\Pagination\PaginationService;

class Repository implements RepositoryInterface {

    /**
     * The entity manager
     *
     * @var EntityManagerInterface
     */

    protected $entities;

    /**
     * The pagination service
     *
     * @var PaginationService
     */

    protected $paginator;

    /**
     * The name of the entity.
     *
     * @var string
     */

    protected $entityName = 'Undefined';

    /**
     * Constructs the DoctrineRepository.
     *
     * @param EntityManagerInterface   $entities
     * @param PaginationService        $paginator
     */
    public function __construct(EntityManagerInterface $entities, PaginationService $paginator) {
        $this->entities = $entities;
        $this->paginator = $paginator;
    }

    /**
     * Retrieves all entities.
     *
     * @param QueryParameters  $queryParameters extra query parameters
     * @return mixed
     */
    public function all(QueryParameters $queryParameters = null) {
        return $this->getQuery(
            $this->createSelectQuery(),
            $queryParameters
        )->getResult();
    }

    /**
     * Retrieves certain columns of entities.
     *
     * @param array           $fields
     * @param QueryParameters $queryParameters an optional array of query scopes
     * @return mixed
     */
    public function columns(array $fields, QueryParameters $queryParameters = null) {
        $select = '';
        foreach($fields as $field) {
            $select .= 'o.' . $field;
            if($field !== last($fields)) {
                $select .= ', ';
            }
        }
        $qb = $this->entities->createQueryBuilder()
            ->select($select)
            ->from($this->entityName, 'o');

        return $this->getQuery($qb, $queryParameters)->getResult();
    }

    /**
     * Lists columns of the entity like this:
     *  1 => Title
     *  3 => Foo
     *  4 => Yoyo
     *
     * @param $key
     * @param $value
     * @param QueryParameters $queryParameters
     * @return array
     */
    public function listKeysAndValues($key, $value, QueryParameters $queryParameters = null) {
        $results = $this->columns([$key, $value], $queryParameters);

        $return = [];
        foreach($results as $result) {
            $return[$result[$key]] = $result[$value];
        }

        return $return;
    }

    /**
     * Retrieves all entities, by page.
     *
     * @param int             $perPage          items per page
     * @param QueryParameters $queryParameters  an optional array of query scopes
     * @param int             $currentPage      current page that overrides the pagination service
     * @return mixed
     */
    public function paginate($perPage = 25, QueryParameters $queryParameters = null, $currentPage = null, $searchQuery = null) {
        $currentPage = $currentPage === null ? $this->paginator->getCurrentPage() : $currentPage;

        $qb = $this->addSearchConditions($this->createSelectQuery(), $searchQuery);

        $qb = $qb->setFirstResult($perPage * ($currentPage - 1))
                 ->setMaxResults($perPage);
        $items = $this->getQuery($qb, $queryParameters)->getResult();

        $count = $this->addSearchConditions($this->createCountQuery(), $searchQuery);
        $count = (int) $this->getQuery($count, $queryParameters)->getSingleScalarResult();

        return $this->paginator->make($items, $count, $perPage);
    }

    public function addSearchConditions($qb, $searchQuery) {
        $class = new \ReflectionClass($this->entityName);
        if($class->implementsInterface(Searchable::class) && $searchQuery != null) {

            $fields = call_user_func([$this->entityName, 'getSearchableFields']);
            $likes = [];
            foreach($fields as $field) {
                $likes[] = $qb->expr()->like('o.' . $field, ':searchQuery');
            }

            $qb = $qb
                ->andWhere(call_user_func_array([$qb->expr(), 'orX'], $likes))
                ->setParameter('searchQuery', '%' . $searchQuery . '%');
        }
        return $qb;
    }

    /**
     * Retrieves a single entity.
     *
     * @param integer         $id
     * @param QueryParameters $queryParameters an optional array of query scopes
     * @return object
     * @throws NoResultException if no result was found
     */
    public function find($id, QueryParameters $queryParameters = null) {
        $q = $this->getQuery(
            $this->createSelectQuery()
                 ->andWhere('o.id = :id')
                 ->setParameter('id', $id),
            $queryParameters
        );

        try {
            return $q->getSingleResult();
        } catch(DoctrineNoResultException $e) {
            throw $this->makeNoResultException($e, $q);
        }
    }

    /**
     * Creates a new entity
     *
     * @return object
     */
    public function make() {
        return new $this->entityName();
    }

    /**
     * Persists an entity.
     *
     * @param object  $entity
     * @param boolean $flush
     * @return void
     */
    public function persist($entity, $flush = true) {
        $this->entities->persist($entity);
        if($flush) {
            $this->entities->flush();
        }
    }

    /**
     * Flushes changes.
     *
     * @return void
     */
    public function flush() {
        $this->entities->flush();
    }

    /**
     * Deletes an entity.
     *
     * @param  object  $entity
     * @param  boolean $flush
     * @return void
     */
    public function delete($entity, $flush = true) {
        $this->entities->remove($entity);
        if($flush) {
            $this->entities->flush();
        }
    }

    /**
     * Retrieves the number of records in the table.
     *
     * @param QueryParameters $queryParameters
     * @return integer
     */
    public function count(QueryParameters $queryParameters = null) {
        return (int) $this->getQuery(
            $this->entities->createCountQuery(),
            $queryParameters
        )->getSingleScalarResult();
    }

    /**
     * Creates a new QueryBuilder instance that is pre-populated to count rows.
     *
     * @return QueryBuilder
     */
    protected function createCountQuery() {
        return $this->entities
            ->createQueryBuilder()
            ->select('count(o.id)')
            ->from($this->entityName, 'o');
    }

    /**
     * Creates a new QueryBuilder instance that is pre-populated for this entity name.
     *
     * @param string $alias
     * @param string $indexBy The index for the form.
     *
     * @return QueryBuilder
     */
    protected function createSelectQuery($alias = 'o', $indexBy = null) {
        return $this->entities
            ->createQueryBuilder()
            ->select($alias)
            ->from($this->entityName, $alias, $indexBy);
    }

    /**
     * @param \Doctrine\ORM\QueryBuilder              $qb
     * @param \Oxygen\Data\Repository\QueryParameters $queryParameters
     * @return \Doctrine\ORM\Query
     */
    protected function getQuery(QueryBuilder $qb, QueryParameters $queryParameters = null, $alias = 'o') {
        if($queryParameters != null) {
            $this->applyScopesToQueryBuilder($qb, $queryParameters->getScopes());
            if($queryParameters->getOrderBy() != null) {
                $this->applyOrderByToQueryBuilder($qb, $queryParameters->getOrderBy(), $alias);
            }
        }

        return $qb->getQuery();
    }

    /**
     * Creates a new QueryBuilder instance that is pre-populated for this entity name.
     * Applies scopes to the query builder as well.
     *
     * @param array  $scopes
     * @param QueryBuilder $qb
     * @throws InvalidArgumentException if the scope was not found
     * @return QueryBuilder
     */
    protected function applyScopesToQueryBuilder(QueryBuilder $qb, array $scopes) {
        foreach((array) $scopes as $scope) {
            $method = 'scope' . ucfirst($scope);
            if(method_exists($this, $method)) {
                $qb = $this->{$method}($qb);
            } else {
                throw new InvalidArgumentException('Scope \'' . $scope . '\' not found');
            }
        }
        return $qb;
    }

    /**
     * Applies the order by request to the query builder.
     *
     * @param \Doctrine\ORM\QueryBuilder $queryBuilder
     * @param array                      $orderBy
     * @param string                     $alias
     * @return \Doctrine\ORM\QueryBuilder
     */
    private function applyOrderByToQueryBuilder(QueryBuilder $queryBuilder, array $orderBy, $alias) {
        $queryBuilder->orderBy($alias . '.' . $orderBy[0], $orderBy[1]);
        return $queryBuilder;
    }

    /**
     * Creates a NoResultException from a QueryBuilder
     *
     * @param \Exception                    $e
     * @param \Doctrine\ORM\QueryBuilder    $qb
     * @return \Oxygen\Data\Exception\NoResultException
     */
    protected function makeNoResultException(\Exception $e, Query $q) {
        return new NoResultException($e, $this->replaceQueryParameters($q->getDQL(), $q->getParameters()));
    }
    /**
     * Replaces placeholders within a given query with the actual values.
     * Used for debugging.
     *
     * @param $query
     * @param $parameters
     * @return string
     */
    private function replaceQueryParameters($query, $parameters) {
        foreach($parameters as $parameter) {
            $value = $parameter->getValue();
            $value = $value instanceof DateTime ? $value->format('Y-m-d H:i:s') : $value;
            $query = str_replace(':' . $parameter->getName(), $value, $query);
        }
        return $query;
    }

    /**
     * Returns a reference to a specified item.
     *
     * @param int $id
     * @return object
     */
    public function getReference($id) {
        return $this->entities->getReference($this->entityName, $id);
    }

    /**
     * Returns the class name of the entity.
     *
     * @return string
     */
    public function getEntityName() {
        return $this->entityName;
    }

}


<?php
/*
 * This file is part of the Skeetr package.
 *
 * (c) Máximo Cuadros <mcuadros@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Skeetr;

use Psr\Log\LoggerInterface;
use Skeetr\Gearman\Worker;
use Skeetr\Client\Socket;
use Skeetr\Client\Journal;
use Skeetr\Client\Channel;
use Skeetr\Client\RPC;
use Skeetr\Runtime\Manager;
use RuntimeException;

class Client
{
    protected $memoryLimit = 67108864; //64mb
    protected $interationsLimit;
    protected $methods = [];
    protected $logger;
    protected $socket;
    protected $callback;
    protected $loop;

    public function __construct(Socket $socket)
    {
        $this->socket = $socket;

        //TODO: Optional
        Manager::auto();
    }

    /**
     * Sets the callback, this callback generate the result of the request
     *
     * @param  string $channelName
     * @return self   The current Process instance
     */
    public function setCallback(Callable $callback)
    {
        $this->callback = $callback;

        return $this;
    }

    /**
     * Sets the memory limit, when this limit is reached the loops ends
     *
     * @param  integer $bytes
     * @return self    The current Process instance
     */
    public function setMemoryLimit($bytes)
    {
        $this->memoryLimit = $bytes;

        return $this;
    }

    /**
     * Sets the iterations limit, when this limit is reached the loops ends
     *
     * @param  integer $times
     * @return self    The current Process instance
     */
    public function setInterationsLimit($times)
    {
        $this->interationsLimit = $times;

        return $this;
    }

    /**
     * Sets the logger instance
     *
     * @param  LoggerInterface $logger
     * @return self            The current Process instance
     */
    public function setLogger(LoggerInterface $logger = null)
    {
        $this->logger = $logger;

        return $this;
    }

    /**
     * Sets the methods
     *
     * @param  Array $methods
     * @return self  The current Process instance
     */
    public function setMethods(Array $methods)
    {
        $this->methods = [];
        foreach ($methods as $method) {
            $this->addMethod($method);
        }

        return $this;
    }

    /**
     * Adds a method instance
     *
     * @param  RPC\Method $method
     * @return self       The current Process instance
     */
    public function addMethod(RPC\Method $method)
    {
        $tmp = explode('\\', get_class($method));
        $this->methods[end($tmp)] = $method;
    }

    /**
     * Returns the callback
     *
     * @return callable
     */
    public function getCallback()
    {
        return $this->callback;
    }

    /**
     * Returns the memory limit
     *
     * @return integer
     */
    public function getMemoryLimit()
    {
        return $this->memoryLimit;
    }

    /**
     * Returns the iterations limit
     *
     * @return integer
     */
    public function getInterationsLimit()
    {
        return $this->interationsLimit;
    }

    /**
     * Returns the logger instance
     *
     * @return LoggerInterface
     */
    public function getLogger()
    {
        return $this->logger;
    }

    /**
     * Returns all the methods
     *
     * @return Array
     */
    public function getMethods()
    {
        return $this->methods;
    }

    /**
     * Returns the method with the given name
     *
     * @param  string $name
     * @return RPC\Method
     */
    public function getMethod($name)
    {
        var_dump(array_keys($this->methods));

        if (!isset($this->methods[$name])) {
            throw new RuntimeException(sprintf(
                'Unable to find RPC method %s', $name
            ));
        }

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

    /**
     * Wait for and perform requests
     */
    public function work()
    {
        $this->initializeMethods();
        $this->initializeSocket();
        $this->loop();
    }

    private function initializeMethods()
    {
        $process = new RPC\Method\Process($this->callback);
        $this->addMethod($process);
    }

    private function initializeSocket()
    {
        $this->socket->connect();
        $this->log('notice', 'Waiting for client...');
        $this->socket->waitForConnection();
        $this->log('notice', 'Waiting for job...');
    }

    protected function loop()
    {
        $this->loop = true;
        while ($this->loop) {
            $request = RPC\Request::fromJSON($this->socket->get());

            $result = $this->getMethod($request->getMethod())->execute($request);

            $response = new RPC\Response();
            $response->setId($request->getId());
            $response->setResult($result);

            $this->socket->put($response->toJSON());

            //$this->checkStatus();*/
            var_dump('request');
        }
    }

    /**
     * Stops the main loop and exits the work function
     *
     * @param string $message optional
     * @param boolean
     */
    public function shutdown($message = null)
    {
        if (!$this->loop) {
            return false;
        }

        if ($message) {
            $this->log('notice', sprintf('Loop stopped: %s', $message));
        }

        $this->loop = false;

        return true;
    }

    protected function checkStatus()
    {
        if ($this->memoryLimit) {
            $memory = memory_get_usage(true);
            if ($memory >= $this->memoryLimit) {
                return $this->shutdown(sprintf(
                    'Memory limit reached %d bytes (%d bytes limit)',
                    $memory, $this->memoryLimit
                ));
            }
        }

        if ($this->interationsLimit) {
            $iterations = $this->journal->getWorks();
            if ($iterations >= $this->interationsLimit) {
                return $this->shutdown(sprintf(
                    'Iteration limit reached %d times (%d limit)',
                    $iterations, $this->interationsLimit
                ));
            }
        }

        return null;
    }

    protected function log($type, $message)
    {
        var_dump($type);

        if (!$this->logger) {
            return false;
        }

        return $this->logger->$type($message);
    }
}