<?php

class sfValidatorImageJCroppable extends sfValidatorBase
{
  protected function configure($options = array(), $messages = array())
  {
    parent::configure($options, $messages);

    $this->addRequiredOption('fieldName');
    $this->addRequiredOption('fieldValue');

    $this->addMessage('badcrop', 'Please select a larger area to crop');
  }

  protected function doClean($values)
  {
    $fieldName = $this->getOption('fieldName');
    $fieldValue = $this->getOption('fieldValue');

    /**
     * If there was previously no image and none has been uploaded then pass
     */
    if (empty($fieldValue) && empty($values[$fieldName]))
    {
      return $values;
    }

    if ($values[$fieldName . '_x1'] == $values[$fieldName . '_x2'])
    {
      throw new sfValidatorError($this, 'badcrop');
    }

    if ($values[$fieldName . '_y1'] == $values[$fieldName . '_y2'])
    {
      throw new sfValidatorError($this, 'badcrop');
    }

    return $values;
  }
}

<?php

class sfValidatorImageJCroppable extends sfValidatorBase
{
  protected function configure($options = array(), $messages = array())
  {
    parent::configure($options, $messages);

    $this->addRequiredOption('fieldName');
    $this->addRequiredOption('fieldValue');

    $this->addMessage('badcrop', 'Please select a larger area to crop');
  }

  protected function doClean($values)
  {
    $fieldName = $this->getOption('fieldName');
    $fieldValue = $this->getOption('fieldValue');

    /**
     * If there was previously no image and none has been uploaded then pass
     */
    if (empty($fieldValue) && empty($values[$fieldName]))
    {
      return $values;
    }

    if ($values[$fieldName . '_x1'] && $values[$fieldName . '_x1'] == $values[$fieldName . '_x2'])
    {
      throw new sfValidatorError($this, 'badcrop');
    }

    if ($values[$fieldName . '_y1'] && $values[$fieldName . '_y1'] == $values[$fieldName . '_y2'])
    {
      throw new sfValidatorError($this, 'badcrop');
    }

    return $values;
  }
}

Fix for uploading new images into a record which exists

git-svn-id: 556f41d716a3fdd6f7eefe65000ef9c8a0afec4c@30712 ee427ae8-e902-0410-961c-c3ed070cd9f9


<?php

class Denkmal_Scraper_Genres {

    /** @var string[] */
    private $_genreList = array();

    /**
     * @param string $genres Genres list as string
     */
    function __construct($genres) {
        foreach (preg_split('#[,|/]#', $genres) as $genre) {
            if ($genre = strtolower(trim($genre))) {
                $this->_genreList[] = $genre;
            }
        }
    }

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

    /**
     * @return string
     */
    public function __toString() {
        $genres = $this->_genreList;
        if (count($genres) > 0) {
            $genres[0] = ucfirst($genres[0]);
        }
        return implode(', ', $genres);
    }
}

<?php

class Denkmal_Scraper_Genres {

    /** @var string[] */
    private $_genreList = array();

    /**
     * @param string|string[] $genres
     */
    function __construct($genres) {
        if (!is_array($genres)) {
            $genres = Functional\map(preg_split('#[,|/]#', $genres), function ($genre) {
                return strtolower(trim($genre));
            });
        }
        $genres = array_filter($genres);
        $this->_genreList = $genres;
    }

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

    /**
     * @return string
     */
    public function __toString() {
        $genres = $this->_genreList;
        if (count($genres) > 0) {
            $genres[0] = ucfirst($genres[0]);
        }
        return implode(', ', $genres);
    }
}

Allow to pass array to scraper-genres

Allow to pass array to scraper-genres


<?php

use Illuminate\Database\Seeder;
use App\Category;
use App\Product;

class CategoriesTableSeeder extends Seeder
{
    public function run()
    {
        $faker = \App::make('Faker\Generator');

        /**
        * Clear up the tables before adding new data
        */
        Category::truncate();
        Product::truncate();

        /**
        * Create 50 categories
        */
        factory(Category::class, 5000)->create()->each(function ($category) use ($faker) {
            /**
            * For each category 2 to 5 products will
            * be created and assigned
            */
            $quantity = $faker->numberBetween(2, 5);

            /**
            * Generate in memory the products
            */
            $products = factory(Product::class, $quantity)->make();

            foreach ($products as $product) {
                /**
                * Using the relatioship save the products
                * to the category
                */
                $category->products()->save($product);
            }
        });
    }
}

<?php

use Illuminate\Database\Seeder;
use App\Category;
use App\Product;

class CategoriesTableSeeder extends Seeder
{
    public function run()
    {
        $faker = \App::make('Faker\Generator');

        /**
        * Clear up the tables before adding new data
        */
        Category::truncate();
        Product::truncate();

        /**
        * Create 50 categories
        */
        factory(Category::class, 200)->create()->each(function ($category) use ($faker) {
            /**
            * For each category 2 to 5 products will
            * be created and assigned
            */
            $quantity = $faker->numberBetween(2, 5);

            /**
            * Generate in memory the products
            */
            $products = factory(Product::class, $quantity)->make();

            foreach ($products as $product) {
                /**
                * Using the relatioship save the products
                * to the category
                */
                $category->products()->save($product);
            }
        });
    }
}

Tweak on seeder for categories.

Tweak on seeder for categories.

5000 was too much. 200 is fine.


<?php

namespace Adldap\Auth\Events;

use Adldap\Connections\ConnectionInterface;

abstract class Event
{
    /**
     * The connection that the username and password is being bound on.
     *
     * @var ConnectionInterface
     */
    public $connection;

    /**
     * The username that is being used for binding.
     *
     * @var string
     */
    public $username;

    /**
     * The password that is being used for binding.
     *
     * @var string
     */
    public $password;

    /**
     * Constructor.
     *
     * @param ConnectionInterface $connection
     * @param string              $username
     * @param string              $password
     */
    public function __construct(ConnectionInterface $connection, $username, $password)
    {
        $this->connection = $connection;
        $this->username = $username;
        $this->password = $password;
    }
}

<?php

namespace Adldap\Auth\Events;

use Adldap\Connections\ConnectionInterface;

abstract class Event
{
    /**
     * The connection that the username and password is being bound on.
     *
     * @var ConnectionInterface
     */
    protected $connection;

    /**
     * The username that is being used for binding.
     *
     * @var string
     */
    protected $username;

    /**
     * The password that is being used for binding.
     *
     * @var string
     */
    protected $password;

    /**
     * Constructor.
     *
     * @param ConnectionInterface $connection
     * @param string              $username
     * @param string              $password
     */
    public function __construct(ConnectionInterface $connection, $username, $password)
    {
        $this->connection = $connection;
        $this->username = $username;
        $this->password = $password;
    }

    /**
     * Returns the events connection.
     *
     * @return ConnectionInterface
     */
    public function getConnection()
    {
        return $this->connection;
    }

    /**
     * Returns the authentication events username.
     *
     * @return string
     */
    public function getUsername()
    {
        return $this->username;
    }

    /**
     * Returns the authentication events password.
     *
     * @return string
     */
    public function getPassword()
    {
        return $this->password;
    }
}

Make properties protected, add get methods


<?php
	define('ID_FILE','id.txt');
	define('UPLOAD_PATH','uploads/');
	$behaviour['FILES_TO_ECHO']=array('txt','js','html','php','htm','shtml','shtm');
	$behaviour['FILES_TO_RETURN']=array('jpg','jpeg','gif','png','pdf','swf');

	if (!is_dir(UPLOAD_PATH)){mkdir(UPLOAD_PATH);}
	if (!is_dir('thumbs/')){mkdir('thumbs/');}
	if (!file_exists(ID_FILE)){$ids=array();store(ID_FILE,$ids);}
	$ids=unstore(ID_FILE);

	function is_in($ext,$type){global $behaviour;if (!empty($behaviour[$type])){return array_search($ext,$behaviour[$type]);}}
	function store($file,$datas){file_put_contents($file,gzdeflate(json_encode($datas)));}
	function unstore($file){return json_decode(gzinflate(file_get_contents($file)),true);}
	function id2file($id){
		global $ids;
		if (isset($ids[$id])){return $ids[$id];}else{return false;}
	}

?>

<?php
	define('ID_FILE','id.txt');
	define('UPLOAD_PATH','uploads/');
	$behaviour['FILES_TO_ECHO']=array('txt','js','html','php','htm','shtml','shtm');
	$behaviour['FILES_TO_RETURN']=array('jpg','jpeg','gif','png','pdf','swf');

	if (!is_dir(UPLOAD_PATH)){mkdir(UPLOAD_PATH);}
	if (!is_file(UPLOAD_PATH.'index.html')){file_put_contents(UPLOAD_PATH.'index.html',' ');}

	if (!is_dir('thumbs/')){mkdir('thumbs/');}
	if (!is_file('thumbs/index.html')){file_put_contents('thumbs/index.html',' ');}

	if (!file_exists(ID_FILE)){$ids=array();store(ID_FILE,$ids);}
	$ids=unstore(ID_FILE);

	function is_in($ext,$type){global $behaviour;if (!empty($behaviour[$type])){return array_search($ext,$behaviour[$type]);}}
	function store($file,$datas){file_put_contents($file,gzdeflate(json_encode($datas)));}
	function unstore($file){return json_decode(gzinflate(file_get_contents($file)),true);}
	function id2file($id){
		global $ids;
		if (isset($ids[$id])){return $ids[$id];}else{return false;}
	}

?>

Fix bug de premier fichier

Fix bug de premier fichier

Lors du premier upload, le fichier n'apparaissait pas, c'est corrigé.


<?php

// This class is used to encapsulate global state between layers without using $GLOBAL[] or
// relying on the consumer being loaded correctly by the dynamic class autoloader
class SV_WordCountSearch_Globals
{
    const WordCountField = 'word_count';
    public static $wordCountThreshold = 20;

    private function __construct() {}
}

<?php

// This class is used to encapsulate global state between layers without using $GLOBAL[] or
// relying on the consumer being loaded correctly by the dynamic class autoloader
class SV_WordCountSearch_Globals
{
    const WordCountField = 'word_count';
    public static $wordCountThreshold = 100;

    private function __construct() {}
}

Raise limit on persisted wordcount

Raise limit on persisted wordcount


<?php

namespace AppVentus\MangopayBundle\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;

/**
 * This is the class that loads and manages your bundle configuration
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
 */
class AppVentusMangopayExtension extends Extension
{
    /**
     * {@inheritDoc}
     */
    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['debug_mode'])
        {
            $container->setParameter('appventus_mangopay.debug_mode',   $config['debug_mode']);
        }

        $container->setParameter('appventus_mangopay.client_id',        $config['client_id']);
        $container->setParameter('appventus_mangopay.client_password',  $config['client_password']);
        $container->setParameter('appventus_mangopay.base_url',         $config['base_url']);

    }
}

<?php

namespace AppVentus\MangopayBundle\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;

/**
 * This is the class that loads and manages your bundle configuration
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
 */
class AppVentusMangopayExtension extends Extension
{
    /**
     * {@inheritDoc}
     */
    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');

        $container->setParameter('appventus_mangopay.debug_mode',       $config['debug_mode'] === true);
        $container->setParameter('appventus_mangopay.client_id',        $config['client_id']);
        $container->setParameter('appventus_mangopay.client_password',  $config['client_password']);
        $container->setParameter('appventus_mangopay.base_url',         $config['base_url']);
    }
}

Set debug mode parameter to a value in any case

Updated MangopayExtension because appventus_mangopay.mango_api is asking for debug_mode in any case


<?php

namespace Brick\App\Session\Storage;

class Lock
{
    /**
     * A storage-specific lock context.
     *
     * @var mixed
     */
    private $context;

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

    /**
     * @param mixed $context
     *
     * @return void
     */
    public function setContext($context) : void
    {
        $this->context = $context;
    }
}

<?php

declare(strict_types=1);

namespace Brick\App\Session\Storage;

class Lock
{
    /**
     * A storage-specific lock context.
     *
     * @var mixed
     */
    private $context;

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

    /**
     * @param mixed $context
     *
     * @return void
     */
    public function setContext($context) : void
    {
        $this->context = $context;
    }
}

Add missing strict types declaration

Add missing strict types declaration


<?php

require "vendor/autoload.php";

require "GreetCommand.php";
require "MigrateNewCommand.php";
require "MigrateRunCommand.php";
require "MigrateInstallCommand.php";

use Symfony\Component\Console\Application;

$app = new Application();
$app->add(new GreetCommand());
$app->add(new MigrateNewCommand());
$app->add(new MigrateRunCommand());
$app->add(new MigrateInstallCommand());
$app->run();

<?php

require "vendor/autoload.php";

//require "GreetCommand.php";
require "MigrateNewCommand.php";
require "MigrateRunCommand.php";
require "MigrateInstallCommand.php";

use Symfony\Component\Console\Application;

$app = new Application();
//$app->add(new GreetCommand());
$app->add(new MigrateNewCommand());
$app->add(new MigrateRunCommand());
$app->add(new MigrateInstallCommand());
$app->run();

Drop the command from the tutorial

Drop the command from the tutorial


<?php

namespace Magister\Services\Http;

use GuzzleHttp\Client;
use Magister\Services\Support\ServiceProvider;
use GuzzleHttp\Subscriber\Cache\CacheSubscriber;

/**
 * Class HttpServiceProvider.
 */
class HttpServiceProvider extends ServiceProvider
{
    /**
     * Register bindings in the container.
     *
     * @return void
     */
    public function register()
    {
        $this->registerGuzzle();
    }

    /**
     * Register the Guzzle driver.
     *
     * @return void
     */
    protected function registerGuzzle()
    {
        $this->app->singleton('http', function ($app) {
            $client = new Client(['base_url' => "https://{$app['school']}.magister.net/api/"]);

            $client->setDefaultOption('exceptions', false);
            $client->setDefaultOption('headers', ['X-API-Client-ID' => '12D8']);
            $client->setDefaultOption('cookies', new SessionCookieJar($app['cookie']));

            CacheSubscriber::attach($client);

            return $client;
        });
    }
}

<?php

namespace Magister\Services\Http;

use GuzzleHttp\Client;
use Magister\Services\Support\ServiceProvider;
use GuzzleHttp\Subscriber\Cache\CacheSubscriber;

/**
 * Class HttpServiceProvider.
 */
class HttpServiceProvider extends ServiceProvider
{
    /**
     * Register bindings in the container.
     *
     * @return void
     */
    public function register()
    {
        $this->registerGuzzle();
    }

    /**
     * Register the Guzzle driver.
     *
     * @return void
     */
    protected function registerGuzzle()
    {
        $this->app->singleton('http', function ($app) {
            $client = new Client(['base_url' => "https://{$app['school']}.magister.net/api/"]);

            $client->setDefaultOption('exceptions', false);

            $client->setDefaultOption('headers', [
                'X-API-Client-ID' => function_exists('env') ? env('MAGISTER_API_KEY', '12D8') : '12D8',
            ]);

            $client->setDefaultOption('cookies', new SessionCookieJar($app['cookie']));

            CacheSubscriber::attach($client);

            return $client;
        });
    }
}

Fix to integratie with Homi's laravel integration


<?php
/**
 * @package deployment
 *
 * Adds default permissions to partner 99
 *
 */

//-- Bootstraping
error_reporting(E_ALL);

require_once(dirname(__FILE__).'/../../../bootstrap.php');
require_once(ROOT_DIR . '/api_v3/bootstrap.php');

$dryRun = true; //TODO: change for real run
if($argc > 1 && $argv[1] == 'realrun')
	$dryRun = false;

define("TEMPLATE_PARTNER_ID", 99 );

//-- Script start
//Get partner 99
$partner99 = PartnerPeer::retrieveByPK(TEMPLATE_PARTNER_ID);

//Enable the vast
$partner99->setEnableVast(true);

//Enable plugin metadata
$partner99->setPluginEnabled('metadata', true);

if($dryRun)
{
	KalturaLog::log('DRY RUN - Adding new permissions [Vast, CustomMetadata, Thumbnails managment] to partner [99]\n');
	KalturaLog::log(var_dump($partner99));
}
else
{
	KalturaLog::log('Adding new permissions [Vast, CustomMetadata, Thumbnails managment] to partner [99]');

	//save changes to DB
	$partner99->save();
}

KalturaLog::log('Done!');

<?php
/**
 * @package deployment
 *
 * Adds default permissions to partner 99
 *
 */

//-- Bootstraping
error_reporting(E_ALL);

require_once(dirname(__FILE__).'/../../../bootstrap.php');
require_once(ROOT_DIR . '/api_v3/bootstrap.php');

$dryRun = true; //TODO: change for real run
if($argc > 1 && $argv[1] == 'realrun')
	$dryRun = false;

define("TEMPLATE_PARTNER_ID", 99 );

//-- Script start
//Get partner 99
$partner99 = PartnerPeer::retrieveByPK(TEMPLATE_PARTNER_ID);

//Enable the vast
$partner99->setEnableVast(true);

//Enable plugin metadata
$partner99->setPluginEnabled('metadata', true);

//Enable plugin metadata
$partner99->setPluginEnabled('contentDistribution', true);

//Disable plugin Live Streaming
$partner99->setLiveStreamEnabled(false);

if($dryRun)
{
	KalturaLog::log('DRY RUN - Adding new permissions [Vast, CustomMetadata, Thumbnails managment] to partner [99]\n');
	KalturaLog::log(var_dump($partner99));
}
else
{
	KalturaLog::log('Adding new permissions [Vast, CustomMetadata, Thumbnails managment] to partner [99]');

	//save changes to DB
	$partner99->save();
}

KalturaLog::log('Done!');

Set partner 99 to have no live streaming
Set partner 99 to have content distribution

git-svn-id: 8a2ccb88241e16c78017770bc38d91d6d5396a5a@59443 6b8eccd3-e8c5-4e7d-8186-e12b5326b719


<?php

/*
 * This file is part of the Behat.
 * (c) Konstantin Kudryashov <ever.zet@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Behat\Testwork\Ordering\Orderer;

use Behat\Testwork\Specification\SpecificationArrayIterator;

/**
 * Prioritises Suites and Features into random order
 *
 * @author Ciaran McNulty <mail@ciaranmcnulty.com>
 */
final class RandomOrderer implements Orderer
{
    /**
     * @param SpecificationIterator[] $scenarioIterators
     * @return SpecificationIterator[]
     */
    public function order(array $scenarioIterators)
    {
        $orderedFeatures = $this->orderFeatures($scenarioIterators);
        shuffle($orderedFeatures);

        return $orderedFeatures;
    }

    /**
     * @param array $scenarioIterators
     * @return array
     */
    private function orderFeatures(array $scenarioIterators)
    {
        $orderedSuites = array();

        foreach ($scenarioIterators as $scenarioIterator) {
            $orderedSpecifications = iterator_to_array($scenarioIterator);
            shuffle($orderedSpecifications);
            $orderedSuites[] = new SpecificationArrayIterator(
                $scenarioIterator->getSuite(),
                $orderedSpecifications
            );
        }

        return $orderedSuites;
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'random';
    }
}

<?php

/*
 * This file is part of the Behat.
 * (c) Konstantin Kudryashov <ever.zet@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Behat\Testwork\Ordering\Orderer;

use Behat\Testwork\Specification\SpecificationArrayIterator;
use Behat\Testwork\Specification\SpecificationIterator;

/**
 * Prioritises Suites and Features into random order
 *
 * @author Ciaran McNulty <mail@ciaranmcnulty.com>
 */
final class RandomOrderer implements Orderer
{
    /**
     * @param SpecificationIterator[] $scenarioIterators
     * @return SpecificationIterator[]
     */
    public function order(array $scenarioIterators)
    {
        $orderedFeatures = $this->orderFeatures($scenarioIterators);
        shuffle($orderedFeatures);

        return $orderedFeatures;
    }

    /**
     * @param array $scenarioIterators
     * @return array
     */
    private function orderFeatures(array $scenarioIterators)
    {
        $orderedSuites = array();

        foreach ($scenarioIterators as $scenarioIterator) {
            $orderedSpecifications = iterator_to_array($scenarioIterator);
            shuffle($orderedSpecifications);
            $orderedSuites[] = new SpecificationArrayIterator(
                $scenarioIterator->getSuite(),
                $orderedSpecifications
            );
        }

        return $orderedSuites;
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'random';
    }
}

Add use statement for SpecificationIterator


<?php

namespace actsmart\actsmart\Sensors\WebChat\Events;

use actsmart\actsmart\Utils\Literals;
use Ds\Map;

class TriggerEvent extends WebChatEvent
{
    const EVENT_NAME = 'event.webchat.trigger';

    private $callbackId = null;

    protected $event_key;

    public function __construct($subject, $arguments = [], $key = null)
    {
        $this->event_key = $key == null ? self::EVENT_NAME : $key;
        parent::__construct($subject, $arguments, $this->event_key);

        $this->callbackId = $subject->data->callback_id ?? null;
    }

    public function getKey()
    {
        return $this->event_key;
    }

    public function getUtterance() : Map
    {
        /* @var \Ds\Map */
        $utterance = parent::getUtterance();

        $utterance->put(Literals::TYPE, Literals::WEB_CHAT_TRIGGER);
        $utterance->put(Literals::CALLBACK_ID, $this->callbackId);
        $utterance->put(Literals::TEXT, '');

        return $utterance;
    }

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

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

<?php

namespace actsmart\actsmart\Sensors\WebChat\Events;

use actsmart\actsmart\Utils\Literals;
use Ds\Map;

class TriggerEvent extends WebChatEvent
{
    const EVENT_NAME = 'event.webchat.trigger';

    private $callbackId = null;

    private $value = null;

    protected $event_key;

    public function __construct($subject, $arguments = [], $key = null)
    {
        $this->event_key = $key == null ? self::EVENT_NAME : $key;
        parent::__construct($subject, $arguments, $this->event_key);

        $this->callbackId = $subject->data->callback_id ?? null;
        $this->value = $subject->data->value ?? null;
    }

    public function getKey()
    {
        return $this->event_key;
    }

    public function getUtterance() : Map
    {
        /* @var \Ds\Map */
        $utterance = parent::getUtterance();

        $utterance->put(Literals::TYPE, Literals::WEB_CHAT_TRIGGER);
        $utterance->put(Literals::CALLBACK_ID, $this->callbackId);
        $utterance->put(Literals::VALUE, $this->value);
        $utterance->put(Literals::TEXT, '');

        return $utterance;
    }

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

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

HNS-43: Add “value” to the trigger event Utterance


<?php

namespace League\Flysystem\UrlGeneration;

use InvalidArgumentException;
use League\Flysystem\Config;
use League\Flysystem\PathPrefixer;

use function array_map;
use function count;
use function crc32;

final class ShardedPrefixPublicUrlGenerator implements PublicUrlGenerator
{
    /** @var PathPrefixer[] */
    private array $prefixers;
    private int $count;

    /**
     * @param string[] $prefixes
     */
    public function __construct(array $prefixes)
    {
        $this->count = count($prefixes);

        if ($this->count === 0) {
            throw new InvalidArgumentException('At least one prefix is required.');
        }

        $this->prefixers = array_map(static fn (string $prefix) => new PathPrefixer($prefix, '/'), $prefixes);
    }

    public function publicUrl(string $path, Config $config): string
    {
        if (1 === count($this->prefixers)) {
            return $this->prefixers[0]->prefixPath($path);
        }

        $index = crc32($path) % $this->count;

        return $this->prefixers[$index]->prefixPath($path);
    }
}

<?php

namespace League\Flysystem\UrlGeneration;

use InvalidArgumentException;
use League\Flysystem\Config;
use League\Flysystem\PathPrefixer;

use function array_map;
use function count;
use function crc32;

final class ShardedPrefixPublicUrlGenerator implements PublicUrlGenerator
{
    /** @var PathPrefixer[] */
    private array $prefixers;
    private int $count;

    /**
     * @param string[] $prefixes
     */
    public function __construct(array $prefixes)
    {
        $this->count = count($prefixes);

        if ($this->count === 0) {
            throw new InvalidArgumentException('At least one prefix is required.');
        }

        $this->prefixers = array_map(static fn (string $prefix) => new PathPrefixer($prefix, '/'), $prefixes);
    }

    public function publicUrl(string $path, Config $config): string
    {
        $index = crc32($path) % $this->count;

        return $this->prefixers[$index]->prefixPath($path);
    }
}

Remove single shard optimization, don't use sharding if you have one shard.


<?php
/**
 * This <server-gardu-reporter> project created by :
 * Name         : syafiq
 * Date / Time  : 27 June 2017, 7:18 PM.
 * Email        : syafiq.rezpector@gmail.com
 * Github       : syafiqq
 */

$lang['landing_index_client_common_layout_table_header_no'] = 'No';
$lang['landing_index_client_common_layout_table_header_substation'] = 'Substation';
$lang['landing_index_client_common_layout_table_header_current'] = 'Current';
$lang['landing_index_client_common_layout_table_header_voltage'] = 'Voltage';
$lang['landing_index_client_common_layout_table_header_location'] = 'Location';

?>

<?php
/**
 * This <server-gardu-reporter> project created by :
 * Name         : syafiq
 * Date / Time  : 27 June 2017, 7:18 PM.
 * Email        : syafiq.rezpector@gmail.com
 * Github       : syafiqq
 */

?>

Move table header to common table header file


<?php
class Scaffold_Bootstrap extends Zend_Application_Module_Bootstrap
{

}

<?php
class Scaffold_Bootstrap extends Zend_Application_Module_Bootstrap
{
    protected function _initResourceLoader()
    {
        $resourceLoader = $this->getResourceLoader();
        $resourceLoader->addResourceType('dao', 'dao', 'Dao');
    }
}

Add forgotten resource loading for DAO in sandbox.


<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\TextUI\XmlConfiguration;

use function sprintf;
use PHPUnit\Util\Xml;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class Migrator
{
    /**
     * @throws MigrationBuilderException
     * @throws MigrationException
     * @throws Exception
     * @throws \PHPUnit\Framework\Exception
     */
    public function migrate(string $filename): string
    {
        $oldXsdFilename = (new SchemaFinder)->find('9.2');

        $configurationDocument = Xml::loadFile(
            $filename,
            false,
            true,
            true
        );

        $validationResult = Xml::validate($configurationDocument, $oldXsdFilename);

        if ($validationResult->hasValidationErrors()) {
            throw new Exception(
                sprintf(
                    '"%s" is not a valid PHPUnit 9.2 XML configuration file:%s',
                    $filename,
                    $validationResult->asString()
                )
            );
        }

        foreach ((new MigrationBuilder)->build('9.2') as $migration) {
            $migration->migrate($configurationDocument);
        }

        $configurationDocument->formatOutput       = true;
        $configurationDocument->preserveWhiteSpace = false;

        return $configurationDocument->saveXML();
    }
}

<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\TextUI\XmlConfiguration;

use function sprintf;
use PHPUnit\Util\Exception as UtilException;
use PHPUnit\Util\Xml;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class Migrator
{
    /**
     * @throws MigrationBuilderException
     * @throws MigrationException
     * @throws Exception
     * @throws UtilException
     */
    public function migrate(string $filename): string
    {
        $oldXsdFilename = (new SchemaFinder)->find('9.2');

        $configurationDocument = Xml::loadFile(
            $filename,
            false,
            true,
            true
        );

        $validationResult = Xml::validate($configurationDocument, $oldXsdFilename);

        if ($validationResult->hasValidationErrors()) {
            throw new Exception(
                sprintf(
                    '"%s" is not a valid PHPUnit 9.2 XML configuration file:%s',
                    $filename,
                    $validationResult->asString()
                )
            );
        }

        foreach ((new MigrationBuilder)->build('9.2') as $migration) {
            $migration->migrate($configurationDocument);
        }

        $configurationDocument->formatOutput       = true;
        $configurationDocument->preserveWhiteSpace = false;

        return $configurationDocument->saveXML();
    }
}

Fix issue identified by Psalm

Fix issue identified by Psalm


<?php
/**
 * This file is part of the CalendArt package
 *
 * For the full copyright and license information, please view the LICENSE file
 * that was distributed with this source code.
 *
 * @copyright Wisembly
 * @license   http://www.opensource.org/licenses/MIT-License MIT License
 */

namespace CalendArt\Adapter\Google\Exception;

use ErrorException;

use GuzzleHttp\Message\Response,
    GuzzleHttp\Exception\ParseException;

/**
 * Whenever the Api returns an unexpected result
 *
 * @author Baptiste Clavié <baptiste@wisembly.com>
 */
class ApiErrorException extends ErrorException
{
    public function __construct(Response $response)
    {
        try {
            $json    = $response->json();
            $message = $json['error']['message'];
        } catch (ParseException $e) {
            $message = $response->getReasonPhrase();
        }

        parent::__construct(sprintf('The request failed and returned an invalid status code ("%d") : %s', $response->getStatusCode(), $message), $response->getStatusCode());
    }
}

<?php
/**
 * This file is part of the CalendArt package
 *
 * For the full copyright and license information, please view the LICENSE file
 * that was distributed with this source code.
 *
 * @copyright Wisembly
 * @license   http://www.opensource.org/licenses/MIT-License MIT License
 */

namespace CalendArt\Adapter\Google\Exception;

use ErrorException;

use GuzzleHttp\Message\Response,
    GuzzleHttp\Exception\ParseException;

/**
 * Whenever the Api returns an unexpected result
 *
 * @author Baptiste Clavié <baptiste@wisembly.com>
 */
class ApiErrorException extends ErrorException
{
    public function __construct(Response $response)
    {
        try {
            $this->details = $response->json();
            $message = $this->details['error']['message'];
        } catch (ParseException $e) {
            $message = $response->getReasonPhrase();
        }

        parent::__construct(sprintf('The request failed and returned an invalid status code ("%d") : %s', $response->getStatusCode(), $message), $response->getStatusCode());
    }

    public function getDetails()
    {
        return $this->details;
    }
}

[Google] Add the possibility to get more details on an api error


<?php

namespace Illuminate\Database;

use Throwable;
use Illuminate\Support\Str;

trait DetectsLostConnections
{
    /**
     * Determine if the given exception was caused by a lost connection.
     *
     * @param  \Throwable  $e
     * @return bool
     */
    protected function causedByLostConnection(Throwable $e)
    {
        $message = $e->getMessage();

        return Str::contains($message, [
            'server has gone away',
            'no connection to the server',
            'Lost connection',
            'is dead or not enabled',
            'Error while sending',
            'decryption failed or bad record mac',
            'server closed the connection unexpectedly',
            'SSL connection has been closed unexpectedly',
            'Error writing data to the connection',
            'Resource deadlock avoided',
            'Transaction() on null',
            'child connection forced to terminate due to client_idle_limit',
            'query_wait_timeout',
            'reset by peer',
            'Physical connection is not usable',
            'TCP Provider: Error code 0x68',
            'getaddrinfo failed: Name or service not known',
            'ORA-03114',
            'Packets out of order. Expected',
            'Adaptive Server connection failed',
            'Communication link failure',
        ]);
    }
}

<?php

namespace Illuminate\Database;

use Throwable;
use Illuminate\Support\Str;

trait DetectsLostConnections
{
    /**
     * Determine if the given exception was caused by a lost connection.
     *
     * @param  \Throwable  $e
     * @return bool
     */
    protected function causedByLostConnection(Throwable $e)
    {
        $message = $e->getMessage();

        return Str::contains($message, [
            'server has gone away',
            'no connection to the server',
            'Lost connection',
            'is dead or not enabled',
            'Error while sending',
            'decryption failed or bad record mac',
            'server closed the connection unexpectedly',
            'SSL connection has been closed unexpectedly',
            'Error writing data to the connection',
            'Resource deadlock avoided',
            'Transaction() on null',
            'child connection forced to terminate due to client_idle_limit',
            'query_wait_timeout',
            'reset by peer',
            'Physical connection is not usable',
            'TCP Provider: Error code 0x68',
            'Name or service not known',
            'ORA-03114',
            'Packets out of order. Expected',
            'Adaptive Server connection failed',
            'Communication link failure',
        ]);
    }
}

Revert "Stricter error message in place of "Name or service not known""

This reverts commit f0258bdd739450104cc196cbea750450f391e763.


<form action="<?php echo $this->getUrl('post/add'); ?>" method="post">
    <input type="text" name="title">

    <textarea name="content">
    </textarea>

    <input type="submit" value="Send"/>
</form>

Add tinymce redactor to form add post

Add tinymce redactor to form add post


<?php
/**
 * This file is part of the Imbo package
 *
 * (c) Christer Edvartsen <cogo@starzinger.net>
 *
 * For the full copyright and license information, please view the LICENSE file that was
 * distributed with this source code.
 */

use Imbo\Auth\AccessControl\Adapter\AdapterInterface,
    Imbo\Auth\AccessControl\Adapter\AbstractAdapter,
    Imbo\Auth\AccessControl\GroupQuery,
    Imbo\Model\Groups as GroupsModel;

/**
 * Use a custom user lookup implementation
 */
class StaticAccessControl extends AbstractAdapter implements AdapterInterface {
    public function hasAccess($publicKey, $resource, $user = null) {
        return $publicKey === 'public';
    }

    public function getPrivateKey($publicKey) {
        return 'private';
    }

    public function getGroups(GroupQuery $query = null, GroupsModel $model) {
        return [];
    }

    public function getGroup($groupName) {
        return false;
    }

    public function userExists($publicKey) {
        return $publicKey === 'public';
    }

    public function publicKeyExists($publicKey) {
        return $publicKey === 'public';
    }

    public function getAccessListForPublicKey($publicKey) {
        return [];
    }

    public function getUsersForResource($publicKey, $resource) {
        return [];
    }

    public function getAccessRule($publicKey, $accessRuleId) {
        return null;
    }
}

return [
    'accessControl' => new StaticAccessControl(),
];

<?php
/**
 * This file is part of the Imbo package
 *
 * (c) Christer Edvartsen <cogo@starzinger.net>
 *
 * For the full copyright and license information, please view the LICENSE file that was
 * distributed with this source code.
 */

use Imbo\Auth\AccessControl\Adapter\AdapterInterface,
    Imbo\Auth\AccessControl\Adapter\AbstractAdapter,
    Imbo\Auth\AccessControl\GroupQuery,
    Imbo\Model\Groups as GroupsModel;

/**
 * Use a custom user lookup implementation
 */
class StaticAccessControl extends AbstractAdapter implements AdapterInterface {
    public function hasAccess($publicKey, $resource, $user = null) {
        return $publicKey === 'public';
    }

    public function getPrivateKey($publicKey) {
        return 'private';
    }

    public function getGroups(GroupQuery $query = null, GroupsModel $model) {
        return [];
    }

    public function getGroup($groupName) {
        return false;
    }

    public function groupExists($groupName) {
        return false;
    }

    public function userExists($publicKey) {
        return $publicKey === 'public';
    }

    public function publicKeyExists($publicKey) {
        return $publicKey === 'public';
    }

    public function getAccessListForPublicKey($publicKey) {
        return [];
    }

    public function getUsersForResource($publicKey, $resource) {
        return [];
    }

    public function getAccessRule($publicKey, $accessRuleId) {
        return null;
    }
}

return [
    'accessControl' => new StaticAccessControl(),
];

Add missing groupExists()-method to static ACL-adapter


<?php

namespace BinSoul\Db;

/**
 * Represents a connection to a database.
 */
interface Connection
{
    /**
     * Opens the connection.
     *
     * @return bool
     */
    public function open();

    /**
     * Closes the connection.
     *
     * @return bool
     */
    public function close();

    /**
     * Executes an arbitrary statement using the given parameters.
     *
     * @param string  $statement
     * @param mixed[] $parameters
     *
     * @return Result
     */
    public function execute($statement, array $parameters);

    /**
     * Starts a new transaction.
     *
     * @return bool
     */
    public function begin();

    /**
     * Commits the current transaction.
     *
     * @return bool
     */
    public function commit();

    /**
     * Rolls back the current transaction.
     *
     * @return bool
     */
    public function rollback();
}

<?php

namespace BinSoul\Db;

/**
 * Represents a connection to a database.
 */
interface Connection
{
    /**
     * Opens the connection.
     *
     * @return bool
     */
    public function open();

    /**
     * Closes the connection.
     *
     * @return bool
     */
    public function close();

    /**
     * Executes an arbitrary statement.
     *
     * @param string  $statement
     * @param mixed[] $parameters
     *
     * @return Result
     */
    public function execute($statement, array $parameters = []);

    /**
     * Starts a new transaction.
     *
     * @return bool
     */
    public function begin();

    /**
     * Commits the current transaction.
     *
     * @return bool
     */
    public function commit();

    /**
     * Rolls back the current transaction.
     *
     * @return bool
     */
    public function rollback();
}

Make the parameters argument optional

Make the parameters argument optional


<?php

/*
 * This file is part of the Sylius package.
 *
 * (c) Paweł Jędrzejewski
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

declare(strict_types=1);

namespace Sylius\Component\Product\Repository;

use Sylius\Component\Product\Model\ProductInterface;
use Sylius\Component\Resource\Repository\RepositoryInterface;

interface ProductRepositoryInterface extends RepositoryInterface
{
    /**
     * @return array|ProductInterface[]
     */
    public function findByName(string $name, string $locale): array;

    /**
     * @return array|ProductInterface[]
     */
    public function findByNamePart(string $phrase, string $locale): array;
}

<?php

/*
 * This file is part of the Sylius package.
 *
 * (c) Paweł Jędrzejewski
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

declare(strict_types=1);

namespace Sylius\Component\Product\Repository;

use Sylius\Component\Product\Model\ProductInterface;
use Sylius\Component\Resource\Repository\RepositoryInterface;

interface ProductRepositoryInterface extends RepositoryInterface
{
    /**
     * @return array|ProductInterface[]
     */
    public function findByName(string $name, string $locale): array;

    /**
     * @return array|ProductInterface[]
     */
    public function findByNamePart(string $phrase, string $locale, ?int $limit = null): array;
}

Add ability to limit products and taxons when looking for name part


<?php

namespace adLDAP\Tests;

use Mockery;

class FunctionalTestCase extends \PHPUnit_Framework_TestCase
{
    protected function mock($class)
    {
        return Mockery::mock($class);
    }
}

<?php

namespace adLDAP\Tests;

use Mockery;

abstract class FunctionalTestCase extends \PHPUnit_Framework_TestCase
{
    protected function mock($class)
    {
        return Mockery::mock($class);
    }
}

Convert functional test case to abstract


<?php

namespace allejo\stakx\tests;

use allejo\stakx\Engines\MarkdownEngine;

class MarkdownEngineTest extends \PHPUnit_Stakx_TestCase
{
    /** @var MarkdownEngine */
    private $mdEngine;

    public function setUp ()
    {
        parent::setUp();

        $this->mdEngine = MarkdownEngine::instance();
    }

    public function testHeaderIdAttr ()
    {
        $content  = '# Hello World';
        $expected = '
Hello World
';
        $compiled = $this->mdEngine->parse($content);

        $this->assertEquals($expected, $compiled);
    }

    public function testCodeBlockWithLanguage ()
    {
        $codeBlock = <<<CODE
```php
<?php

echo "hello world";
```
CODE;
        $compiled = $this->mdEngine->parse($codeBlock);

        $this->assertContains('', $compiled);
    }

    public function testCodeBlockWithNoLanguage ()
    {
        $codeBlock = <<<CODE
```
Plain text!
```
CODE;
        $compiled = $this->mdEngine->parse($codeBlock);

        $this->assertContains('', $compiled);
        $this->assertNotContains('language-', $compiled);
    }

    public function testCodeBlockWithUnsupportedLanguage ()
    {
        $this->setExpectedException(\PHPUnit_Framework_Error_Warning::class);

        $codeBlock = <<<CODE
```toast
toast("some made up");
```
CODE;
        $this->mdEngine->parse($codeBlock);
    }
}

Fix a now, incorrect unit test

Fix a now, incorrect unit test


<?php

namespace Korobi\WebBundle\Controller;

use Korobi\WebBundle\Exception\NotImplementedException;
use Michelf\Markdown;
use Symfony\Component\HttpFoundation\Response;

class DocsController extends BaseController {

    public function renderAction($file) {
        if (!preg_match("/^[A-Za-z0-9_]+$/", $file)) {
            throw $this->createNotFoundException("Invalid doc");
        }

        $fn = $this->get('kernel')->getRootDir() . "/../docs/" . $file . ".md";
        if (!file_exists($fn) || $file === "README") {
            throw $this->createNotFoundException("Doc does not exist, " . $fn);
        }

        $parser = new Markdown;
        $parser->no_entities = true;
        $parser->no_markup = true;
        return $this->render('KorobiWebBundle::doc_item.html.twig', ["content" => $parser->transform(file_get_contents($fn))]);
    }

    public function indexAction() {
        return $this->render('KorobiWebBundle::docs.html.twig');
    }
}

<?php

namespace Korobi\WebBundle\Controller;

use Korobi\WebBundle\Exception\NotImplementedException;
use Michelf\Markdown;
use Symfony\Component\HttpFoundation\Response;

class DocsController extends BaseController {

    public function renderAction($file) {
        if (!preg_match("/^[A-Za-z0-9_]+$/", $file)) {
            throw $this->createNotFoundException("Invalid doc");
        }

        $fn = $this->get('kernel')->getRootDir() . "/../docs/" . $file . ".md";
        if (!file_exists($fn) || $file === "README") {
            throw $this->createNotFoundException("Doc does not exist, " . $fn);
        }

        $parser = new Markdown;
        $parser->no_entities = true;
        $parser->no_markup = true;
        $content = $this->render('KorobiWebBundle::doc_item.html.twig', ["content" => $parser->transform(file_get_contents($fn))]);
        return new Response($content, 200, ["Content-Security-Policy" => "default-src 'self'"]);
    }

    public function indexAction() {
        return $this->render('KorobiWebBundle::docs.html.twig');
    }
}

Enable much stricter CSP on the iframe

Enable much stricter CSP on the iframe


	<? $count = 0; ?>
	<? foreach($files as $file): ?>
		<? if ($count % 2 == 0): ?>

		<? endif; ?>

		<? $this->renderFile($file); ?>
		<? $count++; ?>
	<? endforeach; ?>

	<?php $count = 0; ?>
	<?php foreach($files as $file): ?>
		<?php if ($count % 2 == 0): ?>

		<?php endif; ?>

		<?php $this->renderFile($file); ?>
		<?php $count++; ?>
	<?php endforeach; ?>

Fix <? -> <?php regression

Fix <? -> <?php regression

Fixes #8


<?php
include(__DIR__ . '/init.php');

if (isset($passcode) && $passcode) {
  if (isset($_GET['p']) && password_verify($_GET['p'], $passcode)) {
    echo "document.getElementById('lock').style.display='none';document.title = '".str_replace('\'', '\\\'', htmlentities($site_name))."';setLockCookie();window.addEventListener('scroll', setLockCookie);window.addEventListener('mousemove', setLockCookie);window.addEventListener('keypress', setLockCookie);lockDown();document.body.removeChild(document.getElementById('lock_s'));";
    exit;
  } elseif (isset($_GET['p'])) {
    echo "document.body.removeChild(document.getElementById('lock_s'));";
    exit;
  }
}

header("HTTP/1.1 401 Unauthorized");
exit;

<?php
header('Content-Type: text/javascript');
include(__DIR__ . '/init.php');

if (isset($passcode) && $passcode) {
  if (isset($_GET['p']) && password_verify($_GET['p'], $passcode)) {
    echo "document.getElementById('lock').style.display='none';document.title = '".str_replace('\'', '\\\'', htmlentities($site_name))."';setLockCookie();window.addEventListener('scroll', setLockCookie);window.addEventListener('mousemove', setLockCookie);window.addEventListener('keypress', setLockCookie);lockDown();document.body.removeChild(document.getElementById('lock_s'));";
    exit;
  } elseif (isset($_GET['p'])) {
    echo "document.body.removeChild(document.getElementById('lock_s'));";
    exit;
  }
}

header("HTTP/1.1 401 Unauthorized");
exit;

Set mime type for php js file

Set mime type for php js file


<?php

namespace APIBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use FOS\RestBundle\Controller\Annotations as Rest;
use Nelmio\ApiDocBundle\Annotation\ApiDoc;
use APIBundle\Entity\Exercise;
use APIBundle\Form\Type\EventType;
use APIBundle\Entity\Event;

class InjectTypeController extends Controller
{
    /**
     * @ApiDoc(
     *    description="List inject types"
     * )
     * @Rest\Get("/inject_types")
     */
    public function getInjectTypesAction(Request $request)
    {
        $url = $this->getParameter('worker_url') . '/cxf/contracts';
        try {
            $contracts = json_decode(@file_get_contents($url), true);
        } catch(\Exception $e) {}

        $other = array();
        $other['type'] = 'openex_manual';
        $other['fields'] = array();
        $other['fields'][] = array(
            'name' => 'content',
            'type' => 'textarea',
            'cardinality' => '1',
            'mandatory' => true,
        );

        $contracts[] = $other;

        $output = json_encode($contracts);
        return new Response($output);
    }
}

<?php

namespace APIBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use FOS\RestBundle\Controller\Annotations as Rest;
use Nelmio\ApiDocBundle\Annotation\ApiDoc;
use APIBundle\Entity\Exercise;
use APIBundle\Form\Type\EventType;
use APIBundle\Entity\Event;

class InjectTypeController extends Controller
{
    /**
     * @ApiDoc(
     *    description="List inject types"
     * )
     * @Rest\Get("/inject_types")
     */
    public function getInjectTypesAction(Request $request)
    {
        $logger = $this->get('logger');

        $contracts = array();
        try {
            $url = $this->getParameter('worker_url') . '/cxf/contracts';
            $contracts = json_decode(@file_get_contents($url), true);
        } catch (\Exception $e) {
            $logger->info('Contracts can not be retrieved from worker');
        }

        $other = array();
        $other['type'] = 'openex_manual';
        $other['fields'] = array();
        $other['fields'][] = array(
            'name' => 'content',
            'type' => 'textarea',
            'cardinality' => '1',
            'mandatory' => true,
        );

        $contracts[] = $other;

        $output = json_encode($contracts);
        return new Response($output);
    }
}

Add log if worker is down

Add log if worker is down


{!! Form::errors($errors) !!}

@if (isset($model))
    {!! Form::model($model, ['route' => ['admin.news.update', $model->id], 'method' => 'PUT']) !!}
@else
    {!! Form::open(['url' => 'admin/news']) !!}
@endif
    {!! Form::smartText('title', trans('app.title')) !!}

    {!! Form::smartSelectRelation('newsCat', trans('app.category'), $modelClass) !!}

    {!! Form::smartSelectRelation('creator', trans('app.author'), $modelClass, user()->id) !!}

    {!! Form::smartTextarea('summary', trans('news::summary'), true) !!}

    {!! Form::smartTextarea('text', trans('app.text'), true) !!}

    {!! Form::smartDateTime('published_at', trans('news::publish_at')) !!}

    {!! Form::smartCheckbox('published', trans('app.published'), true) !!}

    {!! Form::smartCheckbox('internal', trans('app.internal')) !!}

    {!! Form::smartCheckbox('enable_comments', trans('app.enable_comments'), true) !!}

    {!! Form::actions() !!}
{!! Form::close() !!}

{!! Form::errors($errors) !!}

@if (isset($model))
    {!! Form::model($model, ['route' => ['admin.news.update', $model->id], 'method' => 'PUT']) !!}
@else
    {!! Form::open(['url' => 'admin/news']) !!}
@endif
    {!! Form::smartText('title', trans('app.title')) !!}

    {!! Form::smartSelectRelation('newsCat', trans('app.category'), $modelClass) !!}

    {!! Form::smartSelectRelation('creator', trans('app.author'), $modelClass, user()->id) !!}

    {!! Form::smartTextarea('summary', trans('news::summary'), true) !!}

    {!! Form::smartTextarea('text', trans('app.text'), true) !!}

    {!! Form::smartImageFile() !!}

    {!! Form::smartDateTime('published_at', trans('news::publish_at')) !!}

    {!! Form::smartCheckbox('published', trans('app.published'), true) !!}

    {!! Form::smartCheckbox('internal', trans('app.internal')) !!}

    {!! Form::smartCheckbox('enable_comments', trans('app.enable_comments'), true) !!}

    {!! Form::actions() !!}
{!! Form::close() !!}

Add image form field to template

Add image form field to template


<?php

namespace PhpWatson\Sdk\Tests\Language\RetrieveAndRank\V1;

use PhpWatson\Sdk\Tests\AbstractTestCase;
use PhpWatson\Sdk\Language\ToneAnalyser\ToneAnalyserService;

class ToneAnalyserV3Test extends AbstractTestCase
{
    /**
     * @var ToneAnalyserService
     */
    public $service;

    public function setUp()
    {
        parent::setUp();
        $this->service = new ToneAnalyserService();
    }

    public function test_if_url_is_set()
    {
        $this->assertEquals(
            'https://watson-api-explorer.mybluemix.net/tone-analyzer/api',
            $this->service->getUrl()
        );
    }

    public function test_if_version_is_set()
    {
        $this->assertEquals(
            'v3',
            $this->service->getVersion()
        );
    }

    public function test_can_analyse_plain_text()
    {
        $response = $this->service->plainText('Example text to analyse, duuh!');

        $this->assertArrayHasKey('document_tone', json_decode($response->getBody()->getContents(), true));
    }
}

<?php

namespace PhpWatson\Sdk\Tests\Language\RetrieveAndRank\V1;

use PhpWatson\Sdk\Tests\AbstractTestCase;
use PhpWatson\Sdk\Language\ToneAnalyser\V3\ToneAnalyserService;

class ToneAnalyserV3Test extends AbstractTestCase
{
    /**
     * @var ToneAnalyserService
     */
    public $service;

    public function setUp()
    {
        parent::setUp();
        $this->service = new ToneAnalyserService();
    }

    public function test_if_url_is_set()
    {
        $this->assertEquals(
            'https://watson-api-explorer.mybluemix.net/tone-analyzer/api',
            $this->service->getUrl()
        );
    }

    public function test_if_version_is_set()
    {
        $this->assertEquals(
            'v3',
            $this->service->getVersion()
        );
    }

    public function test_can_analyse_plain_text()
    {
        $response = $this->service->plainText('Example text to analyse, duuh!');

        $this->assertArrayHasKey('document_tone', json_decode($response->getContent(), true));
    }
}

Refactor for using the new Response class


    <?php foreach ($modules as $moduleId => $module) : ?>
    <div class="modularity-module modularity-js-draggable" data-module-id="<?php echo $moduleId; ?>" data-sidebar-incompability='<?php echo is_array($module['sidebar_incompability']) ? json_encode($module['sidebar_incompability']) : ''; ?>'>

            <?php echo modularity_decode_icon($module); ?>

        <?php echo $module['labels']['name']; ?>

    <?php endforeach; ?>

    <?php foreach ($modules as $moduleId => $module) : ?>
    <div class="modularity-module modularity-js-draggable"
         data-module-id="<?php echo $moduleId; ?>"
         data-sidebar-incompability='<?php echo (isset($module['sidebar_incompability']) && is_array($module['sidebar_incompability'])) ? json_encode($module['sidebar_incompability']) : ''; ?>'>

            <?php echo modularity_decode_icon($module); ?>

        <?php echo $module['labels']['name']; ?>

    <?php endforeach; ?>

Check if module array has property set before using it. Cleaning up messy row to multiple.


<?php

/*
 * This file is part of Psy Shell
 *
 * (c) 2013 Justin Hileman
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Psy\Readline;

use Psy\Readline\GNUReadline;

/**
 * A Libedit-based Readline implementation.
 *
 * This is largely the same as the Readline implementation, but it emulates
 * support for `readline_list_history` since PHP decided it was a good idea to
 * ship a fake Readline implementation that is missing history support.
 *
 * Note that this implementation relies on the `unvis` binary to parse the
 * Libedit history file. Without that, PsySH will fall back to LibeditTransient.
 */
class Libedit extends GNUReadline
{
    /**
     * If `unvis` is available, we can emulate GNU Readline by manually reading
     * and parsing the history file. Without it, we're pretty much outta luck.
     *
     * @return boolean
     */
    public static function isSupported()
    {
        return function_exists('readline') && (`which unvis` !== null);
    }

    /**
     * {@inheritDoc}
     */
    public function listHistory()
    {
        $history = array();
        $file = escapeshellarg($this->historyFile);
        exec("unvis $file", $history);

        // shift the history signature, ensure it's valid
        if (array_shift($history) !== '_HiStOrY_V2_') {
            return array();
        }

        return $history;
    }
}

<?php

/*
 * This file is part of Psy Shell
 *
 * (c) 2013 Justin Hileman
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Psy\Readline;

use Psy\Readline\GNUReadline;

/**
 * A Libedit-based Readline implementation.
 *
 * This is largely the same as the Readline implementation, but it emulates
 * support for `readline_list_history` since PHP decided it was a good idea to
 * ship a fake Readline implementation that is missing history support.
 *
 * Note that this implementation relies on the `unvis` binary to parse the
 * Libedit history file. Without that, PsySH will fall back to LibeditTransient.
 */
class Libedit extends GNUReadline
{
    /**
     * If `unvis` is available, we can emulate GNU Readline by manually reading
     * and parsing the history file. Without it, we're pretty much outta luck.
     *
     * @return boolean
     */
    public static function isSupported()
    {
        return function_exists('readline') && (`which unvis 2>/dev/null` !== null);
    }

    /**
     * {@inheritDoc}
     */
    public function listHistory()
    {
        $history = array();
        $file = escapeshellarg($this->historyFile);
        exec("unvis $file", $history);

        // shift the history signature, ensure it's valid
        if (array_shift($history) !== '_HiStOrY_V2_') {
            return array();
        }

        return $history;
    }
}

Fix for `which` on systems that do dumb things.

Fixes #21


<?php
namespace CdliAutogenUsernameTest;

use CdliAutogenUsername\Generator;

class IntegrationTest extends \PHPUnit_Framework_TestCase
{
    public function testFilterChainsWithNoDatasourceLookup()
    {
        $gen = new Generator(array(
            'filters' => array(
                'digits' => array(
                    'filter' => 'RandomDigits',
                    'options' => array( 'digits' => 5 ),
                ),
                'prefix' => array(
                    'filter' => 'StaticString',
                    'options' => array( 'string' => 'TEST' ),
                ),
            ),
        ));
        $this->assertRegexp('/^[0-9]{5}TEST$/', $gen->generate());
    }
}

<?php
namespace CdliAutogenUsernameTest;

use CdliAutogenUsername\Generator;

class IntegrationTest extends \PHPUnit_Framework_TestCase
{
    public function testFilterChainsWithNoDatasourceLookup()
    {
        $gen = new Generator(array(
            'filters' => array(
                'digits' => array(
                    'filter' => 'RandomDigits',
                    'options' => array( 'digits' => 5 ),
                ),
                'prefix' => array(
                    'filter' => 'StaticString',
                    'options' => array( 'string' => 'TEST' ),
                ),
            ),
        ));
        $this->assertRegexp('/^[0-9]{5}TEST$/', $gen->generate());
    }

    public function testFilterChainsWithDatasourceLookupWhichNeverReturnsTrue()
    {
        $gen = new Generator(array(
            'datasource' => array(
                'plugin' => 'test'
            ),
            'filters' => array(
                'digits' => array(
                    'filter' => 'RandomDigits',
                    'options' => array( 'digits' => 5 ),
                ),
                'prefix' => array(
                    'filter' => 'StaticString',
                    'options' => array( 'string' => 'TEST' ),
                ),
            ),
        ));

        $mock = $this->getMock('CdliAutogenUsername\Datasource\DatasourceInterface');
        $mock->expects($this->any())->method('isUsernameTaken')->will($this->returnCallback(function($value) {
            return false;
        }));
        $gen->getDatasourceBroker()->register('test', $mock);

        $this->assertRegexp('/^[0-9]{5}TEST$/', $gen->generate());
    }

}

Add datasource lookup to the integration test


<?php

/**
 * ShowAllProjectsToVisitor acceptance test
 * @author     Adrien Desfourneaux (aka Dieze) <dieze51@gmail.com>
 * @package    DzProject
 * @subpackage Acceptance
 * @category   Test
 * @license    http://opensource.org/licenses/GPL-2.0 GNU General Public License, version 2
 */

$I = new WebGuy($scenario);
$I->wantTo('See all projects');
$I->amOnPage('/project/show-all/all');

$I->see('Project');
$I->see('Description');
$I->see('Period');

<?php

/**
 * ShowAllProjectsToVisitor acceptance test
 * @author     Adrien Desfourneaux (aka Dieze) <dieze51@gmail.com>
 * @package    DzProject
 * @subpackage Acceptance
 * @category   Test
 * @license    http://opensource.org/licenses/GPL-2.0 GNU General Public License, version 2
 */

$I = new WebGuy($scenario);
$I->wantTo('See all projects');

$I->amOnPage('/project/show-all/all');

$I->see('Projects');

$I->see('Name');
$I->see('Period');

Change labels in ShowAllProjectsToVisitor acceptance test


<?php
# Copyright © 2012 Martin Ueding <dev@martin-ueding.de>

class BookmarkHelper extends AppHelper {
	var $helpers = array('Html');

	function print_bookmark($that, $bookmark) {
		#echo '<img width="16" height="16" src="'.$that->Html->url(array('controller' => 'bookmarks', 'action' => 'favicon', $bookmark['id'])).'" />';
		#echo ' ';

		echo $that->Html->link($bookmark['title'],
			array('controller' => 'bookmarks', 'action' => 'visit', $bookmark['id']),
			array('title' => $bookmark['url']));
		echo ' ';

		echo $that->Html->link(__('View', true),
			array('controller' => 'bookmarks', 'action' => 'view', $bookmark['id']),
			array('class' => 'edit_option'));
		echo ' ';

		echo $that->Html->link(__('Edit', true),
			array('controller' => 'bookmarks', 'action' => 'edit', $bookmark['id']),
			array('class' => 'edit_option'));
		echo ' ';

		echo $that->Html->link(__('Delete', true),
			array('controller' => 'bookmarks', 'action' => 'delete', $bookmark['id']),
			null,
			sprintf(__('Are you sure you want to delete # %s?', true),
			$bookmark['id']),
			array('class' => 'edit_option'));
	}
}

<?php
# Copyright © 2012 Martin Ueding <dev@martin-ueding.de>

class BookmarkHelper extends AppHelper {
	var $helpers = array('Html');

	function print_bookmark($that, $bookmark) {
		#echo '<img width="16" height="16" src="'.$that->Html->url(array('controller' => 'bookmarks', 'action' => 'favicon', $bookmark['id'])).'" />';
		#echo ' ';

		echo $that->Html->link($bookmark['title'],
			array('controller' => 'bookmarks', 'action' => 'visit', $bookmark['id']),
			array('class' => 'bookmark_link', 'title' => $bookmark['url']));
		echo ' ';

		echo $that->Html->link(__('View', true),
			array('controller' => 'bookmarks', 'action' => 'view', $bookmark['id']),
			array('class' => 'edit_option'));
		echo ' ';
	}
}

Add class, remove edit and delete links

Add class, remove edit and delete links


<?php

/**
 * ownCloud
 *
 * @author Jakob Sack
 * @copyright 2011 Jakob Sack kde@jakobsack.de
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU AFFERO GENERAL PUBLIC LICENSE for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with this library.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

class OC_Connector_Sabre_Auth extends Sabre_DAV_Auth_Backend_AbstractBasic {
	/**
	 * Validates a username and password
	 *
	 * This method should return true or false depending on if login
	 * succeeded.
	 *
	 * @return bool
	 */
	protected function validateUserPass($username, $password){
		OC_Util::setUpFS();//login hooks may need early access to the filesystem
		if(OC_User::login($username,$password)){
			OC_Util::setUpFS();
			return true;
		}
		else{
			return false;
		}
	}
}

<?php

/**
 * ownCloud
 *
 * @author Jakob Sack
 * @copyright 2011 Jakob Sack kde@jakobsack.de
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU AFFERO GENERAL PUBLIC LICENSE for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with this library.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

class OC_Connector_Sabre_Auth extends Sabre_DAV_Auth_Backend_AbstractBasic {
	/**
	 * Validates a username and password
	 *
	 * This method should return true or false depending on if login
	 * succeeded.
	 *
	 * @return bool
	 */
	protected function validateUserPass($username, $password){
		OC_Util::setUpFS();//login hooks may need early access to the filesystem
		if(OC_User::login($username,$password)){
			OC_Util::setUpFS($username);
			return true;
		}
		else{
			return false;
		}
	}
}

Fix initialization of OC_Filesystem setup from DAV


<?php
namespace Veles\Tests\Routing\Exceptions;

use Veles\Routing\Exceptions\NotFoundException;

/**
 * Generated by PHPUnit_SkeletonGenerator on 2015-08-12 at 09:05:52.
 * @group Dev
 */
class NotFoundExceptionTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var NotFoundException
     */
    protected $object;

    /**
     * Sets up the fixture, for example, opens a network connection.
     * This method is called before a test is executed.
     */
    protected function setUp()
    {
        $this->object = new NotFoundException;
    }

    /**
     * Tears down the fixture, for example, closes a network connection.
     * This method is called after a test is executed.
     */
    protected function tearDown()
    {
    }

    public function testConstruct()
    {
        $result = $this->object->getCode();
		$msg = 'NotFoundException::__construct() wrong behavior!';
		$this->assertSame(0, $result, $msg);
    }
}

<?php
namespace Veles\Tests\Routing\Exceptions;

use Veles\Routing\Exceptions\NotFoundException;

/**
 * Generated by PHPUnit_SkeletonGenerator on 2015-08-12 at 09:05:52.
 * @group route
 */
class NotFoundExceptionTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var NotFoundException
     */
    protected $object;

    /**
     * Sets up the fixture, for example, opens a network connection.
     * This method is called before a test is executed.
     */
    protected function setUp()
    {
        $this->object = new NotFoundException;
    }

    /**
     * Tears down the fixture, for example, closes a network connection.
     * This method is called after a test is executed.
     */
    protected function tearDown()
    {
    }

    public function testConstruct()
    {
        $result = $this->object->getCode();
		$msg = 'NotFoundException::__construct() wrong behavior!';
		$this->assertSame(0, $result, $msg);
    }
}

Fix test group for NotFoundException

Fix test group for NotFoundException


<?php
$inventory = get_post_meta(get_the_ID(), 'dabc-store-inventory', true);

if ( $inventory['inventory'] ) :

	$store_numbers = array_keys( $inventory['inventory'] );

?>

Store Availability

Last Updated: <?php echo $inventory['last_updated']; ?>

				Store
				Address
				Quantity

			<?php $stores = dabc_query_stores_by_number( $store_numbers ); ?>
			<?php while ( $stores->have_posts() ) : ?>
				<?php $stores->the_post(); ?>
				<?php $store_post_id = get_the_ID(); ?>
				<?php $store_number  = dabc_get_store_number( $store_post_id ); ?>

					<a href="<?php the_permalink(); ?>"><?php the_title(); ?>

					<?php dabc_the_store_address( $store_post_id ); ?>

				<?php echo $inventory['inventory'][$store_number]; ?>

			<?php endwhile; ?>

<?php endif; ?>

<?php

$beer_post_id = get_the_ID();

if ( $inventory = dabc_get_inventory( $beer_post_id ) ) :

	$store_numbers = array_keys( $inventory );

?>

Store Availability

Last Updated: <?php dabc_the_inventory_last_updated(); ?>

				Store
				Address
				Quantity

			<?php $stores = dabc_query_stores_by_number( $store_numbers ); ?>
			<?php while ( $stores->have_posts() ) : ?>
				<?php $stores->the_post(); ?>
				<?php $store_post_id = get_the_ID(); ?>
				<?php $store_number  = dabc_get_store_number( $store_post_id ); ?>

					<a href="<?php the_permalink(); ?>"><?php the_title(); ?>

					<?php dabc_the_store_address( $store_post_id ); ?>

				<?php dabc_the_quantity_for_store( $store_number, $beer_post_id ); ?>

			<?php endwhile; ?>

<?php endif; ?>

Refactor beer availability to use template tags.


<?php
/**
 * @author         Pierre-Henry Soria <hello@ph7cms.com>
 * @copyright      (c) 2018, Pierre-Henry Soria. All Rights Reserved.
 * @license        GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
 * @package        PH7 / App / System / Core / Class
 */

namespace PH7;

use PH7\Framework\Math\Measure\Year as YearMeasure;

class UserBirthDateCore
{
    const DEFAULT_AGE = 30;
    const BIRTHDATE_DELIMITER = '-';

    /**
     * @param string $sBirthDate YYYY-MM-DD format.
     *
     * @return int
     */
    public static function getAgeFromBirthDate($sBirthDate)
    {
        $aAge = explode(self::BIRTHDATE_DELIMITER, $sBirthDate);

        if (self::isInvalidBirthDate($aAge)) {
            return self::DEFAULT_AGE;
        }

        return (new YearMeasure($aAge[0], $aAge[1], $aAge[2]))->get();
    }

    private static function isInvalidBirthDate(array $aAge)
    {
        return count($aAge) < 3;
    }
}

<?php
/**
 * @author         Pierre-Henry Soria <hello@ph7cms.com>
 * @copyright      (c) 2018, Pierre-Henry Soria. All Rights Reserved.
 * @license        GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
 * @package        PH7 / App / System / Core / Class
 */

namespace PH7;

use PH7\Framework\Math\Measure\Year as YearMeasure;

class UserBirthDateCore
{
    const DEFAULT_AGE = 30;
    const BIRTHDATE_DELIMITER = '-';
    const NUMBER_ARRAY_ELEMENTS = 3;

    /**
     * @param string $sBirthDate YYYY-MM-DD format.
     *
     * @return int
     */
    public static function getAgeFromBirthDate($sBirthDate)
    {
        $aAge = explode(self::BIRTHDATE_DELIMITER, $sBirthDate);

        if (self::isInvalidBirthDate($aAge)) {
            return self::DEFAULT_AGE;
        }

        return (new YearMeasure($aAge[0], $aAge[1], $aAge[2]))->get();
    }

    private static function isInvalidBirthDate(array $aAge)
    {
        return count($aAge) < self::NUMBER_ARRAY_ELEMENTS;
    }
}

Store number of required array elements into constant


<?php

declare(strict_types=1);

/**
 * Copyright (c) 2013-2017 OpenCFP
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 *
 * @see https://github.com/opencfp/opencfp
 */

namespace OpenCFP\Infrastructure\Templating;

use OpenCFP\PathInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Twig_Extension;
use Twig_SimpleFunction;

class TwigExtension extends Twig_Extension
{
    /**
     * @var RequestStack
     */
    private $requestStack;

    /**
     * @var UrlGeneratorInterface
     */
    private $urlGenerator;

    /**
     * @var PathInterface
     */
    private $path;

    public function __construct(RequestStack $requestStack, UrlGeneratorInterface $urlGenerator, PathInterface $path)
    {
        $this->requestStack = $requestStack;
        $this->urlGenerator = $urlGenerator;
        $this->path         = $path;
    }

    public function getFunctions()
    {
        return [
            new Twig_SimpleFunction('uploads', function ($path) {
                return $this->path->downloadFromPath() . $path;
            }),
            new Twig_SimpleFunction('assets', function ($path) {
                return '/assets/' . $path;
            }),

            new Twig_SimpleFunction('active', function ($route) {
                return $this->urlGenerator->generate($route)
                    === $this->requestStack->getCurrentRequest()->getRequestUri();
            }),
        ];
    }
}

<?php

declare(strict_types=1);

/**
 * Copyright (c) 2013-2017 OpenCFP
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 *
 * @see https://github.com/opencfp/opencfp
 */

namespace OpenCFP\Infrastructure\Templating;

use OpenCFP\PathInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Twig_Extension;
use Twig_SimpleFunction;

class TwigExtension extends Twig_Extension
{
    /**
     * @var RequestStack
     */
    private $requestStack;

    /**
     * @var UrlGeneratorInterface
     */
    private $urlGenerator;

    /**
     * @var PathInterface
     */
    private $path;

    public function __construct(RequestStack $requestStack, UrlGeneratorInterface $urlGenerator, PathInterface $path)
    {
        $this->requestStack = $requestStack;
        $this->urlGenerator = $urlGenerator;
        $this->path         = $path;
    }

    public function getFunctions()
    {
        return [
            new Twig_SimpleFunction('uploads', function ($path) {
                return $this->path->downloadFromPath() . $path;
            }),
            new Twig_SimpleFunction('assets', function ($path) {
                return  $this->path->webAssetsPath() . $path;
            }),

            new Twig_SimpleFunction('active', function ($route) {
                return $this->urlGenerator->generate($route)
                    === $this->requestStack->getCurrentRequest()->getRequestUri();
            }),
        ];
    }
}

Implement web assets in the twig function


<?php

declare(strict_types=1);

namespace Shlinkio\Shlink\Core\Repository;

use Doctrine\Common\Persistence\ObjectRepository;
use Shlinkio\Shlink\Core\Entity\ShortUrl;

interface ShortUrlRepositoryInterface extends ObjectRepository
{
    /**
     * Gets a list of elements using provided filtering data
     *
     * @param string|array|null $orderBy
     */
    public function findList(
        ?int $limit = null,
        ?int $offset = null,
        ?string $searchTerm = null,
        array $tags = [],
        $orderBy = null
    ): array;

    /**
     * Counts the number of elements in a list using provided filtering data
     */
    public function countList(?string $searchTerm = null, array $tags = []): int;

    public function findOneByShortCode(string $shortCode, ?string $domain = null): ?ShortUrl;

    public function shortCodeIsInUse(string $slug, ?string $domain): bool;
}

<?php

declare(strict_types=1);

namespace Shlinkio\Shlink\Core\Repository;

use Doctrine\Common\Persistence\ObjectRepository;
use Shlinkio\Shlink\Common\Util\DateRange;
use Shlinkio\Shlink\Core\Entity\ShortUrl;

interface ShortUrlRepositoryInterface extends ObjectRepository
{
    /**
     * Gets a list of elements using provided filtering data
     *
     * @param string|array|null $orderBy
     */
    public function findList(
        ?int $limit = null,
        ?int $offset = null,
        ?string $searchTerm = null,
        array $tags = [],
        $orderBy = null,
        ?DateRange $dateRange = null
    ): array;

    /**
     * Counts the number of elements in a list using provided filtering data
     */
    public function countList(?string $searchTerm = null, array $tags = []): int;

    public function findOneByShortCode(string $shortCode, ?string $domain = null): ?ShortUrl;

    public function shortCodeIsInUse(string $slug, ?string $domain): bool;
}

Add date range filter to short url repository interface


<article <?php post_class(); ?>>

<?php the_title(); ?>

		<?php the_content(); ?>

		<?php the_post_thumbnail('medium'); ?>

		<?php
			previous_post_link('%link', 'Previous Post
');
			next_post_link('%link', 'Next Post');
		?>

<article <?php post_class(); ?>>

<?php the_title(); ?>

		<?php the_content(); ?>

		<?php the_post_thumbnail('large'); ?>

		<?php
			previous_post_link('%link', 'Previous Post
');
			next_post_link('%link', 'Next Post');
		?>

Make single post thumbnail bigger

Make single post thumbnail bigger

on single post pages


<?php

namespace Jonnybarnes\EmojiA11y\Test;

use PHPUnit_Framework_TestCase;
use Jonnybarnes\EmojiA11y\EmojiModifier;

class EmojiModifierTest extends PHPUnit_Framework_TestCase
{
    public function setUp()
    {
        $this->emoji = new EmojiModifier();
    }

    public function tearDown()
    {
        $this->emoji = null;
    }

    public function test_emoji_returns_same()
    {
        $this->assertEquals('Test', $this->emoji->makeEmojiAccessible('Test'));
    }
}

<?php

namespace Jonnybarnes\EmojiA11y\Test;

use PHPUnit_Framework_TestCase;
use Jonnybarnes\EmojiA11y\EmojiModifier;

class EmojiModifierTest extends PHPUnit_Framework_TestCase
{
    public function setUp()
    {
        $this->emoji = new EmojiModifier();
    }

    public function tearDown()
    {
        $this->emoji = null;
    }

    public function test_single_emoji()
    {
        $input = 'I’m 😀';
        $excpected = 'I’m 😀';
        $this->assertEquals($excpected, $this->emoji->makeEmojiAccessible($input));
    }
}

Make a test for single character emojis

Make a test for single character emojis


<?php
class Kwc_Basic_BackgroundWindowWidth_Image_Component extends Kwc_Basic_Image_Component
{
    public static function getSettings()
    {
        $ret = parent::getSettings();
        $ret['componentName'] = trlKwf('Background Image').' ('.trlKwf('Optional').')';
        $ret['dimensions'] = array(
            'fullWidth'=>array(
                'text' => trlKwf('full width'),
                'width' => 2560,
                'height' => 0,
                'cover' => true
            )
        );
        $ret['altText'] = false;
        return $ret;
    }

    public function getTemplateVars()
    {
        $ret = parent::getTemplateVars();
        $ret['imageUrl'] = $this->getImageUrl();
        return $ret;
    }
}

<?php
class Kwc_Basic_BackgroundWindowWidth_Image_Component extends Kwc_Basic_Image_Component
{
    public static function getSettings()
    {
        $ret = parent::getSettings();
        $ret['componentName'] = trlKwfStatic('Background Image').' ('.trlKwfStatic('Optional').')';
        $ret['dimensions'] = array(
            'fullWidth'=>array(
                'text' => trlKwfStatic('full width'),
                'width' => 2560,
                'height' => 0,
                'cover' => true
            )
        );
        $ret['altText'] = false;
        return $ret;
    }

    public function getTemplateVars()
    {
        $ret = parent::getTemplateVars();
        $ret['imageUrl'] = $this->getImageUrl();
        return $ret;
    }
}

Use trlStatic in static getSettings

Use trlStatic in static getSettings


<?php

use Illuminate\Database\Seeder;
use App\Models\Exercise;
use App\Models\Factor;

class FactorTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $exercises = Exercise::all();
        foreach ($exercises as $exercise) {
            factory(Factor::class, rand(5, 7))->create([
                'exercise_id' => $exercise->id
            ]);
        }
    }
}

<?php

use Illuminate\Database\Seeder;
use App\Models\Exercise;
use App\Models\Factor;

class FactorTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $exercises = Exercise::all();
        foreach ($exercises as $exercise) {
            factory(Factor::class)->create([
                'exercise_id' => $exercise->id,
                'text'=>'Planning and preparation'
            ]);

            factory(Factor::class)->create([
                'exercise_id' => $exercise->id,
                'text'=>'Communication and interaction'
            ]);

            factory(Factor::class)->create([
                'exercise_id' => $exercise->id,
                'text'=>'Teaching for learning'
            ]);

            factory(Factor::class)->create([
                'exercise_id' => $exercise->id,
                'text'=>'Managing the learning environment'
            ]);

            factory(Factor::class)->create([
                'exercise_id' => $exercise->id,
                'text'=>'Student Evaluation'
            ]);

            factory(Factor::class)->create([
                'exercise_id' => $exercise->id,
                'text'=>'Professionalism'
            ]);
        }
    }
}

Use more realistic data to seed factors table


<?php

namespace Monii\AggregateEventStorage\Fixtures\Blogging;

use Monii\AggregateEventStorage\Fixtures\Blogging\PostId;

class Post
{
    /**
     * @var PostId
     */
    private $postId;

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

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

    public function __construct(PostId $postId, $tags = array(), $comments = array())
    {
        $this->postId = $postId;
        $this->tags = $tags;
        $this->comments = $comments;
    }
}

<?php

namespace Monii\AggregateEventStorage\Fixtures\Blogging;

use Monii\AggregateEventStorage\Fixtures\Blogging\PostId;

class Post
{
    /**
     * @var PostId
     */
    private $postId;

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

    /**
     * @var Comment[]
     */
    private $comments;

    public function __construct(PostId $postId, $tags = array(), $comments = array())
    {
        $this->postId = $postId;
        $this->tags = $tags;
        $this->comments = $comments;
    }
}

Correct the docblock type for an array of objects


<?php

ini_set('date.timezone', 'UTC');

use Symfony\Component\ClassLoader\ApcClassLoader;
use Symfony\Component\HttpFoundation\Request;

$loader = require_once __DIR__.'/../app/bootstrap.php.cache';

// Use APC for autoloading to improve performance.
// Change 'sf2' to a unique prefix in order to prevent cache key conflicts
// with other applications also using APC.
if (function_exists('apc_store')) {
    $loader->unregister();
    $loader = new ApcClassLoader('packagist', $loader);
    $loader->register(true);
}

require_once __DIR__.'/../app/AppKernel.php';
//require_once __DIR__.'/../app/AppCache.php';

$kernel = new AppKernel('prod', false);
$kernel->loadClassCache();
//$kernel = new AppCache($kernel);
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);

<?php

ini_set('date.timezone', 'UTC');

use Symfony\Component\ClassLoader\ApcClassLoader;
use Symfony\Component\HttpFoundation\Request;

$loader = require_once __DIR__.'/../app/bootstrap.php.cache';

// Use APC for autoloading to improve performance.
// Change 'sf2' to a unique prefix in order to prevent cache key conflicts
// with other applications also using APC.
if (function_exists('apc_store')) {
    $apcLoader = new ApcClassLoader('packagist', $loader);
    $loader->unregister();
    $apcLoader->register(true);
}

require_once __DIR__.'/../app/AppKernel.php';
//require_once __DIR__.'/../app/AppCache.php';

$kernel = new AppKernel('prod', false);
$kernel->loadClassCache();
//$kernel = new AppCache($kernel);
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);

Allow ApcClassLoader to be autoloaded by the initial loader


<?php

ProfileRequestHandler::$profileFields[] = 'Twitter';

ProfileRequestHandler::$onBeforeProfileValidated = function($User, $profileChanges, $requestData) {
    // trim @ from front of twitter username
    if (isset($profileChanges['Twitter']) && $profileChanges['Twitter'][0] == '@') {
        $User->Twitter = substr($profileChanges['Twitter'], 1);
    }
};

ProfileRequestHandler::$onProfileSaved = function($User, $profileChanges, $requestData) {
    // assign tags
    if (isset($requestData['tags']) && is_array($requestData['tags'])) {
        foreach ($requestData['tags'] AS $prefix => $tags) {
            Tag::setTags($User, $tags, true, $prefix);
        }
    }
};

<?php

ProfileRequestHandler::$profileFields[] = 'FirstName';
ProfileRequestHandler::$profileFields[] = 'LastName';
ProfileRequestHandler::$profileFields[] = 'Twitter';

ProfileRequestHandler::$onBeforeProfileValidated = function($User, $profileChanges, $requestData) {
    // trim @ from front of twitter username
    if (isset($profileChanges['Twitter']) && $profileChanges['Twitter'][0] == '@') {
        $User->Twitter = substr($profileChanges['Twitter'], 1);
    }
};

ProfileRequestHandler::$onProfileSaved = function($User, $profileChanges, $requestData) {
    // assign tags
    if (isset($requestData['tags']) && is_array($requestData['tags'])) {
        foreach ($requestData['tags'] AS $prefix => $tags) {
            Tag::setTags($User, $tags, true, $prefix);
        }
    }
};

Add FirstName and LastName to profileFields via php-config


<?php

namespace LiteCQRS\Plugin\Monolog;

use LiteCQRS\Bus\MessageHandlerInterface;
use LiteCQRS\Bus\MessageInterface;
use LiteCQRS\DomainEvent;
use LiteCQRS\Command;
use Exception;

use Monolog\Logger;

/**
 * Logs all commands or events and their sucess/failure status
 * into a logger. The input data is json serialized during that process.
 */
class MonologDebugLogger implements MessageHandlerInterface
{
    private $logger;
    private $next;

    public function __construct(MessageHandlerInterface $next, Logger $logger)
    {
        $this->next   = $next;
        $this->logger = $logger;
    }

    public function handle(MessageInterface $message)
    {
        if ($message instanceof Command) {
            $parts = explode("\\", get_class($message));
            $log   = "Command[%s]: ";
            $info  = end($parts) . ": " . json_encode($message);
        } else if ($message instanceof DomainEvent) {
            $log  = "Event[%s]: ";
            $info = $message->getEventName() . ": " . json_encode($message);
        }

        try {
            $this->logger->debug(sprintf($log, 'STARTING') . $info);
            $this->next->handle($message);
            $this->logger->debug(sprintf($log, 'SUCCESS') . $info);
        } catch(Exception $e) {
            $this->logger->err(sprintf($log, 'FAIL') . ' - ' . $e->getMessage());
            throw $e;
        }
    }
}

<?php

namespace LiteCQRS\Plugin\Monolog;

use LiteCQRS\Bus\MessageHandlerInterface;
use LiteCQRS\Bus\MessageInterface;
use LiteCQRS\DomainEvent;
use LiteCQRS\Command;
use Exception;

use Monolog\Logger;

/**
 * Logs all commands or events and their sucess/failure status
 * into a logger. The input data is json serialized during that process.
 */
class MonologDebugLogger implements MessageHandlerInterface
{
    private $logger;
    private $next;

    public function __construct(MessageHandlerInterface $next, Logger $logger)
    {
        $this->next   = $next;
        $this->logger = $logger;
    }

    public function handle(MessageInterface $message)
    {
        if ($message instanceof Command) {
            $parts = explode("\\", get_class($message));
            $log   = "Command[%s]: ";
            $info  = substr(end($parts) . ": " . json_encode($message), 0, 4000);
        } else if ($message instanceof DomainEvent) {
            $log  = "Event[%s]: ";
            $info = substr($message->getEventName() . ": " . json_encode($message), 0, 4000);
        }

        try {
            $this->logger->debug(sprintf($log, 'STARTING') . $info);
            $this->next->handle($message);
            $this->logger->err(sprintf($log, 'SUCCESS') . $info);
        } catch(Exception $e) {
            $this->logger->err(sprintf($log, 'FAIL') . ' - ' . $e->getMessage());
            throw $e;
        }
    }
}

Truncate Log messages to 4000 chars.

Truncate Log messages to 4000 chars.


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class SongController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Song;

class SongController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $songs=Song::all();
        var_dump($songs[0]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}

Test of index action working

Test of index action working


<?php

/**
 * Smarty plugin
 * @package Smarty
 * @subpackage plugins
 */

/**
 * Smarty {suite_check_access} function plugin
 *
 * Type:     function

 * Name:     suite_check_access

 * Purpose:  Check if the current user has access to a record
 *
 * @author Jose C. Massón <jose AT gcoop DOT coop>
 * @param array
 * @param Smarty
 */
function smarty_function_suite_check_access($params, &$smarty)
{
    if (empty($params['module'])) {
        $smarty->trigger_error("sugar_check_access: missing 'module' parameter");
        return;
    }
    if (empty($params['record'])) {
        $smarty->trigger_error("sugar_check_access: missing 'record' parameter");
        return;
    }
    if (empty($params['action'])) {
        $smarty->trigger_error("sugar_check_access: missing 'module' parameter");
        return;
    }
    $ret = false;
    $bean = BeanFactory::getBean($params['module'], $params['record']);
    $ret = (bool) $bean->ACLAccess($params['action']);
    return $ret;
}

<?php

/**
 * Smarty plugin
 * @package Smarty
 * @subpackage plugins
 */

/**
 * Smarty {suite_check_access} function plugin
 *
 * Type:     function

 * Name:     suite_check_access

 * Purpose:  Check if the current user has access to a record
 *
 * @author Jose C. Massón <jose AT gcoop DOT coop>
 * @param array
 * @param Smarty
 */
function smarty_function_suite_check_access($params, &$smarty)
{
    if (empty($params['module'])) {
        $smarty->trigger_error("sugar_check_access: missing 'module' parameter");
        return;
    }
    if (empty($params['record'])) {
        $smarty->trigger_error("sugar_check_access: missing 'record' parameter");
        return;
    }
    if (empty($params['action'])) {
        $smarty->trigger_error("sugar_check_access: missing 'module' parameter");
        return;
    }
    $ret = false;
    $bean = BeanFactory::getBean($params['module'], $params['record']);

    if (is_subclass_of($bean, 'SugarBean')) {
        $ret = (bool) $bean->ACLAccess($params['action']);
    }

    return $ret;
}

Verify is $bean is_subclass_of SugarBean so we can check access


<?php

use Zend\Mvc\Application;
use Zend\Stdlib\ArrayUtils;

/**
 * This makes our life easier when dealing with paths. Everything is relative
 * to the application root now.
 */
chdir(dirname(__DIR__));

// Decline static file requests back to the PHP built-in webserver
if (php_sapi_name() === 'cli-server') {
    $path = realpath(__DIR__ . parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));
    if (__FILE__ !== $path && is_file($path)) {
        return false;
    }
    unset($path);
}

// Composer autoloading
include __DIR__ . '/../vendor/autoload.php';

if (! class_exists(Application::class)) {
    throw new RuntimeException(
        "Unable to load application.\n"
        . "- Type `composer install` if you are developing locally.\n"
        . "- Type `vagrant ssh -c 'composer install'` if you are using Vagrant.\n"
        . "- Type `docker-compose run zf composer install` if you are using Docker.\n"
    );
}

// Retrieve configuration
$appConfig = require __DIR__ . '/../config/application.config.php';
if (file_exists(__DIR__ . '/config/development.config.php')) {
    $appConfig = ArrayUtils::merge($appConfig, require __DIR__ . '/../config/development.config.php');
}

// Run the application!
Application::init($appConfig)->run();

<?php

use Zend\Mvc\Application;
use Zend\Stdlib\ArrayUtils;

/**
 * This makes our life easier when dealing with paths. Everything is relative
 * to the application root now.
 */
chdir(dirname(__DIR__));

// Decline static file requests back to the PHP built-in webserver
if (php_sapi_name() === 'cli-server') {
    $path = realpath(__DIR__ . parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));
    if (__FILE__ !== $path && is_file($path)) {
        return false;
    }
    unset($path);
}

// Composer autoloading
include __DIR__ . '/../vendor/autoload.php';

if (! class_exists(Application::class)) {
    throw new RuntimeException(
        "Unable to load application.\n"
        . "- Type `composer install` if you are developing locally.\n"
        . "- Type `vagrant ssh -c 'composer install'` if you are using Vagrant.\n"
        . "- Type `docker-compose run zf composer install` if you are using Docker.\n"
    );
}

// Retrieve configuration
$appConfig = require __DIR__ . '/../config/application.config.php';
if (file_exists(__DIR__ . '/../config/development.config.php')) {
    $appConfig = ArrayUtils::merge($appConfig, require __DIR__ . '/../config/development.config.php');
}

// Run the application!
Application::init($appConfig)->run();

Fix path in bootstrap script

Fix path in bootstrap script