<?php
/**
 * zf2-cron-helper
 *
 * @link https://github.com/ondrejd/zf2-cron-helper for the canonical source repository
 * @copyright Copyright (c) 2015 Ondřej Doněk.
 * @license https://www.mozilla.org/MPL/2.0/ Mozilla Public License 2.0
 */

namespace CronHelper\Model;

use Zend\Db\Adapter\AdapterInterface;
use Zend\Db\Adapter\Driver\Pdo\Result;
use Zend\Db\ResultSet\HydratingResultSet;
use Zend\Db\Sql\Sql;
use Zend\Db\Sql\Where;
use Zend\Stdlib\Hydrator\ClassMethods;

/**
 * Mapper to database table with CRON jobs.
 *
 * @package CronHelper
 * @subpackage Model
 * @author Ondřej Doněk <ondrejd@gmail.com>
 */
class JobMapper implements JobMapperInterface
{
	/**
	 * @var string $tableName
	 */
	protected $tableName = JobTable::TABLE_NAME;

	/**
	 * @var AdapterInterface $dbAdapter
	 */
	protected $dbAdapter;

	/**
	 * @var Sql $sql
	 */
	protected $sql;

	/**
	 * Constructor.
	 *
	 * @param AdapterInterface $dbAdapter
	 * @return void
	 */
	public function __construct(AdapterInterface $dbAdapter)
	{
		$this->dbAdapter = $dbAdapter;

		$this->sql = new Sql($dbAdapter);
		$this->sql->setTable($this->tableName);
	}

	/**
	 * Return name of database table.
	 *
	 * @return string
	 */
	public function getTableName()
	{
		return $this->tableName;
	}

	/**
	 * @param Result $result
	 * @return HydratingResultSet
	 */
	private function hydrateResult(Result $result)
	{
		$entity = new JobEntity();
		$hydrator = new ClassMethods();
		$resultSet = new HydratingResultSet($hydrator, $entity);
		$resultSet->initialize($result);
		$resultSet->buffer();

		return $resultSet;
	}

	/**
	 * Find jobs.
	 *
	 * @param Where|string|null $where
	 * @param array $options (Optional.)
	 * @return Result|HydratingResultSet
	 */
	public function fetchByWhere($where = null, array $options = array())
	{
		$select = $this->sql->select();

		if ($where instanceof Where) {
			$select->where($where);
		} elseif (is_string($where) && !empty($where)) {
			$select->where($where);
		}

		// Options: limit
		$limit = array_key_exists('limit', $options) ? (int) $limit : null;

		if (!is_null($limit) && (int) $limit > 0) {
			$select->limit($limit);
		}

		$stmt = $this->sql->prepareStatementForSqlObject($select);
		$result = $stmt->execute();

		// Option: hydrate
		$hydrate = array_key_exists('hydrate', $options) ? (bool) $options['hydrate'] : true;

		if ($hydrate !== true) {
			return $result;
		}

		return $this->hydrateResult($result);
	}

	/**
	 * Find jobs(s) by its/their ID(s).
	 *
	 * @param integer|array $id
	 * @param array $options (Optional.)
	 * @return Result|HydratingResultSet|JobEntity|null
	 */
	public function fetchById($id, array $options = array())
	{
		$select = $this->sql->select();
		$where = new Where();

		if (is_array($id)) {
			if (count($id) == 0) {
				return null;
			}
			$where->in('id', $id);
		} else {
			$where->equalTo('id', $id);
		}

		$select->where($where);

		$stmt = $this->sql->prepareStatementForSqlObject($select);
		$result = $stmt->execute();

		// Options: hydrate
		$hydrate = array_key_exists('hydrate', $options) ? (bool) $options['hydrate'] : true;

		if (is_array($id)) {
			if ($hydrate !== true) {
				return $result;
			}

			return $this->hydrateResult($result);
		}

		if ($result->count() == 0) {
			return null;
		}

		if ($hydrate !== true) {
			return $result->current();
		}

		$hydrator = new ClassMethods();
		$entity = new JobEntity();
		$hydrator->hydrate($result->current(), $entity);

		return $entity;
	}

	/**
	 * Save job.
	 *
	 * @param JobEntity $job
	 * @return JobEntity
	 */
	public function save(JobEntity $job)
	{
		$query = null;

		if ((int) $job->getId() == 0) {
			$query = $this->sql->insert();
			$query->values($job->getArrayCopy());
		} else {
			$query = $this->sql->update();
			$query->set($job->getArrayCopy());
			$query->where(array('id' => $job->getId()));
		}

		$stmt = $this->sql->prepareStatementForSqlObject($query);
		$res = $stmt->execute();

		if ((int) $job->getId() == 0) {
			$job->setId((int) $res->getGeneratedValue());
		}

		return $job;
	}

	/**
	 * Delete jobs.
	 *
	 * @param Where|string|null $where
	 * @param array $options (Optional.)
	 * @return Result
	 */
	public function deleteByWhere($where = null, array $options = array())
	{
		$delete = $this->sql->delete();

		if ($where instanceof Where) {
			$delete->where($where);
		} elseif (is_string($where) && !empty($where)) {
			$delete->where($where);
		}

		$delete->where($where);

		// Options: limit
		$limit = array_key_exists('limit', $options) ? (int) $limit : null;

		if (!is_null($limit) && (int) $limit > 0) {
			$delete->limit($limit);
		}

		$stmt = $this->sql->prepareStatementForSqlObject($delete);

		return $stmt->execute();
	}

	/**
	 * Delete jobs(s) by its/their ID(s).
	 *
	 * @param integer|array $id
	 * @return Result|HydratingResultSet|JobEntity|null
	 */
	public function deleteById($id)
	{
		$where = new Where();

		if (is_array($id)) {
			if (count($id) == 0) {
				return null;
			}
			$where->in('id', $id);
		} else {
			$where->equalTo('id', $id);
		}

		return $this->fetchByWhere($where);
	}

    /**
     * Get pending cron jobs.
     *
	 * @param array $options (Optional.)
     * @return HydratingResultSet
     */
    public function getPending(array $options = array())
	{
		$where = new Where();
		$where->equalTo("{$this->tableName}.status", JobEntity::STATUS_PENDING);

		return $this->fetchByWhere($where, $options);
	}

    /**
     * Get running cron jobs.
     *
	 * @param array $options (Optional.)
     * @return HydratingResultSet
     */
    public function getRunning(array $options = array())
	{
		$where = new Where();
		$where->equalTo("{$this->tableName}.status", JobEntity::STATUS_RUNNING);

		return $this->fetchByWhere($where, $options);
	}

    /**
     * Get completed cron jobs (not pending or runnig).
     *
	 * @param array $options (Optional.)
	 * @return HydratingResultSet
     */
    public function getHistory(array $options = array())
	{
		$where = new Where();
		$where->notIn(
			"{$this->tableName}.status",
			array(JobEntity::STATUS_PENDING, JobEntity::STATUS_RUNNING)
		);

		return $this->fetchByWhere($where, $options);
	}
}


<?php
/**
 * LessServerCompiler class file.
 * @author Christoffer Niska <ChristofferNiska@gmail.com>
 * @copyright Copyright © Christoffer Niska 2013-
 * @copyright Copyright © Sam Stenvall 2013-
 * @license http://www.opensource.org/licenses/bsd-license.php New BSD License
 */

require_once 'LessCompiler.php';

/**
 * Server-side LESS compiler.
 */
class LessServerCompiler extends LessCompiler
{
	// Compression methods.
	const COMPRESSION_WHITESPACE = 'whitespace';
	const COMPRESSION_YUI = 'yui';

	/**
	 * @var string the base path.
	 */
	public $basePath;
	/**
	 * @var string absolute path to the nodejs executable.
	 */
	public $nodePath;
	/**
	 * @var string absolute path to the compiler.
	 */
	public $compilerPath = 'lessc';
	/**
	 * @var boolean whether to force evaluation of imports.
	 */
	public $strictImports = false;
	/**
	 * @var string|boolean compression type. Valid values are "whitespace" and "yui".
	 * Set to false to disable compression.
	 */
	public $compression = false;
	/**
	 * @var integer|boolean parser optimization level. Valid values are 0, 1 and 2.
	 * Set to false to disable optimization.
	 */
	public $optimizationLevel = false;
	/**
	 * @var boolean whether to always compile files, even if they have not changed.
	 */
	public $forceCompile = false;

	/**
	 * Initializes the component.
	 * @throws CException if initialization fails.
	 */
	public function init()
	{
		if (!isset($this->basePath))
			$this->basePath = Yii::getPathOfAlias('webroot');

		if ($this->compression !== false
				&& !in_array($this->compression, array(self::COMPRESSION_WHITESPACE, self::COMPRESSION_YUI)))
			throw new CException('Failed to initialize LESS compiler. Property compression must be either "whitespace" or "yui".');

		if ($this->optimizationLevel !== false && !in_array($this->optimizationLevel, array(0, 1, 2)))
			throw new CException('Failed to initialize LESS compiler. Property optimizationLevel must be 0, 1 or 2.');

		parent::init();
	}

	/**
	 * Runs the compiler.
	 * @throws CException if an error occurred.
	 */
	public function run()
	{
		foreach ($this->files as $lessFile => $cssFile)
		{
			$lessPath = realpath($this->basePath . DIRECTORY_SEPARATOR . $lessFile);
			$cssPath = str_replace('/', DIRECTORY_SEPARATOR, $this->basePath . DIRECTORY_SEPARATOR . $cssFile);

			if ($this->needsCompilation($lessPath, $cssPath))
			{
				if (!is_readable($lessPath))
				{
					$errorPath = ($lessPath === false)? ($this->basePath . DIRECTORY_SEPARATOR . $lessFile) : $lessPath;
					throw new CException('Failed to compile LESS. Source path must be readable: "'.$errorPath.'".');
				}

				$this->compileFile($lessPath, $cssPath);
			}
		}
	}

	/**
	 * Checks whether we need to recompile the specified LESS file.
	 * @param string $lessPath the path to the LESS file
	 * @param string $cssPath the path to the CSS file it's compiled to
	 * @return boolean whether we need to recompile it
	 */
	private function needsCompilation($lessPath, $cssPath)
	{
		/**
		 * Checks whether $subject has been modified since $reference was
		 */
		$isNewer = function($subject, $reference) {
			return filemtime($subject) > filemtime($reference);
		};

		// Check for obvious cases
		if ($this->forceCompile || !file_exists($lessPath)
				|| !file_exists($cssPath) || $isNewer($lessPath, $cssPath))
		{
			return true;
		}

		// Finally, check if any imported file has changed
		return $this->checkImports($lessPath, $cssPath, $isNewer);
	}

	/**
	 * Checks for import statements in the specified LESS file and checks each
	 * of them and their imports recursively for changes since the specified
	 * CSS file was changed. The checking is done by the passed callback.
	 * @staticvar boolean $needsRecompile needed to keep track of when we
	 * should break out of the recursion
	 * @param string $lessPath the LESS file
	 * @param string $cssPath the CSS file
	 * @param mixed $callback the function that will check if recompilation is
	 * needed
	 * @return boolean whether the LESS needs to be recompiled
	 */
	private function checkImports($lessPath, $cssPath, $callback)
	{
		static $needsRecompile = false;

		if ($needsRecompile)
			return $needsRecompile;

		$lessContent = file_get_contents($lessPath);
		preg_match_all('/(?<=@import)\s+"([^"]+)/im', $lessContent, $imports);

		foreach ($imports[1] as $import)
		{
			$importPath = realpath(dirname($lessPath).DIRECTORY_SEPARATOR.$import);

			if (file_exists($importPath))
			{
				if ($callback($importPath, $cssPath))
				{
					$needsRecompile = true;
					break;
				}
				else
					$needsRecompile = $this->checkImports($importPath, $cssPath, $callback);
			}
		}

		return $needsRecompile;
	}

	/**
	 * Compiles the given LESS file into the given CSS.
	 * @param string $lessPath path to the less file.
	 * @param string $cssPath path to the css file.
	 * @throws CException if the compilation fails.
	 */
	protected function compileFile($lessPath, $cssPath)
	{
		$options = array();

		if ($this->strictImports === true)
			$options[] = '--strict-imports';

		if ($this->compression === self::COMPRESSION_WHITESPACE)
			$options[] = '--compress';
		else if ($this->compression === self::COMPRESSION_YUI)
			$options[] = '--yui-compress';

		if ($this->optimizationLevel !== false)
			$options[] = '-O' . $this->optimizationLevel;

		if (isset($this->rootPath))
			$options[] = '--rootpath ' . $this->rootPath;

		if ($this->relativeUrls === true)
			$options[] = '--relative-urls';

		// 2>&1 at the end redirects STDERR (where error's appear) to STDOUT
		// (which is returned by shell_exec())
		$nodePath = $this->nodePath? '"' . $this->nodePath . '" ' : '';
		$command = $nodePath . '"' . $this->compilerPath . '" '
			. implode(' ', $options) . ' "' . $lessPath . '" "' . $cssPath . '" 2>&1';

		$return = 0;
		$output = array();
		@exec($command, $output, $return);

		switch ($return)
		{
			case 2:
			case 1:
				// Replace shell color codes in the output
				$output = preg_replace('/\[[0-9]+m/i', '', implode("\n", $output));

				throw new CException(
					'Failed to compile file "' . $lessPath . '" using command: ' . $command . '. The error was: ' . $output);
		}
	}
}


<?php
/**
 * zf2-cron-helper
 *
 * @link https://github.com/ondrejd/zf2-cron-helper for the canonical source repository
 * @copyright Copyright (c) 2015 Ondřej Doněk.
 * @license https://www.mozilla.org/MPL/2.0/ Mozilla Public License 2.0
 */

namespace CronHelper\Model;

use Zend\Db\Adapter\AdapterInterface;
use Zend\Db\Sql\Ddl;
use Zend\Db\Sql\Ddl\Column;
use Zend\Db\Sql\Ddl\Constraint;
use Zend\Db\Sql\Sql;

/**
 * Class for creating/dropping/truncating job table.
 *
 * @package CronHelper
 * @subpackage Model
 * @author Ondřej Doněk <ondrejd@gmail.com>
 */
class JobTable implements JobTableInterface
{
	/**
	 * @var string
	 */
	const TABLE_NAME = 'cron_helper_job';

	/**
	 * @var AdapterInterface $dbAdapter
	 */
	protected $dbAdapter;

	/**
	 * Constructor.
	 *
	 * @param AdapterInterface $dbAdapter
	 * @param string $tableName (Optional.)
	 * @return void
	 */
	public function __construct(AdapterInterface $dbAdapter)
	{
		$this->dbAdapter = $dbAdapter;
	}

	/**
	 * Create database table.
	 *
	 * @return void
	 */
	public function create()
	{
		$adapter = $this->dbAdapter;

		$ddl = new Ddl\CreateTable();
		$ddl->setTable(self::TABLE_NAME)
			->addColumn(new Column\Integer('id', false, null, array('autoincrement' => true)))
			->addColumn(new Column\Varchar('code', 55))
			->addColumn(new Column\Varchar('status', 55))
			->addColumn(new Column\Text('error_msg'))
			->addColumn(new Column\Text('stack_trace'))
			->addColumn(new Column\Varchar('created', 255))
			->addColumn(new Column\Varchar('scheduled', 255))
			->addColumn(new Column\Varchar('executed', 255))
			->addColumn(new Column\Varchar('finished', 255))
			->addConstraint(new Constraint\PrimaryKey('id'));

		$sql = (new Sql($adapter))->getSqlStringForSqlObject($ddl);

		$adapter->query($sql, $adapter::QUERY_MODE_EXECUTE);
	}

	/**
	 * Drop database table.
	 *
	 * @return void
	 */
	public function drop()
	{
		$adapter = $this->dbAdapter;

		$ddl = new Ddl\DropTable(self::TABLE_NAME);
		$sql = (new Sql($adapter))->getSqlStringForSqlObject($ddl);

		$adapter->query($sql, $adapter::QUERY_MODE_EXECUTE);
	}

	/**
	 * Truncate database table.
	 *
	 * @return void
	 */
	public function truncate()
	{
		$adapter = $this->dbAdapter;

		$mapper = new \CronHelper\Model\JobMapper($adapter);
		$where = new \Zend\Db\Sql\Where();

		$mapper->deleteByWhere($where);
	}
}


<?php
/**
 * zf2-cron-helper
 *
 * @link https://github.com/ondrejd/zf2-cron-helper for the canonical source repository
 * @copyright Copyright (c) 2015 Ondřej Doněk.
 * @license https://www.mozilla.org/MPL/2.0/ Mozilla Public License 2.0
 */

namespace CronHelper\Model;

/**
 * Entity that represents job entity.
 *
 * @package CronHelper
 * @subpackage Model
 * @author Ondřej Doněk <ondrejd@gmail.com>
 */
class JobEntity
{
	/**
	 * @var string
	 */
	const STATUS_PENDING = 'pending';

	/**
	 * @var string
	 */
	const STATUS_RUNNING = 'running';

	/**
	 * @var string
	 */
	const STATUS_SUCCESS = 'success';

	/**
	 * @var string
	 */
	const STATUS_MISSED = 'missed';

	/**
	 * @var string
	 */
	const STATUS_ERROR = 'error';

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

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

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

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

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

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

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

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

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

	/**
	 * @param array $data (Optional). Data to set.
	 * @return void
	 */
	public function __construct($data = array())
	{
		$this->exchangeArray($data);
	}

	/**
	 * @param array $data (Optional). Data to set.
	 * @return void
	 */
	public function exchangeArray($data = array())
	{
		$this->setId(array_key_exists('id', $data) ? $data['id'] : null);
		$this->setCode(array_key_exists('code', $data) ? $data['code'] : null);
		$this->setStatus(array_key_exists('status', $data) ? $data['status'] : null);
		$this->setErrorMsg(array_key_exists('error_msg', $data) ? $data['error_msg'] : null);
		$this->setStackTrace(array_key_exists('stack_trace', $data) ? $data['stack_trace'] : null);
		$this->setCreated(array_key_exists('created', $data) ? $data['created'] : null);
		$this->setScheduled(array_key_exists('scheduled', $data) ? $data['scheduled'] : null);
		$this->setExecuted(array_key_exists('executed', $data) ? $data['executed'] : null);
		$this->setFinished(array_key_exists('finished', $data) ? $data['finished'] : null);
	}

	/**
	 * @return array Returns array with entity's data.
	 */
	public function getArrayCopy()
	{
		return array(
			'id' => $this->getId(),
			'code' => $this->getCode(),
			'status' => $this->getStatus(),
			'error_msg' => $this->getErrorMsg(),
			'stack_trace' => $this->getStackTrace(),
			'created' => $this->getCreated(),
			'scheduled' => $this->getScheduled(),
			'executed' => $this->getExecuted(),
			'finished' => $this->getFinished(),
		);
	}

	/**
	 * @param integer $val
	 * @return JobEntity
	 */
	public function setId($val)
	{
		$this->id = is_numeric($val) ? (int) $val : null;
		return $this;
	}

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

	/**
	 * @param string $val
	 * @return JobEntity
	 */
	public function setCode($val)
	{
		$this->code = is_string($val) ? $val : null;
		return $this;
	}

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

	/**
	 * @param string|null $val
	 * @return JobEntity
	 * @throws \InvalidArgumentException Whenever bad status given.
	 */
	public function setStatus($val)
	{
		$status = is_string($val) ? $val : null;

		switch ($status) {
			case self::STATUS_PENDING:
			case self::STATUS_RUNNING:
			case self::STATUS_SUCCESS:
			case self::STATUS_MISSED:
			case self::STATUS_ERROR:
			case null:
				$this->status = $status;
				return $this;
		}

		throw new \InvalidArgumentException('Bad status given!');
	}

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

	/**
	 * @param string $val
	 * @return JobEntity
	 */
	public function setErrorMsg($val)
	{
		$this->errorMsg = is_string($val) ? $val : null;
		return $this;
	}

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

	/**
	 * @param string $val
	 * @return JobEntity
	 */
	public function setStackTrace($val)
	{
		$this->stackTrace = is_string($val) ? $val : null;
		return $this;
	}

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

	/**
	 * @param string $val
	 * @return JobEntity
	 */
	public function setCreated($val)
	{
		$this->created = is_string($val) ? $val : null;
		return $this;
	}

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

	/**
	 * @param string $val
	 * @return JobEntity
	 */
	public function setScheduled($val)
	{
		$this->scheduled = is_string($val) ? $val : null;
		return $this;
	}

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

	/**
	 * @param string $val
	 * @return JobEntity
	 */
	public function setExecuted($val)
	{
		$this->executed = is_string($val) ? $val : null;
		return $this;
	}

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

	/**
	 * @param string $val
	 * @return JobEntity
	 */
	public function setFinished($val)
	{
		$this->finished = is_string($val) ? $val : null;
		return $this;
	}

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

	/**
	 * Returns duration of the job's execution.
	 *
	 * @return integer Time in seconds.
	 * @todo Implement this!
	 */
	public function getDuration()
	{
		$executed = $this->getExecuted();
		$finished = $this->getFinished();

		if (is_null($executed) || is_null($finished)) {
			return 0;
		}

		return strtotime($finished) - strtotime($executed);
	}
}


<?php

namespace Germanazo\CkanApi\Repositories;

class RevisionRepository extends BaseRepository
{
    protected $action_name = 'revision';

    /**
     * @param array $data
     * @link http://docs.ckan.org/en/latest/api/#ckan.logic.action.get.revision_list
     *
     * @return array
     */
    public function all($data)
    {
        $defaults = [];

        $data = array_merge($defaults, $data);

        return parent::list($data);
    }
}


<?php

/*
 * This file is part of the ONGR package.
 *
 * (c) NFQ Technologies UAB <info@nfq.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace ONGR\ApiBundle\Controller;

use Elasticsearch\Common\Exceptions\NoDocumentsToGetException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * CRUD implementation for Api Controller.
 */
class RestController extends AbstractRestController implements RestControllerInterface
{
    /**
     * {@inheritdoc}
     */
    public function getAction(Request $request, $documentId)
    {
        $repository = $this->getRequestRepository($request);

        try {
            $document = $this->getCrudService()->read($repository, $documentId);

            if ($document === null) {
                return $this->renderError($request, 'Document does not exist', Response::HTTP_NOT_FOUND);
            }
        } catch (\Exception $e) {
            return $this->renderError($request, $e->getMessage(), Response::HTTP_BAD_REQUEST);
        }

        return $this->renderRest($request, $document, Response::HTTP_OK);
    }

    /**
     * {@inheritdoc}
     */
    public function postAction(Request $request, $documentId = null)
    {
        $repository = $this->getRequestRepository($request);
        $data = $this->get('ongr_api.request_serializer')->deserializeRequest($request);

        $validation = $this->get('ongr_api.field_validator')
            ->validateFields(
                $request,
                $repository,
                $data
            );

        if (isset($validation['message'])) {
            return $this->renderError(
                $request,
                $validation['message'],
                Response::HTTP_NOT_ACCEPTABLE
            );
        }
        if (!empty($documentId)) {
            $data['_id'] = $documentId;
        }

        try {
            $this->getCrudService()->create($repository, $data);
            $response = $this->getCrudService()->commit($repository);
        } catch (\RuntimeException $e) {
            return $this->renderError($request, $e->getMessage(), Response::HTTP_CONFLICT);
        } catch (\Exception $e) {
            return $this->renderError($request, $e->getMessage(), Response::HTTP_BAD_REQUEST);
        }

        $documentId = $response['items'][0]['create']['_id'];
        $row = $this->getCrudService()->read($repository, $documentId);
        return $this->renderRest($request, $row, Response::HTTP_CREATED);
    }

    /**
     * {@inheritdoc}
     */
    public function putAction(Request $request, $documentId)
    {
        $repository = $this->getRequestRepository($request);
        $data = $this->get('ongr_api.request_serializer')->deserializeRequest($request);

        $validation = $this->get('ongr_api.field_validator')
            ->validateFields(
                $request,
                $repository,
                $data
            );

        if (isset($validation['message'])) {
            return $this->renderError(
                $request,
                $validation['message'],
                Response::HTTP_NOT_ACCEPTABLE
            );
        }

        try {
            $this->getCrudService()->update($repository, $documentId, $data);
            $response = $this->getCrudService()->commit($repository);
        } catch (\RuntimeException $e) {
            return $this->renderError($request, $e->getMessage(), Response::HTTP_BAD_REQUEST);
        } catch (NoDocumentsToGetException $e) {
            return $this->renderError($request, $e->getMessage(), Response::HTTP_NOT_FOUND);
        } catch (\Exception $e) {
            return $this->renderError($request, $e->getMessage(), Response::HTTP_BAD_REQUEST);
        }

        $documentId = $response['items'][0]['update']['_id'];
        $row = $this->getCrudService()->read($repository, $documentId);

        return $this->renderRest($request, $row, Response::HTTP_NO_CONTENT);
    }

    /**
     * {@inheritdoc}
     */
    public function deleteAction(Request $request, $documentId)
    {
        $repository = $this->getRequestRepository($request);

        try {
            $this->getCrudService()->delete($repository, $documentId);
            $response = $this->getCrudService()->commit($repository);
        } catch (\RuntimeException $e) {
            return $this->renderError($request, $e->getMessage(), Response::HTTP_BAD_REQUEST); // Missing _id
        } catch (NoDocumentsToGetException $e) {
            return $this->renderError($request, $e->getMessage(), Response::HTTP_NOT_FOUND);
        } catch (\Exception $e) {
            return $this->renderError($request, $e->getMessage(), Response::HTTP_BAD_REQUEST);
        }

        return $this->renderRest($request, $response, Response::HTTP_NO_CONTENT);
    }
}


<?php

/**
 * Contao Open Source CMS, Copyright (C) 2005-2017 Leo Feyer
 *
 * @copyright  Glen Langer 2012..2017 <http://contao.ninja>
 * @author     Glen Langer (BugBuster)
 * @package    contao-grid_16-bundle
 * @license    LGPL
 * @filesource
 * @see        https://github.com/BugBuster1701/contao-grid_16-bundle
 */

/**
 * Run in a custom namespace, so the class can be replaced
 */
namespace BugBuster\Grid1140;

/**
 * Class Grid16Layout for Hook getPageLayout
 *
 * @author     Glen Langer (BugBuster)
 */
class Grid16Layout extends \PageRegular
{

    /**
     * Hook loadDataContainer, add Grid16 CSS
     *
     * @param PageModel   $objPage
	 * @param LayoutModel $objLayout
	 * @param PageRegular $objPageRegular
     */
    public function addGrid16CSS(\PageModel $objPage, \LayoutModel $objLayout, \PageRegular $objPageRegular)
    {
        /*
         * vor internen laden
         * $GLOBALS['TL_CSS'][]  = 'assets/contao-grid16/css/grid-1120-16-pixel.min.css';
         * nach den anderen
         * $GLOBALS['TL_HEAD'][] = '<link ...>';
         */

        $arrFrameworkGrid16 = \StringUtil::deserialize($objLayout->frameworkGrid16);

        // Add the Grid16 CSS framework style sheets
        if (is_array($arrFrameworkGrid16))
        {
            foreach ($arrFrameworkGrid16 as $strFile)
            {
                if ($objLayout->loadingOrderGrid16 == 'before_framework')
                {
                    $GLOBALS['TL_CSS'][] = 'bundles/bugbustergrid16/' . basename($strFile, '.css') . '.min.css';
                }
                else
                {
                    $GLOBALS['TL_HEAD'][] = '<link rel="stylesheet" href="bundles/bugbustergrid16/' . basename($strFile, '.css') . '.min.css">';
                }

            }
        }

        return;
    }

}


<?php

/*
 * This file is part of the ONGR package.
 *
 * (c) NFQ Technologies UAB <info@nfq.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace ONGR\ApiBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\NodeDefinition;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
use Symfony\Component\HttpFoundation\Request;

/**
 * Validates and merges configuration from your app/config files.
 */
class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritdoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('ongr_api');

        $rootNode
            ->children()
                ->arrayNode('versions')
                    ->info('Defines api versions.')
                    ->useAttributeAsKey('version')
                    ->prototype('array')
                    ->children()
                        ->scalarNode('versions')
                            ->info('Defines a version for current api endpoints.')
                            ->example('v1')
                            ->end()
                        ->append($this->getEndpointNode())
                        ->end()
                ->end()
            ->end();

        return $treeBuilder;
    }

    /**
     * Builds configuration tree for endpoints.
     *
     * @return NodeDefinition
     */
    public function getEndpointNode()
    {
        $builder = new TreeBuilder();
        $node = $builder->root('endpoints');

        $node
            ->info('Defines version endpoints.')
            ->useAttributeAsKey('endpoint')
            ->prototype('array')
                ->children()

                    ->scalarNode('endpoint')
                        ->info('Endpoint name (will be included in url (e.g. products))')
                        ->example('products')
                    ->end()

                    ->scalarNode('repository')
                        ->isRequired()
                        ->info('Document service from Elasticsearch bundle which will be used for data fetching')
                        ->example('es.manager.default.products')
                    ->end()

                    ->arrayNode('methods')
                        ->defaultValue(
                            [
                                Request::METHOD_POST,
                                Request::METHOD_GET,
                                Request::METHOD_PUT,
                                Request::METHOD_DELETE
                            ]
                        )
                        ->prototype('scalar')
                        ->validate()
                            ->ifNotInArray(
                                [
                                    Request::METHOD_HEAD,
                                    Request::METHOD_POST,
                                    Request::METHOD_PATCH,
                                    Request::METHOD_GET,
                                    Request::METHOD_PUT,
                                    Request::METHOD_DELETE
                                ]
                            )
                            ->thenInvalid(
                                'Invalid HTTP method used! Please check your ongr_api endpoint configuration.'
                            )
                            ->end()
                        ->end()
                    ->end()

                    ->booleanNode('allow_extra_fields')
                        ->defaultFalse()
                        ->info(
                            'Allows to pass unknown fields to an api. '.
                            'Make sure you have configured elasticsearch respectively.'
                        )
                    ->end()

                    ->arrayNode('allow_fields')
                        ->defaultValue([])
                        ->info('A list off a allowed fields to operate through api for a document.')
                        ->prototype('scalar')->end()
                    ->end()

                    ->booleanNode('allow_get_all')
                    ->defaultTrue()
                    ->info(
                        'Allows to use `_all` elasticsearch api to get all documents from a type.'
                    )
                    ->end()

                    ->booleanNode('allow_batch')
                    ->defaultTrue()
                    ->info(
                        'Allows to use `_batch` elasticsearch api to pass multiple documents in single API request.'
                    )
                    ->end()

                    ->booleanNode('variants')
                    ->defaultFalse()
                    ->info(
                        'If set to true user can manipulate document variants over API.'
                    )
                    ->end()

                    ->booleanNode('batch')
                    ->defaultTrue()
                    ->info(
                        'If set to true user can sent documents in batch\'s.'
                    )
                    ->end()

                ->end()
            ->end();

        return $node;
    }
}


<?php
/**
 * LessClientCompiler class file.
 * @author Christoffer Niska <ChristofferNiska@gmail.com>
 * @copyright Copyright © Christoffer Niska 2013-
 * @license http://www.opensource.org/licenses/bsd-license.php New BSD License
 */

require_once 'LessCompiler.php';

/**
 * Client-side LESS compiler.
 */
class LessClientCompiler extends LessCompiler
{
	// Compiling environments.
	const ENV_DEVELOPMENT = 'development';
	const ENV_PRODUCTION = 'production';

	// Dump line numbers options.
	const DLN_COMMENTS = 'comments';
	const DLN_MEDIAQUERY = 'mediaQuery';
	const DLN_ALL = 'all';

	/**
	 * @var string compiler environment. Valid values are "development" and "production" (defaults to "production").
	 */
	public $env = self::ENV_PRODUCTION;
	/**
	 * @var boolean whether to load imports asynchronous.
	 */
	public $async = false;
	/**
	 * @var boolean whether to load imports asynchronous when in a page under a file protocol.
	 */
	public $fileAsync = false;
	/**
	 * @var integer when in match mode, time in ms between polls (defaults to 1000).
	 */
	public $poll = 1000;
	/**
	 * @var string whether to dump line numbers. Valid values are "comments", "mediaQuery" and "all".
	 */
	public $dumpLineNumbers;
	/**
	 * @var boolean whether the watch mode should be enabled.
	 */
	public $watch = false;
	/**
	 * @var boolean whether assets should be republished on every request.
	 */
	public $forceCopyAssets = false;

	private $_assetsUrl;

	/**
	 * Initializes the component.
	 * @throws CException if initialization fails.
	 */
	public function init()
	{
		if (!in_array($this->env, array(self::ENV_DEVELOPMENT, self::ENV_PRODUCTION)))
			throw new CException('Failed to initialize LESS compiler. Property env must be either "development" or "production".');

		if (isset($this->dumpLineNumbers)
				&& !in_array($this->dumpLineNumbers, array(self::DLN_COMMENTS, self::DLN_MEDIAQUERY, self::DLN_ALL)))
			throw new CException('Failed to initialize LESS compiler. Property dumpLineNumber must be "comments", "mediaQuery" or "all".');

		parent::init();
	}

	/**
	 * Runs the compiler.
	 * @throws CException if an error occurred.
	 */
	public function run()
	{
		$settings = array(
			'env' => $this->env,
			'async' => $this->async,
			'fileAsync' => $this->fileAsync,
			'poll' => $this->poll,
			'relativeUrls' => $this->relativeUrls,
			'rootpath' => $this->rootPath,
		);

		$app = Yii::app();
		/* @var $cs CClientScript */
		$cs = $app->getClientScript();
		foreach (array_keys($this->files) as $lessFile)
			$cs->registerLinkTag('stylesheet/less', 'text/css', $app->baseUrl . '/' . $lessFile);
		$cs->registerScript(__CLASS__ . '.settings', 'less = ' . CJSON::encode($settings) . ';', CClientScript::POS_HEAD);
		$cs->registerScriptFile($this->getAssetsUrl().'/less.min.js', CClientScript::POS_END);

		if ($this->watch)
			$cs->registerScript(__CLASS__ . '.watch', 'less.watch();', CClientScript::POS_END);
	}

	/**
	 * Returns the URL to the published assets folder.
	 * @return string the URL
	 */
	protected function getAssetsUrl()
	{
		if (!isset($this->_assetsUrl))
		{
			$path = dirname(__FILE__) . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'assets';
			$this->_assetsUrl = Yii::app()->assetManager->publish($path, false, -1, $this->forceCopyAssets);
		}

		return $this->_assetsUrl;
	}
}


<?php

namespace ShawnSandy\Dash;

use App\User;
use Html;
use Illuminate\Support\ServiceProvider;
use ShawnSandy\Bluelines\App\Blueline;
use ShawnSandy\Dash\Builder\GenerateFields;
use ShawnSandy\Dash\Builder\GenerateFormFieldsFacade;
use ShawnSandy\Dash\Builder\GenerateFormsFields;

/**
 * Class Provider
 *
 * @package ShawnSandy\PkgStart
 */
class DashServicesProvider extends ServiceProvider
{
    /**
     * Perform post-registration booting of services.
     *
     * @return void
     */
    public function boot()
    {

        /**
         * Package views
         */
        $this->loadViewsFrom(__DIR__ . '/resources/views', 'dash');
        $this->publishes(
            [
                __DIR__ . '/resources/views' => resource_path('views/vendor/dash'),
            ],
            'dash-views'
        );

        $this->publishes(
            [
                __DIR__ . '/resources/views' => resource_path('views/theme/dash'),
            ],
            'dash-theme'
        );

        /**
         * Package assets
         */
        $this->publishes(
            [
                __DIR__ . '/resources/assets/js/' => public_path('assets/dash/js/'),
                __DIR__ . '/public/css/pagekit/sass/' => public_path('assets/dash/css/'),
                __DIR__ . '/resources/assets/sass/' => public_path('assets/dash/css/'),
            ],
            'dash-assets'
        );

        /**
         * Package config
         */
        $this->publishes(
            [__DIR__ . '/config/config.php' => config_path('dash.php')],
            'dash-config'
        );

        if (!$this->app->runningInConsole()) :
            include_once __DIR__ . '/Helpers/helper.php';
        endif;

        include_once __DIR__ . "/components/html-components.php";
        include_once __DIR__ . "/components/form-components.php";

        $this->themeDefaults();

       view()->composer("dash::index", function ($view) {
            $user_count = User::count();
            $post_count = Blueline::count();
            $view->with(compact("user_count", "post_count"));
        });

    }

    /**
     * Register any package services.
     *
     * @return void
     */
    public function register()
    {

        $this->mergeConfigFrom(
            __DIR__ . '/config/config.php',
            'dash'
        );

        $this->app->bind('Dash', function () {
            return new Dash();
        });

        $this->app->bind('DashForms', function () {
            return new GenerateFormsFields();
        });

        $this->app->bind(GenerateFormFieldsFacade::class, function () {
            return new GenerateFields();
        });

    }

    /**
     * get the default theme
     */
    public function themeDefaults()
    {

        view()->composer("*", function ($view) {
            /* get the theme if set in config */
            $theme = config("dash.theme", null);
            /* if not theme is set in the config */
            /* check the theme folder if exist or use the theme in package*/
            if (!$theme):
                if (view()->exists("theme.dash.index")):
                    $theme = "theme.dash.";
                else :
                    $theme = "dash::";
                endif;
            endif;
            view()->share('dashTheme', $theme);

        });

    }

}


<?php
/**
 * Created by PhpStorm.
 * User: Shawn
 * Date: 3/11/2017
 * Time: 5:16 PM
 */

namespace ShawnSandy\Dash\Builder;

use App\User;
use Collective\Html\FormBuilder;
use Schema;

class GenerateFormsFields
{

    protected $fieldAttributes;

    protected $forms;

    public function __construct()
    {
        $this->fieldAttributes();
        $this->forms = app(FormFields::class);
    }

    public function buildModelFields($model_path)
    {

        $model = app($model_path);
        $table = $model->getTable();
        $fields = collect($this->renderModelFields($model_path))->map(function ($type, $name) use ($table) {
            return $this->render(
                config("forms.$table.field_types." . $name, $type),
                [
                    $name,
                    config("forms.$table.labels." . $name, $name),
                    ["data-table" => $table],
                ]
            );
        });

        return $fields;
    }

    public function buildTableFields($table)
    {

        $fields = collect($this->renderTableFields($table))->map(function ($type, $name) use ($table) {
            return $this->render(
                config("forms.$table.field_types." . $name, $type),
                [
                    $name,
                    config("forms.$table.labels." . $name, $name),
                    ['data-table' => $table]
                ]
            );
        });

        return $fields;
    }

    /**
     * Build fields from array
     *
     * @param array $form_fields [field_name => [label => Text field, type => password ]
     * @param string $config_name
     * @return mixed
     */
    public function buildCustomFields($form_fields = [], $config_name = 'custom_form')
    {
        $fields = collect($form_fields)->map(function ($field, $name) use ($config_name) {
            return $this->render(
                isset($field['type']) ? $field['type'] : 'text',
                [
                    $name,
                    $field['label'],
                    ['data-table' => $config_name]
                ]
            );

        });

        return $fields ;

    }

    /**
     * @param       $field
     * @param array $array
     * @return mixed
     */
    public function render($field, $array = [])
    {
        return $this->forms->render($field, $array);
    }

    /**
     * @param $table_name
     * @return static
     */
    public function renderTableFields($table_name)
    {

        $fields = $this->getColumnsFromTable($table_name);
        $results = $this->buildFields($fields);
        return $results;
    }

    public function renderModelFields($db_model)
    {
        $fields = $this->getColumnsFromModel($db_model);
        $results = $this->buildFields($fields);
        return $results;
    }

    /**
     * @param $fields
     * @return array|mixed|collections
     */
    public function buildFields($fields)
    {
        $results = collect($fields)->flatMap(function ($items, $key) {
            return [$key => $this->mapToFieldAttribute($items)];
        });

        return $results;
    }

    /**
     * @param $table_name
     * @return mixed
     */
    public function getColumnsFromTable($table_name)
    {
        $tables = Schema::getColumnListing($table_name);
        $fields = $this->mapColumnsToFieldType($tables, $table_name);

        return $fields;
    }

    public function getColumnsFromModel($model)
    {
        $column = app($model);
        $fields = $this->mapColumnsToFieldType($column->getFillable(), $column->getTable());

        return $fields;
    }

    /**
     * @param array $columns
     * @param       $table
     * @return mixed
     */
    public function mapColumnsToFieldType(array $columns, $table)
    {

        $fields = collect($columns)->flatMap(function ($item) use ($table) {
            return [$item => Schema::getColumnType($table, $item)];
        });

        return $fields;
    }

    public function mapToFieldAttribute($field)
    {
        $type = $this->fieldAttributes->search(function ($item) use ($field) {
            return in_array($field, $item);
        });

        if (!$type) :
            $type = $this->fieldAttributes->search(function ($item, $key) use ($field) {
                $array = explode("_", $key);

                return (in_array($field, $array));
            });
        endif;

        return $type ? $type : "text";
    }

    public function fieldAttributes()
    {
        $fields['text'] = ['string'];
        $fields['textarea'] = ['text'];
        $fields['richtext'] = ['blob', 'mediumtext', 'longtext', 'blob'];
        $fields['select'] = ['bool'];
        $fields['time'] = ["time"];
        $fields['date'] = ['date'];
        $fields['datetime'] = ['datetime', 'timestamp'];

        $this->fieldAttributes = collect($fields);

        return collect($fields);
    }

    public function setFieldAttributes(array $attributes)
    {
        $this->fieldAttributes = $attributes;

        return $this;
    }

    public function getFieldAttributes()
    {

        return $this->fieldAttributes;
    }
}


<?php

/*
 * This file is part of the ONGR package.
 *
 * (c) NFQ Technologies UAB <info@nfq.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace ONGR\ApiBundle\Service;

use Doctrine\Common\Proxy\Exception\InvalidArgumentException;
use ONGR\ElasticsearchBundle\Service\Manager;
use ONGR\ElasticsearchBundle\Service\Repository;
use Symfony\Component\HttpFoundation\Request;

/**
 * Service to handle requests and get responses from
 * Elasticsearch in BatchController
 */
class BatchRequestHandler
{
    /**
     * @var Crud
     */
    private $crud;

    /**
     * @var Manager
     */
    private $manager;

    /**
     * @var RequestSerializer
     */
    private $requestSerializer;

    /**
     * @param Crud              $crud
     * @param Manager           $manager
     * @param RequestSerializer $requestSerializer
     */
    public function __construct(
        Crud $crud,
        Manager $manager,
        RequestSerializer $requestSerializer
    ) {
        $this->crud = $crud;
        $this->manager = $manager;
        $this->requestSerializer = $requestSerializer;
    }

    /**
     * Handles the requests and returns the json for the response body
     * @param Request    $request
     * @param Repository $repository
     * @param string     $action
     *
     * @return string
     * @throws InvalidArgumentException
     */
    public function handleRequest(Request $request, Repository $repository, $action)
    {
        $commitSize = $this->manager->getBulkCommitSize();
        $documents = $this->requestSerializer->deserializeRequest($request);

        switch ($action) {
            case 'create':
                return $this->create($documents, $repository, $commitSize);
                break;
            case 'update':
                return $this->update($documents, $repository, $commitSize);
                break;
            case 'delete':
                return $this->delete($documents, $repository, $commitSize);
                break;
            default:
                throw new InvalidArgumentException(
                    'handleRequest method can only handle `create`, `update` and `delete` actions.'
                );
        }
    }
    /**
     * Handles create action
     *
     * @param array      $documents
     * @param Repository $repository
     * @param integer    $commitSize
     *
     * @return string
     */
    private function create($documents, $repository, $commitSize)
    {
        if (count($documents) > $commitSize && $commitSize > 1) {
            $esResponse = [];
            $i = 1;
            foreach ($documents as $document) {
                $this->crud->create($repository, $document);
                if ($i++ % ($commitSize - 1) == 0) {
                    $esResponse[] = $this->crud->commit($repository);
                }
            }
        } else {
            foreach ($documents as $document) {
                $this->crud->create($repository, $document);
            }
            $esResponse = $this->crud->commit($repository);
        }
        return json_encode($esResponse);
    }

    /**
     * Handles update action
     *
     * @param array      $documents
     * @param Repository $repository
     * @param integer    $commitSize
     *
     * @return string
     */
    private function update($documents, $repository, $commitSize)
    {
        if (count($documents) > $commitSize && $commitSize > 1) {
            $esResponse = [];
            $i = 1;
            foreach ($documents as $document) {
                $id = $document['_id'];
                unset($document['_id']);
                $this->crud->update($repository, $id, $document);
                if ($i++ % ($commitSize - 1) == 0) {
                    $esResponse[] = $this->crud->commit($repository);
                }
            }
        } else {
            foreach ($documents as $document) {
                $id = $document['_id'];
                unset($document['_id']);
                $this->crud->update($repository, $id, $document);
            }
            $esResponse = $this->crud->commit($repository);
        }
        return json_encode($esResponse);
    }

    /**
     * Handles delete action
     *
     * @param array      $documents
     * @param Repository $repository
     * @param integer    $commitSize
     *
     * @return string
     */
    private function delete($documents, $repository, $commitSize)
    {
        if (count($documents) > $commitSize && $commitSize > 1) {
            $esResponse = [];
            $i = 1;
            foreach ($documents as $document) {
                $this->crud->delete($repository, $document['_id']);
                if ($i++ % ($commitSize - 1) == 0) {
                    $esResponse[] = $this->crud->commit($repository);
                }
            }
        } else {
            foreach ($documents as $document) {
                $this->crud->delete($repository, $document['_id']);
            }
            $esResponse = $this->crud->commit($repository);
        }
        return json_encode($esResponse);
    }
}


<?php

namespace Germanazo\CkanApi\Repositories;

class OrganizationRepository extends BaseRepository
{
    protected $action_name = 'organization';

    /**
     * @param array $data
     * @link http://docs.ckan.org/en/latest/api/#ckan.logic.action.get.organization_list
     *
     * @return array
     */
    public function all($data)
    {
        $defaults = [
            'sort' => 'name asc',
            'limit' => $this->per_page,
            'offset' => 0,
            'all_fields' => true,
            'include_dataset_count' => true,
            'include_extras' => false,
            'include_tags' => false,
            'include_groups' => false,
            'include_users' => false,
        ];

        $data = array_merge($defaults, $data);

        return parent::list($data);
    }
}


<?php

namespace Germanazo\CkanApi\Repositories;

use GuzzleHttp\Exception\ClientException;

class ResourceRepository extends BaseRepository
{
    protected $action_name = 'resource';

    /**
     * Search for all resources
     * @param array $data
     * @link http://docs.ckan.org/en/latest/api/#ckan.logic.action.get.resource_search
     *
     * @return array
     */
    public function all($data = [])
    {
        $defaults = [
            'limit' => $this->per_page,
            'offset' => 0,
        ];

        $data = array_merge($defaults, $data);

        return parent::search($data);
    }

    /**
     * Create a new resource
     * @param array $data
     * @return array
     */
    public function create(array $data = [])
    {
        $this->setActionUri(__FUNCTION__);

        $response = $this->client->post($this->uri, [
            'multipart' => $this->dataToMultipart($data),
        ]);

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

    /**
     * Update a new resource
     * @param array $data
     * @return array
     */
    public function update(array $data = [])
    {
        $this->setActionUri(__FUNCTION__);

        $response = $this->client->post($this->uri, [
            'multipart' => $this->dataToMultipart($data),
        ]);

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


<?php

/*
 * This file is part of the ONGR package.
 *
 * (c) NFQ Technologies UAB <info@nfq.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace ONGR\ApiBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * Batch controller
 */
class BatchController extends AbstractRestController
{
    /**
     * Action to process create batch call.
     *
     * @param Request $request
     * @return Response
     */
    public function postAction(Request $request)
    {
        try {
            $data = $this->get('ongr_api.batch_request_handler')->handleRequest(
                $request,
                $repository = $this->getRequestRepository($request),
                'create'
            );
            return $this->renderRest($request, $data, Response::HTTP_OK);
        } catch (\Exception $e) {
            return $this->renderError($request, $e->getMessage(), Response::HTTP_BAD_REQUEST);
        }
    }

    /**
     * Action to process put batch call.
     *
     * @param Request $request
     * @return Response
     */
    public function putAction(Request $request)
    {
        try {
            $data = $this->get('ongr_api.batch_request_handler')->handleRequest(
                $request,
                $repository = $this->getRequestRepository($request),
                'update'
            );
            return $this->renderRest($request, $data, Response::HTTP_OK);
        } catch (\Exception $e) {
            return $this->renderError($request, $e->getMessage(), Response::HTTP_BAD_REQUEST);
        }
    }

    /**
     * Action to process delete batch call.
     *
     * @param Request $request
     * @return Response
     */
    public function deleteAction(Request $request)
    {
        try {
            $data = $this->get('ongr_api.batch_request_handler')->handleRequest(
                $request,
                $repository = $this->getRequestRepository($request),
                'delete'
            );
            return $this->renderRest($request, $data, Response::HTTP_OK);
        } catch (\Exception $e) {
            return $this->renderError($request, $e->getMessage(), Response::HTTP_BAD_REQUEST);
        }
    }
}


<?php
/**
 * zf2-cron-helper
 *
 * @link https://github.com/ondrejd/zf2-cron-helper for the canonical source repository
 * @copyright Copyright (c) 2015 Ondřej Doněk.
 * @license https://www.mozilla.org/MPL/2.0/ Mozilla Public License 2.0
 */

namespace CronHelper\Service;

use Zend\EventManager\EventManager;
use Zend\EventManager\EventManagerInterface;
use Zend\EventManager\EventManagerAwareInterface;
use Zend\ServiceManager\ServiceManager;
use Zend\ServiceManager\ServiceManagerAwareInterface;

/**
 * `CronHelper` service self.
 *
 * @package CronHelper
 * @subpackage Service
 * @author Ondřej Doněk <ondrejd@gmail.com>
 */
class CronService implements CronServiceInterface, ServiceManagerAwareInterface, EventManagerAwareInterface
{
    /**
     * @var array $options
     */
    protected $options;

    /**
    * @var EventManagerInterface $eventManager
    */
    protected $eventManager;

    /**
    * @var ServiceManager $serviceManager
    */
    protected $serviceManager;

    /**
     * Constructor.
     *
     * @param array $options
     * @return void
     */
    public function __construct(array $options = array())
    {
        $this->setOptions($options);
    }

    /**
     * @return EventManagerInterface
     */
    public function getEventManager()
    {
        if (!($this->eventManager instanceof EventManagerInterface)) {
            $this->setEventManager(new EventManager());
        }

        return $this->eventManager;
    }

    /**
     * @param EventManagerInterface $eventManager
     * @return CronService
     */
    public function setEventManager(EventManagerInterface $eventManager)
    {
        $eventManager->setIdentifiers(array(
            __CLASS__,
            get_called_class()
        ));

        $this->eventManager = $eventManager;
        return $this;
    }

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

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

    /**
     * Get default options.
     *
     * Options array (names of keys correspond with methods of this class
     * so look there for detailed description of a single option):
     *

     *
scheduleAhead integer time in minutes

     *
scheduleLifetime integer time in minutes

     *
maxRunningTime integer time in minutes

     *
successLogLifetime integer time in minutes

     *
failureLogLifetime integer time in minutes

     *
emitEvents boolean emit process events?

     *
allowJsonApi boolean allow JSON API?

     *
jsonApiSecurityHash string security hash for accessing JSON API

     *

     *
     * @return array
     */
    public function getDefaultOptions()
    {
        return array(
            'scheduleAhead' => 1440, // one day before
            'scheduleLifetime' => 15,
            'maxRunningTime' => 0,
            'successLogLifetime' => 1440, // one day
            'failureLogLifetime' => 2880, // two days
            'emitEvents' => false,/* @todo Should be TRUE */
            'allowJsonApi' => false,/* @todo Should be TRUE */
            'jsonApiSecurityHash' => 'SECURITY_HASH'
        );
    }

    /**
     * Get options.
     *
     * @return array
     * @see CronService::getDefaultOptions() There is a detailed options array description.
     */
    public function getOptions()
    {
        return $this->options;
    }

    /**
     * Set options.
     *
     * @param array $options
     * @return CronService
     * @see CronService::getDefaultOptions() There is a detailed options array description.
     */
    public function setOptions(array $options)
    {
        if (!array_key_exists('options', $options)) {
            $options['options'] = array();
        }

        $this->options = array_merge($this->getDefaultOptions(), $options['options']);
        return $this;
    }

    /**
     * Get time in minutes for how long ahead CRON jobs have to be scheduled.
     *
     * @return integer
     */
    public function getScheduleAhead()
    {
        return (int) $this->options['scheduleAhead'];
    }

    /**
     * Set time in minutes for how long ahead CRON jobs have to be scheduled.
     *.
     * @param integer $time
     * @return CronService
     */
    public function setScheduleAhead($time)
    {
        if (!is_numeric($time)) {
            throw new \InvalidArgumentException('`scheduleAhead` expects integer value!');
        }

        $this->options['scheduleAhead'] = (int) $time;
        return $this;
    }

    /**
     * Get time in minutes for how long it takes before the scheduled job
     * is considered missed.
     *
     * @return integer
     */
    public function getScheduleLifetime()
    {
        return (int) $this->options['scheduleLifetime'];
    }

    /**
     * Set time in minutes for how long it takes before the scheduled job
     * is considered missed.
     *
     * @param integer $time
     * @return CronService
     */
    public function setScheduleLifetime($time)
    {
        if (!is_numeric($time)) {
            throw new \InvalidArgumentException('`scheduleLifetime` expects integer value!');
        }

        $this->options['scheduleLifetime'] = (int) $time;
        return $this;
    }

    /**
     * Get maximal running time (in minutes) for the each CRON job.
     *
     * If 0 than no maximal limit is set or the system is used.
     *
     * @return integer
     */
    public function getMaxRunningTime()
    {
        return (int) $this->options['maxRunningTime'];
    }

    /**
     * Set maximal running time (in minutes) for the each CRON job.
     *
     * If 0 than no maximal limit is set or the system is used.
     *
     * @param integer $time
     * @return CronService
     */
    public function setMaxRunningTime($time)
    {
        if (!is_numeric($time)) {
            throw new \InvalidArgumentException('`maxRunningTime` expects integer value!');
        }

        $this->options['maxRunningTime'] = (int) $time;
        return $this;
    }

    /**
     * Get time in minutes for how long to keep records about successfully
     * completed CRON jobs.
     *
     * @return integer
     */
    public function getSuccessLogLifetime()
    {
        return (int) $this->options['successLogLifetime'];
    }

    /**
     * Set time in minutes for how long to keep records about successfully
     * completed CRON jobs.
     *
     * @param integer $time
     * @return CronService
     */
    public function setSuccessLogLifetime($time)
    {
        if (!is_numeric($time)) {
            throw new \InvalidArgumentException('`successLogLifetime` expects integer value!');
        }

        $this->options['successLogLifetime'] = (int) $time;
        return $this;
    }

    /**
     * Get time in minutes for how long to keep records about failed CRON jobs.
     *
     * @return integer
     */
    public function getFailureLogLifetime()
    {
        return (int) $this->options['failureLogLifetime'];
    }

    /**
     * Set time in minutes for how long to keep records about failed CRON jobs.
     *
     * @param integer $time
     * @return CronService
     * @throws \InvalidArgumentException Whenever `$time` is not a numeric value.
     */
    public function setFailureLogLifetime($time)
    {
        if (!is_numeric($time)) {
            throw new \InvalidArgumentException('`failureLogLifetime` expects integer value!');
        }

        $this->options['failureLogLifetime'] = (int) $time;
        return $this;
    }

    /**
     * Get TRUE if events are emitted during job processing.
     *
     * @return boolean
     */
    public function getEmitEvents()
    {
        return (bool) $this->options['emitEvents'];
    }

    /**
     * Set TRUE if events are emitted during job processing.
     *
     * @param boolean $emitEvents
     * @return CronService
     * @throws \InvalidArgumentException Whenever `$emitEvents` is not a boolean value.
     */
    public function setEmitEvents($emitEvents)
    {
        if (!is_bool($emitEvents)) {
            throw new \InvalidArgumentException('`emitEvents` expects boolean value!');
        }

        $this->options['emitEvents'] = (bool) $emitEvents;
        return $this;
    }

    /**
     * Get TRUE if JSON API is allowed.
     *
     * @return boolean
     */
    public function getAllowJsonApi()
    {
        return (bool) $this->options['allowJsonApi'];
    }

    /**
     * Set TRUE if JSON API is allowed.
     *
     * @param boolean $allowJsonApi
     * @return CronService
     * @throws \InvalidArgumentException Whenever `$allowJsonApi` is not a boolean value.
     */
    public function setAllowJsonApi($allowJsonApi)
    {
        if (!is_bool($allowJsonApi)) {
            throw new \InvalidArgumentException('`allowJsonApi` expects boolean value!');
        }

        $this->options['allowJsonApi'] = (bool) $allowJsonApi;
        return $this;
    }

    /**
     * Get JSON API security hash.
     *
     * @return string
     */
    public function getJsonApiSecurityHash()
    {
        return $this->options['jsonApiSecurityHash'];
    }

    /**
     * Set JSON API security hash.
     *
     * @param string $jsonApiSecurityHash
     * @return CronService
     * @throws \InvalidArgumentException Whenever `$jsonApiSecurityHash` is not a string value.
     */
    public function setJsonApiSecurityHash($jsonApiSecurityHash)
    {
        if (!is_string($jsonApiSecurityHash)) {
            throw new \InvalidArgumentException('`jsonApiSecurityHash` expects string value!');
        }

        $this->options['jsonApiSecurityHash'] = (string) $jsonApiSecurityHash;
        return $this;
    }

    /**
     * Returns pending jobs.
     *
     * @return /Traversable
     */
    public function getPending()
    {
        // ...
    }

    /**
     * Reset (clear) all pending jobs.
     *
     * @return CronService
     */
    public function resetPending()
    {
        // ...
    }

    /**
     * Main action - run scheduled jobs and prepare next run.
     *
     * @return CronService
     */
    public function run()
    {
        // ...

        // Trigger event
        //if ($this->getEmitEvents() === true) {
        //    $this->getEventManager()->trigger('run', null, array(/* ... */));
        //}
    }

    /**
     * Run sheduled CRON jobs.
     *
     * @return CronService
     */
    public function process()
    {
        // ...

        // Trigger event
        //if ($this->getEmitEvents() === true) {
        //    $this->getEventManager()->trigger('process', null, array(/* ... */));
        //}
    }

    /**
     * Shedule CRON jobs.
     *
     * Read configuration and insert `CronHelper` database records according to it.
     *
     * @return CronService
     */
    public function schedule()
    {
        // ...

        // Trigger event
        //if ($this->getEmitEvents() === true) {
        //    $this->getEventManager()->trigger('schedule', null, array(/* ... */));
        //}
    }

    /**
     * Cleanup `CronHelper` database according to set timeout options.
     *
     * @return CronService
     */
    public function cleanup()
    {
        // ...

        // Trigger event
        //if ($this->getEmitEvents() === true) {
        //    $this->getEventManager()->trigger('cleanup', null, array(/* ... */));
        //}
    }

    /**
     * Recover CRON jobs that exceeded `max_execution_time` st in system's `php.ini`.
     *
     * @return CronService
     */
    public function recoverRunning()
    {
        // ...
    }

    /**
     * Register CRON job.
     *
     * This method is used for creating CRON jobs directly from application's code.
     *
     * @param string $code
     * @param int|string $frequency
     * @param callback $callback
     * @param array $options (Optional.)
     * @return CronService
     */
    public function register($code, $frequency, $callback, array $options = array())
    {
        // ...

        // Trigger event
        //if ($this->getEmitEvents() === true) {
        //    $this->getEventManager()->trigger('register', null, array(/* ... */));
        //}
    }
}


<?php

namespace Germanazo\CkanApi;

use Illuminate\Support\ServiceProvider;
use GuzzleHttp\Client;
use Germanazo\CkanApi\CkanApiClient;

class CkanServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap application services.
     *
     * @return void
     */
    public function boot()
    {
        $this->mergeConfigFrom(__DIR__ . '/../config/ckan_api.php', 'ckan_api');

        $this->publishes([
            __DIR__ . '/../config/ckan_api.php' => config_path('ckan_api.php'),
        ]);
    }

    /**
     * Register application services.
     *
     * @return void
     */
    public function register()
    {
        $app = $this->app;

        $app->bind('Germanazo\CkanApi\CkanApiClient', function () {

            // Build http client
            $config = [
                'base_uri' => config('ckan_api.url'),
                'headers' => ['Authorization' => config('ckan_api.api_key')],
            ];

            return new CkanApiClient(new Client($config));
        });

        $app->alias('Germanazo\CkanApi\CkanApiClient', 'CkanApi');
    }
}


<?php

namespace Germanazo\CkanApi\Traits;

use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Exception\ServerException;

trait RestApiTrait
{
    /**
     * Get all resources
     *
     * @return array
     */
    public function search($data = [])
    {
        return $this->query(__FUNCTION__, $data);
    }

    /**
     * Get all resources
     *
     * @return array
     */
    public function list($data = [])
    {
        return $this->query(__FUNCTION__, $data);
    }

    /**
     * Create a resource
     *
     * @param array $data
     * @param array $multipart
     * @return array
     */
    public function create(array $data = [])
    {
        return $this->doPostAction(__FUNCTION__, $data);
    }

    /**
     * Delete a resource
     *
     * @param $id
     * @return mixed
     */
    public function delete($id)
    {
        return $this->doPostAction(__FUNCTION__, ['id' => $id]);
    }

    /**
     * Delete a resource
     *
     * @param string $id
     * @param array $data extra parameters
     * @return mixed
     */
    public function show($id, $params = [])
    {
        $data = ['id' => $id] + $params;

        return $this->query(__FUNCTION__, $data);
    }

    /**
     * Update a resource
     *
     * @param array $data
     * @param array $multipart
     * @return array
     */
    public function update(array $data = [])
    {
        return $this->doPostAction(__FUNCTION__, $data);
    }

    /**
     * Set action url
     *
     * @param string $action
     */
    protected function setActionUri($action)
    {
        $this->setUri("action/{$this->action_name}_{$action}");
    }

    /**
     * Create or update a resource
     *
     * @param string $uri
     * @param array $data
     * @return array
     */
    protected function doPostAction($uri, array $data = [])
    {
        $this->setActionUri($uri);

        try {
            $response = $this->client->post($this->uri, ['json' => $data]);
        } catch (ClientException $e) {
            $response = $e->getResponse();
        } catch (ServerException $e) {
            $response = $e->getResponse();
        }

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

    /**
     * Get a simple query
     *
     * @param array $data
     * @return mixed
     */
    protected function query($uri, $data = [])
    {
        $this->setActionUri($uri);

        try {
            $response = $this->client->get($this->uri, ['query' => $data]);
        } catch(ClientException $e) {
            $response = $e->getResponse();
        } catch(ServerException $e) {
            $response = $e->getResponse();
        }

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


<?php

/*
 * This file is part of the ONGR package.
 *
 * (c) NFQ Technologies UAB <info@nfq.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace ONGR\ApiBundle\Routing;

use Symfony\Component\Config\Loader\Loader;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;

/**
 * Loads api routes.
 */
class ElasticsearchLoader extends Loader
{
    /**
     * @var array
     */
    private $versions;

    /**
     * @param array $versions
     */
    public function __construct(array $versions = [])
    {
        $this->versions = $versions;
    }

    /**
     * {@inheritdoc}
     */
    public function load($resource, $type = null)
    {
        $collection = new RouteCollection();

        foreach ($this->versions as $version => $config) {
            foreach ($config['endpoints'] as $document => $endpoint) {
                $this->processRestRoute($collection, $document, $endpoint, $version);
            }
        }

        return $collection;
    }

    /**
     * {@inheritdoc}
     */
    public function supports($resource, $type = null)
    {
        return 'ongr_api' === $type;
    }

    /**
     * Create route for REST action
     *
     * @param RouteCollection $collection
     * @param string $document
     * @param array $endpoint
     * @param string $version
     */
    private function processRestRoute(
        $collection,
        $document,
        $endpoint,
        $version = 'v1'
    ) {

        $defaults = [
            '_documentId' => null,
            '_endpoint' => $endpoint,
            '_version' => $version,
            'repository' => $endpoint['repository'],
        ];

        $pattern = $version . '/' . sprintf('%s/{documentId}', strtolower($document));

        if ($endpoint['batch']) {
            foreach ([Request::METHOD_PUT, Request::METHOD_POST, Request::METHOD_DELETE] as $method) {
                $defaults['_controller'] = 'ONGRApiBundle:Batch:' . ucfirst(strtolower($method));
                $batchPattern = $version . '/' . sprintf('%s', strtolower($document)) . '/_batch';
                $name = strtolower(sprintf('ongr_api_%s_%s_%s', $version, $document, $method));
                $collection->add($name . '_batch', new Route(
                    $batchPattern,
                    $defaults,
                    [],
                    [],
                    "",
                    [],
                    [$method]
                ));
            }
        }

        $name = strtolower(sprintf('ongr_api_%s_%s_all', $version, $document));
        $defaults['_controller'] = 'ONGRApiBundle:GetAll:getAll';
        $postPattern = $version . '/' . sprintf('%s', strtolower($document)).'/_all';
        $collection->add($name, new Route($postPattern, $defaults, [], [], "", [], [Request::METHOD_GET]));

        foreach ($endpoint['methods'] as $method) {
            $name = strtolower(sprintf('ongr_api_%s_%s_%s', $version, $document, $method));
            $defaults['_controller'] = sprintf('ONGRApiBundle:Rest:%s', strtolower($method));

            if ($method == Request::METHOD_POST) {
                $postPattern = $version . '/' . sprintf('%s', strtolower($document));
                $collection->add($name . '_wi', new Route($postPattern, $defaults, [], [], "", [], [$method]));
            }

            $collection->add($name, new Route($pattern, $defaults, [], [], "", [], [$method]));

            if ($endpoint['variants']) {
                $defaults['_controller'] = sprintf('ONGRApiBundle:Variant:%s', strtolower($method));

                if ($method == Request::METHOD_POST || $method == Request::METHOD_GET) {
                    $variantPattern = $pattern . '/_variant';
                    $collection->add(
                        $name . '_variant_wi',
                        new Route($variantPattern, $defaults, [], [], "", [], [$method])
                    );
                }

                $variantPattern = $pattern . '/_variant/{variantId}';
                $collection->add($name . '_variant', new Route($variantPattern, $defaults, [], [], "", [], [$method]));
            }
        }
    }
}


<?php
/**
 * zf2-cron-helper
 *
 * @link https://github.com/ondrejd/zf2-cron-helper for the canonical source repository
 * @copyright Copyright (c) 2015 Ondřej Doněk.
 * @license https://www.mozilla.org/MPL/2.0/ Mozilla Public License 2.0
 */

namespace CronHelper\Controller;

use Zend\Console\ColorInterface as ConsoleColor;
use Zend\Console\Request as ConsoleRequest;
use Zend\Db\Adapter\Adapter as DbAdapter;
use Zend\Mvc\Controller\AbstractActionController;

use CronHelper\Model\JobEntity;
use CronHelper\Model\JobMapper;
use CronHelper\Model\JobTable;
use CronHelper\Service\CronService;

/**
 * Main CronHelper controller.
 *
 * @package CronHelper
 * @subpackage Controller
 * @author Ondřej Doněk <ondrejd@gmail.com>
 */
class IndexController extends AbstractActionController
{
	/**
	 * @var \Zend\Console\Adapter\AdapterInterface $console
	 */
	private $console;

	/**
	 * @var DbAdapter $dbAdapter
	 */
	private $dbAdapter;

	/**
	 * @var CronService $cronService
	 */
	private $cronService;

	/**
	 * @return \Zend\Console\Adapter\AdapterInterface
	 */
	protected function getConsole()
	{
		if (!$this->console instanceof \Zend\Console\Adapter\AdapterInterface) {
			$this->console = $this->getServiceLocator()->get('console');
		}

		return $this->console;
	}

	/**
	 * @return DbAdapter
	 */
	protected function getDbAdapter()
	{
		$serviceLocator = $this->getServiceLocator();

		if ($serviceLocator->has('Zend\Db\Adapter\Adapter')) {
			$this->dbAdapter = $serviceLocator->get('Zend\Db\Adapter\Adapter');
		} else {
			$config = $serviceLocator->get('config');

			if (array_key_exists('cron_helper', $config)) {
				$config = $config['cron_helper'];

				if (array_key_exists('db', $config)) {
					$this->dbAdapter = new DbAdapter($config['db']);
				}
			}
		}

		if (!($this->dbAdapter instanceof DbAdapter)) {
			throw new \RuntimeException(
				'Module "cron_helper" has no database adapter. Probably is ' .
				'missing a proper configuration!'
			);
		}

		return $this->dbAdapter;
	}

	/**
	 * @return CronService
	 */
	protected function getCronService()
	{
		if (!($this->cronService instanceof CronService)) {
			$this->cronService = $this->getServiceLocator()->get('CronHelper\Service\CronService');
		}

		return $this->cronService;
	}

	/**
	 * return JobMapper
	 */
	protected function getJobMapper()
	{
		$dbAdapter = $this->getDbAdapter();
		$mapper = new JobMapper($dbAdapter);

		return $mapper;
	}

	/**
	 * @return boolean
	 */
	protected function isConsoleRequest()
	{
		return 	($this->getRequest() instanceof ConsoleRequest);
	}

	/**
	 * @param Console $console
	 * @return string
	 */
	private function printConsoleBanner($console)
	{
		$console->writeLine(\CronHelper\Module::CONSOLE_BANNER, ConsoleColor::BLUE);
		$console->writeLine();
	}

	/**
	 * Main action.
	 *
	 * @return void
	 * @throws \RuntimeException Whenever is action accessed not via console request.
	 */
	public function indexAction()
	{
		if (!$this->isConsoleRequest()) {
			throw new \RuntimeException('You can only use this action from a console!');
		}

		$console = $this->getConsole();
		$this->printConsoleBanner($console);

		$console->writeLine('TODO Finish indexAction!', ConsoleColor::LIGHT_RED);
	}

	/**
	 * Print info about current status.
	 *
	 * @return void
	 * @throws \RuntimeException Whenever is action accessed not via console request.
	 */
	public function infoAction()
	{
		if (!$this->isConsoleRequest()) {
			throw new \RuntimeException('You can only use this action from a console!');
		}

		$console = $this->getConsole();
		$this->printConsoleBanner($console);

		$mapper = $this->getJobMapper();

		try {
			$pendingJobs = $mapper->getPending()->count();
			$runningJobs = $mapper->getRunning()->count();
			$finishedJobs = $mapper->getHistory()->count();

			$console->writeLine(sprintf('Pending jobs: %s', $pendingJobs));
			$console->writeLine(sprintf('Running jobs: %s', $runningJobs));
			$console->writeLine(sprintf('Finished jobs: %s', $finishedJobs));
		} catch (\PDOException $exception) {
			// Note: It's look like that either database adapter is not properly
			// defined or table database doesn't exist.
			$console->writeLine(
				'Something is bad with your database - either database ' .
				'adapter is not properly configured or database table is ' .
				'not created.', ConsoleColor::LIGHT_RED
			);
		}
	}

	/**
	 * Create storage.
	 *
	 * @return void
	 * @throws \RuntimeException Whenever is action accessed not via console request.
	 */
	public function storageCreateAction()
	{
		if (!$this->isConsoleRequest()) {
			throw new \RuntimeException('You can only use this action from a console!');
		}

		$dbAdapter = $this->getDbAdapter();
		$console = $this->getConsole();
		$this->printConsoleBanner($console);

		try {
			$table = new JobTable($dbAdapter);
			$table->create();
		} catch (\Exception $exception) {
			$console->writeLine('Creating database table failed!', ConsoleColor::LIGHT_RED);
			return;
		}

		$console->writeLine('Storage was successfully created!', ConsoleColor::LIGHT_GREEN);
	}

	/**
	 * Clear storage.
	 *
	 * @return void
	 * @throws \RuntimeException Whenever is action accessed not via console request.
	 */
	public function storageClearAction()
	{
		if (!$this->isConsoleRequest()) {
			throw new \RuntimeException('You can only use this action from a console!');
		}

		$dbAdapter = $this->getDbAdapter();
		$console = $this->getConsole();
		$this->printConsoleBanner($console);

		try {
			$table = new JobTable($dbAdapter);
			$table->truncate();
		} catch (\Exception $exception) {
			$console->writeLine('Truncating database table failed!', ConsoleColor::LIGHT_RED);
			return;
		}

		$console->writeLine('Storage was successfully cleared!', ConsoleColor::LIGHT_GREEN);
	}

	/**
	 * Destroy storage.
	 *
	 * @return void
	 * @throws \RuntimeException Whenever is action accessed not via console request.
	 */
	public function storageDestroyAction()
	{
		if (!$this->isConsoleRequest()) {
			throw new \RuntimeException('You can only use this action from a console!');
		}

		$dbAdapter = $this->getDbAdapter();
		$console = $this->getConsole();
		$this->printConsoleBanner($console);

		try {
			$table = new JobTable($dbAdapter);
			$table->drop();
		} catch (\Exception $exception) {
			$console->writeLine('Dropping database table failed!', ConsoleColor::LIGHT_RED);
			return;
		}

		$console->writeLine('Storage was successfully destroyed!', ConsoleColor::LIGHT_GREEN);
	}
}


<?php

/*
 * This file is part of the ONGR package.
 *
 * (c) NFQ Technologies UAB <info@nfq.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace ONGR\ApiBundle\Service;

use JMS\Serializer\SerializerInterface;
use Symfony\Component\HttpFoundation\Request;

/**
 * This class provides all data for deserialization and serialization of API requests.
 */
class RequestSerializer
{
    /**
     * @var SerializerInterface
     */
    protected $serializer;

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

    /**
     * RequestSerializer constructor.
     *
     * @param SerializerInterface $serializer
     * @param string              $defaultAcceptType
     */
    public function __construct(SerializerInterface $serializer, $defaultAcceptType)
    {
        $this->serializer = $serializer;
        $this->defaultAcceptType = $defaultAcceptType;
    }

    /**
     * @param Request $request
     * @param string  $data
     *
     * @return string
     */
    public function serializeRequest(Request $request, $data)
    {
        $format = $this->checkAcceptHeader($request);

        try {
            return $this->serializer->serialize($data, $format);
        } catch (\Exception $e) {
            throw new \RuntimeException('Could not serialize content to \'' . $format .'\' format.');
        }
    }

    /**
     * @param Request $request
     *
     * @return array
     */
    public function deserializeRequest(Request $request)
    {
        $format = $this->checkAcceptHeader($request);

        try {
            return $this->serializer->deserialize($request->getContent(), 'array', $format);
        } catch (\Exception $e) {
            throw new \RuntimeException(
                'Could not deserialize content from the request.'
            );
        }
    }

    /**
     * Returns acceptance type based on given request.
     *
     * @param Request $request
     *
     * @return string
     */
    public function checkAcceptHeader(Request $request)
    {
        $headers = $request->getAcceptableContentTypes();

        if (array_intersect($headers, ['application/json', 'text/json'])) {
            return 'json';
        } elseif (array_intersect($headers, ['application/xml', 'text/xml'])) {
            return 'xml';
        }

        return $this->defaultAcceptType;
    }
}


<?php
/**
 * File containing the eZIEImageToolCrop class.
 *
 * @copyright Copyright (C) eZ Systems AS.
 * @license For full copyright and license information view LICENSE file distributed with this source code.
 * @version //autogentag//
 * @package ezie
 */
class eZIEImageToolCrop extends eZIEImageAction
{
    /**
    * Creates a crop filter
    *
    * @param  array(int) $region Affected region, as a 4 keys array: w, h, x, y
    * @return array( ezcImageFilter )
    */
    public static function filter( $region )
    {
        $r = array(
            'x'      => intval( $region['x'] ),
            'y'      => intval( $region['y'] ),
            'width'  => intval( $region['w'] ),
            'height' => intval( $region['h'] )
        );
        return array( new ezcImageFilter( 'crop', $r ) );
    }
}

?>


<?php
/**
 * File containing the eZIEImageToolWatermark class.
 *
 * @copyright Copyright (C) eZ Systems AS.
 * @license For full copyright and license information view LICENSE file distributed with this source code.
 * @version //autogentag//
 * @package ezie
 */
class eZIEImageToolWatermark extends eZIEImageAction
{
    /**
     * Watermark filter.
     * Adds the $image watermark at the $region location
     *
     * @param  array $region array with 'x' and 'y' keys
     * @param  string $image Image file name, will be searched in the ezie design folder
     * @return array(ezcImageFilter)s
     */
    public static function filter( $region, $image )
    {
        // the watermark images are in ezie/design/standard/images/watermarks
        // @todo use ini file for image paths instead
        $img_path = realpath( dirname( __FILE__ ) . "/../design/standard/images/watermarks" ) . "/" . $image;

        // retrieve image dimensions
        $analyzer = new ezcImageAnalyzer( $img_path );

        // percentage of the watermark original size to use
        $pc = $region['w'] / $analyzer->data->width;

        return array(
            new ezcImageFilter(
                'watermarkAbsolute',
                array(
                    'image'  => $img_path,
                    'posX'   => $region['x'],
                    'posY'   => $region['y'],
                    'width'  => intval( $region['w'] ),
                    'height' => intval( $region['h'] )
                )
            )
        );
    }
}
?>


<?php
/**
 * File containing the eZAutoloadGenerator class.
 *
 * @copyright Copyright (C) eZ Systems AS.
 * @license For full copyright and license information view LICENSE file distributed with this source code.
 * @version //autogentag//
 * @package kernel
 * @author eZIE Team
 */
class eZIEezcImageConverter
{
    /**
     * @var ezcImageConverter
     */
    private $converter;

    /**
    * Instanciantes the image converter with a set of filters
    *
    * @param array(ezcImageFilter) $filter Filters to add to the image converter
    * @return void
    * @throws ezcBaseSettingValueException Error adding the transformation
    */
    public function __construct( $filter )
    {
        $imageINI = eZINI::instance( 'image.ini' );

        // we get an array of handlers, where order of entries in array gives priority
        // for each entry, we need to check if the matching handler is enabled, and this has to be manual
        $imageHandlers = $imageINI->variable( 'ImageConverterSettings', 'ImageConverters' );
        foreach( $imageHandlers as $imageHandler )
        {
            switch( $imageHandler )
            {
                case 'ImageMagick':
                {
                    $hasImageMagick = ( $imageINI->variable( 'ImageMagick', 'IsEnabled' ) == 'true' );
                    if ( $hasImageMagick )
                        break 2;
                } break;

                // GD2 is required for the image editor
                // @todo Make the image editor degrade as nicely as possible if GD is not bundled
                case 'GD':
                {
                    $hasGD2 =
                        $imageINI->variable( 'GD', 'IsEnabled' ) == 'true' &&
                        $imageINI->variable( 'GDSettings', 'HasGD2' == 'true' );
                    if ( $hasGD2 )
                        break 2;
                } break;
            }
        }

        if ( $hasImageMagick )
        {
            // we need to use the ImageMagick path configured in the image.ini file
            $executable = $imageINI->variable( 'ImageMagick', 'Executable' );

            if ( eZSys::osType() == 'win32' && $imageINI->hasVariable( 'ImageMagick', 'ExecutableWin32' ) )
                $executable = $imageINI->variable( 'ImageMagick', 'ExecutableWin32' );
            else if ( eZSys::osType() == 'mac'  && $imageINI->hasVariable( 'ImageMagick', 'ExecutableMac' ) )
                $executable = $imageINI->variable( 'ImageMagick', 'ExecutableMac' );
            else if ( eZSys::osType() == 'unix' && $imageINI->hasVariable( 'ImageMagick', 'ExecutableUnix' ) )
                $executable = $imageINI->variable( 'ImageMagick', 'ExecutableUnix' );
            if ( $imageINI->hasVariable( 'ImageMagick', 'ExecutablePath' ) && $imageINI->variable( 'ImageMagick', 'ExecutablePath' ) )
                $executable = $imageINI->variable( 'ImageMagick', 'ExecutablePath' ) . eZSys::fileSeparator() . $executable;
            // @todo Remove if ezc indeed do it automatically
            // if ( eZSys::osType() == 'win32' )
            //    $executable = "\"$executable\"";

            $imageHandlerSettings = new ezcImageHandlerSettings(
                'ImageMagick', 'eZIEEzcImageMagickHandler',
                array( 'binary' => $executable )
            );
            $settings = new ezcImageConverterSettings( array( $imageHandlerSettings ) );
        }
        else
        {
            $settings = new ezcImageConverterSettings( array( new ezcImageHandlerSettings( 'GD', 'eZIEEzcGDHandler' ) ) );
        }

        $this->converter = new ezcImageConverter( $settings );

        $mimeType = $imageINI->variable( 'OutputSettings', 'AllowedOutputFormat' );

        $this->converter->createTransformation( 'transformation', $filter, $mimeType );
    }

    /**
    * Performs the ezcImageConverter transformation
    *
    * @param  string $src Source image
    * @param  string $dst Destination image
    * @return void
    */
    public function perform( $src, $dst )
    {
        // fetch the input file locally
        $inClusterHandler = eZClusterFileHandler::instance( $src );
        $inClusterHandler->fetch();

        try {
            $this->converter->transform( 'transformation', $src, $dst );
        }
        catch ( Exception $e )
        {
            $inClusterHandler->deleteLocal();
            throw $e;
        }

        // store the output file to the cluster
        $outClusterHandler = eZClusterFileHandler::instance();

        // @todo Check if the local output file can be deleted at that stage. Theorically yes.
        $outClusterHandler->fileStore( $dst, 'image' );

        // fixing the file permissions
        eZImageHandler::changeFilePermissions( $dst );
    }

    /**
    * Active ezcImageConverter
    * @return ezcImageConverter
    */
    public function getConverter()
    {
        return $this->converter;
    }
}

?>


<?php
/**
 * File containing the eZIEImageAnalyzer class
 * This class overrides ezcImageAnalyzer in order to support the ezpublish cluster constraints
 *
 * @copyright Copyright (C) eZ Systems AS.
 * @license For full copyright and license information view LICENSE file distributed with this source code.
 * @version //autogentag//
 * @package ezie
 */
class eZIEImageAnalyzer extends ezcImageAnalyzer
{
    protected $deleteLocal = true;

    /**
     * Constructor overload
     * Creates a local copy of the image so that it can be analyzed
     *
     * @param string $file
     */
    public function __construct( $file, $deleteLocal = true )
    {
        $clusterHandler = eZClusterFileHandler::instance( $file );
        $clusterHandler->fetch();

        parent::__construct( $file );

        $this->deleteLocal = $deleteLocal;
        if( $this->deleteLocal )
        {
            $clusterHandler->deleteLocal();
        }
    }

    /**
     * Overload of ezcImageAnalyzer::analyzeImage()
     * Creates a temporary local copy of the image file so that it can be analyzed
     *
     * @return void
     */
    public function analyzeImage()
    {
        $clusterHandler = eZClusterFileHandler::instance( $this->filePath );
        $clusterHandler->fetch();

        parent::analyzeImage();

        if( $this->deleteLocal )
        {
            $clusterHandler->deleteLocal();
        }
    }
}

?>


<?php
/**
 * File containing the eZIEEzcImageMagickHandler class.
 *
 * Implements the methods used by the editor (rotate, flip, etc) for image magick.
 *
 * @copyright Copyright (C) eZ Systems AS.
 * @license For full copyright and license information view LICENSE file distributed with this source code.
 * @version //autogentag//
 * @package ezie
 */
class eZIEEzcImageMagickHandler extends ezcImageImagemagickHandler implements eZIEEzcConversions
{
    /**
    * Sets the filtering region
    *
    * @param array $ (int) $region Array of regions, with 4 keys: h+w & x+y
    * @return void
    */
    private function setRegion( $region )
    {
        if ( $region === null )
            return;

        $this->addFilterOption( $this->getActiveReference(),
            '-region',
            "{$region['w']}x{$region['h']}+{$region['x']}+{$region['y']}"
        );
    }

    /**
     * Adds a rotation filter
     *
     * @param int $angle Rotation angle, 0 <= angle <= 360
     * @param string $color
     * @return void
     */
    public function rotate( $angle, $background = 'FFFFFF' )
    {
        $angle = intval( $angle );
        if ( !is_int( $angle ) || ( $angle < 0 ) || ( $angle > 360 ) )
        {
            throw new ezcBaseValueException( 'height', $height, 'angle < 0 or angle > 360' );
        }

        $angle = 360 - $angle;
        $background = "#{$background}";

        $this->addFilterOption(
            $this->getActiveReference(),
            '-background',
            $background
        );

        $this->addFilterOption(
            $this->getActiveReference(),
            '-rotate',
            $angle
        );
    }

    /* (non-PHPdoc)
     * @see extension/ezie/autoloads/eziezc/interfaces/eZIEEzcConversions#horizontalFlip($region)
     */
    public function horizontalFlip( $region = null )
    {
        $this->addFilterOption( $this->getActiveReference(), '-flop' );
    }

    /* (non-PHPdoc)
     * @see extension/ezie/autoloads/eziezc/interfaces/eZIEEzcConversions#verticalFlip($region)
     */
    public function verticalFlip( $region = null )
    {
        $this->addFilterOption( $this->getActiveReference(), '-flip' );
    }

    /* (non-PHPdoc)
     * @see extension/ezie/autoloads/eziezc/interfaces/eZIEEzcConversions#pixelate($width, $height, $region)
     */
    public function pixelate( $width, $height, $region = null )
    {
        $size = ceil( max( $width, $height ) / 42 );

        if ( $region === null )
        {
            $region = array(
                'x' => 0,
                'y' => 0,
                'w' => $width,
                'h' => $height
            );
        }

        $tmpRegion = array(
            'x' => $region['x'],
            'y' => $region['y'],
            'w' => $size,
            'h' => $size
        );

        $activeReference = $this->getActiveReference();
        $blur = ( $size * 3 ) . 'x' . ( $size * 4 );

        $i = $region['x'];

        $i_max = $region['w'] + $region['x'];
        $j_max = $region['h'] + $region['y'];

        for ( ; $i < $i_max; $i += $size )
        {
            $tmpRegion['x'] = $i;

            $j = $region['y'];
            for ( ; $j < $j_max; $j += $size )
            {
                $tmpRegion['y'] = $j;

                $this->setRegion( $tmpRegion );

                $this->addFilterOption( $activeReference,
                    '-blur',
                    $blur
                );
            }
        }
    }

    /*
     * Reimplementation of the very same function of the parent class
     * but without the restriction on the width.
     * See related issue: http://issues.ez.no/IssueView.php?Id=15976&
     *
     * @see lib/ezc/ImageConversion/src/handlers/ezcImageImagemagickHandler#scalePercent($width, $height)
     */
    public function scalePercent( $width, $height )
    {
        if ( !is_int( $height ) || $height < 1 )
        {
            throw new ezcBaseValueException( 'height', $height, 'int > 0' );
        }

        if ( !is_int( $width ) || $width < 1 )
        {
            throw new ezcBaseValueException( 'width', $width, 'int > 0' );
        }
        $this->addFilterOption( $this->getActiveReference(),
            '-resize',
            "{$width}%x{$height}%"
        );
    }

    /* (non-PHPdoc)
     * @see lib/ezc/ImageConversion/src/handlers/ezcImageImagemagickHandler#colorspace($space)
     */
    public function colorspace( $space, $region = null )
    {
        $this->setRegion( $region );

        parent::colorspace( $space );
    }

    /* (non-PHPdoc)
     * @see extension/ezie/autoloads/eziezc/interfaces/eZIEEzcConversions#brightness($value)
     */
    public function brightness( $value, $region = null )
    {
        if ( $value < - 255 || $value > 255 )
        {
            throw new ezcBaseValueException( 'value', $value, 'int >= -255 && int <= 255' );
        }
        // 0 = -255
        // 50 = half as bright = -127
        // 100 = regular brightness = 0
        // 150 = 127
        // 200 = twice as bright = 255
        $value = ( 200 * ( $value + 255 ) ) / 512;

        $this->setRegion( $region );
        $this->addFilterOption( $this->getActiveReference(),
            '-modulate',
            $value
        );
    }

    /* (non-PHPdoc)
     * @see extension/ezie/autoloads/eziezc/interfaces/eZIEEzcConversions#contrast($value)
     */
    public function contrast( $value, $region = null )
    {
        if ( $value < - 100 || $value > 100 )
        {
            throw new ezcBaseValueException( 'value', $value, 'int >= -100 && int <= 100' );
        }

        $round_value = round( $value / 10 );

        if ( $round_value >= 0 )
        {
            $option = '-contrast';
        }
        else
        {
            $option = '+contrast';
            $round_value = - $round_value;
        }

        $this->setRegion( $region );
        for ( $i = 0; $i < $round_value; ++$i )
        {
            $this->addFilterOption(
                $this->getActiveReference(),
                $option
            );
        }
    }
}

?>


<?php

namespace Haleks\Markdown\Compilers;

use Illuminate\View\Compilers\BladeCompiler;
use Illuminate\View\Compilers\CompilerInterface;

class MarkdownBladeCompiler extends BladeCompiler implements CompilerInterface
{
    /**
     * Compile the view at the given path.
     *
     * @param  string  $path
     * @return void
     */
    public function compile($path = null)
    {
        if ($path) {
            $this->setPath($path);
        }

        $contents = $this->compileString($this->files->get($this->getPath()));

        if (! is_null($this->cachePath)) {
            $this->files->put($this->getCompiledPath($this->getPath()), $contents);
        }
    }

    /**
     * Compile the view's markdown with given contents.
     *
     * @param  string  $contents
     * @return void
     */
    public function markdown($contents)
    {
        $contents = app('markdown')->convertToHtml($contents);

        if (! is_null($this->cachePath)) {
            $this->files->put($this->getCompiledPath($this->getPath()), $contents);
        }

        return $contents;
    }
}