<?php

defined('C5_EXECUTE') or die("Access Denied.");
/**
 * @var $router \Concrete\Core\Routing\Router
 */
$router->all('/arrange_blocks/', 'Page\ArrangeBlocks::arrange');
$router->all('/check_in/{cID}/{token}', 'Page::exitEditMode');
$router->all('/create/{ptID}', 'Page::create');
$router->all('/create/{ptID}/{parentID}', 'Page::create');
$router->all('/get_json', 'Page::getJSON');
$router->all('/multilingual/assign', 'Page\Multilingual::assign');
$router->all('/multilingual/create_new', 'Page\Multilingual::create_new');
$router->all('/multilingual/ignore', 'Page\Multilingual::ignore');
$router->all('/multilingual/unmap', 'Page\Multilingual::unmap');
$router->all('/select_sitemap', 'Page\SitemapSelector::view');
$router->all('/sitemap_data', 'Page\SitemapData::view');
$router->all('/sitemap_overlay', '\Concrete\Controller\Element\Dashboard\Sitemap\SitemapOverlay::view');

Add the sitemap overlay route

Add the sitemap overlay route


<?php
/*******************************************************************************
 * Copyright (c) 2015 Eclipse Foundation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Christopher Guindon (Eclipse Foundation) - Initial implementation
 *******************************************************************************/
if (!defined('ABSPATH')) exit;
?>

About

Register

Terms

Schedule

Sponsorship

<?php
/*******************************************************************************
 * Copyright (c) 2015 Eclipse Foundation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Christopher Guindon (Eclipse Foundation) - Initial implementation
 *******************************************************************************/
if (!defined('ABSPATH')) exit;
?>

About

Register

Terms

Code of Conduct

Schedule

Sponsorship

Add link to Code of Conduct in Menu

Add link to Code of Conduct in Menu


<?php

namespace Plummer\Calendarful;

interface EventInterface
{
	public function getId();

	public function getName();

	public function getStartDateFull();

	public function setStartDateFull(\DateTime $startDateFull);

	public function getStartDate();

	public function getStartTime();

	public function getEndDate();

	public function setEndDate(\DateTime $endDate);

	public function getDuration();

	public function getParent();

	public function getParentDate();

    public function getRecurrenceType();

    public function getRecurrenceUntil();

	public function setCalendar(Calendar &$calendar);
}

<?php

namespace Plummer\Calendarful;

interface EventInterface
{
	public function getId();

	public function getName();

	public function getStartDateFull();

	public function setStartDateFull(\DateTime $startDateFull);

	public function getStartDate();

	public function getStartTime();

	public function getEndDate();

	public function setEndDate(\DateTime $endDate);

	public function getDuration();

	public function getParent();

	public function getParentDate();

    public function getRecurrenceType();

    public function getRecurrenceUntil();
}

Remove set calendar method for events.

Remove set calendar method for events.


<?php
$userInfo = get_userdata( get_query_var('author'));
$isAuthor = true;
if (
    !in_array('contributor', $userInfo -> roles) &&
    !in_array('administrator', $userInfo -> roles) &&
    !in_array('author', $userInfo -> roles) &&
    !in_array('editor', $userInfo -> roles)
) {
    $isAuthor = false;
}
?>
<?php get_header(); ?>

                <?php if ($isAuthor === true): ?>

                        <?php echo sprintf(__('Author %s', 'b4st'), '' . get_the_author_meta('user_nicename', $userInfo -> data -> ID) . ''); ?>

                <?php endif; ?>

            <?php if(have_posts()): ?>
               <?php get_template_part('loops/content', get_post_format()); ?>
            <?php else: ?>
               <?php get_template_part('loops/content', 'none'); ?>
            <?php endif; ?>

		   <?php get_sidebar(); ?>

<?php get_footer(); ?>

<?php
$userInfo = get_userdata( get_query_var('author'));
$isAuthor = true;
if (
    !in_array('contributor', $userInfo -> roles) &&
    !in_array('administrator', $userInfo -> roles) &&
    !in_array('author', $userInfo -> roles) &&
    !in_array('editor', $userInfo -> roles)
) {
    $isAuthor = false;
    wp_redirect(get_bloginfo('url').'/404', 404);
}
?>
<?php get_header(); ?>

                <?php if ($isAuthor === true): ?>

                        <?php echo sprintf(__('Author %s', 'b4st'), '' . get_the_author_meta('user_nicename', $userInfo -> data -> ID) . ''); ?>

                <?php endif; ?>

            <?php if(have_posts()): ?>
               <?php get_template_part('loops/content', get_post_format()); ?>
            <?php else: ?>
               <?php get_template_part('loops/content', 'none'); ?>
            <?php endif; ?>

		   <?php get_sidebar(); ?>

<?php get_footer(); ?>

Throw a 404 header on user w/o post crud role


<?php

namespace Kibo\Phast\Services\Css;

use Kibo\Phast\Retrievers\Retriever;
use Kibo\Phast\Security\ServiceSignature;
use Kibo\Phast\Services\ProxyBaseService;

class Service extends ProxyBaseService {

    public function __construct(ServiceSignature $signature, Retriever $retriever) {
        parent::__construct($signature, [], $retriever);
    }

    protected function handle(array $request) {
        $response = parent::handle($request);
        $response->setHeader('Content-Type', 'text/css');
        return $response;
    }

}

<?php

namespace Kibo\Phast\Services\Css;

use Kibo\Phast\Common\CSSURLRewriter;
use Kibo\Phast\Retrievers\Retriever;
use Kibo\Phast\Security\ServiceSignature;
use Kibo\Phast\Services\ProxyBaseService;
use Kibo\Phast\ValueObjects\URL;

class Service extends ProxyBaseService {

    public function __construct(ServiceSignature $signature, Retriever $retriever) {
        parent::__construct($signature, [], $retriever);
    }

    protected function handle(array $request) {
        $response = parent::handle($request);
        $response->setHeader('Content-Type', 'text/css');
        return $response;
    }

    protected function doRequest(array $request) {
        $content = parent::doRequest($request);
        $base = URL::fromString($request['src']);
        return (new CSSURLRewriter())->rewriteRelativeURLs($content, $base);
    }
}

Rewrite css urls in css proxy service

Rewrite css urls in css proxy service


<?php

namespace CatLab\Requirements\Traits;

use CatLab\Requirements\Enums\PropertyType;

/**
 * Class TypeSetter
 * @package CatLab\Requirements\Enums\PropertyType
 */
trait TypeSetter
{
    /**
     * @param $type
     * @return $this
     */
    public abstract function setType($type);

    /**
     * @return $this
     */
    public function int()
    {
        $this->setType(PropertyType::INTEGER);
        return $this;
    }

    /**
     * @return $this
     */
    public function string()
    {
        $this->setType(PropertyType::STRING);
        return $this;
    }

    /**
     * @return $this
     */
    public function bool()
    {
        $this->setType(PropertyType::BOOL);
        return $this;
    }

    /**
     * @return $this
     */
    public function datetime()
    {
        $this->setType(PropertyType::DATETIME);
        return $this;
    }

    /**
     * @return $this
     */
    public function number()
    {
        $this->setType(PropertyType::NUMBER);
        return $this;
    }

    public function object()
    {
        $this->setType(PropertyType::OBJECT);
        return $this;
    }
}

<?php

namespace CatLab\Requirements\Traits;

use CatLab\Requirements\Enums\PropertyType;

/**
 * Class TypeSetter
 * @package CatLab\Requirements\Enums\PropertyType
 */
trait TypeSetter
{
    /**
     * @param $type
     * @return $this
     */
    public abstract function setType($type);

    /**
     * @return $this
     */
    public function int()
    {
        $arguments = func_get_args();
        array_unshift($arguments, PropertyType::INTEGER);
        call_user_func_array([ $this, 'setType' ], $arguments);

        return $this;
    }

    /**
     * @return $this
     */
    public function string()
    {
        $arguments = func_get_args();
        array_unshift($arguments, PropertyType::STRING);
        call_user_func_array([ $this, 'setType' ], $arguments);
        return $this;
    }

    /**
     * @return $this
     */
    public function bool()
    {
        $arguments = func_get_args();
        array_unshift($arguments, PropertyType::BOOL);
        call_user_func_array([ $this, 'setType' ], $arguments);
        return $this;
    }

    /**
     * @return $this
     */
    public function datetime()
    {
        $arguments = func_get_args();
        array_unshift($arguments, PropertyType::DATETIME);
        call_user_func_array([ $this, 'setType' ], $arguments);
        return $this;
    }

    /**
     * @return $this
     */
    public function number()
    {
        $arguments = func_get_args();
        array_unshift($arguments, PropertyType::NUMBER);
        call_user_func_array([ $this, 'setType' ], $arguments);
        return $this;
    }

    /**
     * @return $this
     */
    public function object()
    {
        $arguments = func_get_args();
        array_unshift($arguments, PropertyType::OBJECT);
        call_user_func_array([ $this, 'setType' ], $arguments);
        return $this;
    }
}

Add ability to pass extra parameters for property types.


<?php

namespace Plummer\Calendar;

interface RecurrenceInterface
{
	public function getEvents();
}

<?php

namespace Plummer\Calendar;

interface RecurrenceInterface
{
	public function generate();
}

Rename Recurrence Interface function to a more appropriate name.


<?php
/**
 *
 */

namespace Mvc5\Test\Service;

use Mvc5\App;
use Mvc5\Service\Context;
use Mvc5\Test\Test\TestCase;

/**
 * @runTestsInSeparateProcesses
 */
class ContextTest
    extends TestCase
{
    /**
     *
     */
    function test_bind()
    {
        $app = new App;

        Context::bind($app);

        $this->assertEquals($app, ServiceFacade::service());
    }

    /**
     *
     */
    function test_bind_exception()
    {
        $app = new App;

        Context::bind($app);

        $this->expectExceptionMessage('Service already exists');

        Context::bind($app);
    }

    /**
     *
     */
    function test_instantiate_with_service()
    {
        $app = new App;

        $context = new Context($app);

        $this->assertEquals($app, $context->service());
    }

    /**
     *
     */
    function test_invoke()
    {
        $app = new App;

        $context = new Context;

        $context($app);

        $this->assertEquals($app, $context->service());
    }

    /**
     *
     */
    function test_service_does_not_exist()
    {
        $this->expectExceptionMessage('Service does not exist');

        Context::service();
    }
}

<?php
/**
 *
 */

namespace Mvc5\Test\Service;

use Mvc5\App;
use Mvc5\Service\Context;
use Mvc5\Test\Test\TestCase;

/**
 * @runTestsInSeparateProcesses
 */
class ContextTest
    extends TestCase
{
    /**
     *
     */
    function test_bind()
    {
        $app = new App;

        Context::bind($app);

        $this->assertEquals($app, ServiceFacade::service());
    }

    /**
     *
     */
    function test_bind_exception()
    {
        $app = new App;

        Context::bind($app);

        $this->expectExceptionMessage('Service already exists');

        Context::bind($app);
    }

    /**
     *
     */
    function test_instantiate_with_service()
    {
        $app = new App;

        $context = new Context($app);

        $this->assertEquals($app, $context->service());
    }

    /**
     *
     */
    function test_call_static()
    {
        new Context(new App);

        $this->assertEquals(phpversion(), Context::{'@phpversion'}());
    }

    /**
     *
     */
    function test_invoke()
    {
        $app = new App;

        $context = new Context;

        $context($app);

        $this->assertEquals($app, $context->service());
    }

    /**
     *
     */
    function test_service_does_not_exist()
    {
        $this->expectExceptionMessage('Service does not exist');

        Context::service();
    }
}

Add call static helper method to service context


<?php
/**
 * Delete spam older than 30 days
 */

if(php_sapi_name() !== 'cli') {
	die('CLI only');
}

date_default_timezone_set('Europe/London');

require dirname(__FILE__) . '/../bootstrap.php';

$manager = \FelixOnline\Core\BaseManager::build('FelixOnline\Core\Comment', 'comment');
$manager->filter("spam = 1")
		->filter("timestamp < DATE_SUB(NOW(), INTERVAL 30 DAY);");

$values = $manager->values();

if(!$values) {
	echo "Nothing to do.\n";
	return;
}

$app = App::getInstance();

foreach($values as $record) {
	$id = $record->getId();

	$app['db']->query("DELETE FROM akismet_log WHERE comment_id = ".$id);
	$app['db']->query("DELETE FROM comment WHERE id = ".$id);
}

echo "All done.\n";

<?php
/**
 * Delete spam older than 30 days
 */

if(php_sapi_name() !== 'cli') {
	die('CLI only');
}

date_default_timezone_set('Europe/London');

require dirname(__FILE__) . '/../bootstrap.php';

$manager = \FelixOnline\Core\BaseManager::build('FelixOnline\Core\Comment', 'comment');
$manager->filter("spam = 1")
		->filter("timestamp < DATE_SUB(NOW(), INTERVAL 30 DAY);");

$values = $manager->values();

if(!$values) {
	echo "Nothing to do.\n";
	return;
}

$app = \FelixOnline\Core\App::getInstance();

foreach($values as $record) {
	$id = $record->getId();

	$app['db']->query("DELETE FROM akismet_log WHERE comment_id = ".$id);
	$app['db']->query("DELETE FROM comment WHERE id = ".$id);
}

echo "All done.\n";

Fix a typo on the clean old spam script

Fix a typo on the clean old spam script


<?php
namespace Vanio\WebBundle\Form;

use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\TransformationFailedException;

class MapTransformer implements DataTransformerInterface
{
    /** @var string */
    private $keyName;

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

    /** @var bool */
    private $appendOnEmptyKey;

    public function __construct(string $keyName, string $valueName, bool $appendOnEmptyKey)
    {
        $this->keyName = $keyName;
        $this->valueName = $valueName;
        $this->appendOnEmptyKey = $appendOnEmptyKey;
    }

    /**
     * @param mixed $value
     * @return array
     */
    public function transform($value): array
    {
        return $value;
    }

    /**
     * @param mixed $value
     * @return array
     */
    public function reverseTransform($value): array
    {
        $map = [];

        foreach ($value as $data) {
            if (!array_key_exists($this->keyName, $data) || !array_key_exists($this->valueName, $data)) {
                throw new TransformationFailedException('Invalid data structure.');
            } elseif (array_key_exists((string) $data[$this->keyName], $map)) {
                throw new TransformationFailedException('Duplicate key detected.');
            }

            if ($this->appendOnEmptyKey && $data[$this->keyName] === null) {
                $map[] = $data[$this->valueName];
            } else {
                $map[(string) $data[$this->keyName]] = $data[$this->valueName];
            }
        }

        return $map;
    }
}

<?php
namespace Vanio\WebBundle\Form;

use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\TransformationFailedException;

class MapTransformer implements DataTransformerInterface
{
    /** @var string */
    private $keyName;

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

    /** @var bool */
    private $appendOnEmptyKey;

    public function __construct(string $keyName, string $valueName, bool $appendOnEmptyKey)
    {
        $this->keyName = $keyName;
        $this->valueName = $valueName;
        $this->appendOnEmptyKey = $appendOnEmptyKey;
    }

    /**
     * @param mixed $value
     * @return array
     */
    public function transform($value): array
    {
        return $value ?? [];
    }

    /**
     * @param mixed $value
     * @return array
     */
    public function reverseTransform($value): array
    {
        $map = [];

        foreach ($value as $data) {
            if (!array_key_exists($this->keyName, $data) || !array_key_exists($this->valueName, $data)) {
                throw new TransformationFailedException('Invalid data structure.');
            } elseif (array_key_exists((string) $data[$this->keyName], $map)) {
                throw new TransformationFailedException('Duplicate key detected.');
            }

            if ($this->appendOnEmptyKey && $data[$this->keyName] === null) {
                $map[] = $data[$this->valueName];
            } else {
                $map[(string) $data[$this->keyName]] = $data[$this->valueName];
            }
        }

        return $map;
    }
}

Allow null data for MapType (convert to empty array in transformer).


<?php

/*
 * This file is part of the symfony package.
 * (c) Fabien Potencier <fabien.potencier@symfony-project.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

/**
 * sfWidgetFormInputHidden represents a hidden HTML input tag.
 *
 * @package    symfony
 * @subpackage widget
 * @author     Fabien Potencier <fabien.potencier@symfony-project.com>
 * @version    SVN: $Id$
 */
class sfWidgetFormInputHidden extends sfWidgetFormInput
{
  /**
   * Configures the current widget.
   *
   * @param array $options     An array of options
   * @param array $attributes  An array of default HTML attributes
   *
   * @see sfWidgetFormInput
   */
  protected function configure($options = array(), $attributes = array())
  {
    parent::configure($options, $attributes);

    $this->setOption('is_hidden', true);
    $this->setOption('type', 'hidden');
  }
}

<?php

/*
 * This file is part of the symfony package.
 * (c) Fabien Potencier <fabien.potencier@symfony-project.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

/**
 * sfWidgetFormInputHidden represents a hidden HTML input tag.
 *
 * @package    symfony
 * @subpackage widget
 * @author     Fabien Potencier <fabien.potencier@symfony-project.com>
 * @version    SVN: $Id$
 */
class sfWidgetFormInputHidden extends sfWidgetFormInput
{
  /**
   * Configures the current widget.
   *
   * @param array $options     An array of options
   * @param array $attributes  An array of default HTML attributes
   *
   * @see sfWidgetFormInput
   */
  protected function configure($options = array(), $attributes = array())
  {
    parent::configure($options, $attributes);

    $this->setOption('is_hidden', true);
    $this->setOption('type', 'hidden');
    $this->addOption('multiple', false);
  }

  /**
    * Renders the widget.
    *
    * @param  string $name        The element name
    * @param  string $value       The value displayed in this widget
    * @param  array  $attributes  An array of HTML attributes to be merged with the default HTML attributes
    * @param  array  $errors      An array of errors for the field
    *
    * @return string An HTML tag string
    *
    * @see sfWidgetForm
    */
  public function render($name, $value = null, $attributes = array(), $errors = array())
  {
     if ($this->getOption('multiple'))
     {
       $name .= '[]';
       $attributes['multiple'] = $this->getOption('multiple');
      }
      return parent::render($name, $value, $attributes, $errors);
  }
}

Add option multiple to sfWidgetFormInputHidden


<?php
namespace SimpleAcl\Object;

use SimpleAcl\Object;

/**
 * Implement common function for Role and Resources.
 *
 */
abstract class ObjectAggregate
{
    /**
     * @var Object[]
     */
    protected $objects = array();

    /**
     * @param Object $object
     */
    protected function addObject(Object $object)
    {
        $this->objects[$object->getName()] = $object;
    }

    protected function removeObjects()
    {
        $this->objects = array();
    }

    /**
     * @param string $objectName
     */
    protected function removeObject($objectName)
    {
        foreach ( $this->objects as $objectIndex => $object ) {
            if ( $object->getName() == $objectName ) {
                unset($this->objects[$objectIndex]);
                return;
            }
        }
    }

    /**
     * @param array $objects
     */
    protected function setObjects($objects)
    {
        /** @var Object $object  */
        foreach ($objects as $object) {
            $this->addObject($object);
        }
    }

    /**
     * @return array|Object[]
     */
    protected function getObjects()
    {
        return $this->objects;
    }

    /**
     * @param string $objectName
     * @return null|Object
     */
    protected function getObject($objectName)
    {
        if ( isset($this->objects[$objectName]) ) {
            return $this->objects[$objectName];
        }

        return null;
    }
}

<?php
namespace SimpleAcl\Object;

use SimpleAcl\Object;

/**
 * Implement common function for Role and Resources.
 *
 */
abstract class ObjectAggregate
{
    /**
     * @var Object[]
     */
    protected $objects = array();

    /**
     * @param Object $object
     */
    protected function addObject(Object $object)
    {
        $this->objects[$object->getName()] = $object;
    }

    protected function removeObjects()
    {
        $this->objects = array();
    }

    /**
     * @param string $objectName
     */
    protected function removeObject($objectName)
    {
        unset($this->objects[$objectName]);
    }

    /**
     * @param array $objects
     */
    protected function setObjects($objects)
    {
        /** @var Object $object  */
        foreach ($objects as $object) {
            $this->addObject($object);
        }
    }

    /**
     * @return array|Object[]
     */
    protected function getObjects()
    {
        return $this->objects;
    }

    /**
     * @param string $objectName
     * @return null|Object
     */
    protected function getObject($objectName)
    {
        if ( isset($this->objects[$objectName]) ) {
            return $this->objects[$objectName];
        }

        return null;
    }
}

Simplify implementation of removeObject method.


<?php

require 'hex2base64.php';

$input = "49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d";

$target = "SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t";

$output = hex2base64($input);

echo "Input : $input\n";
echo "Target: $target\n";
echo "Output: $output\n";

if ($target == $output) {
  echo "Match\n";
} else {
  echo "No match\n";
}

?>

<?php

require 'hex2base64.php';

if ($argc == 1) {
  $input = "49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d";

  $target = "SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t";

  $output = hex2base64($input);

  echo "Input : $input\n";
  echo "Target: $target\n";
  echo "Output: $output\n";

  if ($target == $output) {
    echo "Match\n";
  } else {
    echo "No match\n";
  }
} elseif ($argc == 2) {
  $input  = $argv[1];
  $output = hex2base64($input);
  echo $output . "\n";
} else {
  echo "Single hex string only.\n";
}
?>

Add option to provide hex string via command line


<?php
namespace MOC\Redirects\Controller;

use TYPO3\Flow\Annotations as Flow;
use TYPO3\Neos\Service\LinkingService;
use TYPO3\TYPO3CR\Domain\Model\Node;

class RedirectController extends \TYPO3\Flow\Mvc\Controller\ActionController {

	/**
	 * @Flow\Inject
	 * @var LinkingService
	 */
	protected $linkingService;

	/**
	 * @param Node $node
	 * @return void
	 *
	 * @Flow\IgnoreValidation("node")
	 */
	public function redirectAction(Node $node) {
		$this->redirectToUri($this->linkingService->createNodeUri($this->controllerContext, $node), 0, 301);
	}

}

<?php
namespace MOC\Redirects\Controller;

use TYPO3\Flow\Annotations as Flow;
use TYPO3\Neos\Service\LinkingService;
use TYPO3\TYPO3CR\Domain\Model\Node;

class RedirectController extends \TYPO3\Flow\Mvc\Controller\ActionController {

	/**
	 * @Flow\Inject
	 * @var LinkingService
	 */
	protected $linkingService;

	/**
	 * @param Node $node
	 * @return void
	 *
	 * @Flow\IgnoreValidation("node")
	 */
	public function redirectAction(Node $node) {
		$this->redirectToUri($this->linkingService->createNodeUri($this->controllerContext, $node, NULL, NULL, TRUE, array(), '', TRUE), 0, 301);
	}

}

[TASK] Append existing query string to redirects


<?php
// comment out the following two lines when deployed to production
defined('YII_DEBUG') or define('YII_DEBUG', true);
// defined('YII_ENV') or define('YII_ENV', 'dev');
error_reporting(-1);
ini_set('display_errors', true);

require(__DIR__ . '/_protected/vendor/autoload.php');
require(__DIR__ . '/_protected/vendor/yiisoft/yii2/Yii.php');

$config = require(__DIR__ . '/_protected/config/web.php');

(new yii\web\Application($config))->run();

<?php
// comment out the following two lines when deployed to production
// defined('YII_DEBUG') or define('YII_DEBUG', true);
// defined('YII_ENV') or define('YII_ENV', 'dev');
// error_reporting(-1);
// ini_set('display_errors', true);

require(__DIR__ . '/_protected/vendor/autoload.php');
require(__DIR__ . '/_protected/vendor/yiisoft/yii2/Yii.php');

$config = require(__DIR__ . '/_protected/config/web.php');

(new yii\web\Application($config))->run();

Remove debug from production (temp)

Remove debug from production (temp)


<?php

namespace App\Validation\EntityRules;

use App\Entities\User;
use Somnambulist\EntityValidation\AbstractEntityRules;

class UserRules extends AbstractEntityRules
{
    /**
     * Return an array of rules for validating Users
     *
     * @param object $entity
     * @return array
     */
    protected function buildRules($entity)
    {
        return [
            'name'     => 'bail|required|min:2',
            'email'    => 'bail|required|email|unique:'. User::class .',email',
            'password' => 'present',
        ];
    }

    /**
     * @return array
     */
    public function messages()
    {
        return [
            'name'     => 'Name must be at least two characters long.',
            'email'    => 'A person with that email address is already registered.',
            'password' => 'Your password should be at least 8 characters long.',
        ];
    }

    /**
     * Define the entity that this validator supports
     *
     * @param object $entity
     * @return bool
     */
    public function supports($entity)
    {
        return $entity instanceof User;
    }
}

<?php

namespace App\Validation\EntityRules;

use App\Entities\User;
use Somnambulist\EntityValidation\AbstractEntityRules;

class UserRules extends AbstractEntityRules
{
    /**
     * Return an array of rules for validating Users
     *
     * @param object $entity
     * @return array
     */
    protected function buildRules($entity)
    {
        return [
            'name'     => 'bail|required|min:2',
            'email'    => 'bail|required|email',
            'password' => 'present',
        ];
    }

    /**
     * @return array
     */
    public function messages()
    {
        return [
            'name'     => 'Name must be at least two characters long.',
            'email'    => 'A person with that email address is already registered.',
            'password' => 'Your password should be at least 8 characters long.',
        ];
    }

    /**
     * Define the entity that this validator supports
     *
     * @param object $entity
     * @return bool
     */
    public function supports($entity)
    {
        return $entity instanceof User;
    }
}

Remove the uniqueness rule here as it prevented saving changes when the email address was not changed.


<?php
/**
 *
 * (c) Marco Bunge <marco_bunge@web.de>
 *
 * For the full copyright and license information, please view the LICENSE.txt
 * file that was distributed with this source code.
 *
 * Date: 12.02.2016
 * Time: 10:39
 *
 */

namespace Blast\Db\Data;

trait FilterableTrait
{
    /**
     * Filter containing entities
     *
     * @param callable $filter
     * @return array
     */
    public function filter(callable $filter)
    {
        return array_filter(Helper::receiveDataFromObject($this), $filter, ARRAY_FILTER_USE_BOTH);
    }
}

<?php
/**
 *
 * (c) Marco Bunge <marco_bunge@web.de>
 *
 * For the full copyright and license information, please view the LICENSE.txt
 * file that was distributed with this source code.
 *
 * Date: 12.02.2016
 * Time: 10:39
 *
 */

namespace Blast\Db\Data;

trait FilterableTrait
{
    /**
     * Filter data by callback
     *
     * Emulates array_filter behaviour with optional flags ARRAY_FILTER_USE_BOTH for PHP version < 5.6.x
     *
     * Create a callback with key and value parameters and return a boolean.
     *
     * ```
     * FilterableTrait::filter(function($key, $value){
     *  //added to result if value is scalar
     *  return is_scalar($value)
     * });
     * ```
     *
     * @see http://php.net/manual/de/function.array-filter.php
     *
     * @param callable $filter
     * @return array
     */
    public function filter(callable $filter)
    {
        $data = DataHelper::receiveDataFromObject($this);

        if(defined('ARRAY_FILTER_USE_BOTH') && version_compare(PHP_VERSION, '5.6.0') >= 0){
            return array_filter($data, $filter, ARRAY_FILTER_USE_BOTH);
        }

        $results = [];

        //if filter is truthy pass key-value-pair to results
        foreach($data as $key => $value){
            if(call_user_func($filter, $key, $value) == true){
                $results[$key] = $value;
            }
        }

        return $results;
    }
}

Add Fallback for ARRAY_FILTER_USE_BOTH behaviour on array_filter for PHP version < 5.6


<?php

namespace DoctrineExtensions\Query\Mysql;

use Doctrine\ORM\Query\AST\Functions\FunctionNode,
    Doctrine\ORM\Query\Lexer;

/**
 * @author Michael Kimpton <mike@sketchthat.com>
 */
class YearWeek extends FunctionNode
{
    public $date;

    public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker)
    {
        return "YEARWEEK(" . $sqlWalker->walkArithmeticPrimary($this->date) . ")";
    }

    public function parse(\Doctrine\ORM\Query\Parser $parser)
    {
        $parser->match(Lexer::T_IDENTIFIER);
        $parser->match(Lexer::T_OPEN_PARENTHESIS);

        $this->date = $parser->ArithmeticPrimary();

        $parser->match(Lexer::T_CLOSE_PARENTHESIS);
    }
}

<?php

namespace DoctrineExtensions\Query\Mysql;

use Doctrine\ORM\Query\AST\Functions\FunctionNode,
    Doctrine\ORM\Query\Lexer;

/**
 * @author Michael Kimpton <mike@sketchthat.com>
 */
class YearWeek extends FunctionNode
{
    public $date;
    public $mode;

    public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker)
    {
        $sql = "YEARWEEK(" . $sqlWalker->walkArithmeticPrimary($this->date);
        if ($this->mode != null) {
            $sql .= ", " . $sqlWalker->walkLiteral($this->mode);
        }
        $sql .= ")";

        return $sql;
    }

    public function parse(\Doctrine\ORM\Query\Parser $parser)
    {
        $parser->match(Lexer::T_IDENTIFIER);
        $parser->match(Lexer::T_OPEN_PARENTHESIS);

        $this->date = $parser->ArithmeticPrimary();

        if (Lexer::T_COMMA === $parser->getLexer()->lookahead['type']) {
            $parser->match(Lexer::T_COMMA);
            $this->mode = $parser->Literal();
        }

        $parser->match(Lexer::T_CLOSE_PARENTHESIS);
    }
}

Add mode parameter for YEARWEEK

Add mode parameter for YEARWEEK


<?php

return array(
    'import' => array(
        'application.modules.Genetics.models.*',
        'application.modules.Genetics.components.*',
    ),
    'params' => array(
        'menu_bar_items' => array(
            'pedigrees' => array(
                'title' => 'Genetics',
                'uri' => 'Genetics/default/index',
                'position' => 40,
                'restricted' => array('Genetics User'),
            ),
        ),
        'module_partials' => array(
            'patient_summary_column1' => array(
                'Genetics' => array(
                    '_patient_genetics',
                ),
            ),
        ),
        'admin_structure' => array(
            'Studies' => array(
                'Genetics' => '/Genetics/studyAdmin/list',
            ),
        ),
        'admin_menu' => array(
            'Base Change Type' => '/Genetics/baseChangeAdmin/list',
            'Amino Acid Change Type' => '/Genetics/aminoAcidChangeAdmin/list',
            'DNA Sample Change' => '/OphInDnasample/DnaSampleAdmin/list',
            'Genome Versions' => '/Genetics/admin/list'
        ),
    ),
);

<?php

return array(
    'import' => array(
        'application.modules.Genetics.models.*',
        'application.modules.Genetics.components.*',
    ),
    'params' => array(
        'menu_bar_items' => array(
            'pedigrees' => array(
                'title' => 'Genetics',
                'uri' => 'Genetics/default/index',
                'position' => 40,
                'restricted' => array('Genetics User'),
            ),
        ),
        'module_partials' => array(
            'patient_summary_column1' => array(
                'Genetics' => array(
                    '_patient_genetics',
                ),
            ),
        ),
        'admin_structure' => array(
            'Studies' => array(
                'Genetics' => '/Genetics/studyAdmin/list',
            ),
        ),
        'admin_menu' => array(
            'Base Change Type' => '/Genetics/baseChangeAdmin/list',
            'Amino Acid Change Type' => '/Genetics/aminoAcidChangeAdmin/list',
            'Genome Versions' => '/Genetics/admin/list'
        ),
    ),
);

Remove duplicated DNA Sample Change from admin


<?php

namespace App\Exceptions;

use Exception;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that should not be reported.
     *
     * @var array
     */
    protected $dontReport = [
        HttpException::class,
        ModelNotFoundException::class,
    ];

    /**
     * Report or log an exception.
     *
     * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
     *
     * @param  \Throwable  $e
     * @return void
     */
    public function report(Exception $e)
    {
        return parent::report($e);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Throwable  $e
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $e)
    {
        if ($e instanceof ModelNotFoundException) {
            $e = new NotFoundHttpException($e->getMessage(), $e);
        }

        return parent::render($request, $e);
    }
}

<?php

namespace App\Exceptions;

use Exception;
use Illuminate\Auth\Access\UnauthorizedException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Illuminate\Foundation\Validation\ValidationException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that should not be reported.
     *
     * @var array
     */
    protected $dontReport = [
        HttpException::class,
        ModelNotFoundException::class,
        UnauthorizedException::class,
        ValidationException::class,
    ];

    /**
     * Report or log an exception.
     *
     * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
     *
     * @param  \Throwable  $e
     * @return void
     */
    public function report(Exception $e)
    {
        return parent::report($e);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Throwable  $e
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $e)
    {
        return parent::render($request, $e);
    }
}

Clean up exception handler. Add new ignores.


<?php

use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;

class AppKernel extends Kernel
{
    public function registerBundles()
    {
        $bundles = array(
            new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
            new Symfony\Bundle\SecurityBundle\SecurityBundle(),
            new Symfony\Bundle\TwigBundle\TwigBundle(),
            new Symfony\Bundle\MonologBundle\MonologBundle(),
            new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
            new Symfony\Bundle\DoctrineBundle\DoctrineBundle(),
            new Symfony\Bundle\AsseticBundle\AsseticBundle(),
            new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
            new JMS\SecurityExtraBundle\JMSSecurityExtraBundle(),
            new FOS\UserBundle\FOSUserBundle(),
            new And6a\TrombiBundle\And6aTrombiBundle(),
        );

        if (in_array($this->getEnvironment(), array('dev', 'test'))) {
            //$bundles[] = new Acme\DemoBundle\AcmeDemoBundle();
            $bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
            $bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle();
            $bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle();
        }

        return $bundles;
    }

    public function registerContainerConfiguration(LoaderInterface $loader)
    {
        $loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml');
    }
}

<?php

use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;

class AppKernel extends Kernel
{
    public function registerBundles()
    {
        $bundles = array(
            new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
            new Symfony\Bundle\SecurityBundle\SecurityBundle(),
            new Symfony\Bundle\TwigBundle\TwigBundle(),
            new Symfony\Bundle\MonologBundle\MonologBundle(),
            new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
            new Symfony\Bundle\DoctrineBundle\DoctrineBundle(),
            new Symfony\Bundle\AsseticBundle\AsseticBundle(),
            new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
            new JMS\SecurityExtraBundle\JMSSecurityExtraBundle(),
            new And6a\TrombiBundle\And6aTrombiBundle(),
        );

        if (in_array($this->getEnvironment(), array('dev', 'test'))) {
            //$bundles[] = new Acme\DemoBundle\AcmeDemoBundle();
            $bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
            $bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle();
            $bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle();
        }

        return $bundles;
    }

    public function registerContainerConfiguration(LoaderInterface $loader)
    {
        $loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml');
    }
}

Install FOSUser - step 1.4

Install FOSUser - step 1.4


<?php

namespace Bolt\Extension\Bolt\Importwxr;

use Bolt\Extension\Bolt\Importwxr\Controller\ImportController;
use Bolt\Extension\SimpleExtension;
use Bolt\Menu\MenuEntry;

/**
 * Importwxr extension class.
 *
 * @author Your Name <you@example.com>
 */
class ImportwxrExtension extends SimpleExtension
{

    protected function registerMenuEntries()
    {
        $menu = new MenuEntry('importwxr-menu', 'importWXR');
        $menu->setLabel('Import WXR')
            ->setIcon('fa:gear')
            ->setPermission('settings')
        ;
        return [
            $menu,
        ];
    }

    protected function registerBackendControllers()
    {
        return [
            '/extend/importWXR' => new ImportController($this->getContainer(), $this->getConfig()),
        ];
    }

    /**
     * {@inheritdoc}
     */
    protected function getDefaultConfig()
    {
        return [
            'allowed_tags' => ['div', 'p', 'br', 's', 'u', 'strong', 'em', 'i', 'b',  'blockquote', 'a', 'img'],
            'allowed_attributes' => ['id', 'class', 'name', 'value', 'href', 'src', 'alt', 'title']
        ];
    }

}

<?php

namespace Bolt\Extension\Bolt\Importwxr;

use Bolt\Extension\Bolt\Importwxr\Controller\ImportController;
use Bolt\Extension\SimpleExtension;
use Bolt\Menu\MenuEntry;

/**
 * Importwxr extension class.
 *
 * @author Your Name <you@example.com>
 */
class ImportwxrExtension extends SimpleExtension
{

    protected function registerMenuEntries()
    {
        $menu = new MenuEntry('importwxr-menu', 'importWXR');
        $menu->setLabel('Import WXR')
            ->setIcon('fa:gear')
            ->setPermission('settings')
        ;
        return [
            $menu,
        ];
    }

    protected function registerBackendControllers()
    {
        return [
            '/extensions/importWXR' => new ImportController($this->getContainer(), $this->getConfig()),
        ];
    }

    /**
     * {@inheritdoc}
     */
    protected function getDefaultConfig()
    {
        return [
            'allowed_tags' => ['div', 'p', 'br', 's', 'u', 'strong', 'em', 'i', 'b',  'blockquote', 'a', 'img'],
            'allowed_attributes' => ['id', 'class', 'name', 'value', 'href', 'src', 'alt', 'title']
        ];
    }

}

Change extension path in registerBackendControllers()


<?php
/*
 * (c) Sajjad Hashemian <wolaws@gmail.com>
 */

namespace Sijad\Spoiler\Listener;

use Flarum\Event\ConfigureFormatter;
use Illuminate\Contracts\Events\Dispatcher;

class AddBBCode
{
    /**
     * @param Dispatcher $events
     */
    public function subscribe(Dispatcher $events)
    {
        $events->listen(ConfigureFormatter::class, [$this, 'AddBBCode']);
    }

    /**
     * @param ConfigureFormatter $event
     */
    public function AddBBCode(ConfigureFormatter $event)
    {
        // $event->configurator->BBCodes->addFromRepository('SPOILER');

        $event->configurator->BBCodes->addCustom(
            '[SPOILER title={TEXT1;optional}]{TEXT2}[/SPOILER]',
            '

 {TEXT1}

{TEXT2}

'
        );
    }
}

<?php
/*
 * (c) Sajjad Hashemian <wolaws@gmail.com>
 */

namespace Sijad\Spoiler\Listener;

use Flarum\Event\ConfigureFormatter;
use Illuminate\Contracts\Events\Dispatcher;

class AddBBCode
{
    /**
     * @param Dispatcher $events
     */
    public function subscribe(Dispatcher $events)
    {
        $events->listen(ConfigureFormatter::class, [$this, 'addBBCode']);
    }

    /**
     * @param ConfigureFormatter $event
     */
    public function addBBCode(ConfigureFormatter $event)
    {
        // $event->configurator->BBCodes->addFromRepository('SPOILER');

        $event->configurator->BBCodes->addCustom(
            '[SPOILER title={TEXT1;optional}]{TEXT2}[/SPOILER]',
            '

 {TEXT1}

{TEXT2}

'
        );
    }
}

Change function name to camelCase

Change function name to camelCase


<?php
/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\Logger;
use Monolog\TestCase;

class ZendMonitorHandlerTest extends TestCase
{
    protected $zendMonitorHandler;

    public function setUp()
    {
        if (!function_exists('zend_monitor_custom_event')) {
            $this->markTestSkipped('ZendServer is not installed');
        }
    }

    /**
     * @covers  \Monolog\Handler\ZendMonitor::__construct
     * @covers  \Monolog\Handler\ZendMonitor::isZendServer
     */
    public function testIsZendServerReturnsTrue()
    {
        $zendMonitor = new ZendMonitorHandler();
        $this->assertTrue($zendMonitor->isZendServer());
    }

    /**
     * @covers  \Monolog\Handler\ZendMonitor::write
     */
    public function testWrite()
    {
        $zendMonitor = $this->getMockBuilder('Monolog\Handler\ZendMonitorHandler')
            ->setMethods(array('writeZendMonitorCustomEvent'))
            ->getMock();
        $zendMonitor->expects($this->once())
            ->method('writeZendMonitorCustomEvent');
        $zendMonitor->handle(
            array(
                'message'    => 'addDebug Message',
                'context'    => array(),
                'level'      => Logger::DEBUG,
                'level_name' => 'DEBUG',
                'channel'    => 'zendmonitor',
                'extra'      => array(),
                'formatted'  => '[2013-01-30 19:07:32] zendmonitor.DEBUG: addDebug Message [] []'
            )
        );
    }

}

<?php
/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\Logger;
use Monolog\TestCase;

class ZendMonitorHandlerTest extends TestCase
{
    protected $zendMonitorHandler;

    public function setUp()
    {
        if (!function_exists('zend_monitor_custom_event')) {
            $this->markTestSkipped('ZendServer is not installed');
        }
    }

    /**
     * @covers  \Monolog\Handler\ZendMonitor::__construct
     * @covers  \Monolog\Handler\ZendMonitor::isZendServer
     */
    public function testIsZendServerReturnsTrue()
    {
        $zendMonitor = new ZendMonitorHandler();
        $this->assertTrue($zendMonitor->isZendServer());
    }

    /**
     * @covers  \Monolog\Handler\ZendMonitor::write
     */
    public function testWrite()
    {
        $zendMonitor = $this->getMockBuilder('Monolog\Handler\ZendMonitorHandler')
            ->setMethods(array('writeZendMonitorCustomEvent'))
            ->getMock();
        $zendMonitor->expects($this->once())
            ->method('writeZendMonitorCustomEvent');
        $zendMonitor->handle($this->getRecord());
    }

}

Use getRecord to get a record in unit test


<?php
    namespace manuth\TemPHPlate\Properties;
    {
        class Settings
        {
        }
    }
?>

<?php
    namespace ManuTh\TemPHPlate\Properties;
    {
        /**
         * Provides settings for the Project
         */
        class Settings
        {
            /**
             * @var string[]
             * The locales to use to execute php
             */
            public static $Locales = array
            (
                // Windows-Format
                'de-CH',
                'de-DE',
                // Linux-Format
                'de_CH',
                'de_DE',
                'de_CH.UTF8',
                'de_DE.UTF8'
            );
        }
    }
?>

Add languages to the settings-class.

Add languages to the settings-class.


<?php
namespace Payum\YiiExtension;

use Payum\Core\Request\BinaryMaskStatusRequest;
use Payum\Core\Request\Http\RedirectUrlInteractiveRequest;
use Payum\Core\Request\SecuredCaptureRequest;

class PaymentController extends \CController
{
    public function actionCapture()
    {
        $token = $this->getPayum()->getHttpRequestVerifier()->verify($_REQUEST);
        $payment = $this->getPayum()->getRegistry()->getPayment($token->getPaymentName());

        $status = new BinaryMaskStatusRequest($token);
        $payment->execute($status);

        try {
            $capture = new SecuredCaptureRequest($token);
            $payment->execute($capture);
        } catch (RedirectUrlInteractiveRequest $interactiveRequest) {
            $this->redirect($interactiveRequest->getUrl(), true);
            return;
        } catch (\Exception $ex) {
            throw new \Exception('Unsupported request', null, $ex);
        }

        $this->getPayum()->getHttpRequestVerifier()->invalidate($token);

        $this->redirect($token->getAfterUrl());
    }

    /**
     * @return \Payum\YiiExtension\PayumComponent
     */
    protected function getPayum()
    {
        return \Yii::app()->payum;
    }
}

<?php
namespace Payum\YiiExtension;

use Payum\Core\Request\BinaryMaskStatusRequest;
use Payum\Core\Request\InteractiveRequestInterface;
use Payum\Core\Request\Http\RedirectUrlInteractiveRequest;
use Payum\Core\Request\SecuredCaptureRequest;

class PaymentController extends \CController
{
    public function init()
    {
        parent::init();

        \Yii::app()->attachEventHandler('onException', array($this, 'handleError'));
        \Yii::app()->attachEventHandler('onException', array($this, 'handleException'));
    }

    public function actionCapture()
    {
        $token = $this->getPayum()->getHttpRequestVerifier()->verify($_REQUEST);
        $payment = $this->getPayum()->getRegistry()->getPayment($token->getPaymentName());

        $status = new BinaryMaskStatusRequest($token);
        $payment->execute($status);

        $capture = new SecuredCaptureRequest($token);
        $payment->execute($capture);

        $this->getPayum()->getHttpRequestVerifier()->invalidate($token);

        $this->redirect($token->getAfterUrl());
    }

    public function handleError(\CExceptionEvent $event)
    {

    }

    public function handleException(\CExceptionEvent $event)
    {
        if (false == $event->exception instanceof InteractiveRequestInterface) {
            return;
        }

        $interactiveRequest = $event->exception;

        if ($interactiveRequest instanceof RedirectUrlInteractiveRequest) {
            $this->redirect($interactiveRequest->getUrl(), true);
            $event->handled = true;
            return;
        }
    }

    /**
     * @return \Payum\YiiExtension\PayumComponent
     */
    protected function getPayum()
    {
        return \Yii::app()->payum;
    }
}

Handle Exceptions via class method (the good way)


<?php

namespace Happyr\AutoFallbackTranslationBundle\DependencyInjection;

use Happyr\AutoFallbackTranslationBundle\Translator\GoogleTranslator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;

class HappyrAutoFallbackTranslationExtension extends Extension
{
    /**
     * @param array            $configs
     * @param ContainerBuilder $container
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $configs);
        $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
        $loader->load('services.yml');

        if (!$config['enabled']) {
            return;
        }

        switch($config['translation_service']) {
            case 'google':
                $translatorServiceDef = $container->register('happyr.translation.auto.service', GoogleTranslator::class);
                $translatorServiceDef->addArgument($config['google_key']);
                break;
            default:
                throw new \RuntimeException('You must choose a translation service for AutoFallbackTranslatorBundle.');
        }

        $translatorServiceDef->addMethodCall('setCachePool', [new Reference($config['cache_service'])]);

        $container->findDefinition('happyr.translation.auto_fallback_translator')
            ->replaceArgument(0, $config['default_locale'])
            ->replaceArgument(2, $translatorServiceDef)
            ->setDecoratedService('translator');
    }

}

<?php

namespace Happyr\AutoFallbackTranslationBundle\DependencyInjection;

use Happyr\AutoFallbackTranslationBundle\Translator\GoogleTranslator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;

class HappyrAutoFallbackTranslationExtension extends Extension
{
    /**
     * @param array            $configs
     * @param ContainerBuilder $container
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $configs);
        $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
        $loader->load('services.yml');

        if (!$config['enabled']) {
            return;
        }

        switch($config['translation_service']) {
            case 'google':
                $translatorServiceDef = $container->register('happyr.translation.auto.service', GoogleTranslator::class);
                $translatorServiceDef->addArgument($config['google_key']);
                break;
            default:
                throw new \RuntimeException('You must choose a translation service for AutoFallbackTranslatorBundle.');
        }

        $translatorServiceDef->addMethodCall('setCachePool', [new Reference($config['cache_service'])]);

        $container->findDefinition('happyr.translation.auto_fallback_translator')
            ->replaceArgument(0, $config['default_locale'])
            ->replaceArgument(2, $translatorServiceDef)
            ->setDecoratedService('translator', null, 10);
    }

}

Make sure we are the first decorator

Make sure we are the first decorator


<?php

namespace FOS\ElasticaBundle\Serializer;

use JMS\Serializer\SerializationContext;
use JMS\Serializer\SerializerInterface;

class Callback
{
    protected $serializer;
    protected $groups;
    protected $version;

    public function setSerializer($serializer)
    {
        $this->serializer = $serializer;
        if (!method_exists($this->serializer, 'serialize')) {
            throw new \RuntimeException('The serializer must have a "serialize" method.');
        }
    }

    public function setGroups(array $groups)
    {
        $this->groups = $groups;

        if ($this->groups) {
            if (!$this->serializer instanceof SerializerInterface) {
                throw new \RuntimeException('Setting serialization groups requires using "JMS\Serializer\Serializer".');
            }
        }
    }

    public function setVersion($version)
    {
        $this->version = $version;

        if ($this->version) {
            if (!$this->serializer instanceof SerializerInterface) {
                throw new \RuntimeException('Setting serialization version requires using "JMS\Serializer\Serializer".');
            }
        }
    }

    public function serialize($object)
    {
        $context = $this->serializer instanceof SerializerInterface ? new SerializationContext() : array();

        if ($this->groups) {
            $context->setGroups($this->groups);
        }

        if ($this->version) {
            $context->setVersion($this->version);
        }

        return $this->serializer->serialize($object, 'json', $context);
    }
}

<?php

namespace FOS\ElasticaBundle\Serializer;

use JMS\Serializer\SerializationContext;
use JMS\Serializer\SerializerInterface;

class Callback
{
    protected $serializer;
    protected $groups;
    protected $version;

    public function setSerializer($serializer)
    {
        $this->serializer = $serializer;
        if (!method_exists($this->serializer, 'serialize')) {
            throw new \RuntimeException('The serializer must have a "serialize" method.');
        }
    }

    public function setGroups(array $groups)
    {
        $this->groups = $groups;

        if ($this->groups) {
            if (!$this->serializer instanceof SerializerInterface) {
                throw new \RuntimeException('Setting serialization groups requires using "JMS\Serializer\Serializer".');
            }
        }
    }

    public function setVersion($version)
    {
        $this->version = $version;

        if ($this->version) {
            if (!$this->serializer instanceof SerializerInterface) {
                throw new \RuntimeException('Setting serialization version requires using "JMS\Serializer\Serializer".');
            }
        }
    }

    public function serialize($object)
    {
        $context = $this->serializer instanceof SerializerInterface ? SerializationContext::create()->enableMaxDepthChecks() : array();

        if ($this->groups) {
            $context->setGroups($this->groups);
        }

        if ($this->version) {
            $context->setVersion($this->version);
        }

        return $this->serializer->serialize($object, 'json', $context);
    }
}

[FEATURE] Use static instantiation with max depth check


<?php
namespace Repositories;

class ItemCache extends Item
{
  const CACHE_KEY = "itemSearch";
  public function where($text)
  {
    $key = self::CACHE_KEY.":$text";
    return \Cache::remember($key, 60, function () use ($text) {
      return parent::where($text);
    });

  }
}

<?php
namespace Repositories;

class ItemCache extends Item
{
  const CACHE_KEY = "itemSearch";
  public function where($text)
  {
    $key = self::CACHE_KEY.":$text";
    $items = \Cache::remember($key, 60, function () use ($text) {
      return array_map(function ($item) {
        return $item->id;
      }, parent::where($text));
      return $result;
    });

    return array_map(function ($item) {
      return $this->find($item);
    }, $items);

  }
}

Convert search result to simple a simple array and back to full.


<?php

require '../vendor/autoload.php';

$config = json_decode(file_get_contents("config/config.json"), true);
$config['root'] = __DIR__;
$app = new \Slim\App([ 'settings' => $config ]);

require '../dependencies.php';

// Routes
// =============================================================
$app->get('/events', Actions\ListVisibleEventsAction::class);
$app->get('/events/{id}', Actions\GetEventAction::class);

$app->get('/eventblocks/{id}', Actions\GetEventblockAction::class);

$app->get('/reservations', Actions\ListMyReservationsAction::class);
$app->post('/reservations', Actions\CreateReservationAction::class);
$app->put('/reservations/{id}', Actions\ChangeReductionForReservationAction::class);
$app->delete('/reservations/{id}', Actions\DeleteReservationAction::class);

$app->get('/orders', Actions\ListOrdersAction::class);

$app->post('/boxoffice-purchases', Actions\CreateBoxofficePurchaseAction::class);
$app->get('/boxoffice-purchases/{unique_id}', Actions\GetBoxofficePurchaseAction::class);
$app->put('/upgrade-order/{id}', Actions\UpgradeOrderToBoxofficePurchaseAction::class);
// =============================================================

$app->run();

<?php

require '../vendor/autoload.php';

$config = json_decode(file_get_contents("config/config.json"), true);
$config['root'] = __DIR__;
$app = new \Slim\App([ 'settings' => $config ]);

require '../dependencies.php';

// Routes
// =============================================================
$app->get('/events', Actions\ListVisibleEventsAction::class);
$app->get('/events/{id}', Actions\GetEventAction::class);

$app->get('/eventblocks/{id}', Actions\GetEventblockAction::class);

$app->get('/reservations', Actions\ListMyReservationsAction::class);
$app->post('/reservations', Actions\CreateReservationAction::class);
$app->put('/reservations/{id}', Actions\ChangeReductionForReservationAction::class);
$app->delete('/reservations/{id}', Actions\DeleteReservationAction::class);

$app->get('/reservations-expiration-timestamp', Actions\GetReservationsExpirationTimestampAction::class);

$app->get('/orders', Actions\ListOrdersAction::class);

$app->post('/boxoffice-purchases', Actions\CreateBoxofficePurchaseAction::class);
$app->get('/boxoffice-purchases/{unique_id}', Actions\GetBoxofficePurchaseAction::class);
$app->put('/upgrade-order/{id}', Actions\UpgradeOrderToBoxofficePurchaseAction::class);
// =============================================================

$app->run();

Add expiration timestamp endpoint for boxoffice


<?php

namespace Navitia\Component\Test\Request;

use Navitia\Component\Request\MetadatasRequest;

/**
 * Description of MetadatasRequestTest
 *
 * @author rndiaye
 */
class MetadatasRequestTest extends \PHPUnit_Framework_TestCase
{
    /**
     * Test for addToPathFilter
     *
     * @expectedException Navitia\Component\Exception\BadParametersException
     */
    public function testAddToPathFilter()
    {
        $service = new MetadatasRequest();
        $service->addtoPathFilter('bar', 'foo');
    }
}

<?php

namespace Navitia\Tests\Request;

use Navitia\Component\Request\MetadatasRequest;

/**
 * Description of MetadatasRequestTest
 *
 * @author rndiaye
 */
class MetadatasRequestTest extends \PHPUnit_Framework_TestCase
{
    /**
     * Test for addToPathFilter
     *
     * @expectedException Navitia\Component\Exception\BadParametersException
     */
    public function testAddToPathFilter()
    {
        $service = new MetadatasRequest();
        $service->addtoPathFilter('bar', 'foo');
    }
}

Fix namespace for test class

Fix namespace for test class


<?php

namespace Movim;

class Cookie
{
    public static function set()
    {
        if (SESSION_ID == false) {
            self::renew();
        } else {
            self::setCookie(SESSION_ID);
        }
    }

    public static function refresh()
    {
        if (isset($_COOKIE['MOVIM_SESSION_ID'])) {
            self::setCookie($_COOKIE['MOVIM_SESSION_ID']);
        }
    }

    public static function renew()
    {
        self::setCookie(generateKey(32));
    }

    public static function getTime()
    {
        return time()+604800;
    }

    private static function setCookie($key)
    {
        if (!headers_sent()) {
            header_remove('Set-Cookie');
            setcookie('MOVIM_SESSION_ID', $key, self::getTime(), '/', '', true, true);
        }
    }
}

<?php

namespace Movim;

class Cookie
{
    public static function set()
    {
        if (SESSION_ID == false) {
            self::renew();
        } else {
            self::setCookie(SESSION_ID);
        }
    }

    public static function refresh()
    {
        if (isset($_COOKIE['MOVIM_SESSION_ID'])) {
            self::setCookie($_COOKIE['MOVIM_SESSION_ID']);
        }
    }

    public static function renew()
    {
        self::setCookie(generateKey(32));
    }

    public static function getTime()
    {
        return time()+604800;
    }

    private static function setCookie($key)
    {
        if (!headers_sent()) {
            header_remove('Set-Cookie');
            setcookie('MOVIM_SESSION_ID', $key, self::getTime(), '/', '', true);
        }
    }
}

Remove HttpOnly for now as it causes auth issues


<?php

return [
    'all'             => 'Всі',
    'date'            => 'Дата',
    'empty-logs'      => 'Список журналів порожній!',
    'dashboard'       => 'Інформаційна панель',
    'entries'         => 'запис|записів',
    'logs'            => 'Журнали',
    'log'             => 'журнал',
    'log_info'        => 'журнал інформації',
    'download'        => 'Завантажити',
    'delete'          => 'Видалити',
    'file_path'       => 'Шлях до файлу :',
    'log_entries'     => 'Записи журналу :',
    'size'            => 'Розмір :',
    'created_at'      => 'Створено в :',
    'updated_at'      => 'Оновлено в :',
    'pagination'      => 'Сторінка :current із :last',
    'env'             => 'Змінні оточення',
    'levels'          => 'Рівні',
    'level'           => 'Рівень',
    'time'            => 'Час',
    'header'          => 'Опис',
    'actions'         => 'Дії',
    'stack'           => 'Стек',
    'close'           => 'Закрити',
    'delete_log_file' => 'ВИДАЛИТИ ФАЙЛ ЖУРНАЛУ',
    'sure_delete'     => 'Ви впевнені, що хочете :delete_button цей файл журналу :log_file ?',
    'cancel'          => 'Скасувати',
    'delete_file'     => 'ВИДАЛИТИ ФАЙЛ ЖУРНАЛУ',
];

<?php

return [
    'all'        => 'Всі',
    'date'       => 'Дата',
    'empty-logs' => 'Список журналів порожній!',
];

Remove the unused `uk` translations

Remove the unused `uk` translations


<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>@yield('title', $settings['site_title'])</title>

    <link rel="stylesheet" href="/css/app.css" type="text/css" media="screen" charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">

    <link href="{{ asset('/css/app.css') }}" rel="stylesheet">

    <link rel="shortcut icon" href="{{ asset('/assets/images/favicon.ico') }}">
    <link rel="apple-touch-icon" href="{{ asset('/assets/images/apple-touch-icon.png') }}">

    <!--[if lte IE 8]>
    <script src="{{ asset('/assets/vendor/html5shiv.min.js') }}"></script>
    <script src="{{ asset('/assets/vendor/respond.min.js') }}"></script>
    <![endif]-->

    @include('partials.metadata')
</head>
<body>
@include('partials.navigation')

<div class="container">
    @yield('content')
</div>

@include('partials.footer')

@include('partials.admin')

<script src="{{ asset('/js/bundle.js') }}" type="text/javascript" charset="utf-8"></script>

@include('partials.analytics')
</body>
</html>

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">

    <title>@yield('title', $settings['site_title'])</title>

    <link rel="stylesheet" href="/css/app.css" type="text/css" media="screen" charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <link href="{{ asset('/css/app.css') }}" rel="stylesheet">

    <link rel="shortcut icon" href="{{ asset('/assets/images/favicon.ico') }}">
    <link rel="apple-touch-icon" href="{{ asset('/assets/images/apple-touch-icon.png') }}">

    <!--[if lte IE 8]>
    <script src="{{ asset('/assets/vendor/html5shiv.min.js') }}"></script>
    <script src="{{ asset('/assets/vendor/respond.min.js') }}"></script>
    <![endif]-->

    @include('partials.metadata')
</head>
<body>
@include('partials.navigation')

<div class="container">
    @yield('content')
</div>

@include('partials.footer')

@include('partials.admin')

<script src="{{ asset('/js/bundle.js') }}" type="text/javascript" charset="utf-8"></script>

@include('partials.analytics')
</body>
</html>

Add CSRF token meta tag.

Add CSRF token meta tag.


<?php

/**
 * Return a path to the icon.
 * @param integer $size Icon size
 * @param string $context Context for the icon
 * @param string $name Name of the icon
 * @return string Path to the icon
 */
function ti_get_image_path($size, $context, $name) {
	return sfContext::getInstance()->getRequest()->getRelativeUrlRoot()."/sfTangoIconsPlugin/images/{$size}x{$size}/{$context}/{$name}.png";
}

<?php

/**
 * Return a path to the icon.
 * @param string $context Context for the icon
 * @param string $name Name of the icon
 * @param integer $size Icon size
 * @return string Path to the icon
 */
function ti_get_image_path($context, $name, $size) {
	return sfContext::getInstance()->getRequest()->getRelativeUrlRoot()."/sfTangoIconsPlugin/images/{$size}x{$size}/{$context}/{$name}.png";
}

Change the sequence of parameters

Change the sequence of parameters

git-svn-id: 1622d7ec2a250730bdec0066b369b09fce087714@31211 ee427ae8-e902-0410-961c-c3ed070cd9f9


<?php

namespace Psy\Test\Readline;

use Psy\Readline\TabCompletion;
use Psy\Context;

/**
 * Class TabCompletionTest
 * @package Psy\Test\Readline
 */
class TabCompletionTest extends \PHPUnit_Framework_TestCase
{
    public function testClassesCompletion()
    {
        class_alias('\Psy\Test\Readline\TabCompletionTest', 'Foo');
        $context = new Context();
        $tabCompletion = new TabCompletion($context);
        $code = $tabCompletion->processCallback('stdC', 4, array(
           "line_buffer"               => "new stdC",
           "point"                     => 7,
           "end"                       => 7,
        ));
        $this->assertContains('stdClass()', $code);
    }
}

<?php

namespace Psy\Test\Readline;

use Psy\Readline\TabCompletion;
use Psy\Context;

class TabCompletionTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider classesInput
     */
    public function testClassesCompletion($word, $index, $line, $point, $end, $expect)
    {
        $context = new Context();
        $tabCompletion = new TabCompletion($context);

        $code = $tabCompletion->processCallback($word, $index, array(
           'line_buffer' => $line,
           'point'       => $point,
           'end'         => $end,
        ));

        $this->assertContains($expect, $code);
    }

    public function classesInput()
    {
        return array(
            array('stdC', 4, 'new stdC',  7, 7, 'stdClass()'),
            array('stdC', 5, 'new \stdC', 8, 8, 'stdClass()'),
            array('stdC', 5, '(new stdC', 8, 8, 'stdClass()'),
            array('s',    7, 'new \a\\s', 8, 8, 'stdClass()'),
        );
    }
}

Add a dataprovider for tab completion test

Add a couple more complicated `new` invocations.


<?php

	class PointsOfInterestLayerExtensionTest extends SapphireTest {
		public function testUpdateCMSFields() {
			$this->markTestSkipped('TODO');
		}

}

<?php

	class PointsOfInterestLayerExtensionTest extends SapphireTest {

	public function setUpOnce() {
		$this->requiredExtensions = array(
			'POILayerExtensionPageTO' => array('MapExtension', 'PointsOfInterestLayerExtension')
		);
		parent::setUpOnce();
	}

	public function testUpdateCMSFields() {
		$page = new POILayerExtensionPageTO();
		$fields = $page->getCMSFields();
		$tab = $fields->findOrMakeTab('Root.MapLayers');
		$fields = $tab->FieldList();
		$names = array();
		foreach ($fields as $field) {
			$names[] = $field->getName();
		}

		$this->assertEquals(array('POI Layers'), $names);
	}

}

class POILayerExtensionPageTO extends Page implements TestOnly {
}

ENHANCEMENT: Test the points of interest layer extension cms fields


@if($isImage)

    thumbnail($width, $height, $filters) }}" class="{{ $classeNames ?? "" }}" alt="">

@else

        {{ basename($fileModel->file_name) }}

@endif

Update markdown embedd file view

Update markdown embedd file view


<?php

namespace thrieu\grid;

use Yii;
use yii\base\ActionFilter;
use yii\web\Request;

class ClearFilterStateBehavior extends ActionFilter {
    public $id;
    public $params;
    public $clearStateParam = 'clear-state';
    public $redirectToParam = 'redirect-to';
    public $exitIfAjax = true;

    public function beforeAction($action) {
        if(($params = $this->params) === null) {
            $request = Yii::$app->getRequest();
            $params = $request instanceof Request ? $request->post() : [];
        }

        if(isset($params[$this->clearStateParam]) && $params[$this->clearStateParam] != '0') {
            FilterStateTrait::clearFilterStateParams($this->id);

            if(Yii::$app->request->getIsAjax() && $this->exitIfAjax) {
                Yii::$app->end();
            } else if(isset($params[$this->redirectToParam])) {
                Yii::$app->response->redirect($params[$this->redirectToParam]);
            }
            return false;
        }
        return true;
    }
}

<?php

namespace thrieu\grid;

use Yii;
use yii\base\ActionFilter;
use yii\web\Request;

class ClearFilterStateBehavior extends ActionFilter {
    public $id;
    public $params;
    public $clearStateParam = 'clear-state';
    public $redirectToParam = 'redirect-to';
    public $exitIfAjax = true;

    public function beforeAction($action) {
        if(($params = $this->params) === null) {
            $request = Yii::$app->getRequest();
            $params = $request instanceof Request ? $request->post() : [];
        }

        if(isset($params[$this->clearStateParam]) && $params[$this->clearStateParam] != '0') {
            FilterStateTrait::clearFilterStateParams($this->id);

            if(Yii::$app->request->getIsAjax() && $this->exitIfAjax) {
                Yii::$app->end();
            } else {
                $redirectTo = isset($params[$this->redirectToParam]) ?
                    $params[$this->redirectToParam] : Yii::$app->controller->getRoute();
                Yii::$app->response->redirect($redirectTo);
            }
            return false;
        }
        return true;
    }
}

Add default value of redirecTo

Add default value of redirecTo


<?php

namespace AppBundle\Tests\Controller;

use AppBundle\Controller\BooksController;
use AppBundle\Domain\Service\BookService;
use AppBundle\MessageBus\CommandBus;

class BooksControllerTest extends \PHPUnit_Framework_TestCase
{
    public function testIndexActionRetrievesAllBooks()
    {
        $service = $this->getMockBuilder(BookService::class)
            ->disableOriginalConstructor()
            ->getMock();

        $service->expects(self::once())
            ->method('getAll');

        $commandBus = $this->getMockBuilder(CommandBus::class)
            ->disableOriginalConstructor()
            ->getMock();

        $controller = new BooksController($service, $commandBus);
        $controller->indexAction();
    }
}

<?php

namespace AppBundle\Tests\Controller;

use AppBundle\Controller\BooksController;
use AppBundle\Domain\Service\BookService;
use AppBundle\Domain\Service\ObjectNotFoundException;
use AppBundle\EventStore\Uuid;
use AppBundle\MessageBus\CommandBus;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class BooksControllerTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var BookService
     */
    private $service;

    /**
     * @var CommandBus
     */
    private $commandBus;

    protected function setUp()
    {
        $this->service = $this->getMockBuilder(BookService::class)
            ->disableOriginalConstructor()
            ->getMock();

        $this->commandBus = $this->getMockBuilder(CommandBus::class)
            ->disableOriginalConstructor()
            ->getMock();
    }

    public function testIndexActionRetrievesAllBooks()
    {
        $this->service->expects(self::once())
            ->method('getAll');

        $controller = new BooksController($this->service, $this->commandBus);
        $controller->indexAction();
    }

    public function testReadActionRetrievesBookById()
    {
        $id = Uuid::createNew();

        $this->service->expects(self::once())
            ->method('getBook')
            ->with($id);

        $controller = new BooksController($this->service, $this->commandBus);
        $controller->readAction($id);
    }

    public function testReadActionThrowsNotFoundExceptionIfNotFound()
    {
        self::setExpectedException(NotFoundHttpException::class);

        $id = Uuid::createNew();

        $this->service->expects(self::once())
            ->method('getBook')
            ->with($id)
            ->will(self::throwException(new ObjectNotFoundException('Book', $id)));

        $controller = new BooksController($this->service, $this->commandBus);
        $controller->readAction($id);
    }
}

Implement test for read action

Implement test for read action


@if(count($files))

	@foreach($files as $file)

			path.'/'.$file->filename }}" class="thumbnail fancybox" rel="gallery">
				path.'/'.$file->filename, 310, 310) }}" alt="{{ $file->alt_attribute }}">

	@endforeach

@endif

@if(count($files))

	@foreach(array_chunk($files->all(), 4) as $row)

		@foreach($row as $file)

				path.'/'.$file->filename }}" class="thumbnail fancybox" rel="gallery">
					path.'/'.$file->filename, 310, 310) }}" alt="{{ $file->alt_attribute }}">

		@endforeach

	@endforeach

@endif

Use of array_chunk for rows of images

Use of array_chunk for rows of images


<?php

namespace App\Support;

use Illuminate\Support\HtmlString;

if (!function_exists('content')) {
    /**
     * Format user content.
     *
     * @param string $text
     *
     * @return HtmlString
     */
    function format_content(string $text): HtmlString
    {
        return new HtmlString(nl2br(e($text)));
    }
}

<?php

namespace App\Support;

use Illuminate\Support\HtmlString;

if (!function_exists('format_content')) {
    /**
     * Format user content.
     *
     * @param string $text
     *
     * @return HtmlString
     */
    function format_content(string $text): HtmlString
    {
        return new HtmlString(nl2br(e($text)));
    }
}

Fix if statement for format_content declaration


<?php
namespace CodeGen;
use Exception;
use CodeGen\Renderable;
use CodeGen\Raw;
use CodeGen\VariableDeflator;
use ArrayAccess;
use IteratorAggregate;
use ArrayIterator;

/**
 * Argument list for function call
 */
class ArgumentList implements Renderable, ArrayAccess, IteratorAggregate
{
    public $arguments;

    public function __construct(array $arguments = array())
    {
        $this->arguments = $arguments;
    }

    public function setArguments(array $args)
    {
        $this->arguments = $args;
    }

    public function add($arg)
    {
        $this->arguments[] = $arg;
        return $this;
    }

    public function offsetExists($offset)
    {
        return isset($this->arguments[ $offset ]);
    }

    public function offsetGet($offset)
    {
        return $this->arguments[ $offset ];
    }

    public function offsetUnset($offset)
    {
        unset($this->arguments[$offset]);
    }

    public function offsetSet($offset, $value)
    {
        if ($offset) {
            $this->arguments[$offset] = $value;
        } else {
            $this->arguments[] = $value;
        }
    }

    public function getIterator()
    {
        return new ArrayIterator($this->arguments);
    }

    public function render(array $args = array())
    {
        $strs = array();
        foreach ($this->arguments as $arg) {
            $strs[] = VariableDeflator::deflate($arg);
        }
        return join(', ',$strs);
    }
}

<?php
namespace CodeGen;
use Exception;
use CodeGen\Renderable;
use CodeGen\Raw;
use CodeGen\VariableDeflator;
use ArrayAccess;
use IteratorAggregate;
use ArrayIterator;

/**
 * Argument list for function call
 */
class ArgumentList implements Renderable, ArrayAccess, IteratorAggregate
{
    protected $arguments;

    public function __construct(array $arguments = array())
    {
        $this->arguments = $arguments;
    }

    public function setArguments(array $args)
    {
        $this->arguments = $args;
    }

    public function add($arg)
    {
        $this->arguments[] = $arg;
        return $this;
    }

    public function offsetExists($offset)
    {
        return isset($this->arguments[ $offset ]);
    }

    public function offsetGet($offset)
    {
        return $this->arguments[ $offset ];
    }

    public function offsetUnset($offset)
    {
        unset($this->arguments[$offset]);
    }

    public function offsetSet($offset, $value)
    {
        if ($offset) {
            $this->arguments[$offset] = $value;
        } else {
            $this->arguments[] = $value;
        }
    }

    public function getIterator()
    {
        return new ArrayIterator($this->arguments);
    }

    public function render(array $args = array())
    {
        $strs = array();
        foreach ($this->arguments as $arg) {
            $strs[] = VariableDeflator::deflate($arg);
        }
        return join(', ',$strs);
    }
}

Make $arguments public => protected

Make $arguments public => protected


<?php
namespace Craft;

class WistiaPlugin extends BasePlugin
{
	public function getName()
	{
		return 'Wistia';
	}

	public function getDescription()
	{
		return 'Manage videos and output data using the Wistia API.';
	}

	public function getVersion()
	{
		return '0.1.5';
	}

	public function getDeveloper()
	{
		return 'Caddis';
	}

	public function getDeveloperUrl()
	{
		return 'https://www.caddis.co';
	}

	public function getDocumentationUrl()
	{
		return 'https://www.caddis.co/software/craft/wistia';
	}

	public function getSchemaVersion()
	{
		return '1.0.0';
	}

	protected function defineSettings()
	{
		return array(
			'apiKey' => AttributeType::String,
			'cacheDuration' => array(
				AttributeType::Number,
				'default' => 24
			),
			'thumbnailPath' => array(
				AttributeType::String,
				'default' => '/images/videos/'
			)
		);
	}

	public function getSettingsHtml()
	{
		return craft()->templates->render('wistia/plugin/settings', array(
			'settings' => $this->getSettings()
		));
	}
}

<?php
namespace Craft;

class WistiaPlugin extends BasePlugin
{
	public function getName()
	{
		return 'Wistia';
	}

	public function getDescription()
	{
		return 'Manage videos and output data using the Wistia API.';
	}

	public function getVersion()
	{
		return '0.1.5';
	}

	public function getDeveloper()
	{
		return 'Caddis';
	}

	public function getDeveloperUrl()
	{
		return 'https://www.caddis.co';
	}

	public function getDocumentationUrl()
	{
		return 'https://www.caddis.co/software/craft/wistia';
	}

	public function getSchemaVersion()
	{
		return '1.0.0';
	}

	protected function defineSettings()
	{
		return array(
			'apiKey' => AttributeType::String,
			'cacheDuration' => array(
				AttributeType::Number,
				'default' => 24
			),
			'thumbnailPath' => array(
				AttributeType::String,
				'default' => '/images/videos/'
			)
		);
	}

	public function getSettingsHtml()
	{
		return craft()->templates->render('wistia/plugin/settings', array(
			'settings' => $this->getSettings()
		));
	}

	public function registerCachePaths()
	{
		return array(
			$_SERVER['DOCUMENT_ROOT'] . craft()->plugins->getPlugin('wistia')->getSettings()->thumbnailPath => Craft::t('Wistia Preview Images')
		);
	}
}

Add preview images cache clearing

Add preview images cache clearing


<?php

namespace TruckersMP\Models;

use Carbon\Carbon;

class GameTimeModel
{
    /**
     * @var Carbon
     */
    public $time;

    /**
     * GameTimeModel constructor.
     *
     * @param array $response
     * @throws \Exception
     */
    public function __construct(array $response)
    {
        if ($response['error']) {
            throw new \Exception($response['error']);
        }

        $load['minutes'] = $response['game_time'];

        $load['hours'] = $load['minutes'] / 60;
        $load['minutes'] = $load['minutes'] % 60;

        $load['days'] = $load['hours'] / 24;
        $load['hours'] = $load['hours'] % 24;

        $load['months'] = $load['days'] / 30;
        $load['days'] = $load['days'] % 30;

        $load['years'] = intval($load['months'] / 12);
        $load['months'] = $load['months'] % 12;

        $this->time = Carbon::create($load['years'], $load['months'], $load['days'], $load['hours'], $load['minutes']);
    }
}

<?php

namespace TruckersMP\Models;

use Carbon\Carbon;
use TruckersMP\Exceptions\APIErrorException;

class GameTimeModel
{
    /**
     * @var Carbon
     */
    public $time;

    /**
     * GameTimeModel constructor.
     *
     * @param array $response
     * @throws \Exception
     */
    public function __construct(array $response)
    {
        if ($response['error']) {
            throw new APIErrorException($response['error']);
        }

        $load['minutes'] = $response['game_time'];

        $load['hours'] = $load['minutes'] / 60;
        $load['minutes'] = $load['minutes'] % 60;

        $load['days'] = $load['hours'] / 24;
        $load['hours'] = $load['hours'] % 24;

        $load['months'] = $load['days'] / 30;
        $load['days'] = $load['days'] % 30;

        $load['years'] = intval($load['months'] / 12);
        $load['months'] = $load['months'] % 12;

        $this->time = Carbon::create($load['years'], $load['months'], $load['days'], $load['hours'], $load['minutes']);
    }
}

Throw APIErrorException if there's a gametime endpoint error


<?php

namespace allejo\stakx\Twig;

use allejo\stakx\Object\JailObject;
use Twig_Environment;

class BaseUrlFunction
{
    public function __invoke (Twig_Environment $env, $assetPath)
    {
        $globals = $env->getGlobals();

        if ($assetPath instanceof JailObject) {
            $assetPath = $assetPath->getPermalink();
        }
        else if (is_array($assetPath)) {
            $assetPath = $assetPath['permalink'];
        }
        else if (is_null($assetPath)) {
            $assetPath = '/';
        }

        // @TODO 1.0.0 Remove support for 'base' as it's been deprecated
        $base = (array_key_exists('base', $globals['site'])) ? $globals['site']['base'] : $globals['site']['baseurl'];

        $baseURL = (empty($base)) ? '/' : '/' . trim($base, '/') . '/';
        $url     = ltrim($assetPath, '/');

        return ($baseURL . $url);
    }

    public static function get ()
    {
        return new \Twig_SimpleFunction('url', new self(), array(
            'needs_environment' => true
        ));
    }
}

<?php

namespace allejo\stakx\Twig;

use allejo\stakx\Object\FrontMatterObject;
use Twig_Environment;

class BaseUrlFunction
{
    public function __invoke (Twig_Environment $env, $assetPath)
    {
        $globals = $env->getGlobals();

        if ($assetPath instanceof FrontMatterObject)
        {
            $assetPath = $assetPath->getPermalink();
        }

        // @TODO 1.0.0 Remove support for 'base' as it's been deprecated
        $base = (array_key_exists('base', $globals['site'])) ? $globals['site']['base'] : $globals['site']['baseurl'];

        $baseURL = (empty($base)) ? '/' : '/' . trim($base, '/') . '/';
        $url     = ltrim($assetPath, '/');

        return ($baseURL . $url);
    }

    public static function get ()
    {
        return new \Twig_SimpleFunction('url', new self(), array(
            'needs_environment' => true
        ));
    }
}

Revert "Make url() more robust"

Revert "Make url() more robust"

This reverts commit e63a1824923202bc8d78522747e25aadcd67d597.


<?php

/*
 * (c) Jeroen van den Enden <info@endroid.nl>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Endroid\Tests\QrCode;

use Endroid\QrCode\QrCode;

class QrCodeTest extends \PHPUnit_Framework_TestCase
{
    public function testCreateQrCode()
    {
        $qrCode = new QrCode();
        $qrCode->setText("Life is too short to be generating QR codes");
        $qrCode->setSize(300);
        $qrCode->create();

        $this->assertTrue(true);
    }
}

<?php

/*
 * (c) Jeroen van den Enden <info@endroid.nl>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Endroid\Tests\QrCode;

use Endroid\QrCode\QrCode;

class QrCodeTest extends \PHPUnit_Framework_TestCase
{
    public function testCreateQrCode()
    {
        $qrCode = new QrCode();
        $qrCode->setText("Life is too short to be generating QR codes");
        $qrCode->setSize(300);
        $qrCode->create();

        $this->assertTrue(true);
    }

    public function testReadQrCode()
    {
        // TODO: check if the QR code is readable and contains the desired text

        $this->assertTrue(true);
    }
}

Add QR code read test

Add QR code read test


<?php

namespace Dater\Locale;
use Dater\Dater;

class EnUs extends \Dater\Locale {

	protected static $months = array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');
	protected static $weekDays = array('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday');
	protected static $weekDaysShort = array('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun');

	// Referring to https://en.wikipedia.org/wiki/Date_format_by_country
	protected static $formats = array(
		Dater::USER_DATE_FORMAT => 'm/d/Y',
		Dater::USER_TIME_FORMAT => 'G:i',
		Dater::USER_DATETIME_FORMAT => 'm/d/Y G:i',
	);
}

<?php

namespace Dater\Locale;
use Dater\Dater;

class EnUs extends \Dater\Locale {

	protected static $months = array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');
	protected static $weekDays = array('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday');
	protected static $weekDaysShort = array('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun');

	// Referring to https://en.wikipedia.org/wiki/Date_format_by_country
	protected static $formats = array(
		Dater::USER_DATE_FORMAT => 'm/d/Y',
		Dater::USER_TIME_FORMAT => 'H:i',
		Dater::USER_DATETIME_FORMAT => 'm/d/Y H:i',
	);
}

Fix time format for US English

Fix time format for US English


<?php

namespace Faulancer\Http\Adapter;

use Faulancer\Exception\ClientException;
use Faulancer\Http\Request;

/**
 * Class Curl
 * @package Faulancer\Http\Adapter
 * @author  Florian Knapp <office@florianknapp.de>
 */
class Curl extends AbstractAdapter
{
    /**
     * @param Request $request
     * @return void
     */
    public function send(Request $request)
    {
        $ch = curl_init($request->getUri());

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        if (!empty($request->getHeaders())) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $request->getHeaders());
        }

        if ($request->getMethod() === 'POST' && !empty($request->getBody())) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, $request->getBody());
        }

        $this->response = curl_exec($ch);
        curl_close($ch);
    }

    /**
     * @return mixed
     * @throws ClientException
     */
    public function getResponse()
    {
        if (empty($this->response)) {
            throw new ClientException('You have to call the \'send\' method first.');
        }

        return $this->response;
    }

}

<?php

namespace Faulancer\Http\Adapter;

use Faulancer\Exception\ClientException;
use Faulancer\Http\Request;

/**
 * Class Curl
 * @package Faulancer\Http\Adapter
 * @author  Florian Knapp <office@florianknapp.de>
 */
class Curl extends AbstractAdapter
{
    /**
     * @param Request $request
     * @return void
     */
    public function send(Request $request)
    {
        $ch = curl_init($request->getUri());

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        if (!empty($request->getHeaders())) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $request->getHeaders());
        }

        if ($request->getMethod() === 'POST' && !empty($request->getBody())) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, $request->getBody());
        }

        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:58.0) Gecko/20100101 Firefox/58.0');

        $this->response = curl_exec($ch);
        curl_close($ch);
    }

    /**
     * @return mixed
     * @throws ClientException
     */
    public function getResponse()
    {
        if (empty($this->response)) {
            throw new ClientException('You have to call the \'send\' method first.');
        }

        return $this->response;
    }

}

Add user agent to request

Add user agent to request


<?php namespace Craft;

use CValidator;

class CreditCard_NumberValidator extends CValidator
{
    protected function validateAttribute($object, $attribute)
    {
        $number = $object->$attribute;

        if ($number && ! $this->validateLuhn($number)) {
            $message = Craft::t(
                '"{object}->{attribute}" must be a valid credit card number.',
                ['object' => get_class($object), 'attribute' => $attribute]
            );

            $this->addError($object, $attribute, $message);
        }
    }

    protected function validateLuhn($number)
    {
        $check = '';

        foreach (array_reverse(str_split($number)) as $index => $digit) {
            $check .= $index % 2 ? $digit * 2 : $digit;
        }

        return array_sum(str_split($check)) % 10 === 0;
    }
}

<?php namespace Craft;

use CValidator;

class CreditCard_NumberValidator extends CValidator
{
    protected function validateAttribute($object, $attribute)
    {
        $number = $object->$attribute;

        if ($number && ! $this->validateLuhn($number)) {
            $message = Craft::t('Invalid credit card number.');
            $this->addError($object, $attribute, $message);
        }
    }

    protected function validateLuhn($number)
    {
        $check = '';

        foreach (array_reverse(str_split($number)) as $index => $digit) {
            $check .= $index % 2 ? $digit * 2 : $digit;
        }

        return array_sum(str_split($check)) % 10 === 0;
    }
}

Return a more meaningful error message.

Return a more meaningful error message.


<?php
if (file_exists(__DIR__ . '/p2pear.phar')) {
    set_include_path('phar://' . __DIR__ . '/p2pear.phar'
                     . PATH_SEPARATOR . get_include_path());
}
error_reporting(E_ALL & ~(E_NOTICE | E_STRICT | E_DEPRECATED));
require __DIR__ . '/vendor/.composer/autoload.php';
require __DIR__ . '/conf/conf.inc.php';

<?php
if (file_exists(__DIR__ . '/p2pear.phar')) {
    set_include_path('phar://' . __DIR__ . '/p2pear.phar'
                     . PATH_SEPARATOR . get_include_path());
}
error_reporting(E_ALL & ~(E_NOTICE | E_STRICT | E_DEPRECATED));
require __DIR__ . '/vendor/autoload.php';
require __DIR__ . '/conf/conf.inc.php';

Fix Composer autoload file path.

Fix Composer autoload file path.


<!DOCTYPE html>

<title><?php wp_title('«', true, 'right'); bloginfo('name'); ?></title>
<meta charset="utf-8" />
<link rel="stylesheet" type="text/css" href="<?php bloginfo('template_directory'); ?>/style.css" />
<link rel="stylesheet" type="text/css" href="<?php bloginfo('template_directory'); ?>/css/superfish.css" />
<?php
	wp_head();
	comments_popup_script(400, 400);
?>

WicketPixie

< insert site description/status update here >

                        <?php
			if (!is_home()) {
			?>

<a href="<?php bloginfo('home'); ?>">Home

			<?php
			}
			wp_list_pages('sort_column=menu_order&title_li=');
			?>

<!DOCTYPE html>

<title><?php wp_title('«', true, 'right'); bloginfo('name'); ?></title>
<meta charset="utf-8" />
<link rel="stylesheet" type="text/css" href="<?php bloginfo('template_directory'); ?>/style.css" />
<link rel="stylesheet" type="text/css" href="<?php bloginfo('template_directory'); ?>/css/superfish.css" />
<?php
	wp_head();
	comments_popup_script(400, 400);
?>

WicketPixie

<?php bloginfo('description'); ?>

                        <?php
			if (!is_home()) {
			?>

<a href="<?php bloginfo('home'); ?>">Home

			<?php
			}
			wp_list_pages('sort_column=menu_order&title_li=');
			?>

Replace placeholder text with site description

Signed-off-by: Eddie Ringle <bacc1c505cb1756c59242c0a8ee25cd990a210e9@eringle.net>


<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Formatter;

/**
 * Encodes message information into JSON in a format compatible with Loggly.
 *
 * @author Adam Pancutt <adam@pancutt.com>
 */
class LogglyFormatter extends JsonFormatter
{
    /**
     * Overrides the default batch mode to new lines for compatibility with the
     * Loggly bulk API.
     *
     * @param integer $batchMode
     */
    public function __construct($batchMode = self::BATCH_MODE_NEWLINES, $appendNewline = false)
    {
        parent::__construct($batchMode, $appendNewline);
    }

    /**
     * Appends the 'timestamp' parameter for indexing by Loggly.
     *
     * @see https://www.loggly.com/docs/automated-parsing/#json
     * @see \Monolog\Formatter\JsonFormatter::format()
     */
    public function format(array $record)
    {
        if (isset($record["datetime"]) && ($record["datetime"] instanceof \DateTime)) {
            $record["timestamp"] = $record["datetime"]->format("c");
            // TODO 2.0 unset the 'datetime' parameter, retained for BC
        }

        return parent::format($record);
    }
}

<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Formatter;

/**
 * Encodes message information into JSON in a format compatible with Loggly.
 *
 * @author Adam Pancutt <adam@pancutt.com>
 */
class LogglyFormatter extends JsonFormatter
{
    /**
     * Overrides the default batch mode to new lines for compatibility with the
     * Loggly bulk API.
     *
     * @param integer $batchMode
     */
    public function __construct($batchMode = self::BATCH_MODE_NEWLINES, $appendNewline = false)
    {
        parent::__construct($batchMode, $appendNewline);
    }

    /**
     * Appends the 'timestamp' parameter for indexing by Loggly.
     *
     * @see https://www.loggly.com/docs/automated-parsing/#json
     * @see \Monolog\Formatter\JsonFormatter::format()
     */
    public function format(array $record)
    {
        if (isset($record["datetime"]) && ($record["datetime"] instanceof \DateTime)) {
            $record["timestamp"] = $record["datetime"]->format("Y-m-d\TH:i:s.uO");
            // TODO 2.0 unset the 'datetime' parameter, retained for BC
        }

        return parent::format($record);
    }
}

Fix loggly formatter on php 5.6

Fix loggly formatter on php 5.6


<link rel="stylesheet" type="text/css" href="<?=$this->getThemePath()?>/css/services.css">
<?php $this->inc('header.php'); ?>

			<?php $b = new Area('Content'); $b->display($c); ?>

			<?php $b = new Area('Accordion'); $b->display($c); ?>

		<?php $this->inc('elements/footer.php'); ?>

	<?php Loader::element('footer_required'); ?>

Check if there is url fragment and added portrait