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

use KM\Saffron\Request;
use KM\Saffron\Executor;

$router = require __DIR__ . '/router.compiled.php';
$request = Request::createFromGlobals();
$route = $router->dispatch($request);

if ($route) {
    $executor = new Executor($route);
    $executor->fire();
}
else {
    echo 'Error 404';
}

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

use KM\Saffron\Request;
use KM\Saffron\Executor;
use KM\Saffron\RouterFactory;

$factory = new RouterFactory(
    function ($collection) {
        $collection->route('home')
            ->setUri('/')
            ->setTarget('Site\Controller\HomeController');

        $collection->route('product')
            ->setUri('/product/{slug}/{id}')
            ->setTarget('Site\Controller\ProductController')
            ->setRequires(
                [
                    'slug' => '\w+',
                    'id' => '\d+',
                ]
            );
    }
);

$router = $factory->build();
$route = $router->match(\KM\Saffron\Request::createFromGlobals());

if ($route) {
    $executor = new Executor($route);
    $executor->fire();
}
else {
    echo 'Error 404';
}

Adjust example to new solution

Adjust example to new solution


@extends('layout')

@section('content')
    @include('partials.standardHeader')

                    <form action="/upload" class="dropzone" id="that-zone">

Drop files here or click to upload

                                Max: 50Mb

                        {{ csrf_field() }}
                    </form>

                <form action="{{ url('/zip/' . Session::get('hash')) }}" method="POST" id="form">
                    {{ csrf_field() }}

                        <input type="password" name="password" class="input is-large is-expanded" placeholder="Password">

                        {{-- Firefox is a bit wee so we can't use damn buttons with icons --}}

                            Zip up

                </form>

@stop

@extends('layout')

@section('content')
    @include('partials.standardHeader')

                    <form action="/upload" class="dropzone" id="that-zone">

Drop files here or click to upload

                                Max: 50Mb

                        {{ csrf_field() }}
                    </form>

                <form action="{{ url('/zip/' . Session::get('hash')) }}" method="POST" id="form">
                    {{ csrf_field() }}

                        <input type="password" name="password" class="input is-large is-expanded" placeholder="Password">

                        {{-- Firefox is a bit wee so we can't use damn buttons with icons, instead we have to use something else like a div --}}

                            Zip up

                </form>

@stop

Make the firefox comment slightly more verbose


<?php
namespace DBAL\Tests\Caching;

use PHPUnit\Framework\TestCase;

abstract class CacheTest extends TestCase{

    protected $host = '127.0.0.1';
    protected $port = false;

    protected $cache;

    public function setUp() {
        $this->cache->connect($this->host, $this->port);
        if(!$this->cache->save('servicetest', 'isactive', 60)){
            $this->markTestSkipped(
                'No connection is available to the caching server'
            );
        }
    }

    public function tearDown() {
        unset($this->cache);
    }

    public function testConnect(){
        $this->assertObjectHasAttribute('cache', $this->cache->connect($this->host, $this->port));
    }

    public function testCacheAdd(){
        $this->assertTrue($this->cache->save('key1', 'testvalue', 60));
    }

    public function testCacheRetrieve(){
        $this->assertEquals('testvalue', $this->cache->fetch('key1'));
    }

    public function testCacheOverride(){
        $this->cache->replace('key1', 'newvalue', 60);
        $this->assertEquals('newvalue', $this->cache->fetch('key1'));
    }

    public function testCacheDelete(){
        $this->assertTrue($this->cache->delete('key1'));
        $this->assertFalse($this->cache->delete('key1'));
    }

    public function testCacheClear(){
        $this->cache->save('key1', 'testvalue', 60);
        $this->assertTrue((bool)$this->cache->deleteAll());
    }
}

<?php
namespace DBAL\Tests\Caching;

use PHPUnit\Framework\TestCase;

abstract class CacheTest extends TestCase{

    protected $host = '127.0.0.1';
    protected $port = false;

    protected $cache;

    public function setUp() {
        $this->cache->connect($this->host, $this->port);
        if(!$this->cache->save('servicetest', 'isactive', 60)){
            $this->markTestSkipped(
                'No connection is available to the caching server'
            );
        }
    }

    public function tearDown() {
        unset($this->cache);
    }

    public function testConnect(){
        $this->assertObjectHasAttribute('cache', $this->cache->connect($this->host, $this->port));
    }

    public function testCacheAdd(){
        $this->assertTrue($this->cache->save('key1', 'testvalue', 60));
    }

    public function testCacheRetrieve(){
        $this->assertEquals('testvalue', $this->cache->fetch('key1'));
    }

    public function testCacheOverride(){
        $this->cache->replace('key1', 'newvalue', 60);
        $this->assertEquals('newvalue', $this->cache->fetch('key1'));
    }

    public function testCacheDelete(){
        $this->assertTrue($this->cache->delete('key1'));
        $this->assertFalse($this->cache->delete('key1'));
    }

    public function testCacheClear(){
        $this->cache->save('key1', 'testvalue', 60);
        $this->assertTrue($this->cache->deleteAll());
    }
}

Revert "Force boolean as not all set to true/false some are 1/0"

This reverts commit b80e83192363f6f77f70bc7a663cae9ff6ef40cd.


<?php

use Fhaculty\Graph\Graph;

use Fhaculty\Graph\Loader\CompleteGraph;

class CompleteGraphTest extends TestCase
{
    public function testOne(){
        $loader = new CompleteGraph(1);
        $graph = $loader->createGraph();

        $expected = new Graph();
        $expected->createVertex();

        $this->assertGraphEquals($expected,$graph);
    }

    public function testTen(){
        $loader = new CompleteGraph(10);
        $graph = $loader->createGraph();

        $this->assertEquals(10,$graph->getNumberOfVertices()); // $n
        $this->assertEquals(45,$graph->getNumberOfEdges()); // n*(n-1)/2
    }

    public function testDirected(){
        $loader = new CompleteGraph(5);
        $loader->setEnableDirectedEdges(true);
        $graph = $loader->createGraph();

        $this->assertEquals(5,$graph->getNumberOfVertices());
        $this->assertEquals(20,$graph->getNumberOfEdges()); // n*(n-1) for directed graphs
        $this->assertTrue($graph->isDirected());
        $this->assertTrue($graph->isComplete());
    }
}

<?php

use Fhaculty\Graph\Graph;

use Fhaculty\Graph\Loader\CompleteGraph;

class CompleteGraphTest extends TestCase
{
    public function testOne(){
        $loader = new CompleteGraph(1);
        $graph = $loader->createGraph();

        $expected = new Graph();
        $expected->createVertex();

        $this->assertGraphEquals($expected,$graph);
    }

    public function testUndirected(){
        $n = 9;

        $loader = new CompleteGraph($n);
        $graph = $loader->createGraph();

        $this->assertEquals($n,$graph->getNumberOfVertices());
        $this->assertEquals($n*($n-1)/2,$graph->getNumberOfEdges());
    }

    public function testDirected(){
        $n = 8;

        $loader = new CompleteGraph($n);
        $loader->setEnableDirectedEdges(true);
        $graph = $loader->createGraph();

        $this->assertEquals($n,$graph->getNumberOfVertices());
        $this->assertEquals($n*($n-1),$graph->getNumberOfEdges()); // n*(n-1) for directed graphs
        $this->assertTrue($graph->isDirected());
        $this->assertTrue($graph->isComplete());
    }
}

Make number of vertices configurable

Make number of vertices configurable


<?php
namespace Kunnu\Dropbox\Models;

class ModelFactory
{

    /**
     * Make a Model Factory
     * @param  array  $data Model Data
     * @return \Kunnu\Dropbox\Models\ModelInterface
     */
    public static function make(array $data = array())
    {
        if(isset($data['.tag']))
        {
            $tag = $data['.tag'];

            //File
            if($tag === 'file')
                return new FileMetadata($data);

            //Folder
            if($tag === 'folder')
                return new FolderMetadata($data);
        }

        //Base Model
        return new BaseModel($data);
    }
}

<?php
namespace Kunnu\Dropbox\Models;

class ModelFactory
{

    /**
     * Make a Model Factory
     * @param  array  $data Model Data
     * @return \Kunnu\Dropbox\Models\ModelInterface
     */
    public static function make(array $data = array())
    {
        if(isset($data['.tag']))
        {
            $tag = $data['.tag'];

            //File
            if($tag === 'file')
                return new FileMetadata($data);

            //Folder
            if($tag === 'folder')
                return new FolderMetadata($data);
        }

        //List
        if(isset($data['entries']))
        {
            return new MetadataCollection($data);
        }

        //Base Model
        return new BaseModel($data);
    }
}

Make MetadataCollection Model from Factory


<?php

namespace Pvm\ArtisanBeans\Console;

class UnpauseTubeCommand extends PauseTubeCommand
{
    protected $commandName = 'unpause';

    protected $commandArguments = '
        {tube : Tube name}
    ';

    protected $description = 'Upause the tube';

    protected $delay = 0;

    /**
     * {$@inheritdoc}.
     */
    protected function getSuccessMessage($tube)
    {
        return "Tube '$tube' has been unpaused.";
    }
}

<?php

namespace Pvm\ArtisanBeans\Console;

class UnpauseTubeCommand extends PauseTubeCommand
{
    protected $commandName = 'unpause';

    protected $commandArguments = '
        {tube : Tube name}
    ';

    protected $description = 'Upause the tube';

    protected $delay = 0;

    /**
     * {$@inheritdoc}.
     */
    protected function getSuccessMessage($tube)
    {
        return "Tube '$tube' has been unpaused.";
    }

    /**
     *{@inheritdoc}.
     */
    protected function parseCommandArguments()
    {
        // Override parent's parseCommandArguments
        // since we use a predefined value for $this->delay
    }
}

Return back parseCommandArguments and add a proper comment.


<?php

namespace Hootlex\Friendships;

use Illuminate\Support\ServiceProvider;

class FriendshipsServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
	    $this->publishes([
	        __DIR__.'/../src/database/migrations/' => database_path('migrations')
	    ], 'migrations');
    }

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

<?php

namespace Hootlex\Friendships;

use Illuminate\Support\ServiceProvider;

class FriendshipsServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        if (class_exists('CreateFriendshipsTable')) {
            return;
        }

        $timestamp = date('Y_m_d_His', time());
        $stub = __DIR__.'/database/migrations/create_friendships_table.php';
        $target = database_path('migrations').'/'.$timestamp.'_create_friendships_table.php';
        $this->publishes([$stub => $target], 'migrations');
    }

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

Change migration name to current time + publish migration only once!


<?php namespace Orchestra\Support\Providers;

use Orchestra\Support\Providers\Traits\PackageProviderTrait;
use Illuminate\Support\ServiceProvider as BaseServiceProvider;

abstract class ServiceProvider extends BaseServiceProvider
{
    use PackageProviderTrait;
}

<?php namespace Orchestra\Support\Providers;

use Orchestra\Contracts\Config\PackageRepository;
use Orchestra\Support\Providers\Traits\PackageProviderTrait;
use Illuminate\Support\ServiceProvider as BaseServiceProvider;

abstract class ServiceProvider extends BaseServiceProvider
{
    use PackageProviderTrait;

    /**
     * Merge the given configuration with the existing configuration.
     *
     * @param  string  $path
     * @param  string  $key
     * @return void
     */
    protected function mergeConfigFrom($path, $key)
    {
        parent::mergeConfigFrom($path, $key);

        $config = $this->app['config'];

        if ($config instanceof PackageRepository) {
            $config->file($key);
        }
    }
}

Allow to push packages name/key to config repository.

Signed-off-by: crynobone <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com>


<?php

namespace Timegridio\Concierge;

use Illuminate\Routing\Router;
use Illuminate\Support\ServiceProvider;

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

    /**
     * Perform post-registration booting of services.
     *
     * @return void
     */
    public function boot()
    {
        // use this if your package has views
        $this->loadViewsFrom(realpath(__DIR__.'/resources/views'), 'concierge');

        $this->publishes([
            __DIR__.'/../migrations/' => base_path('/database/migrations'),
        ]);
    }

    /**
     * Define the routes for the application.
     *
     * @param  \Illuminate\Routing\Router  $router
     *
     * @return void
     */
    public function setupRoutes(Router $router)
    {
        $router->group(['namespace' => 'Timegridio\Concierge\Http\Controllers'], function ($router) {
            require __DIR__.'/Http/routes.php';
        });
    }

    /**
     * Register any package services.
     *
     * @return void
     */
    public function register()
    {
        $this->registerConcierge();
    }

    /**
     * Register package.
     *
     * @return Concierge
     */
    private function registerConcierge()
    {
        $this->app->bind('concierge', function ($app) {
            return new Concierge($app);
        });
    }
}

<?php

namespace Timegridio\Concierge;

use Illuminate\Routing\Router;
use Illuminate\Support\ServiceProvider;

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

    /**
     * Perform post-registration booting of services.
     *
     * @return void
     */
    public function boot()
    {
        // use this if your package has views
        $this->loadViewsFrom(realpath(__DIR__.'/resources/views'), 'concierge');

        $this->publishes([
            __DIR__.'/../migrations/' => base_path('/database/migrations'),
        ]);
    }

    /**
     * Register any package services.
     *
     * @return void
     */
    public function register()
    {
        $this->registerConcierge();
    }

    /**
     * Register package.
     *
     * @return Concierge
     */
    private function registerConcierge()
    {
        $this->app->bind('concierge', function ($app) {
            return new Concierge($app);
        });
    }
}

Remove method since this packaged does not use routing


<?php

namespace EGALL\Transformer;

use Illuminate\Support\ServiceProvider;
use EGALL\Transformer\Contracts\Transformer as TransformerContract;
use EGALL\Transformer\Contracts\CollectionTransformer as CollectionTransformerContract;

/**
 * Transformer service provider.
 *
 * @package EGALL\Transformer
 * @author Erik Galloway <erik@mybarnapp.com>
 */
class TransformerServiceProvider extends ServiceProvider
{

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

    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {

        $this->app->bind(TransformerContract::class, Transformer::class);
        $this->app->bind(CollectionTransformerContract::class, CollectionTransformer::class);
    }
}

<?php

namespace EGALL\Transformer;

use Illuminate\Support\ServiceProvider;
use EGALL\Transformer\Contracts\Transformer as TransformerContract;
use EGALL\Transformer\Contracts\CollectionTransformer as CollectionTransformerContract;

/**
 * Transformer service provider.
 *
 * @package EGALL\Transformer
 * @author Erik Galloway <erik@mybarnapp.com>
 */
class TransformerServiceProvider extends ServiceProvider
{

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

    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {

        $this->app->bind(TransformerContract::class, Transformer::class);
        $this->app->bind(CollectionTransformerContract::class, CollectionTransformer::class);
    }

    /**
     * Get the services provided by the provider.
     *
     * @return array
     */
    public function provides()
    {

        return [Transformer::class, CollectionTransformer::class];

    }
}

Define the provider method in service provider to defer loading


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

namespace PH7;

use PH7\Framework\Http\Http;

abstract class Cron extends Framework\Cron\Run\Cron
{
    public function __construct()
    {
        parent::__construct();

        // Check delay
        $this->isAlreadyExec();
    }

    /**
     * Check if the cron has already been executed.
     *
     * @return void If cron has already been executed, the script stops with exit() function and an explanatory message.
     */
    public function isAlreadyExec()
    {
        if (!$this->checkDelay()) {
            Http::setHeadersByCode(403);

            exit(t('This cron has already been executed.'));
        }
    }
}

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

namespace PH7;

use PH7\Framework\Http\Http;

abstract class Cron extends Framework\Cron\Run\Cron
{
    public function __construct()
    {
        parent::__construct();

        // Check delay
        $this->isAlreadyExec();
    }

    /**
     * Check if the cron has already been executed.
     *
     * @return void If cron has already been executed, the script stops with exit() function and an explanatory message.
     *
     * @throws Framework\Http\Exception
     */
    public function isAlreadyExec()
    {
        if (!$this->checkDelay()) {
            Http::setHeadersByCode(403);

            exit(t('This cron has already been executed.'));
        }
    }
}

Add missing phpdoc @throws tag

Add missing phpdoc @throws tag


<?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\Bundle\SecurityBundle\EventListener;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Security\Core\Authorization\TraceableAccessDecisionManager;
use Symfony\Component\Security\Core\Event\VoteEvent;

/**
 * Listen to vote events from traceable voters.
 *
 * @author Laurent VOULLEMIER <laurent.voullemier@gmail.com>
 *
 * @internal
 */
class VoteListener implements EventSubscriberInterface
{
    private $traceableAccessDecisionManager;

    public function __construct(TraceableAccessDecisionManager $traceableAccessDecisionManager)
    {
        $this->traceableAccessDecisionManager = $traceableAccessDecisionManager;
    }

    /**
     * Event dispatched by a voter during access manager decision.
     */
    public function onVoterVote(VoteEvent $event)
    {
        $this->traceableAccessDecisionManager->addVoterVote($event->getVoter(), $event->getAttributes(), $event->getVote());
    }

    public static function getSubscribedEvents()
    {
        return ['debug.security.authorization.vote' => 'onVoterVote'];
    }
}

<?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\Bundle\SecurityBundle\EventListener;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Security\Core\Authorization\TraceableAccessDecisionManager;
use Symfony\Component\Security\Core\Event\VoteEvent;

/**
 * Listen to vote events from traceable voters.
 *
 * @author Laurent VOULLEMIER <laurent.voullemier@gmail.com>
 *
 * @internal
 */
class VoteListener implements EventSubscriberInterface
{
    private $traceableAccessDecisionManager;

    public function __construct(TraceableAccessDecisionManager $traceableAccessDecisionManager)
    {
        $this->traceableAccessDecisionManager = $traceableAccessDecisionManager;
    }

    /**
     * Event dispatched by a voter during access manager decision.
     */
    public function onVoterVote(VoteEvent $event)
    {
        $this->traceableAccessDecisionManager->addVoterVote($event->getVoter(), $event->getAttributes(), $event->getVote());
    }

    public static function getSubscribedEvents(): array
    {
        return ['debug.security.authorization.vote' => 'onVoterVote'];
    }
}

Add return types to internal|final|private methods


<?php

/*
NOTE: This module requires bson_encode() and bson_decode(),
      which can be obtained by installing the MongoDB driver.
      For example, on Debian/Ubuntu:
          $ sudo apt-get install php5-mongo
*/

require_once('gorpc.php');

class BsonRpcClient extends GoRpcClient {
	const LEN_PACK_FORMAT = 'V';
	const LEN_PACK_SIZE = 4;

	protected function send_request(GoRpcRequest $req) {
		$this->write(bson_encode($req->header));
		$this->write(bson_encode($req->body));
	}

	protected function read_response() {
		// Read the header.
		$data = $this->read_n(LEN_PACK_SIZE);
		$len = unpack(LEN_PACK_FORMAT, $data)[0];
		$header = $data . $this->read_n($len - LEN_PACK_SIZE);

		// Read the body.
		$data = $this->read_n(LEN_PACK_SIZE);
		$len = unpack(LEN_PACK_FORMAT, $data)[0];
		$body = $data . $this->read_n($len - LEN_PACK_SIZE);

		// Decode and return.
		return new GoRpcResponse(bson_decode($header), bson_decode($body));
	}
}

<?php

/*
NOTE: This module requires bson_encode() and bson_decode(),
      which can be obtained by installing the MongoDB driver.
      For example, on Debian/Ubuntu:
          $ sudo apt-get install php5-mongo
*/

require_once('gorpc.php');

class BsonRpcClient extends GoRpcClient {
	const LEN_PACK_FORMAT = 'V';
	const LEN_PACK_SIZE = 4;

	protected function send_request(GoRpcRequest $req) {
		$this->write(bson_encode($req->header));
		$this->write(bson_encode($req->body));
	}

	protected function read_response() {
		// Read the header.
		$data = $this->read_n(self::LEN_PACK_SIZE);
		$len = unpack(self::LEN_PACK_FORMAT, $data)[0];
		$header = $data . $this->read_n($len - self::LEN_PACK_SIZE);

		// Read the body.
		$data = $this->read_n(self::LEN_PACK_SIZE);
		$len = unpack(self::LEN_PACK_FORMAT, $data)[0];
		$body = $data . $this->read_n($len - self::LEN_PACK_SIZE);

		// Decode and return.
		return new GoRpcResponse(bson_decode($header), bson_decode($body));
	}
}

Fix class-level constants in PHP.

Fix class-level constants in PHP.


<?php

/**
* String tools
*/
class Util_StrTool {
    public static function is_blank($str)
    {
        return empty(trim($str));
    }

    public static function null_if_blank($str)
    {
        return Util_StrTool::is_blank($str) ? null : $str;
    }
}

<?php

/**
* String tools
*/
class Util_StrTool {
    public static function is_blank($str)
    {
        return empty(trim($str));
    }

    public static function null_if_blank($str)
    {
        return self::is_blank($str) ? null : $str;
    }
}

Refactor - Rename it simpler

Refactor - Rename it simpler


<?php

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

class AddActionsToUnitsRelation extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		Schema::table('units', function($table)
		{
			$table->integer('action_id')->unsigned;
			$table->foreign('action_id')->references('id')->on('actions');
		});
	}

	/**
	 * Reverse the migrations.
	 *
	 * @return void
	 */
	public function down()
	{
		Schema::table('units', function($table)
		{
			$table->dropColumn('action_id');
		});
	}

}

<?php

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

class AddActionsToUnitsRelation extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		Schema::table('actions', function($table)
		{
			$table->integer('unit_id')->unsigned;
			$table->foreign('unit_id')->references('id')->on('units');
		});
	}

	/**
	 * Reverse the migrations.
	 *
	 * @return void
	 */
	public function down()
	{
		Schema::table('actions', function($table)
		{
			$table->dropColumn('unit_id');
		});
	}

}

Fix foreign key relation between units <-> actions.


<?php
// ~/Sites/presentation/mvc-basics/app/Http/Controllers/EventTicketController.php
// Using your text editor, add the following method (public function) below the
// existing update() method.

public function delete($id)
{
    // Instantiate the EventTicket model based on the $id to update the existing row
    $ticket = EventTicket::findOrFail($id);

    // Delete the ticket row from the database using the built-in model method.
    $ticket->delete();

    return redirect()->route('event.tickets.index');
}

<?php
// ~/Sites/presentation/mvc-basics/app/Http/Controllers/EventTicketController.php
// Using your text editor, locate the destroy() function and replace the `//` placeholder
// comment with the following code.

public function destroy($id)
{
    // Instantiate the EventTicket model based on the $id to update the existing row
    $ticket = EventTicket::findOrFail($id);

    // Delete the ticket row from the database using the built-in model method.
    $ticket->delete();

    return redirect()->route('event.tickets.index');
}

Update laravel/mvc-basics/step-by-step/41 with new destroy method name


<?php
if(isset($CreateGameMessage))
{
	echo $CreateGameMessage;
} ?>

		Players
		Current Turn

<?php
	foreach($ChessGames as $ChessGame)
	{ ?>

			<?php
				echo $ChessGame->getWhitePlayer()->getLinkedDisplayName(false); ?> vs <?php echo $ChessGame->getBlackPlayer()->getLinkedDisplayName(false); ?>

			<?php
				echo $ChessGame->getCurrentTurnPlayer()->getLinkedDisplayName(false); ?>

<a class="buttonA" href="<?php echo $ChessGame->getPlayGameHREF(); ?>"> Play

<?php
	}
?>

<form action="<?php echo Globals::getChessCreateHREF(); ?>" method="POST">
	Challenge:
	<select id="player_id" name="player_id"><?php
		foreach($PlayerList as $PlayerID => $PlayerName)
		{
			?><option value="<?php echo $PlayerID; ?>"><?php echo $PlayerName; ?></option><?php
		} ?>
	</select>

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

Move into one class attribute.

Move into one class attribute.


<?php

generate_mock_once('HTMLPurifier_ErrorCollector');

/**
 * Extended error collector mock that has the ability to expect context
 */
class HTMLPurifier_ErrorCollectorEMock extends HTMLPurifier_ErrorCollectorMock
{

    private $_context;
    private $_expected_context = array();
    private $_expected_context_at = array();

    public function prepare(&$context) {
        $this->_context =& $context;
    }

    public function expectContext($key, $value) {
        $this->_expected_context[$key] = $value;
    }
    public function expectContextAt($step, $key, $value) {
        $this->_expected_context_at[$step][$key] = $value;
    }

    public function send($v1, $v2) {
        // test for context
        $context = SimpleTest::getContext();
        $test = $context->getTest();

        // compat
        if (empty($this->_mock)) {
            $mock = $this;
        } else {
            $mock = $this->_mock;
        }

        foreach ($this->_expected_context as $key => $value) {
            $test->assertEqual($value, $this->_context->get($key));
        }
        $step = $mock->getCallCount('send');
        if (isset($this->_expected_context_at[$step])) {
            foreach ($this->_expected_context_at[$step] as $key => $value) {
                $test->assertEqual($value, $this->_context->get($key));
            }
        }
        // boilerplate mock code, does not have return value or references
        $args = func_get_args();
        $mock->_invoke('send', $args);
    }

}

<?php

generate_mock_once('HTMLPurifier_ErrorCollector');

/**
 * Extended error collector mock that has the ability to expect context
 */
class HTMLPurifier_ErrorCollectorEMock extends HTMLPurifier_ErrorCollectorMock
{

    private $_context;
    private $_expected_context = array();
    private $_expected_context_at = array();

    public function prepare(&$context) {
        $this->_context =& $context;
    }

    public function expectContext($key, $value) {
        $this->_expected_context[$key] = $value;
    }
    public function expectContextAt($step, $key, $value) {
        $this->_expected_context_at[$step][$key] = $value;
    }

    public function send($v1, $v2) {
        // test for context
        $context = SimpleTest::getContext();
        $test = $context->getTest();

        // compat
        if (empty($this->_mock)) {
            $mock = $this;
        } else {
            $mock = $this->_mock;
        }

        foreach ($this->_expected_context as $key => $value) {
            $test->assertEqual($value, $this->_context->get($key));
        }
        $step = $mock->getCallCount('send');
        if (isset($this->_expected_context_at[$step])) {
            foreach ($this->_expected_context_at[$step] as $key => $value) {
                $test->assertEqual($value, $this->_context->get($key));
            }
        }
        // boilerplate mock code, does not have return value or references
        $args = func_get_args();
        $mock->invoke('send', $args);
    }

}

Fix another fatal error from SimpleTest refactoring.

git-svn-id: 25f448894bd6eb0cddf10ded73b4f5a7ea3203f3@1696 48356398-32a2-884e-a903-53898d9a118a


<?php
namespace inklabs\kommerce\Service;

use inklabs\kommerce\Entity as Entity;
use inklabs\kommerce\tests\Helper as Helper;

class CatalogPromotionTest extends Helper\DoctrineTestCase
{
    /* @var CatalogPromotion */
    protected $catalogPromotionService;
    protected $catalogPromotions;

    public function setUp()
    {
        $this->catalogPromotions = [
            $this->getCatalogPromotion(1),
            $this->getCatalogPromotion(2),
            $this->getCatalogPromotion(3),
        ];

        foreach ($this->catalogPromotions as $catalogPromotion) {
            $this->entityManager->persist($catalogPromotion);
        }
        $this->entityManager->flush();

        $this->catalogPromotionService = new CatalogPromotion($this->entityManager);
    }

    private function getCatalogPromotion($num)
    {
        $catalogPromotion = new Entity\CatalogPromotion;
        $catalogPromotion->setCode('test' . $num);
        $catalogPromotion->setName('test' . $num);
        $catalogPromotion->setType('percent');
        $catalogPromotion->setValue(10);
        $catalogPromotion->setRedemptions(0);
        $catalogPromotion->setStart(new \DateTime('2014-01-01', new \DateTimeZone('UTC')));
        $catalogPromotion->setEnd(new \DateTime('2014-12-31', new \DateTimeZone('UTC')));
        return $catalogPromotion;
    }

    public function testFindAll()
    {
        $catalogPromotions = $this->catalogPromotionService->findAll();

        $this->assertEquals($this->catalogPromotions, $catalogPromotions);
    }
}

<?php
namespace inklabs\kommerce\Service;

use inklabs\kommerce\Entity as Entity;
use inklabs\kommerce\tests\Helper as Helper;

class CatalogPromotionTest extends Helper\DoctrineTestCase
{
    public function testFindAll()
    {
        $this->entityManager->persist($this->getCatalogPromotion(1));
        $this->entityManager->persist($this->getCatalogPromotion(2));
        $this->entityManager->flush();

        $catalogPromotionService = new CatalogPromotion($this->entityManager);
        $catalogPromotions = $catalogPromotionService->findAll();

        $this->assertEquals(2, count($catalogPromotions));
    }

    /**
     * @return Entity\CatalogPromotion
     */
    private function getCatalogPromotion($num)
    {
        $catalogPromotion = new Entity\CatalogPromotion;
        $catalogPromotion->setCode('TST' . $num);
        $catalogPromotion->setName('test' . $num);
        $catalogPromotion->setType('percent');
        $catalogPromotion->setValue(10);
        $catalogPromotion->setRedemptions(0);
        $catalogPromotion->setStart(new \DateTime('2014-01-01', new \DateTimeZone('UTC')));
        $catalogPromotion->setEnd(new \DateTime('2014-12-31', new \DateTimeZone('UTC')));
        return $catalogPromotion;
    }
}

Reorganize for 100% for CatalogPromotion Service.


<?php

namespace Nitrapi\OAuth;

use Nitrapi\Nitrapi;

class OAuth {

    /**
     * @var Nitrapi
     */
    private $api;

    public function __construct(Nitrapi $api) {
        $this->api = $api;
    }

    /**
     * Returns a specific OAuth 2.0 Client by id.
     *
     * @param $id
     * @return Client
     */
    public function getClient($id) {
        $_client = $this->api->dataGet('/oauth/' . $id)['client'];
        return new Client($this->api, $_client);
    }

    /**
     * Returns all your OAuth 2.0 clients.
     *
     * @return array
     */
    public function getClients() {
        $clients = [];
        $_clients = $this->api->dataGet('/oauth')['clients'];

        foreach ($_clients as $_client) {
            new Client($this->api, $_client);
        }

        return $clients;
    }

    /**
     * Creates a new OAuth 2.0 client.
     *
     * @param array $data
     * @return Client
     */
    public function createClient(array $data) {
        $_client = $this->api->dataPost('/oauth/', $data)['client'];
        return new Client($this->api, $_client);
    }

}

<?php

namespace Nitrapi\OAuth;

use Nitrapi\Nitrapi;

class OAuth {

    /**
     * @var Nitrapi
     */
    private $api;

    public function __construct(Nitrapi $api) {
        $this->api = $api;
    }

    /**
     * Returns a specific OAuth 2.0 Client by id.
     *
     * @param $id
     * @return Client
     */
    public function getClient($id) {
        $_client = $this->api->dataGet('/oauth/' . $id)['client'];
        return new Client($this->api, $_client);
    }

    /**
     * Returns all your OAuth 2.0 clients.
     *
     * @return array
     */
    public function getClients() {
        $clients = [];
        $_clients = $this->api->dataGet('/oauth')['clients'];

        foreach ($_clients as $_client) {
            $clients[] = new Client($this->api, $_client);
        }

        return $clients;
    }

    /**
     * Creates a new OAuth 2.0 client.
     *
     * @param array $data
     * @return Client
     */
    public function createClient(array $data) {
        $_client = $this->api->dataPost('/oauth/', $data)['client'];
        return new Client($this->api, $_client);
    }

}

Add Clients to client array

Add Clients to client array


<?php

use PhpCsFixer\Fixer\ClassNotation\VisibilityRequiredFixer;
use PhpCsFixer\Fixer\Operator\BinaryOperatorSpacesFixer;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symplify\EasyCodingStandard\ValueObject\Option;

return static function (ContainerConfigurator $containerConfigurator): void {
    $containerConfigurator->import('vendor/sylius-labs/coding-standard/ecs.php');

    $containerConfigurator->parameters()->set(Option::SKIP, [
        VisibilityRequiredFixer::class => ['*Spec.php'],
    ]);

    $containerConfigurator->services()->set(BinaryOperatorSpacesFixer::class)->call('configure', [[]]);
};

<?php

use PhpCsFixer\Fixer\ClassNotation\VisibilityRequiredFixer;
use PhpCsFixer\Fixer\Operator\BinaryOperatorSpacesFixer;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symplify\EasyCodingStandard\Config\ECSConfig;
use Symplify\EasyCodingStandard\ValueObject\Option;

return static function (ECSConfig $config): void {
    $config->import('vendor/sylius-labs/coding-standard/ecs.php');

    $config->skip([
        VisibilityRequiredFixer::class => ['*Spec.php'],
    ]);

    $config->ruleWithConfiguration(BinaryOperatorSpacesFixer::class, []);
};

Update ECS configuration to fix the build


<?php
    $id = 'ID_'.md5(uniqid(rand(), true));

    if (!isset($adformat))
        $adformat = null;
    $create = $adformat == null ? true : false;
    $linkText = isset($linkText) ? $linkText : ($create ? 'Neues Werbeformat anlegen' : $adformat->name);
?>
{{ $linkText }}{!! isset($linkHtml) ? $linkHtml : '' !!}

    <form method="POST" action="{{ !$create ? route('adformats.update', $adformat->id) : route('adformats.create', $issue->id) }}" autocomplete="off">
        {!! csrf_field() !!}
        Name
        <input type="text" value="{{ !$create ? $adformat->name : '' }}" placeholder="1/2 Seite bunt" name="name" id="{{ $id }}_name">

            Preis

                <input type="number" value="{{ !$create ? $adformat->price : '' }}" placeholder="1000" name="price" id="{{ $id }}_price">

                Cent

        <button type="submit" class="button">{{ $create ? 'Anlegen' : 'Änderung speichern' }}</button>
    </form>

<?php
    $id = 'ID_'.md5(uniqid(rand(), true));

    if (!isset($adformat))
        $adformat = null;
    $create = $adformat == null ? true : false;
    $linkText = isset($linkText) ? $linkText : ($create ? 'Neues Werbeformat anlegen' : $adformat->name);
?>
{{ $linkText }}{!! isset($linkHtml) ? $linkHtml : '' !!}

    <form method="POST" action="{{ !$create ? route('adformats.update', $adformat->id) : route('adformats.create', $issue->id) }}" autocomplete="off">
        {!! csrf_field() !!}
        Name
		<input type="text" value="{{ !$create ? $adformat->name : '' }}" placeholder="1/2 Seite bunt" name="name" id="{{ $id }}_name">
		Preis

			<input type="number" value="{{ !$create ? $adformat->price : '' }}" placeholder="1000" name="price" id="{{ $id }}_price" class="input-group-field">
			Cent

        <button type="submit" class="button">{{ $create ? 'Anlegen' : 'Änderung speichern' }}</button>
    </form>

Fix price input field styling.

Fix price input field styling.


<?php
namespace Phortress;

use PhpParser\Node\Expr\Assign;
use PhpParser\Node\Expr\New_;
use PhpParser\Node\Expr\Variable;
use PhpParser\Node\Name;
use PhpParser\Node\Stmt;

class ClassInstanceEnvironment extends Environment {
	use EnvironmentHasFunctionsTrait {
		createFunction as traitCreateFunction;
	}

	/**
	 * The class environment for this instance.
	 *
	 * @var ClassEnvironment
	 */
	private $classEnvironment;

	/**
	 * @param string $name The name of the class.
	 * @param ClassEnvironment $classEnvironment The class environment for instances of this class.
	 */
	public function __construct($name, $classEnvironment) {
		parent::__construct($name, $classEnvironment);
		$this->classEnvironment = $classEnvironment;
	}

	public function shouldResolveVariablesInParentEnvironment() {
		// Only ourself.
		return false;
	}

	public function createChild() {
		return $this;
	}

	/**
	 * @inheritdoc
	 * @param Stmt\ClassMethod $function
	 */
	public function createFunction(Stmt $function) {
		assert($function instanceof Stmt\ClassMethod, 'Only accepts class methods');
		$result = $this->traitCreateFunction($function);

		// Assign $this
		$result->variables['this'] = (new Assign(
				new Variable('this'),
				new New_(new Name($this->classEnvironment->getName()))
			));

		return $result;
	}
}

<?php
namespace Phortress;

use PhpParser\Node\Expr\Assign;
use PhpParser\Node\Expr\New_;
use PhpParser\Node\Expr\Variable;
use PhpParser\Node\Name;
use PhpParser\Node\Param;
use PhpParser\Node\Stmt;

class ClassInstanceEnvironment extends Environment {
	use EnvironmentHasFunctionsTrait {
		createFunction as traitCreateFunction;
	}

	/**
	 * The class environment for this instance.
	 *
	 * @var ClassEnvironment
	 */
	private $classEnvironment;

	/**
	 * @param string $name The name of the class.
	 * @param ClassEnvironment $classEnvironment The class environment for instances of this class.
	 */
	public function __construct($name, $classEnvironment) {
		parent::__construct($name, $classEnvironment);
		$this->classEnvironment = $classEnvironment;
	}

	public function shouldResolveVariablesInParentEnvironment() {
		// Only ourself.
		return false;
	}

	public function createChild() {
		return $this;
	}

	/**
	 * @inheritdoc
	 * @param Stmt\ClassMethod $function
	 */
	public function createFunction(Stmt $function) {
		assert($function instanceof Stmt\ClassMethod, 'Only accepts class methods');
		$result = $this->traitCreateFunction($function);

		// Assign $this
		$result->variables['this'] = new Param(
			'this',
			null,
			new Name($this->classEnvironment->getName())
		);

		return $result;
	}
}

Make this a parameter of the function.

Make this a parameter of the function.


<?php
class pages extends CI_Controller {
    public function view($page = 'home')
    {
        if (! file_exists('/app/codeigniter/application/views/pages/' . $page . '.php'))
        {
            print("not found");
            show_404();
        }

        $data['title'] = ucfirst($page);  // Capitalize the first letter

        $this->load->view('templates/header', $data);
        $this->load->view('pages/' . $page, $data);
        $this->load->view('templates/footer', $data);
    }
}
?>

<?php
class pages extends CI_Controller {

    public function view($page = 'home')
    {
        if (! file_exists('/app/codeigniter/application/views/pages/' . $page . '.php'))
        {
            print("not found");
            show_404();
        }

        $data['title'] = ucfirst($page);  // Capitalize the first letter

        $this->load->view('templates/header', $data);

        $twilio = $this->config->item('twilio');

        if(empty($twilio['sid']) || empty($twilio['secret']))
            $this->load->view('pages/credentials', $data );
        else
            $this->load->view('pages/' . $page, $data);

        $this->load->view('templates/footer', $data);
    }

}
?>

Add conditional logic to home page.

Add conditional logic to home page.


<?php declare(strict_types=1);
/*.
    require_module 'standard';
    require_module 'json';
.*/

namespace App\Handler;

use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;

final class ApiError extends \Slim\Handlers\Error
{

    public function __invoke(Request $request, Response $response, \Exception $exception)
    {
        $statusCode = 500;
        if (is_int($exception->getCode()) && $exception->getCode() !== 0 && $exception->getCode() < 599) {
            $statusCode = $exception->getCode();
        }
        $className = new \ReflectionClass(get_class($exception));
        $data = [
        'message' => $exception->getMessage(),
        'status' => $className->getShortName(),
        'code' => $statusCode,
        'type' => 'error',
        'file' => $exception->getFile(),
        'line' => $exception->getLine()
        ];
        $body = json_encode($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
        error_log($body);
        return $response->withStatus($statusCode)->withHeader('Content-type', 'application/problem+json')->write($body);

    }

    /* End ApiError Class */
}

<?php declare(strict_types=1);
/*.
    require_module 'standard';
    require_module 'json';
.*/

namespace App\Handler;

use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;

final class ApiError extends \Slim\Handlers\Error
{

    public function __invoke(Request $request, Response $response, \Exception $exception)
    {
        $statusCode = 500;
        if (is_int($exception->getCode()) && $exception->getCode() !== 0 && $exception->getCode() < 599) {
            $statusCode = $exception->getCode();
        }
        $className = new \ReflectionClass(get_class($exception));
        $data = [
        'message' => $exception->getMessage(),
        'status' => $className->getShortName(),
        'code' => $statusCode,
        'type' => 'error',
        'file' => $exception->getFile(),
        'line' => $exception->getLine(),
        'trace' => $exception->getTraceAsString(),
        ];
        $body = json_encode($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
        error_log($body);
        return $response->withStatus($statusCode)->withHeader('Content-type', 'application/problem+json')->write($body);

    }

    /* End ApiError Class */
}

Add stack trace to api errors

Add stack trace to api errors


<?php

namespace Oro\Bundle\CalendarBundle\Migrations\Data\ORM;

use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\Common\DataFixtures\DependentFixtureInterface;

use Oro\Bundle\DashboardBundle\Migrations\Data\ORM\AbstractDashboardFixture;

class LoadDashboardData extends AbstractDashboardFixture implements DependentFixtureInterface
{
    /**
     * {@inheritdoc}
     */
    public function getDependencies()
    {
        return ['Oro\Bundle\DashboardBundle\Migrations\Data\ORM\LoadDashboardData'];
    }

    /**
     * {@inheritdoc}
     */
    public function load(ObjectManager $manager)
    {
        $mainDashboard = $this->findAdminDashboard($manager, 'main');

        if (!$mainDashboard) {
            $this->addNewDashboardWidget($manager, $mainDashboard, 'my_calendar')
                ->setLayoutPosition([1, 20]);

            $manager->flush();
        }
    }
}

<?php

namespace Oro\Bundle\CalendarBundle\Migrations\Data\ORM;

use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\Common\DataFixtures\DependentFixtureInterface;

use Oro\Bundle\DashboardBundle\Migrations\Data\ORM\AbstractDashboardFixture;

class LoadDashboardData extends AbstractDashboardFixture implements DependentFixtureInterface
{
    /**
     * {@inheritdoc}
     */
    public function getDependencies()
    {
        return ['Oro\Bundle\DashboardBundle\Migrations\Data\ORM\LoadDashboardData'];
    }

    /**
     * {@inheritdoc}
     */
    public function load(ObjectManager $manager)
    {
        $mainDashboard = $this->findAdminDashboard($manager, 'main');

        if ($mainDashboard) {
            $this->addNewDashboardWidget($manager, $mainDashboard, 'my_calendar')
                ->setLayoutPosition([1, 20]);

            $manager->flush();
        }
    }
}

BAP-3903: Create dashboard loading command
- fix typo


<?php echo w_template_title(); ?>

    <?php if (category_description()) :?>

<?php echo category_description(); ?>

    <?php endif; ?>

<?php if (have_posts()) : ?>
    <?php while (have_posts()) : ?>
        <?php the_post(); ?>
        <?php get_template_part('partials/article-list-item'); ?>
    <?php endwhile; ?>
<?php endif; ?>

    <?php get_template_part('partials/pager') ?>

<?php echo h()->w_template_title(); ?>

    <?php if (category_description()) :?>

<?php echo category_description(); ?>

    <?php endif; ?>

<?php if (have_posts()) : ?>
    <?php while (have_posts()) : ?>
        <?php the_post(); ?>
        <?php get_template_part('partials/article-list-item'); ?>
    <?php endwhile; ?>
<?php endif; ?>

    <?php get_template_part('partials/pager') ?>

Update w_template_title() to be h()->w_template_title()


<?php
/**
 * BEAR.Framework
 *
 * @license http://opensource.org/licenses/bsd-license.php BSD
 */
namespace BEAR\Framework\Resource\View;

use BEAR\Resource\Object as ResourceObject;
use BEAR\Resource\Requestable;
use BEAR\Resource\Renderable;

/**
 * Request renderer
 *
 * @package    BEAR.Framework
 * @subpackage View
 */
class JsonRenderer implements Renderable
{
    /**
     * (non-PHPdoc)
     * @see BEAR\Resource.Renderable::render()
     */
    public function render(ResourceObject $ro)
    {
        // evaluate all request in body.
        array_walk_recursive($ro->body, function(&$element) {
            if ($element instanceof Requestable) {
                $element = $element();
            }
        });
        $ro->view = @json_encode($ro->body, JSON_PRETTY_PRINT);

        return $ro->view;
    }
}

<?php
/**
 * BEAR.Framework
 *
 * @license http://opensource.org/licenses/bsd-license.php BSD
 */
namespace BEAR\Framework\Resource\View;

use BEAR\Resource\Object as ResourceObject;
use BEAR\Resource\Requestable;
use BEAR\Resource\Renderable;

/**
 * Request renderer
 *
 * @package    BEAR.Framework
 * @subpackage View
 */
class JsonRenderer implements Renderable
{
    /**
     * (non-PHPdoc)
     * @see BEAR\Resource.Renderable::render()
     */
    public function render(ResourceObject $ro)
    {
        // evaluate all request in body.
        if (is_array($ro->body) || $ro->body instanceof \Traversable) {
            array_walk_recursive($ro->body, function(&$element) {
                if ($element instanceof Requestable) {
                    $element = $element();
                }
            });
        }
        $ro->view = @json_encode($ro->body, JSON_PRETTY_PRINT);

        return $ro->view;
    }
}

Apply only for walkable contents.

Apply only for walkable contents.


<?php

namespace App\Commands;

class CreateAsset extends CreateSomething
{
    /** @var integer */
    protected $workspaceId;

    /** @var integer */
    protected $userId;

    /**
     * CreateAsset constructor.
     *
     * @param int $id
     * @param string $name
     * @param array $details
     * @param int $workspaceId
     * @param int $userId
     */
    public function __construct(int $id, string $name, array $details, int $workspaceId, int $userId)
    {
        parent::__construct($id, $name, $details);

        $this->workspaceId = $workspaceId;
        $this->userId      = $userId;
    }

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

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

<?php

namespace App\Commands;

class CreateAsset extends CreateSomething
{
}

Simplify this command, it was overcomplicated


<?php
if (defined('PHAST_SERVICE')) {
    $service = PHAST_SERVICE;
} else if (!isset ($_GET['service'])) {
    http_response_code(404);
    exit;
} else {
    $service = $_GET['service'];
}

if (isset ($_GET['src']) && !headers_sent())  {
    header('Location: ' . $_GET['src']);
} else {
    http_response_code(404);
    exit;
}

require_once __DIR__ . '/bootstrap.php';
$config = require_once PHAST_CONFIG_FILE;
$response = (new \Kibo\Phast\Factories\Services\ServicesFactory())
    ->make($service, $config)
    ->serve(\Kibo\Phast\HTTP\Request::fromGlobals());

header_remove('Location');
http_response_code($response->getCode());
foreach ($response->getHeaders() as $name => $value) {
    header($name . ': ' . $value);
}

echo $response->getContent();

<?php
if (defined('PHAST_SERVICE')) {
    $service = PHAST_SERVICE;
} else if (!isset ($_GET['service'])) {
    http_response_code(404);
    exit;
} else {
    $service = $_GET['service'];
}

if (isset ($_GET['src']) && !headers_sent())  {
    header('Location: ' . $_GET['src']);
} else {
    http_response_code(404);
    exit;
}

require_once __DIR__ . '/bootstrap.php';
$config = require_once PHAST_CONFIG_FILE;
try {

    $response = (new \Kibo\Phast\Factories\Services\ServicesFactory())
        ->make($service, $config)
        ->serve(\Kibo\Phast\HTTP\Request::fromGlobals());
} catch (\Kibo\Phast\Exceptions\UnauthorizedException $e) {
    exit();
}

header_remove('Location');
http_response_code($response->getCode());
foreach ($response->getHeaders() as $name => $value) {
    header($name . ': ' . $value);
}

echo $response->getContent();

Handle unauthorized exceptions (do not pollute error log)


<?php

class SV_WordCountSearch_XenForo_Model_Thread extends XFCP_SV_WordCountSearch_XenForo_Model_Thread
{
    public function getThreadmarkWordCountByThread($threadId)
    {
        $cache = \XenForo_Application::getCache();

        if ($cache)
        {
            $cacheKey = "SV_WordCountSearch_threadmarks_thread{$threadId}";

            $wordCount = unserialize($cache->load($cacheKey));

            if ($wordCount)
            {
                return $wordCount;
            }
        }

        $posts = $this->_getDb()->fetchAll("
            SELECT post_words.word_count
            FROM threadmarks
            INNER JOIN xf_post_words AS post_words ON
                (post_words.post_id = threadmarks.post_id)
            WHERE threadmarks.thread_id = ?
                AND threadmarks.message_state = 'visible'
        ", $threadId);

        $wordCount = 0;
        foreach ($posts as $post)
        {
            $wordCount += $post['word_count'];
        }

        if ($cache)
        {
            $cache->save(serialize($wordCount), $cacheKey, array(), 14400);
        }

        return $wordCount;
    }
}

<?php

class SV_WordCountSearch_XenForo_Model_Thread extends XFCP_SV_WordCountSearch_XenForo_Model_Thread
{
    /**
     * The TTL for cached thread word count queries. Default is 4 hours.
     */
    const WORD_COUNT_CACHE_TTL = 14400;

    public function getThreadmarkWordCountByThread($threadId)
    {
        $cache = \XenForo_Application::getCache();

        if ($cache)
        {
            $cacheKey = "SV_WordCountSearch_threadmarks_thread{$threadId}";

            $wordCount = unserialize($cache->load($cacheKey));

            if ($wordCount)
            {
                return $wordCount;
            }
        }

        $posts = $this->_getDb()->fetchAll("
            SELECT post_words.word_count
            FROM threadmarks
            INNER JOIN xf_post_words AS post_words ON
                (post_words.post_id = threadmarks.post_id)
            WHERE threadmarks.thread_id = ?
                AND threadmarks.message_state = 'visible'
        ", $threadId);

        $wordCount = 0;
        foreach ($posts as $post)
        {
            $wordCount += $post['word_count'];
        }

        if ($cache)
        {
            $cache->save(
                (string) $wordCount,
                $cacheKey,
                array(),
                self::WORD_COUNT_CACHE_TTL
            );
        }

        return $wordCount;
    }
}

Update thread query cache logic

Update thread query cache logic

- Move TTL to class constant
- Cast count to string instead of serializing


#!/usr/bin/env php
<?php
/**
 * @package Smrtr\MysqlVersionControl\Bin
 * @author Joe Green <joe.green@smrtr.co.uk>
 */

require_once realpath(dirname(__FILE__).'/../../../autoload.php');

$app = new \Symfony\Component\Console\Application('smyver');

$app->add(new \Smrtr\MysqlVersionControl\Command\Up);
$app->add(new \Smrtr\MysqlVersionControl\Command\Teardown);

$app->run();

#!/usr/bin/env php
<?php
/**
 * @package Smrtr\MysqlVersionControl\Bin
 * @author Joe Green <joe.green@smrtr.co.uk>
 */

require_once realpath(dirname(__FILE__).'/../../../autoload.php');

$app = new \Symfony\Component\Console\Application('smyver');

$app->add(new \Smrtr\MysqlVersionControl\Command\Status);
$app->add(new \Smrtr\MysqlVersionControl\Command\Up);
$app->add(new \Smrtr\MysqlVersionControl\Command\Teardown);

$app->run();

Add status command to CLI app

Add status command to CLI app


<?php
class Infusionsoft_RecurringOrder extends Infusionsoft_Generated_RecurringOrder{
    var $customFieldFormId = -10;
    public function __construct($id = null, $app = null){
    	parent::__construct($id, $app);
    }

    //Find the Id first order charged for this subscription
    public static function getFirstOrderId ($recurringOrderId) {
        //load recurringOrder
        $recurringOrder = new Infusionsoft_RecurringOrder($recurringOrderId);

        //If there was an originating shopping cart or order form order, that is the first order
        if ($recurringOrder->OriginatingOrderId != 0) {
            return $recurringOrder->OriginatingOrderId;
        } else {
            //find all Orders with a matching JobRecurringId and put them in this array, sorted by date.
            $matchingOrders = Infusionsoft_DataService::queryWithOrderBy(new Infusionsoft_Job(), array('JobRecurringId' => $recurringOrderId),'DateCreated');

            $earliestMatchingOrder = array_shift($matchingOrders);
            return $earliestMatchingOrder->Id;
        }
    }
}

<?php
class Infusionsoft_RecurringOrder extends Infusionsoft_Generated_RecurringOrder{
    var $customFieldFormId = -10;
    public function __construct($id = null, $app = null){
    	parent::__construct($id, $app);
    }

    //Find the Id first order charged for this subscription
    public static function getFirstOrderId ($recurringOrderId) {
        //load recurringOrder
        $recurringOrder = new Infusionsoft_RecurringOrder($recurringOrderId);

        //If there was an originating shopping cart or order form order, that is the first order
        if ($recurringOrder->OriginatingOrderId != 0) {
            return $recurringOrder->OriginatingOrderId;
        } else {
            //find all Orders with a matching JobRecurringId and put them in this array, sorted by date.
            $matchingOrders = Infusionsoft_DataService::queryWithOrderBy(new Infusionsoft_Job(), array('JobRecurringId' => $recurringOrderId),'DateCreated');

            if (!empty($matchingOrders)){
                $earliestMatchingOrder = array_shift($matchingOrders);
                return $earliestMatchingOrder->Id;
            } else {
                return false;
            }

        }
    }
}

Add empty check to earliestMatchingOrder query. This was throwing an error when the subscription was brand-new and had no orders yet


<?php
class Kwc_Chained_Start_Component extends Kwc_Abstract
{
    public static function getSettings()
    {
        $ret = parent::getSettings();
        $ret['flags']['hasAllChainedByMaster'] = true;
        return $ret;
    }

    public static function validateSettings($settings, $componentClass)
    {
        parent::validateSettings($settings, $componentClass);
        if (!isset($settings['flags']['chainedType']) || !is_string($settings['flags']['chainedType'])) {
            throw new Kwf_Exception("Flag 'chainedType' not set for '$componentClass'.");
        }
    }

    public static function getAllChainedByMasterFromChainedStart($componentClass, $master, $chainedType, $parentDataSelect = array())
    {
        if (Kwc_Abstract::getFlag($componentClass, 'chainedType') != $chainedType) return array();
        $ret = array();
        foreach (Kwf_Component_Data_Root::getInstance()->getComponentsByClass($componentClass, $parentDataSelect) as $chainedStart) {
            //if additional subroots are above trl subroot (eg. domains)
            if ($sr = $chainedStart->parent->getSubroot()) {
                if ($sr != $master->getSubroot()->parent->getSubroot()) {
                    continue;
                }
            }
            $i = Kwc_Chained_Abstract_Component::getChainedByMaster($master, $chainedStart, $chainedType, $parentDataSelect);
            if ($i) $ret[] = $i;
        }
        return $ret;
    }
}

<?php
class Kwc_Chained_Start_Component extends Kwc_Abstract
{
    public static function getSettings()
    {
        $ret = parent::getSettings();
        $ret['flags']['hasAllChainedByMaster'] = true;
        return $ret;
    }

    public static function validateSettings($settings, $componentClass)
    {
        parent::validateSettings($settings, $componentClass);
        if (!isset($settings['flags']['chainedType']) || !is_string($settings['flags']['chainedType'])) {
            throw new Kwf_Exception("Flag 'chainedType' not set for '$componentClass'.");
        }
    }

    public static function getAllChainedByMasterFromChainedStart($componentClass, $master, $chainedType, $parentDataSelect = array())
    {
        if (Kwc_Abstract::getFlag($componentClass, 'chainedType') != $chainedType) return array();
        $ret = array();
        foreach (Kwf_Component_Data_Root::getInstance()->getComponentsByClass($componentClass, $parentDataSelect) as $chainedStart) {
            //if additional subroots are above trl subroot (eg. domains)
            if ($sr = $chainedStart->parent->getSubroot()) {
                $masterSr = $master->getSubroot();
                if ($masterSr->parent && $sr != $masterSr->parent->getSubroot()) {
                    continue;
                }
            }
            $i = Kwc_Chained_Abstract_Component::getChainedByMaster($master, $chainedStart, $chainedType, $parentDataSelect);
            if ($i) $ret[] = $i;
        }
        return $ret;
    }
}

Fix getChainedByMaster if there are not additional subroots

fixes test


<?php
/*
 * Copyright (c) 2012 David Negrier
 *
 * See the file LICENSE.txt for copying permission.
 */

require_once __DIR__."/../../../autoload.php";

use Mouf\Actions\InstallUtils;
use Mouf\MoufManager;

// Let's init Mouf
InstallUtils::init(InstallUtils::$INIT_APP);

// Let's create the instance
$moufManager = MoufManager::getMoufManager();
if (!$moufManager->instanceExists("userService")) {
	$userService = $moufManager->createInstance("Mouf\\Security\\UserService\\UserService");
	$userService->setName("userService");
	if ($moufManager->instanceExists("errorLogLogger")) {
		$userService->getProperty("log")->setValue($moufManager->getInstanceDescriptor("errorLogLogger"));
	}
	if ($moufManager->instanceExists("sessionManager")) {
		$userService->getProperty("sessionManager")->setValue($moufManager->getInstanceDescriptor("sessionManager"));
	}
}

// Let's rewrite the MoufComponents.php file to save the component
$moufManager->rewriteMouf();

// Finally, let's continue the install
InstallUtils::continueInstall();
?>

<?php
/*
 * Copyright (c) 2012 David Negrier
 *
 * See the file LICENSE.txt for copying permission.
 */

require_once __DIR__."/../../../autoload.php";

use Mouf\Actions\InstallUtils;
use Mouf\MoufManager;

// Let's init Mouf
InstallUtils::init(InstallUtils::$INIT_APP);

// Let's create the instance
$moufManager = MoufManager::getMoufManager();
if (!$moufManager->instanceExists("userService")) {
	$userService = $moufManager->createInstance("Mouf\\Security\\UserService\\UserService");
	$userService->setName("userService");
	if ($moufManager->instanceExists("errorLogLogger")) {
		$userService->getProperty("log")->setValue($moufManager->getInstanceDescriptor("errorLogLogger"));
	}
	if ($moufManager->instanceExists("sessionManager")) {
		$userService->getProperty("sessionManager")->setValue($moufManager->getInstanceDescriptor("sessionManager"));
	}
	$userService->getProperty('sessionPrefix')->setValue('ROOT_URL')->setOrigin('config');
}

// Let's rewrite the MoufComponents.php file to save the component
$moufManager->rewriteMouf();

// Finally, let's continue the install
InstallUtils::continueInstall();
?>

Add value ROOT_URL for sessionPrefix

Add value ROOT_URL for sessionPrefix


<?php
namespace Codeception\Module;

/**
 * WordPress helper will download and install WordPress if it is not installed then install and activate plugin
 * When it tears down, it will deactivate the plugin and delete it from WordPress,
 * but will not delete the WordPress files.
 */

class WordPressHelper extends \Codeception\Module
{
    private $path_to_wordpress = '/var/www/html/';
    private $database_name = 'wordpress';

    public function _beforeSuite() {
        if (!file_exists("{$this->path_to_wordpress}wp-config-sample.php")) {
            exec("wp core download --path={$this->path_to_wordpress}");
        }
        $db = new \mysqli('db', 'root', $_ENV['DB_ENV_MYSQL_ROOT_PASSWORD']);
        $db->prepare("CREATE DATABASE {$this->database_name};")->execute();
    }

    public function _afterSuite() {
        $db = new \mysqli('db', 'root', $_ENV['DB_ENV_MYSQL_ROOT_PASSWORD']);
        $db->prepare("DROP DATABASE {$this->database_name};")->execute();
    }
}

<?php
namespace Codeception\Module;

/**
 * WordPress helper will download and install WordPress if it is not installed then install and activate plugin
 * When it tears down, it will deactivate the plugin and delete it from WordPress,
 * but will not delete the WordPress files.
 */

class WordPressHelper extends \Codeception\Module
{
    private $path_to_wordpress = '/var/www/html/';
    private $database_name = 'wordpress';
    private $database_host = 'db';
    private $database_user = 'root';

    public function _beforeSuite() {
        if (!file_exists("{$this->path_to_wordpress}wp-config-sample.php")) {
            exec("wp core download --path={$this->path_to_wordpress}");
        }
        $db = new \mysqli($this->database_host, 'root', $_ENV['DB_ENV_MYSQL_ROOT_PASSWORD']);
        $db->prepare("CREATE DATABASE {$this->database_name};")->execute();

        exec("wp core config --path={$this->path_to_wordpress} --dbname={$this->database_name}
                --dbuser={$this->database_user} --dbpass={$_ENV['DB_ENV_MYSQL_ROOT_PASSWORD']}
                --dbhost={$this->database_host}");
        exec('wp core install --url=localhost --title="just a wordpress site" --admin_user=a
            --admin_password=a --admin_email="a@a.a" --skip-email');
    }

    public function _afterSuite() {
        $db = new \mysqli('db', 'root', $_ENV['DB_ENV_MYSQL_ROOT_PASSWORD']);
        $db->prepare("DROP DATABASE {$this->database_name};")->execute();
    }
}

Install WordPress before running testing


<?php

class CM_InputStream_AbstractTest extends CMTest_TestCase {

    public function testRead() {
        $input = $this->getMockBuilder('CM_InputStream_Abstract')->setMethods(array('_read'))->getMockForAbstractClass();
        $input->expects($this->exactly(3))->method('_read')->will($this->onConsecutiveCalls('foo', 'foo', 'bar'));
        $input->expects($this->at(0))->method('_read')->with('Hint ');
        $input->expects($this->at(1))->method('_read')->with(null);
        $input->expects($this->at(2))->method('_read')->with(null);

        /** @var $input CM_InputStream_Abstract */
        $this->assertSame('foo', $input->read('Hint'));
        $this->assertSame('foo', $input->read());
        $this->assertSame('bar', $input->read(null, 'bar'));
    }

    public function testConfirm() {
        $input = $this->getMockBuilder('CM_InputStream_Abstract')->setMethods(array('read'))->getMockForAbstractClass();
        $input->expects($this->exactly(3))->method('read')->with('Hint (y/n)', 'default')->will($this->onConsecutiveCalls('invalid value', 'y', 'n'));

        /** @var $input CM_InputStream_Abstract */
        $this->assertTrue($input->confirm('Hint', 'default'));
        $this->assertFalse($input->confirm('Hint', 'default'));
    }
}

<?php

class CM_InputStream_AbstractTest extends CMTest_TestCase {

    public function testRead() {
        $input = $this->mockClass('CM_InputStream_Abstract')->newInstance();
        $readMethod = $input->mockMethod('_read')
            ->at(0, function ($hint) {
                $this->assertSame('Hint ', $hint);
                return 'foo';
            })
            ->at(1, function ($hint) {
                $this->assertNull($hint);
                return '';
            });
        /** @var $input CM_InputStream_Abstract */
        $this->assertSame('foo', $input->read('Hint'));
        $this->assertSame('bar', $input->read(null, 'bar'));
        $this->assertSame(2, $readMethod->getCallCount());
    }

    public function testConfirm() {
        $input = $this->getMockBuilder('CM_InputStream_Abstract')->setMethods(array('read'))->getMockForAbstractClass();
        $input->expects($this->exactly(3))->method('read')->with('Hint (y/n)', 'default')->will($this->onConsecutiveCalls('invalid value', 'y', 'n'));

        /** @var $input CM_InputStream_Abstract */
        $this->assertTrue($input->confirm('Hint', 'default'));
        $this->assertFalse($input->confirm('Hint', 'default'));
    }
}

Adjust tests to use mocka

Adjust tests to use mocka


<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Request;
use Ramsey\Uuid\Uuid;

class UserController extends Controller
{
    public function icon($user)
    {
        if (!Uuid::isValid($user)) {
            abort(422);
        }

        try {
            $user = User::findOrFail($user);
            $file = $user->icon ? $user->icon : '/images/user.png';
            return response()->file(public_path($file));
        } catch (ModelNotFoundException $e) {
            abort(404);
        }
    }

    public function index(Request $request)
    {
        $offset = intval($request->input('start', 0));
        $users = User::select(['user_id', 'display_name'])
            ->offset(is_int($offset) ? $offset : 0)
            ->take(10)
            ->get();
        return view('user/index', ['users' => $users, 'title' => 'View User']);
    }

    public function create()
    {
        return view('user/create', ['title' => 'Create User']);
    }

    public function show($user)
    {
        try {
            $user = User::findOrFail($user);
            return view('user/show', ['theUser' => $user]);
        } catch (ModelNotFoundException $e) {
            abort(404);
        }
    }
}

<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Request;
use Ramsey\Uuid\Uuid;

class UserController extends Controller
{
    public function icon($user)
    {
        if (!Uuid::isValid($user)) {
            abort(422);
        }

        try {
            $user = User::findOrFail($user);
            $file = $user->icon ? $user->icon : '/images/user.png';
            return response()->file(public_path($file));
        } catch (ModelNotFoundException $e) {
            abort(404);
        }
    }

    public function index(Request $request)
    {
        $offset = intval($request->input('start', 0));
        $users = User::select(['user_id', 'display_name'])
            ->offset(is_int($offset) ? $offset : 0)
            ->take(10)
            ->get();
        return view('user/index', ['users' => $users, 'title' => 'View User']);
    }

    public function create()
    {
        return view('user/create', ['title' => 'Create User']);
    }

    public function show($user)
    {
        try {
            if (!Uuid::isValid($user)) {
                abort(422);
            }
            $user = User::with('roles')->with('permissions')->findOrFail($user);
            return view('user/show', ['theUser' => $user]);
        } catch (ModelNotFoundException $e) {
            abort(404);
        }
    }
}

Add relationship to user show view

Add relationship to user show view


<?php
namespace Concrete\Core\Area\Layout\Preset\Provider;

use Concrete\Core\Foundation\Service\Provider as ServiceProvider;

class ManagerServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->app->singleton('manager/area_layout_preset_provider', function($app) {
            $manager = new Manager($app);
            $manager->register(new UserProvider());
            $manager->register(new ActiveThemeProvider());

            return $manager;
        });
    }
}

<?php

namespace Concrete\Core\Area\Layout\Preset\Provider;

use Concrete\Core\Foundation\Service\Provider as ServiceProvider;
use Concrete\Core\Application\Application;

class ManagerServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->app->singleton(
            Manager::class,
            static function(Application $app): Manager {
                $manager = new Manager($app);
                $manager->register(new UserProvider());
                $manager->register(new ActiveThemeProvider());
                return $manager;
            }
        );
        $this->app->alias(Manager::class, 'manager/area_layout_preset_provider');
    }
}

Make the layout preset provider a singleton


<?php
// vim: set ai ts=4 sw=4 ft=php:
//
// License for all code of this FreePBX module can be found in the license file inside the module directory
// Copyright 2006-2014 Schmooze Com Inc.

// Intelligence goes here to detect system types.
// This should be included from every class in Dash2.

$this->systemtype = "linux";

<?php
// vim: set ai ts=4 sw=4 ft=php:
//
// License for all code of this FreePBX module can be found in the license file inside the module directory
// Copyright 2006-2014 Schmooze Com Inc.

// Intelligence goes here to detect system types.
// This should be included from every class in Dash2.

if (PHP_OS == "FreeBSD") {
	$this->systemtype = "freebsd";
} else {
	$this->systemtype = "linux";
}

Support identification of FreeBSD systems


<?php

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

class CreateRecruitingCampaignTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('recruiting_campaign', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->integer('notification_template_id');

            $table->integer('created_by');
            $table->timestamps();

            $table->foreign('created_by')->references('id')->on('users');
            $table->foreign('notification_template_id')->references('id')->on('notification_templates');
        });
    }

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

<?php

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

class CreateRecruitingCampaignTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('recruiting_campaigns', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->enum('status', ['new', 'in_progress', 'completed']);
            $table->unsignedInteger('notification_template_id')->nullable();

            $table->unsignedInteger('created_by');
            $table->timestamps();

            $table->foreign('created_by')->references('id')->on('users');
            $table->foreign('notification_template_id')->references('id')->on('notification_templates');
        });
    }

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

Add `status` column; some nullables; typos


<?php
/*
 * Base Controller
 */

use FelixOnline\Core;

class BaseController {
	protected $theme; // placeholder for theme class
	protected $db;

	function __construct() {
		global $db;
		global $safesql;
		$this->db = $db;
		$this->safesql = $safesql;

		/*
		 * Set theme here so that it can be overridden by a controller if necessary
		 */
		$theme = new Core\Theme('2014');
		$this->theme = $theme->getClass(); // used so that theme can specify a theme class if necessary
		$this->theme->setSite('main');
	}
}

<?php
/*
 * Base Controller
 */

use FelixOnline\Core;

class BaseController {
	protected $theme; // placeholder for theme class
	protected $db;

	function __construct() {
		global $db;
		global $safesql;
		$this->db = $db;
		$this->safesql = $safesql;

		/*
		 * Set theme here so that it can be overridden by a controller if necessary
		 */
		$theme = new Core\Theme('2014');
		$this->theme = $theme->getClass(); // used so that theme can specify a theme class if necessary
		$this->theme->setSite('main');
	}

	function HEAD($matches)
	{
		// Used by updowntester
		ob_end_flush();
		exit;
	}
}

Implement support for the HEAD method in controllers


<?php
namespace DlcCategory\Entity;

/**
 * The category entity interface
 */
interface CategoryInterface
{
    /**
     * Getter for $id
     *
     * @return int $id
     */
    public function getId();

    /**
     * Setter for $id
     *
     * @param int $id
     */
    public function setId($id);

    /**
     * Getter for $name
     *
     * @return string $name
     */
    public function getName();

    /**
     * Setter for $name
     *
     * @param string $name
     */
    public function setName($name);

    /**
     * Getter for $title
     *
     * @return string $title
     */
    public function getTitle();

    /**
     * Setter for $title
     *
     * @param string $title
     */
    public function setTitle($title);

    /**
     * Getter for $description
     *
     * @return string $description
     */
    public function getDescription();

    /**
     * Setter for $description
     *
     * @param string $description
     */
    public function setDescription($description);

    /**
     * Getter for $thumbnail
     *
     * @return string $thumbnail
     */
    public function getThumbnail();

    /**
     * Setter for $thumbnail
     *
     * @param  string $thumbnail
     * @return Category
     */
    public function setThumbnail($thumbnail);
}

<?php
namespace DlcCategory\Entity;

/**
 * The category entity interface
 */
interface CategoryInterface
{
    /**
     * Setter for $id
     *
     * @param int $id
     */
    public function setId($id);

    /**
     * Getter for $name
     *
     * @return string $name
     */
    public function getName();

    /**
     * Setter for $name
     *
     * @param string $name
     */
    public function setName($name);

    /**
     * Getter for $title
     *
     * @return string $title
     */
    public function getTitle();

    /**
     * Setter for $title
     *
     * @param string $title
     */
    public function setTitle($title);

    /**
     * Getter for $description
     *
     * @return string $description
     */
    public function getDescription();

    /**
     * Setter for $description
     *
     * @param string $description
     */
    public function setDescription($description);

    /**
     * Getter for $thumbnail
     *
     * @return string $thumbnail
     */
    public function getThumbnail();

    /**
     * Setter for $thumbnail
     *
     * @param  string $thumbnail
     * @return Category
     */
    public function setThumbnail($thumbnail);
}

Remove getId() from category interace because it already exists in the node interface


<?php

namespace Frontend\Modules\Search\Widgets;

/*
 * This file is part of Fork CMS.
 *
 * For the full copyright and license information, please view the license
 * file that was distributed with this source code.
 */

use Frontend\Core\Engine\Base\Widget as FrontendBaseWidget;
use Frontend\Core\Engine\Form as FrontendForm;
use Frontend\Core\Engine\Navigation as FrontendNavigation;

/**
 * This is a widget with the search form
 */
class Form extends FrontendBaseWidget
{
    /**
     * @var FrontendForm
     */
    private $frm;

    /**
     * Execute the extra
     */
    public function execute()
    {
        parent::execute();
        $this->loadTemplate();
        $this->loadForm();
        $this->parse();
    }

    /**
     * Load the form
     */
    private function loadForm()
    {
        $this->frm = new FrontendForm('search', FrontendNavigation::getURLForBlock('Search'), 'get', null, false);
        $widgetField = $this->frm->addText('q_widget');

        $widgetField->setAttributes(
            array(
                'itemprop' => 'query-input',
                'data-role' => 'fork-widget-search-field',
            )
        );
    }

    /**
     * Parse the data into the template
     */
    private function parse()
    {
        $this->addJS('/js/vendors/typeahead.bundle.min.js', 'Core', false, true);
        $this->addCSS('Search.css');
        $this->frm->parse($this->tpl);
    }
}

<?php

namespace Frontend\Modules\Search\Widgets;

/*
 * This file is part of Fork CMS.
 *
 * For the full copyright and license information, please view the license
 * file that was distributed with this source code.
 */

use Frontend\Core\Engine\Base\Widget as FrontendBaseWidget;
use Frontend\Core\Engine\Form as FrontendForm;
use Frontend\Core\Engine\Navigation as FrontendNavigation;

/**
 * This is a widget with the search form
 */
class Form extends FrontendBaseWidget
{
    /**
     * @var FrontendForm
     */
    private $frm;

    /**
     * Execute the extra
     */
    public function execute()
    {
        parent::execute();
        $this->loadTemplate();
        $this->loadForm();
        $this->parse();
    }

    /**
     * Load the form
     */
    private function loadForm()
    {
        $this->frm = new FrontendForm('search', FrontendNavigation::getURLForBlock('Search'), 'get', null, false);
        $widgetField = $this->frm->addText('q_widget');

        $widgetField->setAttributes(
            array(
                'itemprop' => 'query-input',
                'data-role' => 'fork-widget-search-field',
            )
        );
    }

    /**
     * Parse the data into the template
     */
    private function parse()
    {
        $this->addJS('/js/vendors/typeahead.bundle.min.js', true, false);
        $this->addCSS('Search.css');
        $this->frm->parse($this->tpl);
    }
}

Fix loading the typeahead js in the search widget


<?php if(!isset($category)): ?>

write for us

Interested in becoming a news reporter? Or just have a favourite something to share with Imperial? Write for Felix - it's easy!

Got a tip you'd like to share? We welcome anonymous messages too.

				<a class="button" href="<?php echo STANDARD_URL; ?>issuearchive/">Find out how to contribute
			<?php else: ?>

write for <?php echo $category->getLabel(); ?>

TO BE IMPLEMENTED!!!

			<?php endif; ?>

<?php if(!isset($category)): ?>

write for us

Interested in becoming a news reporter? Or just have a favourite something to share with Imperial? Write for Felix - it's easy!

Got a tip you'd like to share? We welcome anonymous messages too.

					<a class="button small" href="<?php echo STANDARD_URL; ?>issuearchive/">Find out how to contribute

			<?php else: ?>

write for <?php echo $category->getLabel(); ?>

Want to write for this section? Drop the editors a line via the contact details above and they'll let you how to get involved - contributors always welcome!

			<?php endif; ?>

Tidy up of contrib policy

Tidy up of contrib policy


<?php

class Vocabulary extends Model {
    public function get_set() {
        return $this->belongs_to('Set');
    }

    /**
     * Filters
     */

    public static function active($orm) {
        return $orm->where_gte('level', 0)->order_by_asc('due');
    }

    public static function inactive($orm) {
        return $orm->where_lt('level', 0)->order_by_asc('id');
    }

    public static function level($orm, $min, $max) {
        return $orm->where_gte('level', $min)->where_lte('level', $max);
    }

    public static function due($orm) {
        return $orm->filter('active')->where_lte('due', date('Y-m-d H:i:s'));
    }

    public static function due_tomorrow($orm) {
        $datetime = new DateTime('tomorrow');
        return $orm->filter('active')->where_lte('due', $datetime->format('Y-m-d H:i:s'));
    }

    public static function learned_today($orm) {
        return $orm->filter('active')->where('init_date', date('Y-m-d'));
    }
}

<?php

class Vocabulary extends Model {
    public function get_set() {
        return $this->belongs_to('Set');
    }

    public function get_human_due_date() {
        // TODO
        return $this->due;
    }

    /**
     * Filters
     */

    public static function active($orm) {
        return $orm->where_gte('level', 0)->order_by_asc('due');
    }

    public static function inactive($orm) {
        return $orm->where_lt('level', 0)->order_by_asc('id');
    }

    public static function level($orm, $min, $max) {
        return $orm->where_gte('level', $min)->where_lte('level', $max);
    }

    public static function in_set($orm, $set) {
        if (!$set) return $orm;
        return $orm->where('set_id', $set->id);
    }

    public static function due($orm) {
        return $orm->filter('active')->where_lte('due', date('Y-m-d H:i:s'));
    }

    public static function due_tomorrow($orm) {
        $datetime = new DateTime('tomorrow');
        return $orm->filter('active')->where_lte('due', $datetime->format('Y-m-d H:i:s'));
    }

    public static function learned_today($orm) {
        return $orm->filter('active')->where('init_date', date('Y-m-d'));
    }
}

Add some more filters & methods

Add some more filters & methods


<?php

namespace Oro\Bundle\ActivityListBundle;

use Oro\Bundle\ActivityListBundle\DependencyInjection\Compiler\AddStrategyCompilerPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Bundle\Bundle;

use Oro\Bundle\ActivityListBundle\DependencyInjection\Compiler\ActivityListProvidersPass;

class OroActivityListBundle extends Bundle
{
    /**
     * {@inheritdoc}
     */
    public function build(ContainerBuilder $container)
    {
        parent::build($container);

        $container->addCompilerPass(new ActivityListProvidersPass());
    }
}

<?php

namespace Oro\Bundle\ActivityListBundle;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Bundle\Bundle;

use Oro\Bundle\ActivityListBundle\DependencyInjection\Compiler\ActivityListProvidersPass;

class OroActivityListBundle extends Bundle
{
    /**
     * {@inheritdoc}
     */
    public function build(ContainerBuilder $container)
    {
        parent::build($container);

        $container->addCompilerPass(new ActivityListProvidersPass());
    }
}

CRM-4138: Append or replace activities on account merge
- cleanup


<?php namespace ThibaudDauce\MoloquentInheritance;

use Illuminate\Database\Eloquent\ScopeInterface;
use Illuminate\Database\Eloquent\Builder;

class MoloquentInheritanceScope implements ScopeInterface {

	/**
	 * All of the extensions to be added to the builder.
	 *
	 * @var array
	 */
	protected $extensions = ['OnlyParent'];

	/**
	 * Apply the scope to a given Eloquent query builder.
	 *
	 * @param  \Illuminate\Database\Eloquent\Builder  $builder
	 * @return void
	 */
	public function apply(Builder $builder)
	{
	}

	/**
	 * Remove the scope from the given Eloquent query builder.
	 *
	 * @param  \Illuminate\Database\Eloquent\Builder  $builder
	 * @return void
	 */
	public function remove(Builder $builder)
	{
	}

	/**
	 * Extend the query builder with the needed functions.
	 *
	 * @param  \Illuminate\Database\Eloquent\Builder  $builder
	 * @return void
	 */
	public function extend(Builder $builder)
	{
	}

	/**
	 * Add the only-trashed extension to the builder.
	 *
	 * @param  \Illuminate\Database\Eloquent\Builder  $builder
	 * @return void
	 */
	protected function addOnlyParent(Builder $builder)
	{
	}
}

<?php namespace ThibaudDauce\MoloquentInheritance;

use Illuminate\Database\Eloquent\ScopeInterface;
use Illuminate\Database\Eloquent\Builder;

class MoloquentInheritanceScope implements ScopeInterface {

	/**
	 * All of the extensions to be added to the builder.
	 *
	 * @var array
	 */
	protected $extensions = ['OnlyParent'];

	/**
	 * Apply the scope to a given Eloquent query builder.
	 *
	 * @param  \Illuminate\Database\Eloquent\Builder  $builder
	 * @return void
	 */
	public function apply(Builder $builder)
	{
    $builder->where('parent_classes', 'all', [static::class]);
	}

	/**
	 * Remove the scope from the given Eloquent query builder.
	 *
	 * @param  \Illuminate\Database\Eloquent\Builder  $builder
	 * @return void
	 */
	public function remove(Builder $builder)
	{
	}

	/**
	 * Extend the query builder with the needed functions.
	 *
	 * @param  \Illuminate\Database\Eloquent\Builder  $builder
	 * @return void
	 */
	public function extend(Builder $builder)
	{
	}

	/**
	 * Add the only-trashed extension to the builder.
	 *
	 * @param  \Illuminate\Database\Eloquent\Builder  $builder
	 * @return void
	 */
	protected function addOnlyParent(Builder $builder)
	{
	}
}

Add where clause in moloquent inheritance scope


<?php

namespace Vivait\DelayedEventBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * This is the class that validates and merges configuration from your app/config files
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
 */
class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritDoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('vivait_delayed_event');

        $rootNode
            ->children()
                ->scalarNode('queue_transport')
//                    ->validate()
//                    ->ifTrue(function($value) { return !$this->container->hasDefinition('vivait_inspector.queue.'. $value); })
//                        ->thenInvalid('Invalid queue transport "%s"')
//                    ->end()
                ->end()
                ->scalarNode('serializer')
//                    ->validate()
//                    ->ifTrue(function($value) { return !$this->container->hasDefinition('vivait_inspector.serializer.'. $value); })
//                        ->thenInvalid('Invalid serializer "%s"')
//                    ->end()
                ->end()
            ->end()
        ->end();

        return $treeBuilder;
    }
}

<?php

namespace Vivait\DelayedEventBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * This is the class that validates and merges configuration from your app/config files
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
 */
class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritDoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('vivait_delayed_event');

        $rootNode
            ->children()
                ->scalarNode('queue_transport')
                    ->defaultValue('beanstalkd')
//                    ->validate()
//                    ->ifTrue(function($value) { return !$this->container->hasDefinition('vivait_inspector.queue.'. $value); })
//                        ->thenInvalid('Invalid queue transport "%s"')
//                    ->end()
                ->end()
//                ->scalarNode('serializer')
////                    ->validate()
////                    ->ifTrue(function($value) { return !$this->container->hasDefinition('vivait_inspector.serializer.'. $value); })
////                        ->thenInvalid('Invalid serializer "%s"')
////                    ->end()
//                ->end()
            ->end()
        ->end();

        return $treeBuilder;
    }
}

Set default for queue transport.

Set default for queue transport.


Fix country config for google books harvesting

(should have been part of 5d5652b0)


@extends('emails.template')

@section('content')
    Here's your weekly report for {{ $space->name }}.

    This week (#{{ $week }}) you've

Spent CURRENCY {{ number_format($totalSpent / 100, 2) }}

        @if (count($largestSpendingWithTag))

Most of which you've spent on {{ $largestSpendingWithTag[0]->tag_name }} (CURRENCY {{ number_format($largestSpendingWithTag[0]->amount / 100, 2) }})

        @endif

    If you don't want to receive a weekly report, head over to settings and let us know.
@endsection

@extends('emails.template')

@section('content')
    Here's your weekly report for {{ $space->name }}.

    This week (#{{ $week }}) you've

Spent {!! $space->currency->symbol !!} {{ number_format($totalSpent / 100, 2) }}

        @if (count($largestSpendingWithTag))

Most of which you've spent on {{ $largestSpendingWithTag[0]->tag_name }} ({!! $space->currency->symbol !!} {{ number_format($largestSpendingWithTag[0]->amount / 100, 2) }})

        @endif

    If you don't want to receive a weekly report, head over to settings and let us know.
@endsection

Make WeeklyReport mail use currency related to space it's reporting on


<?php

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

class AppKernel extends Kernel
{
    public function registerBundles()
    {
        $bundles = array(
            new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
            new Symfony\Bundle\SecurityBundle\SecurityBundle(),
            new Symfony\Bundle\TwigBundle\TwigBundle(),
            new Symfony\Bundle\MonologBundle\MonologBundle(),
            new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
            new Symfony\Bundle\AsseticBundle\AsseticBundle(),
            new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
            new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
            new Hermes\ReportBundle\HermesReportBundle(),
            new Hermes\ModelBundle\HermesModelBundle(),
        );

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

        return $bundles;
    }

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

<?php

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

class AppKernel extends Kernel
{
    public function registerBundles()
    {
        $bundles = array(
            new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
            new Symfony\Bundle\SecurityBundle\SecurityBundle(),
            new Symfony\Bundle\TwigBundle\TwigBundle(),
            new Symfony\Bundle\MonologBundle\MonologBundle(),
            new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
            new Symfony\Bundle\AsseticBundle\AsseticBundle(),
            new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
            new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
            new Hermes\ReportBundle\HermesReportBundle(),
            new Hermes\ModelBundle\HermesModelBundle(),
        );

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

        return $bundles;
    }

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

Remove ACME bundle (default one in symfony)