<?php

namespace SilverStripe\FullTextSearch\Search\Extensions;

use SilverStripe\Core\Extension;
use TractorCow\ClassProxy\Generators\ProxyGenerator;
use SilverStripe\FullTextSearch\Search\Updaters\SearchUpdater;

/**
 * Class ProxyDBExtension
 * @package SilverStripe\FullTextSearch\Search\Extensions
 *
 * This database connector proxy will allow {@link SearchUpdater::handle_manipulation} to monitor database schema
 * changes that may need to be propagated through to search indexes.
 *
 */
class ProxyDBExtension extends Extension
{
    /**
     * @param ProxyGenerator $proxy
     *
     * Ensure the search index is kept up to date by monitoring SilverStripe database manipulations
     */
    public function updateProxy(ProxyGenerator &$proxy)
    {
        $proxy = $proxy->addMethod('manipulate', function ($args, $next) {
            $manipulation = $args[0];
            SearchUpdater::handle_manipulation($manipulation);
            return $next(...$args);
        });
    }
}

<?php

namespace SilverStripe\FullTextSearch\Search\Extensions;

use SilverStripe\Core\Extension;
use TractorCow\ClassProxy\Generators\ProxyGenerator;
use SilverStripe\FullTextSearch\Search\Updaters\SearchUpdater;

/**
 * This database connector proxy will allow {@link SearchUpdater::handle_manipulation} to monitor database schema
 * changes that may need to be propagated through to search indexes.
 *
 */
class ProxyDBExtension extends Extension
{
    /**
     * @param ProxyGenerator $proxy
     *
     * Ensure the search index is kept up to date by monitoring SilverStripe database manipulations
     */
    public function updateProxy(ProxyGenerator &$proxy)
    {
        $proxy = $proxy->addMethod('manipulate', function ($args, $next) {
            $manipulation = $args[0];
            SearchUpdater::handle_manipulation($manipulation);
            return $next(...$args);
        });
    }
}

Update doc blocks at class level

Update doc blocks at class level


<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace app\assets;

use yii\web\AssetBundle;

/**
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class AppAsset extends AssetBundle
{
    public $basePath = '@webroot';
    public $baseUrl = '@web';
    public $css = [
        'css/site.css',
    ];
    public $js = [
    ];
    public $depends = [
        'yii\web\YiiAsset',
        'yii\bootstrap\BootstrapAsset',
    ];
}

<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace app\assets;

use yii\web\AssetBundle;

/**
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class AppAsset extends AssetBundle
{
    public $basePath = '@webroot';
    public $baseUrl = '@web';
    public $css = [
        'css/site.css',
    ];
    public $js = [
    ];
    public $depends = [
        'yii\web\YiiAsset',
    ];
}

Remove bootstrap asset from app asset

Remove bootstrap asset from app asset


<?php

require_once 'Swat/Swat.php';
require_once 'Swat/exceptions/SwatException.php';

/**
 * The base object type
 *
 * @package   Swat
 * @copyright 2004-2005 silverorange
 * @license   http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
 */
class SwatObject
{
	public function __toString()
	{
		Swat::printObject($this);
	}
}

?>

<?php

require_once 'Swat/Swat.php';
require_once 'Swat/exceptions/SwatException.php';

/**
 * The base object type
 *
 * @package   Swat
 * @copyright 2004-2005 silverorange
 * @license   http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
 */
class SwatObject
{
	public function __toString()
	{
		ob_start();
		Swat::printObject($this);
		return ob_get_clean();
	}
}

?>

Return a string instead of printing.

Return a string instead of printing.

svn commit r2846


<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreatePrayerRequestsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('prayer_requests', function (Blueprint $table) {
            $table->increments('id');
            $table->string('text', 140);
            $table->unsignedInteger('contact_id');
            $table->boolean('approved');
            $table->timestamp('sent_at');
            $table->timestamps();

            $table->foreign('contact_id')->references('id')->on('contacts');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('prayer_requests');
    }
}

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreatePrayerRequestsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('prayer_requests', function (Blueprint $table) {
            $table->increments('id');
            $table->string('text');
            $table->unsignedInteger('contact_id');
            $table->boolean('approved');
            $table->timestamp('sent_at');
            $table->timestamps();

            $table->foreign('contact_id')->references('id')->on('contacts');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('prayer_requests');
    }
}

feat: Remove 140 hard limit from prayer request


<?php

namespace Phug\Test;

class CasesTest extends AbstractRendererTest
{
    public function caseProvider()
    {
        return array_map(function ($file) {
            $file = realpath($file);
            $pugFile = substr($file, 0, -5).'.pug';

            return [$file, $pugFile, basename($pugFile).' should render '.basename($file)];
        }, glob(__DIR__.'/../cases/*.html'));
    }

    /**
     * @dataProvider caseProvider
     */
    public function testRender($expected, $actual, $message)
    {
        self::assertSameLines(file_get_contents($expected), $this->renderer->render($actual), $message);
    }
}

<?php

namespace Phug\Test;

use DateTimeImmutable;

class CasesTest extends AbstractRendererTest
{
    public function caseProvider()
    {
        return array_map(function ($file) {
            $file = realpath($file);
            $pugFile = substr($file, 0, -5).'.pug';

            return [$file, $pugFile, basename($pugFile).' should render '.basename($file)];
        }, glob(__DIR__.'/../cases/*.html'));
    }

    /**
     * @dataProvider caseProvider
     */
    public function testRender($expected, $actual, $message)
    {
        self::assertSameLines(file_get_contents($expected), $this->renderer->render($actual), $message);
    }

    /**
     * @group update
     */
    public function testIfCasesAreUpToDate()
    {
        $context = stream_context_create([
            'http' => [
                'method' => 'GET',
                'header' => [
                    'User-Agent: PHP'
                ]
            ]
        ]);
        $json = json_decode(file_get_contents(
            'https://api.github.com/repos/pugjs/pug/commits?path=packages/pug/test/cases',
            false,
            $context
        ));
        $lastCommit = new DateTimeImmutable($json[0]->commit->author->date);
        $upToDate = new DateTimeImmutable('@'.filemtime(glob(__DIR__.'/cases/*.pug')[0]));

        self::assertTrue(
            $lastCommit <= $upToDate,
            'Cases should be updated with php tests/update.php, '.
            'then you should commit the new cases.'
        );
    }
}

Check that cases are up to date comparing to pugjs ones


<?php

require_once('tests/php/base.php');

class SyntaxTests extends UnitTestCase {
    public function testFrameworkSyntax() {
        $test_files = glob("{framework/php/cashmusic.php,framework/php/*/*.php,framework/php/classes/*/*.php}", GLOB_BRACE);
        foreach ($test_files as $file){
            system("php -l $file", $code);
            $this->assertTrue($code == 0);
        }
    }
    public function testInstallerSyntax() {
        $test_files = glob("installers/php/*.php");
        foreach ($test_files as $file){
            system("php -l $file", $code);
            $this->assertTrue($code == 0);
        }
    }
    public function testInterfaceSyntax() {
        $test_files = glob("{interfaces/php/*/*.php,interfaces/php/*/*/*.php,interfaces/php/*/*/*/*.php,interfaces/php/*/*/*/*/*.php}", GLOB_BRACE);
        foreach ($test_files as $file){
            system("php -l $file", $code);
            $this->assertTrue($code == 0);
        }
    }
}
?>

<?php

require_once('tests/php/base.php');

class SyntaxTests extends UnitTestCase {
    public function checkSyntax($file) {
        $output = exec("php -l $file", $array, $code);
        $this->assertTrue($code == 0, $output);
    }

    public function testFrameworkSyntax() {
        $test_files = glob("{framework/php/cashmusic.php,framework/php/*/*.php,framework/php/classes/*/*.php}", GLOB_BRACE);
        foreach ($test_files as $file){
            $this->checkSyntax($file);
        }
    }
    public function testInstallerSyntax() {
        $test_files = glob("installers/php/*.php");
        foreach ($test_files as $file){
            $this->checkSyntax($file);
        }
    }
    public function testInterfaceSyntax() {
        $test_files = glob("{interfaces/php/*/*.php,interfaces/php/*/*/*.php,interfaces/php/*/*/*/*.php,interfaces/php/*/*/*/*/*.php}", GLOB_BRACE);
        foreach ($test_files as $file){
            $this->checkSyntax($file);
        }
    }
}
?>

Refactor some duplicate code into a checkSyntax function which isn't as noisy


<?php

namespace JasonLewis\ResourceWatcher\Integration;

use Illuminate\Support\ServiceProvider;
use JasonLewis\ResourceWatcher\Tracker;
use JasonLewis\ResourceWatcher\Watcher;

class LaravelServiceProvider extends ServiceProvider
{
    /**
     * Indicates if loading of the provider is deferred.
     *
     * @var bool
     */
    protected $defer = true;

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
    	$this->app->singleton('watcher', function ($app) {
            return new Watcher(new Tracker, $app['files']);
        });
    }

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

<?php

namespace JasonLewis\ResourceWatcher\Integration;

use Illuminate\Support\ServiceProvider;
use JasonLewis\ResourceWatcher\Tracker;
use JasonLewis\ResourceWatcher\Watcher;

class LaravelServiceProvider extends ServiceProvider
{
    /**
     * Indicates if loading of the provider is deferred.
     *
     * @var bool
     */
    protected $defer = true;

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
    	$this->app->singleton('watcher', function ($app) {
            return new Watcher(new Tracker, $app['files']);
        });

        $this->app->alias('watcher', 'JasonLewis\ResourceWatcher\Watcher');
    }

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

Add an alias for the bound watcher instance.

Signed-off-by: Jason Lewis <b136be6b8ecc2c62ceb9857ec62bf85489a45e0c@gmail.com>


<?php namespace net\xp_framework\unittest\core\generics;

use util\Objects;

/**
 * Lookup map
 */
#[@generic(self= 'K, V', parent= 'K, V')]
class Lookup extends AbstractDictionary {

  #[@generic(var= '[:V]')]
  protected $elements= [];

  /**
   * Put a key/value pairt
   *
   * @param   K key
   * @param   V value
   */
  #[@generic(params= 'K, V')]
  public function put($key, $value) {
    $this->elements[Objects::hashOf($key)]= $value;
  }

  /**
   * Returns a value associated with a given key
   *
   * @param   K key
   * @return  V value
   * @throws  util.NoSuchElementException
   */
  #[@generic(params= 'K', return= 'V')]
  public function get($key) {
    $offset= Objects::hashOf($key);
    if (!isset($this->elements[$offset])) {
      throw new \util\NoSuchElementException('No such key '.\xp::stringOf($key));
    }
    return $this->elements[$offset];
  }

  /**
   * Returns all values
   *
   * @return  V[] values
   */
  #[@generic(return= 'V[]')]
  public function values() {
    return array_values($this->elements);
  }
}

<?php namespace net\xp_framework\unittest\core\generics;

use util\Objects;

/**
 * Lookup map
 */
#[@generic(self= 'K, V', parent= 'K, V')]
class Lookup extends AbstractDictionary {
  protected $size;

  #[@generic(var= '[:V]')]
  protected $elements= [];

  /**
   * Put a key/value pairt
   *
   * @param   K key
   * @param   V value
   */
  #[@generic(params= 'K, V')]
  public function put($key, $value) {
    $this->elements[Objects::hashOf($key)]= $value;
    $this->size= sizeof($this->elements);
  }

  /**
   * Returns a value associated with a given key
   *
   * @param   K key
   * @return  V value
   * @throws  util.NoSuchElementException
   */
  #[@generic(params= 'K', return= 'V')]
  public function get($key) {
    $offset= Objects::hashOf($key);
    if (!isset($this->elements[$offset])) {
      throw new \util\NoSuchElementException('No such key '.\xp::stringOf($key));
    }
    return $this->elements[$offset];
  }

  /**
   * Returns all values
   *
   * @return  V[] values
   */
  #[@generic(return= 'V[]')]
  public function values() {
    return array_values($this->elements);
  }

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

Verify non-generic members also work just fine


<?php

namespace Flagbit\Bundle\CurrencyBundle\Tests;

use Flagbit\Bundle\CurrencyBundle\DependencyInjection\Configuration;
use Symfony\Component\Config\Definition\Processor;

class ConfigurationTest extends \PHPUnit_Framework_TestCase
{
    protected function process($config)
    {
        $processor = new Processor();

        return $processor->processConfiguration(new Configuration(), $config);
    }

    public function provideValidCurrency()
    {
        return array(
            array('EUR'),
            array('USD'),
            array('CHF'),
        );
    }

    /**
     * @dataProvider provideValidCurrency
     */
    public function testValidDefaultCurrency($currency)
    {
        $config = array(
            array(
                'default_currency' => $currency,
            )
        );

        $config = $this->process($config);

        $this->assertEquals($currency, $config['default_currency']);
    }

    public function provideInvalidCurrency()
    {
        return array(
            array('foobar'),
            array('eur'),
        );
    }

    /**
     * @dataProvider provideInvalidCurrency
     * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException
     */
    public function testInvalidDefaultCurrency($currency)
    {
        $config = array(
            array(
                'default_currency' => $currency,
            )
        );

        $this->process($config);
    }
}

<?php

namespace Flagbit\Bundle\CurrencyBundle\Tests;

use Flagbit\Bundle\CurrencyBundle\DependencyInjection\Configuration;
use Symfony\Component\Config\Definition\Processor;

class ConfigurationTest extends \PHPUnit_Framework_TestCase
{
    protected function process($config)
    {
        $processor = new Processor();

        return $processor->processConfiguration(new Configuration(), $config);
    }

    public function provideValidCurrency()
    {
        return array(
            array('EUR'),
            array('USD'),
            array('CHF'),
        );
    }

    /**
     * Test Default Currency to prevent BC breaks
     */
    public function testProcessedDefaultCurrency()
    {
        $config = array(array());

        $config = $this->process($config);

        $this->assertEquals('EUR', $config['default_currency']);
    }

    /**
     * @dataProvider provideValidCurrency
     */
    public function testValidDefaultCurrency($currency)
    {
        $config = array(
            array(
                'default_currency' => $currency,
            )
        );

        $config = $this->process($config);

        $this->assertEquals($currency, $config['default_currency']);
    }

    public function provideInvalidCurrency()
    {
        return array(
            array('foobar'),
            array('eur'),
        );
    }

    /**
     * @dataProvider provideInvalidCurrency
     * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException
     */
    public function testInvalidDefaultCurrency($currency)
    {
        $config = array(
            array(
                'default_currency' => $currency,
            )
        );

        $this->process($config);
    }
}

Create test case for default currency

Create test case for default currency


<?php
use Pux\Dispatcher\APCDispatcher;
use Pux\Mux;

class APCDispatcherTest extends PHPUnit_Framework_TestCase
{
    public function test()
    {
        if ( ! extension_loaded('apc') || ! extension_loaded('apcu') ) {
            skip('APC or APCu extension is required.');
        }

        $mux = new Mux;
        $mux->add('/product/add', ['ProductController', 'addAction']);
        $dispatcher = new APCDispatcher($mux, array(
            'namespace' => 'tests',
            'expiry' => 10,
        ));
        ok($dispatcher);
        $route = $dispatcher->dispatch('/product/add');
        ok($route);
        $route = $dispatcher->dispatch('/product/add');
        ok($route);

        $route = $dispatcher->dispatch('/product/del');
        ok($route == false);
    }
}

<?php
use Pux\Dispatcher\APCDispatcher;
use Pux\Mux;

class APCDispatcherTest extends PHPUnit_Framework_TestCase
{
    public function test()
    {
        if ( ! extension_loaded('apc') && ! extension_loaded('apcu') ) {
            skip('APC or APCu extension is required.');
        }

        $mux = new Mux;
        $mux->add('/product/add', ['ProductController', 'addAction']);
        $dispatcher = new APCDispatcher($mux, array(
            'namespace' => 'tests',
            'expiry' => 10,
        ));
        ok($dispatcher);
        $route = $dispatcher->dispatch('/product/add');
        ok($route);
        $route = $dispatcher->dispatch('/product/add');
        ok($route);

        $route = $dispatcher->dispatch('/product/del');
        ok($route == false);
    }
}

Fix apc extension checking condition

Fix apc extension checking condition


<?php
include_once '../src/round_robin.php';

$teams = ['The 1st', '2 Good', 'We 3', '4ward'];

$schedule = schedule($teams, (($temp = count($teams)) % 2 === 0 ? $temp - 1 : $temp) * 2);

?>
<!DOCTYPE html>

        <title>Schedule Example</title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

Example

            This example generates a schedule where each contestant meets each
            other twice, once home and once away.

Sample Schedule

        <?php foreach($schedule as $round=>$matchups){ ?>

Round <?=$round?>

        <?php foreach($matchups as $matchup) { ?>

<?=$matchup[0] ?? '*BYE*'?> vs. <?=$matchup[1] ?? '*BYE*'?>

        <?php } ?>

        <?php } ?>

<?php
include_once '../src/round_robin.php';

$teams = ['The 1st', '2 Good', 'We 3', '4ward'];

$schedule = schedule($teams, (($count = count($teams)) % 2 === 0 ? $count - 1 : $count) * 2);

?>
<!DOCTYPE html>

        <title>Schedule Example</title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

Example

            This example generates a schedule where each contestant meets each
            other twice, once home and once away.

Sample Schedule

        <?php foreach($schedule as $round=>$matchups){ ?>

Round <?=$round?>

        <?php foreach($matchups as $matchup) { ?>

<?=$matchup[0] ?? '*BYE*'?> vs. <?=$matchup[1] ?? '*BYE*'?>

        <?php } ?>

        <?php } ?>

Change temp variable to something more descriptive


<?php

namespace BisonLab\SakonninBundle\Menu;

use Knp\Menu\FactoryInterface;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerAwareTrait;

/*
 * Hopefully not required.
 * (A script in scripts.html.twig does check for unread and sets the color
 * of "Messages" here to red.)
 */

class Builder implements ContainerAwareInterface
{
    use ContainerAwareTrait;

    public function messageMenu(FactoryInterface $factory, array $options, $menu = null)
    {
        $menu->addChild('Messages');
        $menu['Messages']->setAttribute('id', 'message_menu');
        $menu['Messages']->addChild('Read new messages',
                array('route' => 'message_unread'));
        $menu['Messages']['Read new messages']->setAttribute('id', 'menu_unread');
        $menu['Messages']->addChild('My message log', array( 'route' => 'message'));
        $menu['Messages']->addChild('Write PM', array('uri' => '#'));
        $menu['Messages']['Write PM']->setLinkAttribute('onclick', 'createPmMessage()');
        return $menu;
    }
}

<?php

namespace BisonLab\SakonninBundle\Menu;

use Knp\Menu\FactoryInterface;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerAwareTrait;

class Builder implements ContainerAwareInterface
{
    use ContainerAwareTrait;

    public function messageMenu(FactoryInterface $factory, array $options)
    {
        $menu = $container = null;
        if (isset($options['menu'])) {
            $menu = $options['menu'];
        } else {
            $menu = $factory->createItem('root');
        }
        if (isset($options['container'])) {
            $container = $options['container'];
        } else {
            $container = $this->container;
        }

        $menu->addChild('Messages');
        $menu['Messages']->setAttribute('id', 'message_menu');
        $menu['Messages']->addChild('Read new messages',
                array('route' => 'message_unread'));
        $menu['Messages']['Read new messages']->setAttribute('id', 'menu_unread');
        $menu['Messages']->addChild('My message log', array( 'route' => 'message'));
        $menu['Messages']->addChild('Write PM', array('uri' => '#'));
        $menu['Messages']['Write PM']->setLinkAttribute('onclick', 'createPmMessage()');
        return $menu;
    }
}

Make the message menu callable from other menu builders or be autonomous.


<?php namespace App\Exceptions;

use Exception, Redirect;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;

class Handler extends ExceptionHandler {

	/**
	 * A list of the exception types that should not be reported.
	 *
	 * @var array
	 */
	protected $dontReport = [
		'Symfony\Component\HttpKernel\Exception\HttpException'
	];

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

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

}

<?php namespace App\Exceptions;

use Exception, Redirect;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;

class Handler extends ExceptionHandler {

	/**
	 * A list of the exception types that should not be reported.
	 *
	 * @var array
	 */
	protected $dontReport = [
		'Symfony\Component\HttpKernel\Exception\HttpException'
	];

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

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

		if ($exceptionClass === "Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException")
			return Redirect::back();
		elseif ($exceptionClass === "Illuminate\Session\TokenMismatchException")
			return Redirect::to('/')->with('error', "Uw sessie is verlopen, log opnieuw in en probeer het opnieuw");

		if ($this->isHttpException($e))
		{
			return $this->renderHttpException($e);
		} else
		{
			return parent::render($request, $e);
		}
	}

}

Handle the error for CSRF and MethodNotAllowed differently


<?php

namespace TheCrypticAce\Lazy\Concerns;

use Illuminate\Contracts\Support\Jsonable;
use Illuminate\Contracts\Support\Arrayable;

trait Arrays
{
    public function toArray()
    {
        $items = $this->map(function ($value) {
            return $value instanceof Arrayable ? $value->toArray() : $value;
        });

        return $items->all();
    }

    public function all()
    {
        return iterator_to_array($this->items, true);
    }

    public function eager()
    {
        return new static($this->all());
    }
}

<?php

namespace TheCrypticAce\Lazy\Concerns;

use Illuminate\Contracts\Support\Jsonable;
use Illuminate\Contracts\Support\Arrayable;

trait Arrays
{
    public function toArray()
    {
        $items = $this->map(function ($value) {
            return $value instanceof Arrayable ? $value->toArray() : $value;
        });

        return $items->all();
    }

    public function all()
    {
        return iterator_to_array($this->items, true);
    }

    public function eager()
    {
        return new static($this->all());
    }

    public function collect()
    {
        return collect($this->all());
    }
}

Add convenience method to convert to an Illuminate collection


<?php
/**
 * This file is part of PMG\Queue
 *
 * Copyright (c) PMG <https://www.pmg.com>
 *
 * For full copyright information see the LICENSE file distributed
 * with this source code.
 *
 * @license     http://opensource.org/licenses/MIT MIT
 */

namespace PMG\Queue;

/**
 * Default implementation of the `Envelop` with no extras.
 *
 * @since   2.0
 */
class DefaultEnvelope implements Envelope
{
    protected $message;
    protected $attemps;

    public function __construct(Message $message, $attempts=0)
    {
        $this->message = $message;
        $this->attempts = $attempts;
    }

    /**
     * {@inheritdoc}
     */
    public function attempts()
    {
        return $this->attempts;
    }

    /**
     * {@inheritdoc}
     */
    public function unwrap()
    {
        return $this->message;
    }

    /**
     * {@inheritdoc}
     */
    public function retry()
    {
        $new = clone $this;
        $new->attempts++;

        return $new;
    }
}

<?php
/**
 * This file is part of PMG\Queue
 *
 * Copyright (c) PMG <https://www.pmg.com>
 *
 * For full copyright information see the LICENSE file distributed
 * with this source code.
 *
 * @license     http://opensource.org/licenses/MIT MIT
 */

namespace PMG\Queue;

/**
 * Default implementation of the `Envelop` with no extras.
 *
 * @since   2.0
 */
class DefaultEnvelope implements Envelope
{
    protected $message;
    protected $attempts;

    public function __construct(Message $message, $attempts=0)
    {
        $this->message = $message;
        $this->attempts = $attempts;
    }

    /**
     * {@inheritdoc}
     */
    public function attempts()
    {
        return $this->attempts;
    }

    /**
     * {@inheritdoc}
     */
    public function unwrap()
    {
        return $this->message;
    }

    /**
     * {@inheritdoc}
     */
    public function retry()
    {
        $new = clone $this;
        $new->attempts++;

        return $new;
    }
}

Correct a Property Name Typo

Correct a Property Name Typo


<?php

namespace Bernard\Event;

use Bernard\Envelope;
use Bernard\Queue;
use Symfony\Component\EventDispatcher;

/**
 * @package Bernard
 */
class PingEvent extends EventDispatcher\Event
{
    protected $queue;

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

    /**
     * @return Queue
     */
    public function getQueue()
    {
        return $this->queue;
    }
}

<?php

namespace Bernard\Event;

use Bernard\Envelope;
use Bernard\Queue;
use Symfony\Component\EventDispatcher\Event;

/**
 * @package Bernard
 */
class PingEvent extends Event
{
    protected $queue;

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

    /**
     * @return Queue
     */
    public function getQueue()
    {
        return $this->queue;
    }
}

Use fully qualified name space

Use fully qualified name space


<?php
/**
 * @license MIT
 * @author Igor Sorokin <dspbee@pivasic.com>
 */
namespace Dspbee\Bundle\Data;

/**
 * Initialize class properties from array.
 *
 * Class TDataFilter
 * @package Dspbee\Core
 */
trait TDataInit
{
    /**
     * Init class members.
     *
     * @param array $data
     */
    public function initFromArray(array $data)
    {
        foreach ($data as $name => $value) {
            $method = 'set' . ucfirst($name);
            if (method_exists($this, $method)) {
                call_user_func_array([$this, $method], [$value]);
            } else {
                if (property_exists(get_called_class(), $name)) {
                    $this->$name = $value;
                }
            }
        }
    }
}

<?php
/**
 * @license MIT
 * @author Igor Sorokin <dspbee@pivasic.com>
 */
namespace Dspbee\Bundle\Data;

/**
 * Initialize class properties from array.
 *
 * Class TDataFilter
 * @package Dspbee\Core
 */
trait TDataInit
{
    /**
     * Init class members.
     *
     * @param array $data
     */
    public function initFromArray(array $data)
    {
        foreach ($data as $name => $value) {
            $method = 'set' . ucfirst($name);
            if (method_exists($this, $method)) {
                call_user_func_array([$this, $method], [$value]);
            } else {
                if (property_exists(get_called_class(), $name)) {
                    $this->$name = $value;
                }
            }
        }
    }

    /**
     * Init class members from $_POST array.
     *
     * @param null $callback
     */
    public function initFromPost($callback = null)
    {
        $input = $_POST;
        if (null !== $callback) {
            $input = array_map($callback, $input);
        }
        $this->initFromArray($input);
    }
}

Add init from POST array

Add init from POST array


<?php

namespace Docker\Tests;

use Docker\Docker;
use Docker\Http\DockerClient as Client;
use PHPUnit_Framework_TestCase;

class TestCase extends PHPUnit_Framework_TestCase
{
    private $docker;

    public function getDocker()
    {
        $client = new Client(array(), 'tcp://127.0.0.1:4243');

        if (null === $this->docker) {
            $this->docker = new Docker($client);
        }

        return $this->docker;
    }
}

<?php

namespace Docker\Tests;

use Docker\Docker;
use Docker\Http\DockerClient as Client;
use PHPUnit_Framework_TestCase;

class TestCase extends PHPUnit_Framework_TestCase
{
    private $docker;

    public function getDocker()
    {
        $client = new Client();

        if (null === $this->docker) {
            $this->docker = new Docker($client);
        }

        return $this->docker;
    }
}

Use default behavior to get docker host in tests, DOCKER_HOST env variable or unix:///var/run/docker.sock by default


<?php
namespace Rocketeer\Plugins\Laravel;

use Illuminate\Container\Container;
use Rocketeer\Abstracts\AbstractPlugin;

class LaravelPlugin extends AbstractPlugin
{
    /**
     * Additional lookups to
     * add to Rocketeer
     *
     * @type array
     */
    protected $lookups = array(
        'binaries'   => array(
            'Rocketeer\Plugins\Laravel\Binaries\%s',
        ),
        'strategies' => array(
            'Rocketeer\Plugins\Laravel\Strategies\%sStrategy',
        ),
    );

    /**
     * @param Container $app
     *
     * @return Container
     */
    public function register(Container $app)
    {
        $app->singleton('rocketeer.strategies.framework', 'Rocketeer\Plugins\Laravel\Strategies\Framework\LaravelStrategy');

        return $app;
    }
}

<?php
namespace Rocketeer\Plugins\Laravel;

use Illuminate\Contracts\Container\Container;
use Rocketeer\Abstracts\AbstractPlugin;

class LaravelPlugin extends AbstractPlugin
{
    /**
     * Additional lookups to
     * add to Rocketeer
     *
     * @type array
     */
    protected $lookups = array(
        'binaries'   => array(
            'Rocketeer\Plugins\Laravel\Binaries\%s',
        ),
        'strategies' => array(
            'Rocketeer\Plugins\Laravel\Strategies\%sStrategy',
        ),
    );

    /**
     * @param Container $app
     *
     * @return Container
     */
    public function register(Container $app)
    {
        $app->singleton('rocketeer.strategies.framework', 'Rocketeer\Plugins\Laravel\Strategies\Framework\LaravelStrategy');

        return $app;
    }
}

Update plugin to use new interface

Update plugin to use new interface


<?php namespace Philipbrown\Math;

class Math {

  /**
   * @var integer
   */
  protected $scale = 0;

  /**
   * Create
   *
   * @param $value string
   * @return Math\Number
   */
  public function create($value)
  {
    return new Number($value);
  }

  /**
   * Set Scale
   *
   * @param $scale integer
   */
  public function setScale($scale)
  {
    $scale = new PositiveNumber($scale);

    return $this->scale = $scale;
  }

  public function add($left, $right)
  {

  }

}

<?php namespace Philipbrown\Math;

class Math {

  /**
   * @var integer
   */
  protected $scale = 0;

  /**
   * Create
   *
   * @param $value string
   * @return Math\Number
   */
  public function create($value)
  {
    return new Number($value);
  }

  /**
   * Set Scale
   *
   * @param $scale integer
   */
  public function setScale($scale)
  {
    if(! $scale instanceof PositiveNumber)
    $scale = new PositiveNumber($scale);

    return $this->scale = $scale;
  }

  public function add($left, $right)
  {

  }

}

Add instanceof check to setScale method

Add instanceof check to setScale method


<?php

namespace Mulgrew\Model;

use DateTime;

class Revision
{
    /**
     * Revision Identifier
     * @column(type="string", length="40", )
     * @var integer
     */
    protected $id;

    /**
     * The page
     * @var Mulgrew\Model\Page
     * @ManyToOne(targetEntity="Mulgrew\Model\Page", inversedBy="revisions")
     */
    protected $page;

    /**
     * The user who created the revision
     * @var Mulgrew\Model\User
     */
    protected $user;

    /**
     * Opcodes to get to the previous revision
     * @var string|null
     */
    protected $opcodes;

    /**
     * Optional comment for this revision
     * @var string
     */
    protected $comment;

    /**
     * The date and time the revision was created.
     * @var DateTime
     */
    protected $datetime;
}

<?php

namespace Mulgrew\Model;

use DateTimeInterface;

class Revision
{
    /**
     * Revision Identifier
     * @column(type="string", length="40", )
     * @var integer
     */
    protected $id;

    /**
     * The page
     * @var Mulgrew\Model\Page
     * @ManyToOne(targetEntity="Mulgrew\Model\Page", inversedBy="revisions")
     */
    protected $page;

    /**
     * The user who created the revision
     * @var Mulgrew\Model\User
     */
    protected $user;

    /**
     * Opcodes to get to the previous revision
     * @var string|null
     */
    protected $opcodes;

    /**
     * Optional comment for this revision
     * @var string
     */
    protected $comment;

    /**
     * The date and time the revision was created.
     * @var DateTimeInterface
     */
    protected $datetime;
}

Use interface rather than a class.

Use interface rather than a class.


<?php
declare(strict_types=1);

require_once __DIR__.'/../__CondorcetAutoload.php';

///
    $number_of_votes = 100_000_000;
    $number_of_candidates = 8;
///

$candidateName = 'A';

$candidates = [];

for ($i=0; $i < $number_of_candidates ; $i++) :
    $candidates[] = $candidateName++;
endfor;

$file = fopen(__DIR__.'/large.votes','w+');
$cache = '';

for ($i=0; $i < $number_of_votes; $i++) :

    shuffle($candidates);

    $cache .= implode('>',$candidates)."\n";

    if (strlen($cache) > 5_000_000) :
        fwrite($file,$cache);
        $cache = '';
    endif;

endfor;

fclose($file);

<?php
declare(strict_types=1);

require_once __DIR__.'/../__CondorcetAutoload.php';

///
    $number_of_votes = 100_000_000;
    $number_of_candidates = 8;
///

$candidateName = 'A';

$candidates = [];

for ($i=0; $i < $number_of_candidates ; $i++) :
    $candidates[] = $candidateName++;
endfor;

$file = fopen(__DIR__.'/large.votes','w+');
$cache = '';

for ($i=0; $i < $number_of_votes; $i++) :

    shuffle($candidates);

    $cache .= implode('>',$candidates)."\n";

    if (strlen($cache) > 5_000_000) :
        fwrite($file,$cache);
        $cache = '';
    endif;

endfor;

fwrite($file,$cache);

fclose($file);

Fix large Input file generator

Fix large Input file generator


<?php
/**
*
*/
class Log extends CI_Model
{
	public function auth($acount, $dbs){
		$db = $this->load->database($dbs, true);
		$data = $this->db->query("select rtrim(ltrim(clave)) as pass from secr where rtrim(ltrim(upper(usuario)))='" . $acount . "'");

		if ($data->num_rows() > 0) {
			return $data->row();
		}
	}
}
?>

<?php
/**
*
*/
class Log extends CI_Model
{
	public function auth($acount, $dbs){
		$db = $this->load->database($dbs, true);
		$data = $this->db->query("select rtrim(ltrim(clave)) as pass from secr where rtrim(ltrim(upper(usuario)))='" . $acount . "'");

		if ($data->num_rows() > 0) {
			return $data->row();
		}else{
			return false;
		}
	}
}
?>

Add false return for no results

Add false return for no results


<?php

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

namespace Surfnet\StepupMiddleware\MiddlewareBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Processor;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;

class SurfnetStepupMiddlewareMiddlewareExtension extends Extension
{
    public function load(array $config, ContainerBuilder $container)
    {
        $processor = new Processor();
        $config = $processor->processConfiguration(new Configuration(), $config);

        $container->setParameter('middleware.config.email_validation_window', $config['email_verification_window']);
    }
}

<?php

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

namespace Surfnet\StepupMiddleware\MiddlewareBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Processor;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;

class SurfnetStepupMiddlewareMiddlewareExtension extends Extension
{
    public function load(array $config, ContainerBuilder $container)
    {
        $processor = new Processor();
        $config = $processor->processConfiguration(new Configuration(), $config);

        $definition = (new Definition())
            ->setClass('Surfnet\Stepup\Identity\Value\EmailVerificationWindow')
            ->setFactory('Surfnet\Stepup\Identity\Value\EmailVerificationWindow::fromSeconds')
            ->setArguments([$config['email_verification_window']]);

        $container->setDefinition('identity.config.email_validation_window', $definition);
    }
}

Make configured email verification window available as service


<?php

namespace app\modules\rest\versions\v1\controllers;

use Yii;
use app\models\Poll;
use app\models\Code;
use app\modules\rest\controllers\VotingRestController;
use yii\helpers\ArrayHelper;
use app\components\filters\TokenFilter;
use yii\base\UserException;

class PollController extends VotingRestController
{
    public $modelClass = 'app\models\Poll';

    public function actionGet()
    {
        $token = Yii::$app->request->get('token'); // Better way to get this?

        $code = Code::findCodeByToken($token);
        if (!$code || !$code->isValid()) {
            throw new UserException(Yii::t('app', 'Invalid voting code'));
        } elseif ($code->isUsed()) {
            throw new UserException(Yii::t('app', 'This voting code has already been used'));
        }

        $poll = $code->getPoll()->with(['options', 'organizer'])->one();
        $options = $poll->getOptions()->all();
        $organizer = $poll->getOrganizer()->one();
        $pollFields = ['title', 'question', 'select_min', 'select_max', 'start_time', 'end_time'];

        $data = ArrayHelper::merge($poll->toArray($pollFields), ['options' => ArrayHelper::getColumn($options, function($option) {
            $optionFields = ['id', 'text'];
            return $option->toArray($optionFields);
        }), 'organizer' => $organizer->toArray(['name', 'email'])]);
        return $data;
    }
}

<?php

namespace app\modules\rest\versions\v1\controllers;

use Yii;
use app\models\Poll;
use app\models\Code;
use app\modules\rest\controllers\VotingRestController;
use yii\helpers\ArrayHelper;
use app\components\filters\TokenFilter;
use yii\base\UserException;

class PollController extends VotingRestController
{
    public $modelClass = 'app\models\Poll';

    public function actionGet()
    {
        $token = Yii::$app->request->get('token'); // Better way to get this?

        $code = Code::findCodeByToken($token);
        if (!$code || !$code->isValid()) {
            throw new UserException(Yii::t('app', 'Invalid voting code'));
        } elseif ($code->isUsed()) {
            throw new UserException(Yii::t('app', 'This voting code has already been used'));
        }

        $poll = $code->getPoll()->with(['options', 'organizer'])->one();
        $options = $poll->getOptions()->all();
        $organizer = $poll->getOrganizer()->one();
        $pollFields = ['title', 'question', 'info', 'select_min', 'select_max', 'start_time', 'end_time'];

        $data = ArrayHelper::merge($poll->toArray($pollFields), ['options' => ArrayHelper::getColumn($options, function($option) {
            $optionFields = ['id', 'text'];
            return $option->toArray($optionFields);
        }), 'organizer' => $organizer->toArray(['name', 'email'])]);
        return $data;
    }
}

Include poll info field in JSON response


<?php
namespace Air\BookishBundle\Lib;

class NytApiHandler
{
    private $nytApiKey;
    private $guzzleClient;

    public function __construct($nytApiKey, $guzzleClient)
    {
        $this->nytApiKey = $nytApiKey;
        $this->guzzleClient = $guzzleClient;
    }

    public function getNytApiKey()
    {
        return $this->nytApiKey;
    }

    public function getBestSellersOverview($date = '2014-01-01')
    {
        $request = $this->guzzleClient->get('/svc/books/v2/lists/overview.json?published_date=' . $date . '&api-key=' . $this->getNytApiKey());
        $response = $request->send();
        $responseArray  = $response->json();
        $responseArray  = $this->convertKeysToCamelCase($responseArray);
        var_dump($responseArray);
        return $responseArray;
    }

    private function convertKeysToCamelCase($apiResponseArray)
    {
        array_walk_recursive($apiResponseArray, 'self::convertKeys');
    }

    private static function convertKeys(&$item, &$key)
    {
        if (preg_match('/_/', $key)) {
            echo $key;
            $key = str_replace('_', '',  $key);
            $key = lcfirst($key);
        }
    }

}

<?php
namespace Air\BookishBundle\Lib;

class NytApiHandler
{
    private $nytApiKey;
    private $guzzleClient;

    public function __construct($nytApiKey, $guzzleClient)
    {
        $this->nytApiKey = $nytApiKey;
        $this->guzzleClient = $guzzleClient;
    }

    public function getNytApiKey()
    {
        return $this->nytApiKey;
    }

    public function getBestSellersOverview($date = '2014-01-01')
    {
        $request = $this->guzzleClient->get('/svc/books/v2/lists/overview.json?published_date=' . $date . '&api-key=' . $this->getNytApiKey());
        $response = $request->send();
        $responseArray  = $response->json();
        return $this->convertKeysToCamelCase($responseArray);

    }

    private function convertKeysToCamelCase($apiResponseArray)
    {
        $arr = [];
        foreach ($apiResponseArray as $key => $value) {
            if (preg_match('/_/', $key)) {
                $key = preg_replace_callback('/_([^_]*)/', function($matches) {
                    return ucfirst($matches[1]);
                }, $key);
            }

            if (is_array($value))
                $value = $this->convertKeysToCamelCase($value);

            $arr[$key] = $value;
        }
        return $arr;
    }

}

Implement a method to convert udesrscore case to camelCase


<?php
/**
 * the home page
 *
 * @package WordPress
 * @subpackage Twenty_Eleven
 */

get_header(); ?>

Anonymous friends
trusted face-to-face.

Create secure social networks using shared QR codes. Share them with whomever you trust, face-to-face.

				Download App

<?php get_sidebar(); ?>
<?php get_footer(); ?>

Update release link on public site.

Update release link on public site.


<?php
class Wub_Success
{
    public $message = "There was a success for something.... idk what.";

    public $continueURL = NULL;

    public $saveType = NULL;

    public $ajaxRedirect = NULL;

    function __construct($options = array())
    {
        if (isset($_GET['for'])) {
            switch ($_GET['for']) {
                case "login":
                    $this->message = "You have been logged in!  Please click continue if you are not redirected.";
                    $options['continueURL'] = Wub_Controller::$url . "home";
                    break;
                case "accounts":
                    if ($this->saveType == 'create') {
                        $this->message = "Thank you for registering.  You will now need to log in.";
                        $this->continueURL = Wub_Controller::$url . "login";
                    } else {
                        $this->message = "You account has been saved!";
                    }
                    break;
                default:
                    break;
            }
        }

        if (isset($_GET['message'])) {
            $this->message = $_GET['message'];
        }

        if (isset($options['continueURL'])) {
            $this->continueURL = $options['continueURL'];
        }

        if (isset($options['saveType'])) {
            $this->saveType = $options['saveType'];
        }

        if (isset($options['ajaxredirect'])) {
            $this->ajaxRedirect = $options['ajaxredirect'];
        }
    }
}

<?php
class Wub_Success
{
    public $message = "There was a success for something.... idk what.";

    public $continueURL = NULL;

    public $saveType = NULL;

    public $ajaxRedirect = NULL;

    function __construct($options = array())
    {
        if (isset($_GET['message'])) {
            $this->message = $_GET['message'];
        }

        if (isset($options['continueURL'])) {
            $this->continueURL = $options['continueURL'];
        }

        if (isset($options['saveType'])) {
            $this->saveType = $options['saveType'];
        }

        if (isset($options['ajaxredirect'])) {
            $this->ajaxRedirect = $options['ajaxredirect'];
        }

        if (isset($_GET['for'])) {
            switch ($_GET['for']) {
                case "login":
                    $this->message = "You have been logged in!  Please click continue if you are not redirected.";
                    $options['continueURL'] = Wub_Controller::$url . "home";
                    break;
                case "accounts":
                    if ($this->saveType == 'create') {
                        $this->message = "Thank you for registering.  You will now need to log in.";
                        $this->continueURL = Wub_Controller::$url . "login";
                    } else {
                        $this->message = "You account has been saved!";
                    }
                    break;
                default:
                    break;
            }
        }
    }
}

Move the logic for "for" to the end of the constructor so that everything else is set first.


<?
include '../scat.php';

$criteria= array();

$term= $_REQUEST['term'];
$terms= preg_split('/\s+/', $term);

foreach ($terms as $term) {
  $term= $db->real_escape_string($term);
  $criteria[]= "(person.name LIKE '%$term%'
             OR person.company LIKE '%$term%'
             OR person.email LIKE '%$term%'
             OR person.loyalty_number LIKE '%$term%'
             OR person.phone LIKE '%$term%')";
}

if (!$_REQUEST['all'])
  $criteria[]= 'active';

if (($type= $_REQUEST['role'])) {
  $criteria[]= "person.role = '" . $db->escape($type) . "'";
}

if (empty($criteria)) {
  $criteria= '1=1';
} else {
  $criteria= join(' AND ', $criteria);
}

$q= "SELECT id,
            CONCAT(IFNULL(name, ''),
                   IF(name != '' AND company != '', ' / ', ''),
                   IFNULL(company, ''))
                AS value,
            loyalty_number
       FROM person
      WHERE $criteria
      ORDER BY value";

$r= $db->query($q)
  or die_query($db, $q);

$list= array();
while ($row= $r->fetch_assoc()) {
  if (!$row['value']) $row['value']= $row['loyalty_number'];
  $list[]= $row;
}

echo jsonp($list);

<?
include '../scat.php';
include '../lib/person.php';

$criteria= array();

$term= $_REQUEST['term'];
$terms= preg_split('/\s+/', $term);

foreach ($terms as $term) {
  $term= $db->real_escape_string($term);
  $criteria[]= "(person.name LIKE '%$term%'
             OR person.company LIKE '%$term%'
             OR person.email LIKE '%$term%'
             OR person.loyalty_number LIKE '%$term%'
             OR person.phone LIKE '%$term%')";
}

if (!$_REQUEST['all'])
  $criteria[]= 'active';

if (($type= $_REQUEST['role'])) {
  $criteria[]= "person.role = '" . $db->escape($type) . "'";
}

if (empty($criteria)) {
  $criteria= '1=1';
} else {
  $criteria= join(' AND ', $criteria);
}

$q= "SELECT id,
            CONCAT(IFNULL(name, ''),
                   IF(name != '' AND company != '', ' / ', ''),
                   IFNULL(company, ''))
                AS value,
            loyalty_number
       FROM person
      WHERE $criteria
      ORDER BY value";

$r= $db->query($q)
  or die_query($db, $q);

$list= array();
while ($row= $r->fetch_assoc()) {
  if (!$row['value']) $row['value']= format_phone($row['loyalty_number']);
  $list[]= $row;
}

echo jsonp($list);

Format loyalty number when shown as name in search


<?php

namespace VladimirYuldashev\LaravelQueueRabbitMQ\Console;

use Exception;
use Illuminate\Console\Command;
use VladimirYuldashev\LaravelQueueRabbitMQ\Queue\Connectors\RabbitMQConnector;

class QueueDeclareCommand extends Command
{
    protected $signature = 'rabbitmq:queue-declare
                           {name : The name of the queue to declare}
                           {connection=rabbitmq : The name of the queue connection to use}
                           {--durable=1}
                           {--auto-delete=0}';

    protected $description = 'Declare queue';

    /**
     * @param RabbitMQConnector $connector
     * @throws Exception
     */
    public function handle(RabbitMQConnector $connector): void
    {
        $config = $this->laravel['config']->get('queue.connections.'.$this->argument('connection'));

        $queue = $connector->connect($config);

        if ($queue->isQueueExists($this->argument('name'))) {
            $this->warn('Queue already exists.');

            return;
        }

        $queue->declareQueue(
            $this->argument('name'),
            (bool) $this->option('durable'),
            (bool) $this->option('auto-delete')
        );

        $this->info('Queue declared successfully.');
    }
}

<?php

namespace VladimirYuldashev\LaravelQueueRabbitMQ\Console;

use Exception;
use Illuminate\Console\Command;
use VladimirYuldashev\LaravelQueueRabbitMQ\Queue\Connectors\RabbitMQConnector;

class QueueDeclareCommand extends Command
{
    protected $signature = 'rabbitmq:queue-declare
                           {name : The name of the queue to declare}
                           {connection=rabbitmq : The name of the queue connection to use}
                           {--durable=1}
                           {--max-priority=4}
                           {--auto-delete=0}';

    protected $description = 'Declare queue';

    /**
     * @param RabbitMQConnector $connector
     * @throws Exception
     */
    public function handle(RabbitMQConnector $connector): void
    {
        $config = $this->laravel['config']->get('queue.connections.'.$this->argument('connection'));

        $queue = $connector->connect($config);

        if ($queue->isQueueExists($this->argument('name'))) {
            $this->warn('Queue already exists.');

            return;
        }
        $maxPriority = (int) $this->option('max-priority');
        $arguments = [
            'x-max-priority' => $maxPriority
        ];
        $queue->declareQueue(
            $this->argument('name'),
            (bool) $this->option('durable'),
            (bool) $this->option('auto-delete'),
            $arguments
        );

        $this->info('Queue declared successfully.');
    }
}

Add Max priority for queue declare

Add Max priority for queue declare


<?php

namespace PhpGitHooks\Module\Configuration\Infrastructure\Hook;

use Symfony\Component\Process\Process;

class HookCopier
{
    protected $hookDir = '.git/hooks/';

    public function copyPreCommitHook(): void
    {
        $this->copyHookFile('pre-commit');
    }

    public function copyCommitMsgHook(): void
    {
        $this->copyHookFile('commit-msg');
    }

    public function copyPrePushHook(): void
    {
        $this->copyHookFile('pre-push');
    }

    public function copyPrepareCommitMsgHook(): void
    {
        $this->copyHookFile('prepare-commit-msg');
    }

    protected function hookExists(string $hookFile): bool
    {
        return file_exists(sprintf('%s%s', $this->hookDir, $hookFile));
    }

    protected function copyFile(string $hookFile): void
    {
        $copy = new Process(sprintf("mkdir -p {$this->hookDir} && cp %s %s", $hookFile, $this->hookDir));
        $copy->run();
    }

    protected function setPermissions(string $hookFile): void
    {
        $permissions = new Process(sprintf('chmod 775 %s%s', $this->hookDir, $hookFile));
        $permissions->run();
    }

    protected function copyHookFile(string $file): void
    {
        if (false === $this->hookExists($file)) {
            $this->copyFile(sprintf('%s/%s', __DIR__ . '/../../../../Infrastructure/Hook', $file));
            $this->setPermissions($file);
        }
    }
}

<?php

namespace PhpGitHooks\Module\Configuration\Infrastructure\Hook;

use Symfony\Component\Process\Process;

class HookCopier
{
    public const DEFAULT_GIT_HOOKS_DIR = '.git/hooks';

    protected $hookDir = self::DEFAULT_GIT_HOOKS_DIR;

    public function copyPreCommitHook(): void
    {
        $this->copyHookFile('pre-commit');
    }

    public function copyCommitMsgHook(): void
    {
        $this->copyHookFile('commit-msg');
    }

    public function copyPrePushHook(): void
    {
        $this->copyHookFile('pre-push');
    }

    public function copyPrepareCommitMsgHook(): void
    {
        $this->copyHookFile('prepare-commit-msg');
    }

    protected function hookExists(string $hookFile): bool
    {
        return file_exists(sprintf('%s%s', $this->hookDir, $hookFile));
    }

    protected function copyFile(string $hookFile): void
    {
        $copy = new Process(sprintf("mkdir -p {$this->hookDir} && cp %s %s", $hookFile, $this->hookDir));
        $copy->run();
    }

    protected function setPermissions(string $hookFile): void
    {
        $permissions = new Process(sprintf('chmod 775 %s%s', $this->hookDir, $hookFile));
        $permissions->run();
    }

    protected function copyHookFile(string $file): void
    {
        if (false === $this->hookExists($file)) {
            $this->copyFile(sprintf('%s/%s', __DIR__ . '/../../../../Infrastructure/Hook', $file));
            $this->setPermissions($file);
        }
    }
}

Move hooks directory to a constant

Move hooks directory to a constant

That way one could ask for the default directory from its code while still
extend the class and change the path to another one.


<?php
/*
Template Name: 2 Spalten und Bilder
*/
?>

            <?php while (have_posts()) : the_post(); ?>
            <?php get_template_part('templates/page', 'header'); ?>

                    <?php get_template_part('templates/content', 'page'); ?>
                    <?php endwhile ?>

                    <?php the_field('2-col-pics-text_col2'); ?>

        <?php if( have_rows('2-col-pics_pictures') ) { ?>

            <?php while ( have_rows('2-col-pics_pictures') ) { the_row(); ?>

                    <?php $sub = get_sub_field('2-col-pics_picture'); ?>
                    <img src="<?php echo $sub['url']; ?>">

            <?php } ?>

        <?php } ?>

<?php
/*
Template Name: 2 Spalten und Bilder
*/
?>

            <?php while (have_posts()) : the_post(); ?>
            <?php get_template_part('templates/page', 'header'); ?>

                    <?php get_template_part('templates/content', 'page'); ?>
                    <?php endwhile ?>

                    <?php the_field('2-col-pics-text_col2'); ?>

        <?php if( have_rows('2-col-pics_pictures') ) { ?>

            <?php while ( have_rows('2-col-pics_pictures') ) { the_row(); ?>

                    <?php $sub = get_sub_field('2-col-pics_picture'); ?>
                    <img src="<?php echo $sub['url']; ?>" rel="lightbox[pp_gal]">

            <?php } ?>

        <?php } ?>

Fix lightbox on two col page.

Fix lightbox on two col page.


<?php

use Illuminate\Database\Seeder;

class OrganisationsTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        DB::table('organisations')->insert([
            'name'                      => 'Wellington Gliding Club',
            'addr1'                     => 'PO Box 30 200',
            'addr2'                     => 'Lower Hutt',
            'addr3'                     => '',
            'addr4'                     => '',
            'country'                   => 'New Zealand',
            'contact_name'              => 'Flash Gordon',
            'email'                     => 'flash.gordon@gmail.com',
            'timezone'                  => 'Pacific/Auckland',
            'aircraft_prefix'           => 'ZK',
            'tow_height_charging'       => 1,
            'tow_time_based'            => 0,
            'default_location'          => 'Greytown',
            'name_othercharges'         => 'Airways',
            'def_launch_lat'            => '-41.104941',
            'def_launch_lon'            => '175.499121',
            'map_centre_lat'            => '-41.104941',
            'map_centre_lon'            => '175.499121',
            'twitter_consumerKey'       => '????',
            'twitter_consumerSecret'    => '????',
            'twitter_accessToken'       => '????',
            'twitter_accessTokenSecret' => '????',
        ]);
    }
}

<?php

use Illuminate\Database\Seeder;

class OrganisationsTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        DB::table('organisations')->insert([
            'id'                        => 1,
            'name'                      => 'Wellington Gliding Club',
            'addr1'                     => 'PO Box 30 200',
            'addr2'                     => 'Lower Hutt',
            'addr3'                     => '',
            'addr4'                     => '',
            'country'                   => 'New Zealand',
            'contact_name'              => 'Flash Gordon',
            'email'                     => 'flash.gordon@gmail.com',
            'timezone'                  => 'Pacific/Auckland',
            'aircraft_prefix'           => 'ZK',
            'tow_height_charging'       => 1,
            'tow_time_based'            => 0,
            'default_location'          => 'Greytown',
            'name_othercharges'         => 'Airways',
            'def_launch_lat'            => '-41.104941',
            'def_launch_lon'            => '175.499121',
            'map_centre_lat'            => '-41.104941',
            'map_centre_lon'            => '175.499121',
            'twitter_consumerKey'       => '????',
            'twitter_consumerSecret'    => '????',
            'twitter_accessToken'       => '????',
            'twitter_accessTokenSecret' => '????',
        ]);
    }
}

Fix id of first organisation.

Fix id of first organisation.


<?php

namespace DoctrineDbalIbmiTest;

use Doctrine\ORM\EntityManager;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Tools\Setup;

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

class Bootstrap
{
    /**
     * @var EntityManagerInterface
     */
    private static $entityManager;

    /**
     * @return EntityManagerInterface
     * @throws \PHPUnit_Framework_SkippedTestError
     * @throws \InvalidArgumentException
     * @throws \Doctrine\ORM\ORMException
     */
    public static function getEntityManager()
    {
        if (null === self::$entityManager) {
            if (!extension_loaded('ibm_db2')) {
                throw new \PHPUnit_Framework_SkippedTestError('DB2 connection is unavailable, skipping test');
            }

            $configuration = Setup::createAnnotationMetadataConfiguration([
                __DIR__ . '/entity/',
            ], true);

            $connection = require __DIR__ . '/config/local.php';

            self::$entityManager = EntityManager::create($connection, $configuration);
        }

        self::$entityManager->clear();
        return self::$entityManager;
    }
}

<?php

namespace DoctrineDbalIbmiTest;

use Doctrine\ORM\EntityManager;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Tools\Setup;

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

class Bootstrap
{
    /**
     * @var EntityManagerInterface
     */
    private static $entityManager;

    /**
     * @return EntityManagerInterface
     * @throws \PHPUnit_Framework_SkippedTestError
     * @throws \InvalidArgumentException
     * @throws \Doctrine\ORM\ORMException
     */
    public static function getEntityManager()
    {
        if (null === self::$entityManager) {
            if (!extension_loaded('ibm_db2')) {
                throw new \PHPUnit_Framework_SkippedTestError('DB2 connection is unavailable, skipping test');
            }

            $configuration = Setup::createAnnotationMetadataConfiguration([
                __DIR__ . '/entity/',
            ], true);

            if (!file_exists(__DIR__ . '/config/local.php')) {
                throw new \PHPUnit_Framework_SkippedTestError('test/config/local.php not found');
            }

            $connection = require __DIR__ . '/config/local.php';

            self::$entityManager = EntityManager::create($connection, $configuration);
        }

        self::$entityManager->clear();
        return self::$entityManager;
    }
}

Throw exception if config not found

Throw exception if config not found


<?php

namespace Distill\Cli\Command;

use Distill\Distill;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class AboutCommand extends Command
{

    /**
     * App version.
     * @var string
     */
    protected $appVersion;

    /**
     * Constructor.
     * @param string $appVersion App version
     */
    public function __construct($appVersion)
    {
        parent::__construct();

        $this->appVersion = $appVersion;
    }

    /**
     * {@inheritdoc}
     */
    protected function configure()
    {
        $this
            ->setName('about')
            ->setDescription('Extracts files from a compressed archive')
        ;
    }

    /**
     * {@inheritdoc}
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {

        $output->writeln(sprintf("\n <info>Distill CLI</info> <comment>%s</comment>", $this->appVersion));
        $output->writeln(" ~~~~~~~~~~~~~~~~~~~~");

        $output->writeln(" Command line tool to extract files from compressed archives. Supports bz2, gz, phar, rar, tar, tar.bz2, tar.gz, tar.xz, 7z, xz and zip archives.\n");

        $output->writeln(" Available commands:");

        $output->writeln("   <info>extract <dir-name></info>  Extracts files from compressed archives.");
        $output->writeln("                   Example: <comment>$ distill-cli extract example.tar.gz example/</comment>\n");
    }

}

<?php

namespace Distill\Cli\Command;

use Distill\Distill;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class AboutCommand extends Command
{

    /**
     * App version.
     * @var string
     */
    protected $appVersion;

    /**
     * Constructor.
     * @param string $appVersion App version
     */
    public function __construct($appVersion)
    {
        parent::__construct();

        $this->appVersion = $appVersion;
    }

    /**
     * {@inheritdoc}
     */
    protected function configure()
    {
        $this
            ->setName('about')
            ->setDescription('Extracts files from a compressed archive')
        ;
    }

    /**
     * {@inheritdoc}
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $output->writeln(sprintf("\n <info>Distill CLI</info> <comment>%s</comment>", $this->appVersion));
        $output->writeln(" ~~~~~~~~~~~~~~~~~~~~");

        $output->writeln(" Command line tool to extract files from compressed archives. Supports bz2, gz, phar, rar, tar, tar.bz2, tar.gz, tar.xz, 7z, xz and zip archives.\n");

        $output->writeln(" Available commands:");

        $output->writeln("   <info>extract <dir-name></info>  Extracts files from compressed archives.");
        $output->writeln("                   Example: <comment>$ distill-cli extract example.tar.gz example/</comment>\n");

        return 0;
    }

}

Return code for about command

Return code for about command


<?= '<?xml version="1.0" encoding="UTF-8" ?>' ?>
<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
  <channel>
    <title><?= @$tpl['channel_title'] ?: 'Fortune Daddy' ?></title>
    <link><?= @$tpl['channel_link'] ?: ("http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']) ?></link>
    <description><?= @$tpl['description'] ?></description>
    <pubDate><?= date('r') ?></pubDate>
    <language>en</language>
    <item>
      <title><?= htmlentities($tpl['quote']) ?></title>
      <link><?= @$tpl['quote_link'] ?: ("http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']) ?></link>
      <description><?= htmlentities($tpl['quote']) ?></description>
      <guid isPermalink="false"><?= rand() ?></guid>
      <pubDate><?= date('r') ?></pubDate>
    </item>
  </channel>
</rss>

<?= '<?xml version="1.0" encoding="UTF-8" ?>' ?>
<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
  <channel>
    <title><?= @$tpl['channel_title'] ?: 'Fortune Daddy' ?></title>
    <link><?= @$tpl['channel_link'] ?: ("http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']) ?></link>
    <description><?= @$tpl['description'] ?></description>
    <pubDate><?= date('r') ?></pubDate>
    <language>en</language>
    <item>
      <title><?= htmlentities($tpl['quote']) ?></title>
      <link><?= @$tpl['quote_link'] ?: ("http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']) ?></link>
      <description><?= htmlentities($tpl['quote']) ?></description>
      <guid isPermalink="false"><?= md5($tpl['quote']) ?></guid>
      <pubDate><?= date('r') ?></pubDate>
    </item>
  </channel>
</rss>

Use md5 to generate better guid

Use md5 to generate better guid


<?php

require_once __DIR__.'/../paths.php';
require_once VENDOR_DIR.'autoload.php';
require_once STENCIL_DIR.'post.php';

use Stencil\Stencil as Stencil;
use Stencil\Post as Post;

class PostTest extends PHPUnit_Framework_TestCase
{
  public function testClass()
  {
    $post = new Post();

    $this->assertEquals($post->title, '');
  }
}

<?php

require_once __DIR__.'/../paths.php';
require_once VENDOR_DIR.'autoload.php';
require_once STENCIL_DIR.'post.php';

use Stencil\Stencil as Stencil;
use Stencil\Post as Post;

class PostTest extends PHPUnit_Framework_TestCase
{
  public function testClassConstruct()
  {
    $post = new Post();

    $this->assertEquals($post->title, '');
    $this->assertEquals($post->date, time());
    $this->assertEquals($post->layout, '');
    $this->assertEquals($post->content, '');
  }
}

Write test for class construct

Write test for class construct


<?php

declare(strict_types=1);

namespace Funktions;

/**
 * Return a value based on a test
 *
 * @param boolean $test
 * @param callable $truthy
 * @param callable $falsy
 * @return mixed
 */
function condition(bool $test, callable $truthy, callable $falsy)
{
    if ($test) {
        return call_user_func($truthy);
    }
    return call_user_func($falsy);
}

/**
 * Loop over items and pass them to a generator
 *
 * @param iterable $iterable
 * @param callable $callable
 * @return array
 */
function loop(iterable $iterable, callable $callable): array
{
    $array = [];
    foreach ($iterable as $item) {
        $generator = call_user_func($callable, $item);
        if ($generator instanceof Generator === false) {
            throw Exception('Callable must be a generator');
        }
        $array = array_merge($array, iterator_to_array($generator));
    }
    return $array;
}

/**
 * Loop in a generator until a returned condition
 *
 * @param callable $callable
 * @return array
 */
function loop_until(callable $callable): array
{
    $array = [];
    do {
        $generator = call_user_func($callable);
        if ($generator instanceof Generator === false) {
            throw Exception('Callable must be a generator');
        }
        $array = array_merge($array, iterator_to_array($generator));
    }
    while(!$generator->getReturn());
    return $array;
}

<?php

declare(strict_types=1);

namespace Funktions;

use Exception;

/**
 * Return a value based on a test
 *
 * @param boolean $test
 * @param callable $truthy
 * @param callable $falsy
 * @return mixed
 */
function condition(bool $test, callable $truthy, callable $falsy)
{
    if ($test) {
        return call_user_func($truthy);
    }
    return call_user_func($falsy);
}

/**
 * Loop over items and pass them to a generator
 *
 * @param iterable $iterable
 * @param callable $callable
 * @return array
 */
function loop(iterable $iterable, callable $callable): array
{
    $array = [];
    foreach ($iterable as $item) {
        $generator = call_user_func($callable, $item);
        if ($generator instanceof Generator === false) {
            throw new Exception('Callable must be a generator');
        }
        $array = array_merge($array, iterator_to_array($generator));
    }
    return $array;
}

/**
 * Loop in a generator until a returned condition
 *
 * @param callable $callable
 * @return array
 */
function loop_until(callable $callable): array
{
    $array = [];
    do {
        $generator = call_user_func($callable);
        if ($generator instanceof Generator === false) {
            throw Exception('Callable must be a generator');
        }
        $array = array_merge($array, iterator_to_array($generator));
    }
    while(!$generator->getReturn());
    return $array;
}

Fix exception call in loop()

Fix exception call in loop()


<?php

namespace WyriHaximus\React\Tests;

use Evenement\EventEmitter;
use Phake;
use React\EventLoop\Factory;
use WyriHaximus\React\ProcessOutcome;

class FunctionsTest extends \PHPUnit_Framework_TestCase
{
    public function testChildProcessPromise()
    {
        $loop = Factory::create();
        $process = Phake::partialMock('React\ChildProcess\Process', [
            'uptime',
        ]);
        $process->stderr = new ReadableStreamStub();
        $process->stdout = new ReadableStreamStub();
        Phake::when($process)->start($loop)->thenReturnCallback(function () use ($process, $loop) {
            \WyriHaximus\React\futurePromise($loop, $process)->then(function ($process) {
                $process->stderr->emit('data', ['abc']);
                $process->stdout->emit('data', ['def']);
                $process->emit('exit', [123]);
            });
        });

        $called = false;
        \WyriHaximus\React\childProcessPromise($loop, $process)->done(function ($result) use (&$called) {
            //$this->assertEquals(new ProcessOutcome(123, 'abc', 'def'), $result);
            $this->assertSame(123, $result->getExitCode());
            $this->assertSame('abc', $result->getStderr());
            $this->assertSame('def', $result->getStdout());
            $called = true;
        });
        $loop->run();
        $this->assertTrue($called);
    }
}

<?php

namespace WyriHaximus\React\Tests;

use Evenement\EventEmitter;
use Phake;
use React\EventLoop\Factory;
use WyriHaximus\React\ProcessOutcome;

class FunctionsTest extends \PHPUnit_Framework_TestCase
{
    public function testChildProcessPromise()
    {
        $loop = Factory::create();
        $process = Phake::partialMock('React\ChildProcess\Process', [
            'uptime',
            null,
            null,
            []
        ]);
        $process->stderr = new ReadableStreamStub();
        $process->stdout = new ReadableStreamStub();
        Phake::when($process)->start($loop)->thenReturnCallback(function () use ($process, $loop) {
            \WyriHaximus\React\futurePromise($loop, $process)->then(function ($process) {
                $process->stderr->emit('data', ['abc']);
                $process->stdout->emit('data', ['def']);
                $process->emit('exit', [123]);
            });
        });

        $called = false;
        \WyriHaximus\React\childProcessPromise($loop, $process)->done(function ($result) use (&$called) {
            $this->assertEquals(new ProcessOutcome(123, 'abc', 'def'), $result);
            $this->assertSame(123, $result->getExitCode());
            $this->assertSame('abc', $result->getStderr());
            $this->assertSame('def', $result->getStdout());
            $called = true;
        });
        $loop->run();
        $this->assertTrue($called);
    }
}

Destroy all pipes since we don't need them for mocking


<?php

use Mro95\FormBuilder\Form;
use Mro95\FormBuilder\FormBuilderFactory;
use Mro95\FormBuilder\View\FormViewBuilder;

class TestForm extends PHPUnit_Framework_TestCase
{
    public function testOne()
    {
        $builderFactory = new FormBuilderFactory();
        $builder = $builderFactory->fromJson('tests/test-form2.json');
        $form = $builder->build();

        $builder = new FormViewBuilder($form);
        $formView = $builder->build();
        dump($formView->render());

        $this->assertInstanceOf(Form::class, $form);
    }
}

<?php

use PHPUnit\Framework\TestCase;
use Mro95\FormBuilder\Form;
use Mro95\FormBuilder\FormBuilderFactory;
use Mro95\FormBuilder\View\FormViewBuilder;

class TestForm extends TestCase
{
    public function testOne()
    {
        $builderFactory = new FormBuilderFactory();
        $builder = $builderFactory->fromJson('tests/test-form2.json');
        $form = $builder->build();

        $builder = new FormViewBuilder($form);
        $formView = $builder->build();
        dump($formView->render());

        $this->assertInstanceOf(Form::class, $form);
    }
}

Add fix for new phpunit

Add fix for new phpunit


            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#menu">
                {{ Lang::get('cachet.dashboard.toggle_navigation') }}

            </button>
             Cachet

 {{ Lang::get('cachet.dashboard.status_page') }}

 {{ Lang::get('cachet.logout') }}

Switch to just icons for home and sign out in dashboard nav


<?php

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

namespace Symfony\Component\DependencyInjection\Loader\Configurator;

use Symfony\Bridge\Twig\Extension\FormExtension;
use Symfony\Bridge\Twig\Form\TwigRendererEngine;
use Symfony\Component\Form\FormRenderer;

return static function (ContainerConfigurator $container) {
    $container->services()
        ->set('twig.extension.form', FormExtension::class)

        ->set('twig.form.engine', TwigRendererEngine::class)
            ->args([param('twig.form.resources'), service('twig')])

        ->set('twig.form.renderer', FormRenderer::class)
            ->args([service('twig.form.engine'), service('security.csrf.token_manager')->nullOnInvalid()])
            ->tag('twig.runtime')
    ;
};

<?php

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

namespace Symfony\Component\DependencyInjection\Loader\Configurator;

use Symfony\Bridge\Twig\Extension\FormExtension;
use Symfony\Bridge\Twig\Form\TwigRendererEngine;
use Symfony\Component\Form\FormRenderer;

return static function (ContainerConfigurator $container) {
    $container->services()
        ->set('twig.extension.form', FormExtension::class)
            ->args([service('translator')->nullOnInvalid()])

        ->set('twig.form.engine', TwigRendererEngine::class)
            ->args([param('twig.form.resources'), service('twig')])

        ->set('twig.form.renderer', FormRenderer::class)
            ->args([service('twig.form.engine'), service('security.csrf.token_manager')->nullOnInvalid()])
            ->tag('twig.runtime')
    ;
};

[Form] Implement Twig helpers to get field variables


<?php

namespace Listabierta\Bundle\MunicipalesBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class CandidacyStep2Type extends AbstractType
{
	public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('program', 'file', array('required' => true))
	            ->add('continue', 'submit', array('attr' => array('class' => 'submit')));
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
    }

    public function getName()
    {
        return 'candidacy_step2';
    }
}

<?php

namespace Listabierta\Bundle\MunicipalesBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Validator\Constraints as Assert;

class CandidacyStep2Type extends AbstractType
{
	public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('program', 'file', array(
        					'required' => true,
        					'constraints' => array(
        						new Assert\NotBlank(),
        					)
        				)
        			)
        		->add('legal_conditions', 'file', array(
        					'required' => true,
        					'constraints' => array(
        							new Assert\NotBlank(),
        					)
        				)
        			)
        		->add('recall_term', 'file', array(
        					'required' => true,
        					'constraints' => array(
        							new Assert\NotBlank(),
        					)
        				)
        			)
        		->add('participatory_term', 'file', array(
        					'required' => true,
        					'constraints' => array(
        							new Assert\NotBlank(),
        					)
        				)
        			)
        		->add('voter_conditions', 'file', array(
        					'required' => true,
        					'constraints' => array(
        							new Assert\NotBlank(),
        					)
        				)
        			)
        		->add('technical_constrains', 'file', array(
        					'required' => true,
        					'constraints' => array(
        							new Assert\NotBlank(),
        					)
        				)
        			)
	            ->add('continue', 'submit', array('attr' => array('class' => 'submit')));
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
    }

    public function getName()
    {
        return 'candidacy_step2';
    }
}

Update fields form for step 2

Update fields form for step 2


<?php

namespace AlgoWeb\PODataLaravel\Models\ObjectMap\Entities\Associations;

class AssociationStubMonomorphic extends AssociationStubBase
{
    /**
     * @param \AlgoWeb\PODataLaravel\Models\ObjectMap\Entities\Associations\AssociationStubBase $otherStub
     *
     * @return bool
     */
    public function isCompatible(AssociationStubBase $otherStub)
    {
        if (!parent::isCompatible($otherStub)) {
            return false;
        }
        $isNull = null == $this->getThroughField();
        $otherNull = null == $otherStub->getThroughField();

        if ($isNull != $otherNull) {
            return false;
        }
        $thisChain = $this->getThroughFieldChain();
        $otherChain = $otherStub->getThroughFieldChain();
        $thisThroughCount = count($thisChain) - 1;
        $otherThroughCount = count($otherChain) - 1;
        if ($thisThroughCount !== $otherThroughCount) {
            return false;
        }
        for ($i=0; $i <= $thisThroughCount;++$i) {
            if ($thisChain[$i] !== $otherChain[$otherThroughCount -$i]) {
                return false;
            }
        }

        return ($this->getTargType() === $otherStub->getBaseType())
            && ($this->getBaseType() === $otherStub->getTargType())
            && ($this->getForeignField() === $otherStub->getKeyField())
            && ($this->getKeyField() === $otherStub->getForeignField());
    }

    /**
     * {@inheritdoc}
     */
    public function morphicType()
    {
        return 'monomorphic';
    }
}

<?php

namespace AlgoWeb\PODataLaravel\Models\ObjectMap\Entities\Associations;

class AssociationStubMonomorphic extends AssociationStubBase
{
    /**
     * @param \AlgoWeb\PODataLaravel\Models\ObjectMap\Entities\Associations\AssociationStubBase $otherStub
     *
     * @return bool
     */
    public function isCompatible(AssociationStubBase $otherStub)
    {
        if (!parent::isCompatible($otherStub)) {
            return false;
        }
        $thisChain = $this->getThroughFieldChain();
        $otherChain = $otherStub->getThroughFieldChain();
        $thisThroughCount = count($thisChain) - 1;
        $otherThroughCount = count($otherChain) - 1;
        if ($thisThroughCount !== $otherThroughCount) {
            return false;
        }
        for ($i=0; $i <= $thisThroughCount;++$i) {
            if ($thisChain[$i] !== $otherChain[$otherThroughCount -$i]) {
                return false;
            }
        }

        return ($this->getTargType() === $otherStub->getBaseType())
            && ($this->getBaseType() === $otherStub->getTargType())
            && ($this->getForeignField() === $otherStub->getKeyField())
            && ($this->getKeyField() === $otherStub->getForeignField());
    }

    /**
     * {@inheritdoc}
     */
    public function morphicType()
    {
        return 'monomorphic';
    }
}

Remove through field check, as we now check the entire through chain


<?php

return array(

	/**
	 * You can get a steam API key from http://steamcommunity.com/dev/apikey
	 * Once you get your key, add it here.
	*/
	'steamApiKey' => env('STEAM_API_KEY'),
);

<?php

return [

    /**
     * You can get a steam API key from http://steamcommunity.com/dev/apikey
     * Once you get your key, add it here.
    */
    'steamApiKey' => env('STEAM_API_KEY'),
];

Use spaces and new array syntax

Use spaces and new array syntax


<?php
/**
 * Public entry point for application
 */
require_once('../src/app.php');

<?php
/**
 * Public entry point for application
 */
require_once(__DIR__ . '/../src/app.php');

Use fully qualified path to app.php

Use fully qualified path to app.php

As we don't know where the current working directory is, use a fully
qualified path to app.php. This allows use of the PHP built in web
server if it's run from the root directory like this:

php -S 0.0.0.0:8888 -t public public/index.php


<?php
namespace wcf\system\cronjob;
use wcf\data\cronjob\Cronjob;
use wcf\system\trophy\condition\TrophyConditionHandler;

/**
 * Assigns automatically trophies.
 *
 * @author	Joshua Ruesweg
 * @copyright	2001-2018 WoltLab GmbH
 * @license	GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package	WoltLabSuite\Core\System\Cronjob
 * @since	3.1
 */
class AssignTrophiesCronjob extends AbstractCronjob {
	/**
	 * @inheritDoc
	 */
	public function execute(Cronjob $cronjob) {
		parent::execute($cronjob);

		if (MODULE_TROPHY) {
			TrophyConditionHandler::getInstance()->assignTrophies(100);
			TrophyConditionHandler::getInstance()->revokeTrophies(100);
		}
	}
}

<?php
namespace wcf\system\cronjob;
use wcf\data\cronjob\Cronjob;
use wcf\system\trophy\condition\TrophyConditionHandler;

/**
 * Assigns automatically trophies.
 *
 * @author	Joshua Ruesweg
 * @copyright	2001-2018 WoltLab GmbH
 * @license	GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package	WoltLabSuite\Core\System\Cronjob
 * @since	3.1
 */
class AssignTrophiesCronjob extends AbstractCronjob {
	/**
	 * @inheritDoc
	 */
	public function execute(Cronjob $cronjob) {
		parent::execute($cronjob);

		if (MODULE_TROPHY) {
			TrophyConditionHandler::getInstance()->revokeTrophies(100);
			TrophyConditionHandler::getInstance()->assignTrophies(100);
		}
	}
}

Switch revoking and adding trophies to make level trophies possible


<?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\UserQuery,
    Imbo\Auth\AccessControl\GroupQuery;

/**
 * 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 getUsers(UserQuery $query = null) {
        return ['public'];
    }

    public function getGroups(GroupQuery $query = null) {
        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 [];
    }
}

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\UserQuery,
    Imbo\Auth\AccessControl\GroupQuery;

/**
 * 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 getUsers(UserQuery $query = null) {
        return ['public'];
    }

    public function getGroups(GroupQuery $query = null) {
        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 getAccessRule($publicKey, $accessRuleId) {
        return null;
    }
}

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

Add missing implementation in StaticAccessControl


<?php

class Application_View_Helper_Loggedin extends Zend_View_Helper_Abstract
{
    public function loggedin()
    {
        $menuLoggedIn = '';

        $auth = Zend_Auth::getInstance();
        $data = $auth->getStorage()->read();
        $menuLoggedIn .= "

                ".$data['name']."

".Zend_Registry::get('Zend_Translate')->translate('m011')."

".Zend_Registry::get('Zend_Translate')->translate('m013')."

".Zend_Registry::get('Zend_Translate')->translate('m012')."

";

        return $menuLoggedIn;

    }

}

Fix wrong click-action binding for loggedin menu

Signed-off-by: Fran Diéguez <1a0d2d7b2e688322d0c86dcf5420732151ae4348@mabishu.com>


<?php
class db_dcs_log extends CI_Model{
	function get_all(){
		$q = $this->db->get('dcs_log');
		return $q->result();
	}

	function get_date(){
		$this->db->distinct();
		$this->db->select('date(time) as date');
		$this->db->order_by('time', 'desc');
		$q = $this->db->get('dcs_log');
		return $q->result();
	}

	function get_date_detail($param){
		$this->db->where('date(time)', date('Y-m-d', strtotime($param)));
		$this->db->order_by('time', 'desc');
		$q = $this->db->get('dcs_log');
		return $q->result();
	}

	function get_today(){
		$this->db->where('date(time)', date('Y-m-d'));
		$this->db->order_by('time', 'desc');
		$q = $this->db->get('dcs_log');
		return $q->result();
	}

	function insert($data){
		$this->db->insert('dcs_log', $data);
	}
}

<?php
class db_dcs_log extends CI_Model{
	function get_all(){
		$this->db->order_by('time', 'desc');
		$q = $this->db->get('dcs_log');
		return $q->result();
	}

	function get_date(){
		$this->db->distinct();
		$this->db->select('date(time) as date');
		$this->db->order_by('time', 'desc');
		$q = $this->db->get('dcs_log');
		return $q->result();
	}

	function get_date_detail($param){
		$this->db->where('date(time)', date('Y-m-d', strtotime($param)));
		$this->db->order_by('time', 'desc');
		$q = $this->db->get('dcs_log');
		return $q->result();
	}

	function get_today(){
		$this->db->where('date(time)', date('Y-m-d'));
		$this->db->order_by('time', 'desc');
		$q = $this->db->get('dcs_log');
		return $q->result();
	}

	function insert($data){
		$this->db->insert('dcs_log', $data);
	}
}

Add time sorting from db

Add time sorting from db


<?php

namespace App\Entity;

use ApiPlatform\Core\Annotation\ApiProperty;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\InheritanceType("JOINED")
 * @ORM\DiscriminatorColumn(name="entityType", type="string")
 */
abstract class AbstractContentNodeOwner extends BaseEntity {
    /**
     * @ORM\OneToOne(targetEntity="ContentNode", inversedBy="owner")
     * @ORM\JoinColumn(nullable=true)
     */
    public ?ContentNode $rootContentNode = null;

    public function setRootContentNode(?ContentNode $rootContentNode) {
        // unset the owning side of the relation if necessary
        if (null === $rootContentNode && null !== $this->rootContentNode) {
            $this->rootContentNode->owner = null;
        }

        // set the owning side of the relation if necessary
        if (null !== $rootContentNode && $rootContentNode->owner !== $this) {
            $rootContentNode->owner = $this;
        }

        $this->rootContentNode = $rootContentNode;
    }

    /**
     * @return ContentNode[]
     */
    #[ApiProperty(writable: false)]
    public function getContentNodes(): array {
        if (null != $this->rootContentNode) {
            return $this->rootContentNode->getRootDescendants();
        }

        return [];
    }
}

<?php

namespace App\Entity;

use ApiPlatform\Core\Annotation\ApiProperty;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\InheritanceType("JOINED")
 * @ORM\DiscriminatorColumn(name="entityType", type="string")
 */
abstract class AbstractContentNodeOwner extends BaseEntity {
    /**
     * @ORM\OneToOne(targetEntity="ContentNode", inversedBy="owner")
     * @ORM\JoinColumn(nullable=true)
     */
    public ?ContentNode $rootContentNode = null;

    public function setRootContentNode(?ContentNode $rootContentNode) {
        // unset the owning side of the relation if necessary
        if (null === $rootContentNode && null !== $this->rootContentNode) {
            $this->rootContentNode->owner = null;
        }

        // set the owning side of the relation if necessary
        if (null !== $rootContentNode && $rootContentNode->owner !== $this) {
            $rootContentNode->owner = $this;
        }

        $this->rootContentNode = $rootContentNode;
    }

    /**
     * @return ContentNode[]
     */
    #[ApiProperty(writable: false)]
    public function getContentNodes(): array {
        return $this->rootContentNode?->getRootDescendants() ?? [];
    }
}

Simplify getter using php 8 syntax

Simplify getter using php 8 syntax


<?php

class ComponentTableSeeder extends Seeder {

	/**
	 * Run the database seeds.
	 *
	 * @return void
	 */
	public function run()
	{
		Eloquent::unguard();

		$defaultComponents = [
			[
				"name" => "API",
				"description" => "Used by third-parties to connect to us"
			],
			[
				"name" => "Payments",
				"description" => "Backed by Stripe"
			],
			[
				"name" => "Website"
			]
		];

		Component::truncate();

		foreach($defaultComponents as $setting) {
			Component::create($setting);
		}
	}
}

<?php

class ComponentTableSeeder extends Seeder {

	/**
	 * Run the database seeds.
	 *
	 * @return void
	 */
	public function run()
	{
		Eloquent::unguard();

		$defaultComponents = [
			[
				"name" => "API",
				"description" => "Used by third-parties to connect to us"
			], [
				"name" => "Payments",
				"description" => "Backed by Stripe"
			], [
				"name" => "Website"
			]
		];

		Component::truncate();

		foreach($defaultComponents as $component) {
			Component::create($component);
		}
	}
}

Fix bad var name for components

Fix bad var name for components


<?php

/**
 * Date/Time related functions
 * @author M2Mobi, Heinz Wiesinger
 */
class M2DateTime
{

    /**
     * Constructor
     */
    public function __construct()
    {

    }

    /**
     * Destructor
     */
    public function __destruct()
    {

    }

    /**
     * Return today's date (YYYY-MM-DD)
     * @return String Today's date
     */
    public static function today()
    {
        return date('Y-m-d');
    }

    /**
     * Return tomorrow's date (YYYY-MM-DD)
     * @return String Tomorrow's date
     */
    public static function tomorrow()
    {
        return date('Y-m-d', strtotime("+1 day"));
    }

    /**
     * Return the current time (HH:MM:SS)
     * @return String current time
     */
    public static function now()
    {
        return strftime("%H:%M:%S", time());
    }

}

?>

<?php

/**
 * Date/Time related functions
 * @author M2Mobi, Heinz Wiesinger
 */
class M2DateTime
{

    /**
     * Constructor
     */
    public function __construct()
    {

    }

    /**
     * Destructor
     */
    public function __destruct()
    {

    }

    /**
     * Return today's date (YYYY-MM-DD)
     * @return String Today's date
     */
    public static function today()
    {
        return date('Y-m-d');
    }

    /**
     * Return tomorrow's date (YYYY-MM-DD)
     * @return String Tomorrow's date
     */
    public static function tomorrow()
    {
        return date('Y-m-d', strtotime("+1 day"));
    }

    /**
     * Return the current time (HH:MM:SS)
     * @return String current time
     */
    public static function now()
    {
        return strftime("%H:%M:%S", time());
    }

    /**
     * Returns a MySQL compatible date definition
     * @param Integer $timestamp PHP-like Unix Timestamp
     * @return String $date Date as a string
     */
    public static function get_date($timestamp)
    {
        return date('Y-m-d', $timestamp);
    }

    /**
     * Returns a MySQL compatible time definition
     * @param Integer $timestamp PHP-like Unix Timestamp
     * @return String $time Time as a string
     */
    public static function get_time($timestamp)
    {
        return strftime("%H:%M:%S", $timestamp);
    }
}

?>

application: Add new static methods to M2DateTime class

  -) get_date() for returning a MySQL compatible date string
  -) get_time() for returning a MySQL compatible time string