<?php

namespace Amelia\Rememberable;

use Amelia\Rememberable\Query\Builder as QueryBuilder;
use Amelia\Rememberable\Eloquent\Builder as EloquentBuilder;
use Illuminate\Database\Eloquent\Model;

trait Rememberable
{
    protected static function bootRememberable()
    {
        if (static::rememberable()) {
            static::saving(function (Model $model) {
                $model->flush(get_class($model).':'.$model->getKey());
            });
        }
    }

    /**
     * Get a new query builder instance for the connection.
     *
     * @return \Illuminate\Database\Query\Builder
     */
    protected function newBaseQueryBuilder()
    {
        $conn = $this->getConnection();

        $grammar = $conn->getQueryGrammar();

        $builder = new QueryBuilder($conn, $grammar, $conn->getPostProcessor(), $this);

        if (static::rememberable()) {
            $builder->remember(-1);
        }

        return $builder;
    }

    /**
     * Override the eloquent query builder.
     *
     * @param \Illuminate\Database\Query\Builder $query
     * @return \Amelia\Rememberable\Eloquent\Builder
     */
    public function newEloquentBuilder($query)
    {
        return new EloquentBuilder($query);
    }

    /**
     * Check if we're "rememberable".
     *
     * @return bool
     */
    public static function rememberable()
    {
        return isset(static::$rememberable) && static::$rememberable === true;
    }
}

<?php

namespace Amelia\Rememberable;

use Amelia\Rememberable\Query\Builder as QueryBuilder;
use Amelia\Rememberable\Eloquent\Builder as EloquentBuilder;
use Illuminate\Database\Eloquent\Model;

trait Rememberable
{
    protected static function bootRememberable()
    {
        if (static::rememberable()) {
            static::saved(function (Model $model) {
                $model->flush(get_class($model).':'.$model->getKey());
            });

            static::deleted(function (Model $model) {
                $model->flush(get_class($model).':'.$model->getKey());
            });
        }
    }

    /**
     * Get a new query builder instance for the connection.
     *
     * @return \Illuminate\Database\Query\Builder
     */
    protected function newBaseQueryBuilder()
    {
        $conn = $this->getConnection();

        $grammar = $conn->getQueryGrammar();

        $builder = new QueryBuilder($conn, $grammar, $conn->getPostProcessor(), $this);

        if (static::rememberable()) {
            $builder->remember(-1);
        }

        return $builder;
    }

    /**
     * Override the eloquent query builder.
     *
     * @param \Illuminate\Database\Query\Builder $query
     * @return \Amelia\Rememberable\Eloquent\Builder
     */
    public function newEloquentBuilder($query)
    {
        return new EloquentBuilder($query);
    }

    /**
     * Check if we're "rememberable".
     *
     * @return bool
     */
    public static function rememberable()
    {
        return isset(static::$rememberable) && static::$rememberable === true;
    }
}

Make rememberable cache flushes trigger on deletes too


<?php

namespace SheaDawson\UserSwitcher;

use SilverStripe\Control\Director;
use SilverStripe\Control\Controller;
use SilverStripe\Security\Permission;

/**
 * UserSwitcher
 *
 * @author Shea Dawson <shea@livesource.co.nz>
 * @license BSD http://silverstripe.org/bsd-license/
 */
class UserSwitcher
{
    public function canUserSwitch()
    {
        $session = Controller::curr()->getRequest()->getSession();
        return Director::isDev() && ($session->get('UserSwitched') || Permission::check('ADMIN'));
    }
}

<?php

namespace SheaDawson\UserSwitcher;

use SilverStripe\Control\Director;
use SilverStripe\Control\Controller;
use SilverStripe\Security\Permission;

/**
 * UserSwitcher
 *
 * @author Shea Dawson <shea@livesource.co.nz>
 * @license BSD http://silverstripe.org/bsd-license/
 */
class UserSwitcher
{
    public function canUserSwitch()
    {
        $session = Controller::curr()->getRequest()->getSession();
        return !Director::isLive() && ($session->get('UserSwitched') || Permission::check('ADMIN'));
    }
}

Allow user switching in test environments


<?php

namespace App\Tests;

use App\Entity\Comment;
use Codeception\Util\HttpCode;

class CommentCest
{
    public function createComment(FunctionalTester $I)
    {
        $I->amOnLocalizedPage('/login');
        $I->submitForm('#main form', ['_username' => 'john_user', '_password' => 'kitten']);
        $I->seeResponseCodeIs(HttpCode::OK);
        $I->seeCurrentRouteIs('blog_index');
        $I->click('article.post > h2 a');
        $I->seeResponseCodeIs(HttpCode::OK);
        $I->seeCurrentRouteIs('blog_post');
        $I->dontSee('Hi, Symfony!');
        $I->fillField('comment[content]', 'Hi, Symfony!');
        $I->submitForm('#post-add-comment > form', []);
        $I->seeCurrentRouteIs('blog_post');
        $I->see('Hi, Symfony!');
        $I->seeInRepository(Comment::class, ['content' => 'Hi, Symfony!']);
    }

}

<?php

namespace App\Tests;

use App\Entity\Comment;
use Codeception\Util\HttpCode;

class CommentCest
{
    public function createComment(FunctionalTester $I)
    {
        $I->amOnLocalizedPage('/login');
        $I->submitForm('#main form', ['_username' => 'john_user', '_password' => 'kitten']);
        $I->seeResponseCodeIs(HttpCode::OK);
        $I->seeCurrentRouteIs('blog_index');
        $I->click('article.post > h2 a');
        $I->seeResponseCodeIs(HttpCode::OK);
        $I->seeCurrentRouteIs('blog_post');
        $I->dontSee('Hi, Symfony!');
        $I->fillField('comment[content]', 'Hi, Symfony!');
        $I->submitForm('#post-add-comment > form', []);
        $I->seeCurrentRouteIs('blog_post');
        $I->see('Hi, Symfony!');
        // This particular assertion is a bit of overkill, but it also serves as a testcase
        // of `seeInRepository` method with complex associations. Here is how this assertion
        // translates to English:
        //
        //   * I see a comment entity with content equal to 'Hi, Symfony!'
        //   * and 'author' association points to a user entity with username equal to 'john_user'
        //   ** note: john_user is one who created the comment, as it is used in login
        //      procedure above
        //   * and 'post' association points to a post entity which...
        //   * ...has an associated comment entity which...
        //   * ...has same content and author with same username.
        $I->seeInRepository(Comment::class, [
            'content' => 'Hi, Symfony!',
            'author' => [
                'username' => 'john_user',
            ],
            'post' => [
                'comments' => [
                    'content' => 'Hi, Symfony!',
                    'author' => [
                        'username' => 'john_user'
                    ]
                ]
            ]
        ]);
    }

}

Test deep association queries in Doctrine2::seeInRepository


<?php

namespace FullyBaked\Pslackr;

use PHPUnit_Framework_TestCase;

class PslackrTest extends PHPUnit_Framework_TestCase
{
    public function testConstructorSetsConfigProperty()
    {
        $config = ['domain' => 'tester', 'token' => '123456'];

        $relection = new \ReflectionClass('FullyBaked\Pslackr\Pslackr');
        $tokenAttr = $relection->getProperty('token');
        $tokenAttr->setAccessible(true);
        $domainAttr = $relection->getProperty('domain');
        $domainAttr->setAccessible(true);

        $slack = new Pslackr($config);

        $this->assertEquals($config['token'], $tokenAttr->getValue($slack));
        $this->assertEquals($config['domain'], $domainAttr->getValue($slack));
    }
}

<?php

namespace FullyBaked\Pslackr;

use PHPUnit_Framework_TestCase;

class PslackrTest extends PHPUnit_Framework_TestCase
{
    public function testConstructorSetsConfigProperty()
    {
        $config = ['domain' => 'tester', 'token' => '123456'];

        $relection = new \ReflectionClass('FullyBaked\Pslackr\Pslackr');
        $tokenAttr = $relection->getProperty('token');
        $tokenAttr->setAccessible(true);

        $slack = new Pslackr($config);

        $this->assertEquals($config['token'], $tokenAttr->getValue($slack));
    }
}

Update test to reflect changes to class

Update test to reflect changes to class


<?php

/**
 * @package shop
 * @subpackage exceptions
 */
class ShopBuyableException extends Exception {

}

/**
 * @package shop
 * @subpackage exceptions
 */
class ShopBuyableException_NotEnoughStock extends ShopBuyableException {

}

Remove reference of stock from the main module.


<?php

namespace OpenDominion\Http\Controllers;

use Auth;
use OpenDominion\Services\Dominion\SelectorService;

class HomeController extends AbstractController
{
    public function getIndex()
    {
        // Only redirect to status/dashboard if we have no referer
        if (Auth::check() && (request()->server('HTTP_REFERER') !== '') && (url()->previous() === url()->current())) {
            $dominionSelectorService = app(SelectorService::class);

            if ($dominionSelectorService->hasUserSelectedDominion()) {
                return redirect()->route('dominion.status');
            }

            return redirect()->route('dashboard');
        }

        return view('pages.home');
    }
}

<?php

namespace OpenDominion\Http\Controllers;

use Auth;
use OpenDominion\Services\Dominion\SelectorService;

class HomeController extends AbstractController
{
    public function getIndex()
    {
        // Only redirect to status/dashboard if we have no referer
        if (Auth::check() && (request()->server('HTTP_REFERER') !== '') && (url()->previous() === url()->current())) {
            $dominionSelectorService = app(SelectorService::class);

            if ($dominionSelectorService->tryAutoSelectDominionForAuthUser()) {
                return redirect()->route('dominion.status');
            }

            return redirect()->route('dashboard');
        }

        return view('pages.home');
    }
}

Fix not going to dominion status page after logging via 'remember me'


<?php

namespace webtoolsnz\scheduler;

/**
 * Class ErrorHandler
 * @package webtoolsnz\scheduler
 */
class ErrorHandler extends \yii\console\ErrorHandler
{
    /**
     * @var TaskRunner
     */
    public $taskRunner;

    /**
     *  We need to override the register method to inject our own shutdown handler before the internal yii handler
     *  is registered.
     */
    public function register()
    {
        register_shutdown_function([$this, 'schedulerShutdownHandler']);
        return parent::register();
    }

    public function schedulerShutdownHandler()
    {
        $error = error_get_last();
        if ($this->taskRunner && E_ERROR == $error['type']) {
            $this->taskRunner->handleError($error['type'], $error['message'], $error['file'], $error['line']);
        }
    }
}

<?php

namespace webtoolsnz\scheduler;

/**
 * Class ErrorHandler
 * @package webtoolsnz\scheduler
 */
class ErrorHandler extends \yii\console\ErrorHandler
{
    /**
     * @var TaskRunner
     */
    public $taskRunner;

    /**
     *  We need to override the register method to register our own shutdown handler and prevent yii from
     *  intercepting our error handler.
     */
    public function register()
    {
        register_shutdown_function([$this, 'schedulerShutdownHandler']);
    }

    public function schedulerShutdownHandler()
    {
        $error = error_get_last();
        if ($this->taskRunner && E_ERROR == $error['type']) {
            $this->taskRunner->handleError($error['type'], $error['message'], $error['file'], $error['line']);
        }

        // Allow yiis error handler to take over and handle logging
        parent::handleFatalError();
    }
}

Update fatal error handling to work with newer versions of yii


<?php

namespace App\Providers;

use Illuminate\Support\Facades\Storage;
use Illuminate\Support\ServiceProvider;

class MicropubSessionProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        //allow micropub use in development
        if (env('APP_DEBUG') == true) {
            session(['me' => env('APP_URL')]);
            if (Storage::exists('dev-token')) {
                session(['token' => Storage::get('dev-token')]);
            }
        }
    }

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

<?php

namespace App\Providers;

use Illuminate\Support\Facades\Storage;
use Illuminate\Support\ServiceProvider;

class MicropubSessionProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        //allow micropub use in development
        if (config('app.env') !== 'production') {
            session(['me' => env('APP_URL')]);
            if (Storage::exists('dev-token')) {
                session(['token' => Storage::get('dev-token')]);
            }
        }
    }

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

Set a micropub token when not in production


<?php

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

class CreateRoutes extends Migration
{
	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		Schema::create('routes', function (Blueprint $table) {
			$table->increments('id');

			$table->string('path', 255)->index();
			$table->string('slug', 60)->nullable();
            $table->boolean('is_canonical')->boolean()->default(false);

			$table->integer('page_id')->unsigned();
            $table->integer('site_id')->unsigned()->nullable();

			$table->integer('parent_id')->nullable();
			$table->integer('lft')->nullable();
			$table->integer('rgt')->nullable();
			$table->integer('depth')->nullable();

            $table->foreign('site_id', 'site_id_fk')->references('id')->on('sites');
            $table->foreign('page_id', 'page_id_fk')->references('id')->on('pages')->onDelete('cascade');
		});
	}

	/**
	 * Reverse the migrations.
	 *
	 * @return void
	 */
	public function down()
	{
        Schema::table('routes', function(Blueprint $table) {
            $table->dropForeign('site_id_fk');
            $table->dropForeign('page_id_fk');
        });

		Schema::drop('routes');
	}
}

<?php

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

class CreateRoutes extends Migration
{
	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		Schema::create('routes', function (Blueprint $table) {
			$table->increments('id');

			$table->string('path')->index();
			$table->string('slug', 60)->nullable();
			$table->boolean('is_canonical')->boolean()->default(false);

			$table->integer('page_id')->unsigned();
			$table->integer('site_id')->unsigned()->nullable();

			$table->integer('parent_id')->nullable();
			$table->integer('lft')->nullable();
			$table->integer('rgt')->nullable();
			$table->integer('depth')->nullable();

			$table->foreign('site_id', 'site_id_fk')->references('id')->on('sites');
			$table->foreign('page_id', 'page_id_fk')->references('id')->on('pages')->onDelete('cascade');
		});
	}

	/**
	 * Reverse the migrations.
	 *
	 * @return void
	 */
	public function down()
	{
		Schema::table('routes', function(Blueprint $table) {
			$table->dropForeign('site_id_fk');
			$table->dropForeign('page_id_fk');
		});

		Schema::drop('routes');
	}
}

Change route path column to default 191 chars long for the migration to work correctly with utf8mb4_unicode_ci collation (for now at least, until Sam's changes blow it all up).


<?php
namespace CodeDay\Clear\Models\Application;

use Illuminate\Database\Eloquent;

class Webhook extends \Eloquent {
    protected $table = 'applications_webhooks';

    public function application()
    {
      return $this->belongsTo('\CodeDay\Clear\Models\Application', 'application_id', 'public');
    }

    public function Execute($data)
    {
        $opts = ['http' => ['method'  => 'POST']];
        $body = [];

        $body['data'] = $data;

        $body['private'] = $this->application->private;
        $body['event'] = $this->event;

        $opts['http']['header'] = 'Content-type: application/x-www-form-urlencoded';
        $opts['http']['content'] = http_build_query($body);

        $url = $this->url;
        try {
          \Queue::push(function ($job) use ($opts, $url) {
            $context  = stream_context_create($opts);
            @file_get_contents($url, false, $context);
            $job->delete();
          });
        } catch (\Exception $ex) {}
    }

    public static function Fire($event, $data)
    {
      $all_hooks = self::where('event', '=', $event)->get();
      foreach ($all_hooks as $hook) {
        $hook->Execute($data);
      }
    }

    protected static function boot()
    {
      parent::boot();

      static::creating(function ($model) {
        $model->id  = str_random(16);
      });
    }
}

<?php
namespace CodeDay\Clear\Models\Application;

use Illuminate\Database\Eloquent;

class Webhook extends \Eloquent {
    protected $table = 'applications_webhooks';

    public function application()
    {
      return $this->belongsTo('\CodeDay\Clear\Models\Application', 'application_id', 'public');
    }

    public function Execute($data)
    {
        $opts = ['http' => ['method'  => 'POST']];
        $body = [];

        $body['data'] = $data;

        $body['private'] = $this->application->private;
        $body['event'] = $this->event;

        $opts['http']['header'] = 'Content-type: application/json';
        $opts['http']['content'] = json_encode($body);

        $url = $this->url;
        try {
          \Queue::push(function ($job) use ($opts, $url) {
            $context  = stream_context_create($opts);
            @file_get_contents($url, false, $context);
            $job->delete();
          });
        } catch (\Exception $ex) {}
    }

    public static function Fire($event, $data)
    {
      $all_hooks = self::where('event', '=', $event)->get();
      foreach ($all_hooks as $hook) {
        $hook->Execute($data);
      }
    }

    protected static function boot()
    {
      parent::boot();

      static::creating(function ($model) {
        $model->id  = str_random(16);
      });
    }
}

Send application/json instead of urlencoded for webhooks


<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="author" content="Bludit CMS">

<!-- Dynamic title tag -->
<?php echo Theme::metaTags('title'); ?>

<!-- Dynamic description tag -->
<?php echo Theme::metaTags('description'); ?>

<!-- Include Favicon -->
<?php echo Theme::favicon('img/favicon.png'); ?>

<!-- Include Bootstrap CSS file bootstrap.css -->
<?php echo Theme::cssBootstrap(); ?>

<!-- Include CSS Styles from this theme -->
<?php echo Theme::css('css/style.css'); ?>

<!-- Load Bludit Plugins: Site head -->
<?php Theme::plugins('siteHead'); ?>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="generator" content="Bludit">

<!-- Dynamic title tag -->
<?php echo Theme::metaTags('title'); ?>

<!-- Dynamic description tag -->
<?php echo Theme::metaTags('description'); ?>

<!-- Include Favicon -->
<?php echo Theme::favicon('img/favicon.png'); ?>

<!-- Include Bootstrap CSS file bootstrap.css -->
<?php echo Theme::cssBootstrap(); ?>

<!-- Include CSS Styles from this theme -->
<?php echo Theme::css('css/style.css'); ?>

<!-- Load Bludit Plugins: Site head -->
<?php Theme::plugins('siteHead'); ?>

Change tag and include generator tag

Change tag and include generator tag


<?php

declare(strict_types=1);

/*
 * This file is part of gpupo/submarino-sdk
 * Created by Gilmar Pupo <contact@gpupo.com>
 * For the information of copyright and license you should read the file
 * LICENSE which is distributed with this source code.
 * Para a informação dos direitos autorais e de licença você deve ler o arquivo
 * LICENSE que é distribuído com este código-fonte.
 * Para obtener la información de los derechos de autor y la licencia debe leer
 * el archivo LICENSE que se distribuye con el código fuente.
 * For more information, see <https://opensource.gpupo.com/>.
 *
 */

use Symfony\Component\Dotenv\Dotenv;

if (!class_exists('\Gpupo\Common\Console\Application')) {
    require __DIR__.'/../vendor/autoload.php';
}

if (!class_exists(Dotenv::class)) {
    throw new RuntimeException('Please run "composer require symfony/dotenv" to load the ".env" files configuring the application.');
}
    // load all the .env files
    (new Dotenv())->loadEnv(dirname(__DIR__).'/.env');

<?php

declare(strict_types=1);

/*
 * This file is part of gpupo/submarino-sdk
 * Created by Gilmar Pupo <contact@gpupo.com>
 * For the information of copyright and license you should read the file
 * LICENSE which is distributed with this source code.
 * Para a informação dos direitos autorais e de licença você deve ler o arquivo
 * LICENSE que é distribuído com este código-fonte.
 * Para obtener la información de los derechos de autor y la licencia debe leer
 * el archivo LICENSE que se distribuye con el código fuente.
 * For more information, see <https://opensource.gpupo.com/>.
 *
 */

use Symfony\Component\Dotenv\Dotenv;

if (!class_exists('\Gpupo\Common\Console\Application')) {
    require __DIR__.'/../vendor/autoload.php';
}

if (!class_exists(Dotenv::class)) {
    throw new RuntimeException('Please run "composer require symfony/dotenv" to load the ".env" files configuring the application.');
}
    // load all the .env files
    (new Dotenv(true))->loadEnv(dirname(__DIR__).'/.env');

Update Dotenv config to the new version

Update Dotenv config to the new version


<?php

class ImportAdminExtension extends Extension{

	/**
	 * Prevent existing import form from showing up
	 * @todo: there should be a better way to disable from an extension, rather than
	 * disabling it after it has been created
	 */
	public function updateImportForm(&$form){
		if(Config::inst()->get('ModelAdmin','removelegacyimporters') === true){
			$form = null;
		}
	}

	/**
	 * Add in new bulk GridFieldImporter
	 */
	public function updateEditForm($form){
		if(Config::inst()->get('ModelAdmin','addbetterimporters') === true){
			$modelclass = $this->owner->modelClass;
			$grid = $form->Fields()->fieldByName($modelclass);
			$config =  $grid->getConfig();
			//don't proceed if there is already an importer
			if($config->getComponentByType("GridFieldImporter")){
				return;
			}
			$config->addComponent(new GridFieldImporter('before'));
		}
	}

}

<?php

class ImportAdminExtension extends Extension{

	/**
	 * Prevent existing import form from showing up
	 * @todo: there should be a better way to disable from an extension, rather than
	 * disabling it after it has been created
	 */
	public function updateImportForm(&$form){
		if(Config::inst()->get('ModelAdmin','removelegacyimporters') === true){
			$form = null;
		}
	}

	/**
	 * Add in new bulk GridFieldImporter
	 */
	public function updateEditForm($form){
		if($doadd = Config::inst()->get('ModelAdmin','addbetterimporters')){
			$modelclass = $this->owner->modelClass;
			$grid = $form->Fields()->fieldByName($modelclass);
			$config =  $grid->getConfig();

			//don't proceed if there is already an importer
			if($config->getComponentByType("GridFieldImporter")){
				return;
			}
			//don't proceed if can't create
			if(!singleton($modelclass)->canCreate(Member::currentUser())){
				return;
			}
			//allow config to avoid adding when there are existing importers
			$importerClasses = $this->owner->stat('model_importers');
			if(
				$doadd === "scaffolded" &&
				!is_null($importerClasses) &&
				isset($importerClasses[$modelclass])
			){
				return;
			}

			//add the component
			$config->addComponent(new GridFieldImporter('before'));
		}
	}

}

Allow only adding importers to model admins with scaffolded importers


@extends('layouts.default')

@section('content')

Support Tickets

            Title
            Priority
            Status
            Replies
            Owner
            Updated At

        @foreach ($tickets as $ticket)
            @if (Sentry::inGroup(Sentry::findGroupByName('Admins')) || $ticket->owner_id == Sentry::getUser()->id)

                        id)) }}">
                            {{ $ticket->title }}

                        {{ $ticket->priority->title }}

                        {{ $ticket->status->title }}

                        {{ $ticket->replies }}

                        {{ $ticket->owner->username }}

                        {{ $ticket->updated_at }}

            @endif
        @endforeach

@stop

@extends('layouts.default')

@section('content')

Support Tickets

        @foreach($statuses as $status)
            {{ $status }}
        @endforeach

            Title
            Priority
            Status
            Replies
            Owner
            Updated At

        @foreach ($tickets as $ticket)
            @if (Sentry::inGroup(Sentry::findGroupByName('Admins')) || $ticket->owner_id == Sentry::getUser()->id)

                        id)) }}">
                            {{ $ticket->title }}

                        {{ $ticket->priority->title }}

                        {{ $ticket->status->title }}

                        {{ $ticket->replies }}

                        {{ $ticket->owner->username }}

                        {{ $ticket->updated_at }}

            @endif
        @endforeach

@stop

Add links to status filtering

Add links to status filtering


<?php
// Copyright (c) 2018 Fernando Bevilacqua <dovyski@gmail.com>
// Licensed under the MIT license, see LICENSE file.

namespace Codebot;

class Signal {
	private $listeners;

	private function getKey($theListener) {
		if(is_string($theListener)) {
			return $theListener;
		} else if(is_array($theListener)) {
			return (is_string($theListener[0]) ? $theListener[0] : spl_object_hash($theListener[0])) . $theListener[1];
		} else {
			throw new \Exception('Invalid listener: it should be string or array(class, method).');
		}
	}

	public function add($theListener) {
		$aKey = $this->getKey($theListener);

		if(!isset($this->listeners[$aKey])) {
			$this->listeners[$aKey] = $theListener;
			return true;
		}

		return false;
	}

	public function remove($theListener) {
		$aKey = $this->getKey($theListener);

		if(isset($this->listeners[$aKey])) {
			unset($this->listeners[$aKey]);
			return true;
		}

		return false;
	}

	public function dispatch(array $theParams = array()) {
		foreach($this->listeners as $aKey => $aListener) {
			call_user_func_array($aListener, $theParams);
		}
	}
}

?>

<?php
// Copyright (c) 2018 Fernando Bevilacqua <dovyski@gmail.com>
// Licensed under the MIT license, see LICENSE file.

namespace Codebot;

class Signal {
	private $listeners;

	private function getKey($theListener) {
		if(is_string($theListener)) {
			return $theListener;
		} else if(is_array($theListener)) {
			return (is_string($theListener[0]) ? $theListener[0] : spl_object_hash($theListener[0])) . $theListener[1];
		} else {
			throw new \Exception('Invalid listener: it should be string or array(class, method).');
		}
	}

	public function add($theListener) {
		$aKey = $this->getKey($theListener);

		if(!isset($this->listeners[$aKey])) {
			$this->listeners[$aKey] = $theListener;
			return true;
		}

		return false;
	}

	public function remove($theListener) {
		$aKey = $this->getKey($theListener);

		if(isset($this->listeners[$aKey])) {
			unset($this->listeners[$aKey]);
			return true;
		}

		return false;
	}

	public function dispatch(array $theParams = array()) {
		if(count($this->listeners) == 0) {
			return;
		}
		foreach($this->listeners as $aKey => $aListener) {
			call_user_func_array($aListener, $theParams);
		}
	}
}

?>

Fix warning when no listener is registered


<?php

/**
 * PluginComuna
 *
 * This class has been auto-generated by the Doctrine ORM Framework
 *
 * @package    ##PACKAGE##
 * @subpackage ##SUBPACKAGE##
 * @author     ##NAME## <##EMAIL##>
 * @version    SVN: $Id: Builder.php 7490 2010-03-29 19:53:27Z jwage $
 */
abstract class PluginComuna extends BaseComuna
{
  public function __toString() {
    return $this->getNombre();
  }

  public function getNombreConRegion($separador = ', ') {
    return $this->getNombre() . $separador . $this->getProvincia()->getRegion()->__toString();
  }
}

<?php

/**
 * PluginComuna
 *
 * This class has been auto-generated by the Doctrine ORM Framework
 *
 * @package    ##PACKAGE##
 * @subpackage ##SUBPACKAGE##
 * @author     ##NAME## <##EMAIL##>
 * @version    SVN: $Id: Builder.php 7490 2010-03-29 19:53:27Z jwage $
 */
abstract class PluginComuna extends BaseComuna
{
  public function __toString() {
    return ($this->getId())? $this->getNombre():'No especificada.';
  }

  public function getNombreConRegion($separador = ', ') {
    return $this->getNombre() . $separador . $this->getProvincia()->getRegion()->__toString();
  }
}

Fix de retorno __toString() erroneo cuando se relaciona un objeto Null.


{!! '<?'.'php' !!}
declare(strict_types=1);

namespace phln\{{$ns}};

use function phln\fn\curryN;

const {{$name}} = '\\phln\\{{$ns}}\\{{$name}}';
const 𝑓{{$name}} = '\\phln\\{{$ns}}\\𝑓{{$name}}';

function {{$name}}()
{
    return curryN(N, 𝑓{{$name}});
}

function 𝑓{{$name}}()
{
}

{!! '<?'.'php' !!}
declare(strict_types=1);

namespace phln\{{$ns}};

use function phln\fn\curryN;

const {{$name}} = '\\phln\\{{$ns}}\\{{$name}}';
const 𝑓{{$name}} = '\\phln\\{{$ns}}\\𝑓{{$name}}';

/**
 * Dummy description of {{$name}} function.
 *
 * @phlnSignature * -> *
 * @phlnCategory {{$ns}}
 * @return \Closure|mixed
 * @example
 *      \phln\{{$ns}}\{{$name}}();
 */
function {{$name}}()
{
    return curryN(0, 𝑓{{$name}}, func_get_args());
}

function 𝑓{{$name}}()
{
}

Add dumym docblock when creating function

Closes #34


<?php

namespace Orchestra\Foundation\Providers;

use Illuminate\Contracts\Foundation\Application;
use Orchestra\Foundation\Console\Commands\AssembleCommand;
use Orchestra\Foundation\Console\Commands\ConfigureMailCommand;
use Orchestra\Support\Providers\CommandServiceProvider as ServiceProvider;

class CommandServiceProvider extends ServiceProvider
{
    /**
     * The commands to be registered.
     *
     * @var array
     */
    protected $commands = [
        'Assemble' => 'orchestra.commands.assemble',
        'ConfigureMail' => 'orchestra.commands.configure-mail',
    ];

    /**
     * Register the command.
     *
     * @return void
     */
    protected function registerAssembleCommand(): void
    {
        $this->app->singleton('orchestra.commands.assemble', static function (Application $app) {
            $foundation = $app->make('orchestra.app');

            return new AssembleCommand($foundation, $foundation->memory());
        });
    }

    /**
     * Register the command.
     *
     * @return void
     */
    protected function registerConfigureMailCommand(): void
    {
        $this->app->singleton('orchestra.commands.configure-mail', static function () {
            return new ConfigureMailCommand();
        });
    }
}

<?php

namespace Orchestra\Foundation\Providers;

use Illuminate\Contracts\Foundation\Application;
use Orchestra\Foundation\Console\Commands\AssembleCommand;
use Orchestra\Foundation\Console\Commands\ConfigureMailCommand;
use Orchestra\Support\Providers\CommandServiceProvider as ServiceProvider;

class CommandServiceProvider extends ServiceProvider
{
    /**
     * The commands to be registered.
     *
     * @var array
     */
    protected $commands = [
        'Assemble' => 'orchestra.commands.assemble',
        'ConfigureMail' => 'orchestra.commands.configure-mail',
    ];

    /**
     * Register the command.
     *
     * @return void
     */
    protected function registerAssembleCommand(): void
    {
        $this->app->singleton('orchestra.commands.assemble', static function () {
            return new AssembleCommand();
        });
    }

    /**
     * Register the command.
     *
     * @return void
     */
    protected function registerConfigureMailCommand(): void
    {
        $this->app->singleton('orchestra.commands.configure-mail', static function () {
            return new ConfigureMailCommand();
        });
    }
}

Remove DI on command construct.

Remove DI on command construct.

Signed-off-by: Mior Muhammad Zaki <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com>


<?php

$feature_color = 'cyan';
$feature_kind = 'quote';

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

<?php

$feature_color = 'cyan';
$feature_kind = 'quote';
$feature_size = 'sm';

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

Reduce Hero Quote Cyan size

Reduce Hero Quote Cyan size


<?php

use Arcanesoft\Blog\Bases\Migration;
use Illuminate\Database\Schema\Blueprint;

/**
 * Class     CreateBlogPostsTable
 *
 * @author   ARCANEDEV <arcanedev.maroc@gmail.com>
 *
 * @see \Arcanesoft\Blog\Models\Post
 */
class CreateBlogPostsTable extends Migration
{
    /* -----------------------------------------------------------------
     |  Constructor
     | -----------------------------------------------------------------
     */

    /**
     * CreateBlogPostsTable constructor.
     */
    public function __construct()
    {
        parent::__construct();

        $this->setTable('posts');
    }

    /* -----------------------------------------------------------------
     |  Main Methods
     | -----------------------------------------------------------------
     */

    /**
     * {@inheritdoc}
     */
    public function up()
    {
        $this->createSchema(function(Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('author_id')->default(0);
            $table->unsignedInteger('category_id');
            $table->string('locale', 5)->default(config('app.locale'));
            $table->string('title');
            $table->string('slug');
            $table->text('excerpt');
            $table->string('thumbnail')->nullable();
            $table->longtext('content_raw');
            $table->longtext('content_html');
            $table->boolean('is_draft')->default(false);
            $table->timestamps();
            $table->timestamp('published_at');
            $table->softDeletes();

            $table->unique(['locale', 'slug']);
        });
    }
}

<?php

use Arcanesoft\Blog\Bases\Migration;
use Illuminate\Database\Schema\Blueprint;

/**
 * Class     CreateBlogPostsTable
 *
 * @author   ARCANEDEV <arcanedev.maroc@gmail.com>
 *
 * @see \Arcanesoft\Blog\Models\Post
 */
class CreateBlogPostsTable extends Migration
{
    /* -----------------------------------------------------------------
     |  Constructor
     | -----------------------------------------------------------------
     */

    /**
     * CreateBlogPostsTable constructor.
     */
    public function __construct()
    {
        parent::__construct();

        $this->setTable('posts');
    }

    /* -----------------------------------------------------------------
     |  Main Methods
     | -----------------------------------------------------------------
     */

    /**
     * {@inheritdoc}
     */
    public function up()
    {
        $this->createSchema(function(Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('author_id')->default(0);
            $table->unsignedInteger('category_id');
            $table->string('locale', 5)->default(config('app.locale'));
            $table->string('title');
            $table->string('slug');
            $table->text('excerpt');
            $table->string('thumbnail')->nullable();
            $table->longtext('content_raw');
            $table->longtext('content_html');
            $table->boolean('is_draft')->default(false);
            $table->timestamps();
            $table->timestamp('published_at')->nullable();
            $table->softDeletes();

            $table->unique(['locale', 'slug']);
        });
    }
}

Fix the MySQL issue with not nullable timestamp


<?php

class ResponseHelpers {
  public static function respondNotFound() {
    @header("HTTP/1.0 404 Not Found");
  }

  public static function respondServerError() {
    @header("HTTP/1.1 500 Internal Server Error");
  }

  public static function outputWithJsonHeader($obj) {
    @header("Content-Type:application/json; charset=utf-8");
    $wrapper = array("data" => $obj);
    print json_encode($wrapper);
  }
}

<?php

class ResponseHelpers {
  public static function respondNotFound() {
    @header("HTTP/1.0 404 Not Found");
  }

  public static function respondServerError() {
    @header("HTTP/1.1 500 Internal Server Error");
  }

  public static function outputWithJsonHeader($obj) {
    @header("Content-Type:application/json; charset=utf-8");
    print json_encode($obj);
  }
}

Modify API so responses are no longer wrapped


TEST PAGE

<?php echo time();?>

<?php echo date('Y-m-d H:i:s T');?>

Add date to test page

Add date to test page


<?php

namespace Incenteev\TranslationCheckerBundle\DependencyInjection;

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

class Configuration implements ConfigurationInterface
{
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $treeBuilder->root('incenteev_translation_checker')
            ->children()
                ->arrayNode('extraction')
                    ->addDefaultsIfNotSet()
                    ->fixXmlConfig('bundle')
                    ->children()
                        ->arrayNode('bundles')
                            ->prototype('scalar')->end()
                        ->end()
                        ->arrayNode('js')
                            ->addDefaultsIfNotSet()
                            ->fixXmlConfig('path')
                            ->children()
                                ->scalarNode('default_domain')
                                    ->info('The default domain used for JS translation (should match the JsTranslationBundle config)')
                                    ->defaultValue('messages')
                                ->end()
                                ->arrayNode('paths')
                                    ->prototype('scalar')->end()
                                ->end()
                            ->end()
                        ->end()
                    ->end()
                ->end()
            ->end();

        return $treeBuilder;
    }
}

<?php

namespace Incenteev\TranslationCheckerBundle\DependencyInjection;

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

class Configuration implements ConfigurationInterface
{
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder('incenteev_translation_checker');

        if (method_exists($treeBuilder, 'getRootNode')) {
            $rootNode = $treeBuilder->getRootNode();
        } else {
            $rootNode = $treeBuilder->root('incenteev_translation_checker');
        }

        $rootNode
            ->children()
                ->arrayNode('extraction')
                    ->addDefaultsIfNotSet()
                    ->fixXmlConfig('bundle')
                    ->children()
                        ->arrayNode('bundles')
                            ->prototype('scalar')->end()
                        ->end()
                        ->arrayNode('js')
                            ->addDefaultsIfNotSet()
                            ->fixXmlConfig('path')
                            ->children()
                                ->scalarNode('default_domain')
                                    ->info('The default domain used for JS translation (should match the JsTranslationBundle config)')
                                    ->defaultValue('messages')
                                ->end()
                                ->arrayNode('paths')
                                    ->prototype('scalar')->end()
                                ->end()
                            ->end()
                        ->end()
                    ->end()
                ->end()
            ->end();

        return $treeBuilder;
    }
}

Fix deprecated usage of the config component


<?php

final class PhabricatorSearchConfigOptions
  extends PhabricatorApplicationConfigOptions {

  public function getName() {
    return pht('Search');
  }

  public function getDescription() {
    return pht('Options relating to Search.');
  }

  public function getIcon() {
    return 'fa-search';
  }

  public function getGroup() {
    return 'apps';
  }

  public function getOptions() {
    return array(
      $this->newOption('search.elastic.host', 'string', null)
        ->setLocked(true)
        ->setDescription(pht('Elastic Search host.'))
        ->addExample('http://elastic.example.com:9200/', pht('Valid Setting')),
      $this->newOption('search.elastic.namespace', 'string', 'phabricator')
        ->setLocked(true)
        ->setDescription(pht('Elastic Search index.'))
        ->addExample('phabricator2', pht('Valid Setting')),
      $this->newOption('search.elastic.version', 'string', null)
        ->setLocked(true)
        ->setDescription(pht('Elastic Version, used for functions that work for a specific elastic version.')),
      $this->newOption('search.elastic.enabled', 'bool', false)
        ->setDescription(pht('Enable the elasticsearch backend.'))
        ->setBoolOptions(array(pht('Enable: Use elasticsearch'),
                               pht('Disable: Use MySQL')))
    );
  }

}

<?php

final class PhabricatorSearchConfigOptions
  extends PhabricatorApplicationConfigOptions {

  public function getName() {
    return pht('Search');
  }

  public function getDescription() {
    return pht('Options relating to Search.');
  }

  public function getIcon() {
    return 'fa-search';
  }

  public function getGroup() {
    return 'apps';
  }

  public function getOptions() {
    return array(
      $this->newOption('search.elastic.host', 'string', null)
        ->setLocked(true)
        ->setDescription(pht('Elastic Search host.'))
        ->addExample('http://elastic.example.com:9200/', pht('Valid Setting')),
      $this->newOption('search.elastic.namespace', 'string', 'phabricator')
        ->setLocked(true)
        ->setDescription(pht('Elastic Search index.'))
        ->addExample('phabricator2', pht('Valid Setting')),
      $this->newOption('search.elastic.version', 'int', null)
        ->setLocked(true)
        ->setDescription(pht('Elastic Version, used for functions that work for a specific elastic version.')),
      $this->newOption('search.elastic.enabled', 'bool', false)
        ->setDescription(pht('Enable the elasticsearch backend.'))
        ->setBoolOptions(array(pht('Enable: Use elasticsearch'),
                               pht('Disable: Use MySQL')))
    );
  }

}

Make search.elastic.version an int not a string

Summary:
Puppet is not budging in allowing me to use an int so let's just make it a int.

This fixes prod for when we want to change versions too.

Change-Id: I348d674762953433bd77c6ff8efb4246d5d68b73

Reviewers: mmodell, Dzahn

Subscribers: jenkins

Differential Revision: https://phabricator.wikimedia.org/D562


<?php

namespace Benwilkins\FCM;

use GuzzleHttp\Client;
use Illuminate\Support\ServiceProvider;
use Illuminate\Notifications\ChannelManager;

/**
 * Class FcmNotificationServiceProvider.
 */
class FcmNotificationServiceProvider extends ServiceProvider
{
    /**
     * Register.
     */
    public function register()
    {
        $app = $this->app;
        $this->app->make(ChannelManager::class)->extend('fcm', function () use ($app) {
            return new FcmChannel(new Client(), config('services.fcm.key'));
        });
    }
}

<?php

namespace Benwilkins\FCM;

use GuzzleHttp\Client;
use Illuminate\Support\ServiceProvider;
use Illuminate\Notifications\ChannelManager;

/**
 * Class FcmNotificationServiceProvider.
 */
class FcmNotificationServiceProvider extends ServiceProvider
{
    /**
     * Register.
     */
    public function register()
    {
        $app = $this->app;
        $this->app->make(ChannelManager::class)->extend('fcm', function () use ($app) {
            return new FcmChannel(resolve(Client::class), config('services.fcm.key'));
        });
    }
}

Resolve Guzzle from the container

Resolve Guzzle from the container

In case someone is swapping Guzzle out with a mock or something else...


<?php

$message = 'Requires the PHP7 amqp extension.';

return class_exists('AMQPQueue');

<?php

$message = 'Requires the amqp extension.';

return class_exists('AMQPQueue');

Update test fixture support message

Update test fixture support message


<?php

namespace Larapi;

use Illuminate\Support\ServiceProvider;

class LarapiServiceProvider extends ServiceProvider {

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

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

	/**
	 * Register the service provider.
	 *
	 * @return void
	 */
	public function register()
	{
		$this->app['larapi'] = $this->app->share(function($app){
			return new Larapi;
		});
		$this->app->booting(function(){
			$loader = \Illuminate\Foundation\AliasLoader::getInstance();
			$loader->alias('Larapi', 'Larapi\Facades\Larapi');
		});
	}

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

}

<?php

namespace Larapi;

use Illuminate\Support\ServiceProvider;

class LarapiServiceProvider extends ServiceProvider {

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

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

	/**
	 * Register the service provider.
	 *
	 * @return void
	 */
	public function register()
	{
		$this->app->bind('larapi', function ($app) {
		    return new Larapi;
		});

		$this->app->booting(function(){
			$loader = \Illuminate\Foundation\AliasLoader::getInstance();
			$loader->alias('Larapi', 'Larapi\Facades\Larapi');
		});
	}

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

}

Replace deprecated share() method for Laravel 5.4 compatibility


<?
//Application entry point
define('ROOT', dirname(__FILE__));

include(ROOT.'/lib/autoload.php');
include(ROOT.'/vendor/autoload.php');

if($config['env'] == 'dev'){
	include(ROOT.'/assets/css.php');
	include(ROOT.'/assets/js.php');
}

routeRequest();
?>

<?
//Application entry point
ob_start();

define('ROOT', dirname(__FILE__));

include(ROOT.'/lib/autoload.php');
include(ROOT.'/vendor/autoload.php');

if($config['env'] == 'dev'){
	include(ROOT.'/assets/css.php');
	include(ROOT.'/assets/js.php');
}

routeRequest();
ob_end_flush();
?>

Add output buffering so we have option to send headers later on


<?php

namespace spec\PhpSpec\CodeAnalysis;

use PhpSpec\CodeAnalysis\NamespaceResolver;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;

class StaticRejectingNamespaceResolverSpec extends ObjectBehavior
{
    function let(NamespaceResolver $namespaceResolver)
    {
        $this->beConstructedWith($namespaceResolver);
    }

    function it_is_initializable()
    {
        $this->shouldHaveType('PhpSpec\CodeAnalysis\NamespaceResolver');
    }

    function it_delegates_analysis_to_wrapped_resolver(NamespaceResolver $namespaceResolver)
    {
        $this->analyse('foo');

        $namespaceResolver->analyse('foo')->shouldhaveBeenCalled();
    }

    function it_delegates_resolution_to_wrapped_resolver(NamespaceResolver $namespaceResolver)
    {
        $namespaceResolver->resolve('Bar')->willReturn('Foo\Bar');

        $this->resolve('Bar')->shouldReturn('Foo\Bar');
    }

    function it_does_not_allow_resolution_of_scalar_types()
    {
        $this->shouldThrow('PhpSpec\CodeAnalysis\DisallowedScalarTypehintException')->duringResolve('int');
        $this->shouldThrow('PhpSpec\CodeAnalysis\DisallowedScalarTypehintException')->duringResolve('float');
        $this->shouldThrow('PhpSpec\CodeAnalysis\DisallowedScalarTypehintException')->duringResolve('string');
        $this->shouldThrow('PhpSpec\CodeAnalysis\DisallowedScalarTypehintException')->duringResolve('bool');
    }
}

<?php

namespace spec\PhpSpec\CodeAnalysis;

use PhpSpec\CodeAnalysis\DisallowedScalarTypehintException;
use PhpSpec\CodeAnalysis\NamespaceResolver;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;

class StaticRejectingNamespaceResolverSpec extends ObjectBehavior
{
    function let(NamespaceResolver $namespaceResolver)
    {
        $this->beConstructedWith($namespaceResolver);
    }

    function it_is_initializable()
    {
        $this->shouldHaveType('PhpSpec\CodeAnalysis\NamespaceResolver');
    }

    function it_delegates_analysis_to_wrapped_resolver(NamespaceResolver $namespaceResolver)
    {
        $this->analyse('foo');

        $namespaceResolver->analyse('foo')->shouldhaveBeenCalled();
    }

    function it_delegates_resolution_to_wrapped_resolver(NamespaceResolver $namespaceResolver)
    {
        $namespaceResolver->resolve('Bar')->willReturn('Foo\Bar');

        $this->resolve('Bar')->shouldReturn('Foo\Bar');
    }

    function it_does_not_allow_resolution_of_scalar_types()
    {
        $this->shouldThrow(DisallowedScalarTypehintException::class)->duringResolve('int');
        $this->shouldThrow(DisallowedScalarTypehintException::class)->duringResolve('float');
        $this->shouldThrow(DisallowedScalarTypehintException::class)->duringResolve('string');
        $this->shouldThrow(DisallowedScalarTypehintException::class)->duringResolve('bool');
        $this->shouldThrow(DisallowedScalarTypehintException::class)->duringResolve('iterable');
    }
}

Add iterable to list of not allowed doubles types in specification


<?php

namespace LongRunning\Bundle\LongRunningBundle\DependencyInjection;

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

class Configuration implements ConfigurationInterface
{
    public function __construct($alias)
    {
        $this->alias = $alias;
    }

    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();

        $rootNode = $treeBuilder->root($this->alias);
        $rootNode
            ->children()
                ->arrayNode('bernard')
                    ->canBeEnabled()
                ->end()
                ->arrayNode('doctrine_orm')
                    ->canBeEnabled()
                ->end()
                ->arrayNode('doctrine_dbal')
                    ->canBeEnabled()
                ->end()
                ->arrayNode('monolog')
                    ->canBeEnabled()
                ->end()
                ->arrayNode('swift_mailer')
                    ->canBeEnabled()
                ->end()
                ->arrayNode('sentry')
                    ->canBeEnabled()
                ->end()
                ->arrayNode('simple_bus_rabbit_mq')
                    ->canBeEnabled()
                ->end()
            ->end();

        return $treeBuilder;
    }
}

<?php

namespace LongRunning\Bundle\LongRunningBundle\DependencyInjection;

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

class Configuration implements ConfigurationInterface
{
    public function __construct($alias)
    {
        $this->alias = $alias;
    }

    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder($this->alias);

        if (method_exists($treeBuilder, 'getRootNode')) {
            $rootNode = $treeBuilder->getRootNode();
        } else {
            // BC layer for symfony/config 4.1 and older
            $rootNode = $treeBuilder->root($this->alias);
        }

        $rootNode
            ->children()
                ->arrayNode('bernard')
                    ->canBeEnabled()
                ->end()
                ->arrayNode('doctrine_orm')
                    ->canBeEnabled()
                ->end()
                ->arrayNode('doctrine_dbal')
                    ->canBeEnabled()
                ->end()
                ->arrayNode('monolog')
                    ->canBeEnabled()
                ->end()
                ->arrayNode('swift_mailer')
                    ->canBeEnabled()
                ->end()
                ->arrayNode('sentry')
                    ->canBeEnabled()
                ->end()
                ->arrayNode('simple_bus_rabbit_mq')
                    ->canBeEnabled()
                ->end()
            ->end();

        return $treeBuilder;
    }
}

Update bundle configuration for Symfony 4.2 change


<?php

declare(strict_types=1);

namespace Wingu\FluffyPoRobot\Translation\Loader;

use Symfony\Component\Translation\Exception\InvalidResourceException;
use Symfony\Component\Yaml\Exception\ParseException;
use Symfony\Component\Yaml\Parser as YamlParser;
use Symfony\Component\Yaml\Yaml;
use function array_values;
use function is_array;
use function Safe\file_get_contents;
use function Safe\sprintf;

class YamlFileLoader extends FileLoader
{
    /**
     * {@inheritdoc}
     */
    protected function loadResource(string $resource) : array
    {
        try {
            $yamlParser   = new YamlParser();
            $translations = $yamlParser->parse(file_get_contents($resource), Yaml::DUMP_OBJECT_AS_MAP);
        } catch (ParseException $e) {
            throw new InvalidResourceException(sprintf('Error parsing YAML, invalid file "%s"', $resource), 0, $e);
        }

        $messages = [];
        foreach ($translations as $key => $message) {
            $messages[$key] = is_array($message) ? array_values($message) : $message;
        }

        return $messages;
    }
}

<?php

declare(strict_types=1);

namespace Wingu\FluffyPoRobot\Translation\Loader;

use Symfony\Component\Translation\Exception\InvalidResourceException;
use Symfony\Component\Yaml\Exception\ParseException;
use Symfony\Component\Yaml\Parser as YamlParser;
use Symfony\Component\Yaml\Yaml;
use function array_values;
use function is_array;
use function Safe\file_get_contents;
use function Safe\sprintf;

class YamlFileLoader extends FileLoader
{
    /**
     * {@inheritdoc}
     */
    protected function loadResource(string $resource) : array
    {
        try {
            $yamlParser   = new YamlParser();
            $translations = $yamlParser->parse(file_get_contents($resource), Yaml::DUMP_OBJECT_AS_MAP);
        } catch (ParseException $e) {
            throw new InvalidResourceException(sprintf('Error parsing YAML, invalid file "%s"', $resource), 0, $e);
        }

        if ($translations === null) {
            return [];
        }

        $messages = [];
        foreach ($translations as $key => $message) {
            $messages[$key] = is_array($message) ? array_values($message) : $message;
        }

        return $messages;
    }
}

Check if any translations are present in file


<?php namespace Leean\Endpoints\Inc;

/**
 * Class Template
 *
 * @package Leean\Endpoints\Inc
 */
class Template
{
	/**
	 * Returns the type for the post, the term template applies to what type of
	 * post is or what type of template is using.
	 *
	 * @param Int|\WP_Post $post The post
	 * @return string
	 */
	public static function get( $post ) {
		$post = is_a( $post, 'WP_Post' ) ? $post : get_post( $post );
		$type = $post->post_type;
		if ( 'page' === $type ) {
			$template_slug = get_page_template_slug( $post->ID );
			$type = empty( $template_slug )
				? 'default'
				: basename( $template_slug, '.php' );
		}
		return $type;
	}
}

<?php namespace Leean\Endpoints\Inc;

/**
 * Class Template
 *
 * @package Leean\Endpoints\Inc
 */
class Template
{
	/**
	 * Returns the type for the post, the term template applies to what type of
	 * post is or what type of template is using.
	 *
	 * @param Int|\WP_Post $post The post
	 * @return string
	 */
	public static function get( $post ) {
		$post = is_a( $post, 'WP_Post' ) ? $post : get_post( $post );
		$type = $post->post_type;
		if ( 'page' === $type ) {
			$template_slug = get_page_template_slug( $post->ID );
			if ( ! empty( $template_slug ) ) {
				$type .= '-' . wp_basename( $template_slug, '.php' );
			}
		}
		return $type;
	}
}

Append template name and replace by i18n friendly version of basename


<?php

namespace Omnipay\AuthorizeNet\Message;

use Omnipay\Tests\TestCase;

class AIMRefundRequestTest extends TestCase
{
    public function setUp()
    {
        $this->request = new AIMRefundRequest($this->getHttpClient(), $this->getHttpRequest());
        $this->request->initialize(
            array(
                'amount' => '12.00',
                'transactionReference' => '60O2UZ',
                'currency' => 'USD',
                'card' => $this->getValidCard(),
            )
        );
    }

    public function testGetData()
    {
        $data = $this->request->getData();

        $card = $this->getValidCard();

        $this->assertSame('CREDIT', $data['x_type']);
        $this->assertSame('60O2UZ', $data['x_trans_id']);
        $this->assertSame($card['number'], $data['x_card_num']);
        $this->assertSame('12.00', $data['x_amount']);
    }
}

<?php

namespace Omnipay\AuthorizeNet\Message;

use Omnipay\Tests\TestCase;

class AIMRefundRequestTest extends TestCase
{
    public function setUp()
    {
        $this->request = new AIMRefundRequest($this->getHttpClient(), $this->getHttpRequest());
        $this->request->initialize(
            array(
                'amount' => '12.00',
                'transactionReference' => '60O2UZ',
                'currency' => 'USD',
                'card' => $this->getValidCard(),
            )
        );
    }

    public function testGetData()
    {
        $data = $this->request->getData();

        $card = $this->getValidCard();

        $this->assertSame('CREDIT', $data['x_type']);
        $this->assertSame('60O2UZ', $data['x_trans_id']);
        $this->assertSame($card['number'], $data['x_card_num']);
        $this->assertSame('12.00', $data['x_amount']);

        $this->assertArrayHasKey('x_exp_date', $data);
    }

    public function testRefundWithSimplifiedCard()
    {
        $simplifiedCard = array(
            'firstName' => 'Example',
            'lastName' => 'User',
            'number' => '1111',
        );

        $this->request->setCard($simplifiedCard);

        $data = $this->request->getData();

        $this->assertSame($simplifiedCard['number'], $data['x_card_num']);

        $this->assertArrayNotHasKey('x_exp_date', $data);
    }
}

[AIMRefundRequest] Add test when no credit card expiry dates are set


	<?php
	$notices = \FelixOnline\Core\BaseManager::build('FelixOnline\Core\Notice', 'notices');
	$notices->filter('hidden = 0')
		->filter('end_time > NOW()')
		->filter('start_time < NOW()');

	$converter = new \Sioen\Converter();

	if($no_frontpage_only) {
		$notices->filter('frontpage = TRUE');
	}

	$notices = $notices->order('sort_order', 'DESC')->values();

	if (!is_null($notices)) {
		?>

				<?php
		foreach($notices as $notice) { ?>
			<?php
				$text = preg_replace('/
]*><\\/p[^>]*>/i', '', $converter->toHTML($notice->getContent()));
				$text = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $text); // Some
^B
 tags can get through some times
				$text = strip_tags($text, '
'); // Shrink down the valid tag list
				$text = preg_replace("/
]*?>/", "", $text);
				$text = str_replace("
", "
", $text); // Replace p with br as p is messy in the notice area
			?>

<?php echo strtoupper(date('D j M, g:i A', $notice->getStartTime())); ?> <?php echo $text; ?>

		<?php }
				?>

		<?php
	} ?>

	<?php
	$notices = \FelixOnline\Core\BaseManager::build('FelixOnline\Core\Notice', 'notices');
	$notices->filter('hidden = 0')
		->filter('end_time > NOW()')
		->filter('start_time < NOW()');

	$converter = new \Sioen\Converter();

	if($no_frontpage_only) {
		$notices->filter('frontpage = TRUE');
	}

	$notices = $notices->order('sort_order', 'DESC')->values();

	if (!is_null($notices)) {
		?>

				<?php
		foreach($notices as $notice) { ?>
			<?php
				$text = strip_tags($notice->getContent(), '');
			?>

<?php echo strtoupper(date('D j M, g:i A', $notice->getStartTime())); ?> <?php echo $text; ?>

		<?php }
				?>

		<?php
	} ?>

Convert notice sot use new model format

Convert notice sot use new model format


<?php

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        // $this->call(UserTableSeeder::class);
    }
}

<?php

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $this->call(UserTableSeeder::class);
        $this->call(ImageTableSeeder::class);
        $this->call(ArticleTableSeeder::class);
        $this->call(CountryTableSeeder::class);
        $this->call(CityTableSeeder::class);
        $this->call(PlaceTableSeeder::class);
        $this->call(TagTableSeeder::class);
        $this->call(PlaceTagTableSeeder::class);
        $this->call(ArticleTagTableSeeder::class);
        $this->call(CountryImageTableSeeder::class);
        $this->call(CityImageTableSeeder::class);
        $this->call(PlaceImageTableSeeder::class);
        $this->call(ArticleImageTableSeeder::class);
    }
}

Call other seeds through classes.

Call other seeds through classes.


<?php

namespace App\Http\Controllers;

use App\Http\Transformers\ServiceTransformer;
use App\Models\Service;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class ServicesController extends Controller
{
    /**
     * Get all entities
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index(Request $request)
    {
        $label = $request->get('label', '');
        $uri = $request->get('uri', '');

        $services = Service::where('label', 'like', '%' . $label . '%');

        if (!empty($uri)) {
            $services->where('uri', $uri);
        }

        $services->where('draft', false);

        return response()->collection(new ServiceTransformer(), $services->get());
    }

    /**
     * Get with id
     * Base get and return the service
     *
     * @return Response
     */
    public function show(Service $service)
    {
        if($service->draft){
            $exception = new ModelNotFoundException();
            $exception->setModel(Service::class);
            throw $exception;
        }

        return response()->item(new ServiceTransformer(), $service);
    }
}

<?php

namespace App\Http\Controllers;

use App\Http\Transformers\ServiceTransformer;
use App\Models\Service;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class ServicesController extends Controller
{
    /**
     * Get all entities
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index(Request $request)
    {
        $label = $request->get('label', '');
        $uri = $request->get('uri', '');
        $source = $request->get('source', '');
        $sourceId = $request->get('sourceId', '');

        $services = Service::where('label', 'like', '%' . $label . '%');

        if (!empty($uri)) {
            $services->where('uri', $uri);
        }
        if (!empty($source)) {
            $services->where('source', $source);
        }
        if (!empty($sourceId)) {
            $services->where('identifier', $sourceId);
        }

        $services->where('draft', false);

        return response()->collection(new ServiceTransformer(), $services->get());
    }

    /**
     * Get with id
     * Base get and return the service
     *
     * @return Response
     */
    public function show(Service $service)
    {
        if($service->draft){
            $exception = new ModelNotFoundException();
            $exception->setModel(Service::class);
            throw $exception;
        }

        return response()->item(new ServiceTransformer(), $service);
    }
}

Add source and sourceId query parameter support

To match the spec published on SwaggerHub.


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Inertia\Inertia;
use App\Models\Platform;

class TimelineController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return Inertia::render('Timeline/Show', [
            'platforms' => Platform::orderBy('position')->paginate(50)->map(function ($platform) {
                return [
                    'id' => $platform->id,
                    'name' => $platform->name,
                    'color' => $platform->color,
                    'icon' => $platform->icon,
                    'legacy' => $platform->legacy,
                    'url' => route('front.timeline.show', $platform, false)
                ];
            }),
            'status' => session('status')
        ]);
    }
}

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Inertia\Inertia;
use App\Models\Platform;

class TimelineController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return Inertia::render('Timeline/Show', [
            'platforms' => Platform::orderBy('position')->get()->map(function ($platform) {
                return [
                    'name' => $platform->name,
                    'color' => $platform->color,
                    'icon' => $platform->icon,
                    'legacy' => $platform->legacy,
                    'url' => route('front.timeline.show', $platform, false)
                ];
            }),
            'status' => session('status')
        ]);
    }
}

Drop pagination for Timeline platforms

Drop pagination for Timeline platforms


<?php namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class InverterServiceProvider extends ServiceProvider {

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

	/**
	 * Bootstrap any inverter services.
	 *
	 * @return void
	 */
	public function boot()
	{
		//
	}

	/**
	 * Register any inverter services.
	 *
	 * @return void
	 */
	public function register()
	{
		switch (env('INV_DRIVER')) {
			case 'stecagrid':
				$driver = 'StecaGrid';
				break;
		}

		$this->app->singleton('App\Contracts\Inverter', 'App\Services\Inverters\\'.$driver);
	}

	/**
	 * Get the services provided by this provider.
	 *
	 * @return array
	 */
	public function provides()
	{
		return ['App\Contracts\Inverter'];
	}

}

<?php namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class InverterServiceProvider extends ServiceProvider {

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

	/**
	 * Bootstrap any inverter services.
	 *
	 * @return void
	 */
	public function boot()
	{
		//
	}

	/**
	 * Register any inverter services.
	 *
	 * @return void
	 */
	public function register()
	{
		switch (env('INV_DRIVER')) {
			case 'stecagrid':
				$driver = 'StecaGrid';
				break;

			default:
				$this->app->abort(501, 'Configured driver not supported.');
				break;

		}

		$this->app->singleton('App\Contracts\Inverter', 'App\Services\Inverters\\'.$driver);
	}

	/**
	 * Get the services provided by this provider.
	 *
	 * @return array
	 */
	public function provides()
	{
		return ['App\Contracts\Inverter'];
	}

}

Throw an exception if the configured driver does not exist.


<?php

namespace Igorw\Trashbin;

class FileStorage implements Storage
{
    private $storageDirectory;

    public function __construct($storageDirectory)
    {
        $this->storageDirectory = rtrim($storageDirectory, '\\/') . DIRECTORY_SEPARATOR;
    }

    public function get($id)
    {
        if( !file_exists( $this->pathTo($id) ) ) {
            return false;
        }
        return json_decode( file_get_contents($this->pathTo($id) ));
    }

    public function set($id, array $value)
    {
        return file_put_contents($this->pathTo($id), json_encode($value)) !== false;
    }

    private function pathTo($id)
    {
        return $this->storageDirectory . $id . '.json';
    }
}

<?php

namespace Igorw\Trashbin;

class FileStorage implements Storage
{
    private $storageDirectory;

    public function __construct($storageDirectory)
    {
        $this->storageDirectory = rtrim($storageDirectory, '\\/').'/';
    }

    public function get($id)
    {
        if (!file_exists($this->pathTo($id))) {
            return false;
        }
        return json_decode(file_get_contents($this->pathTo($id)));
    }

    public function set($id, array $value)
    {
        return file_put_contents($this->pathTo($id), json_encode($value)) !== false;
    }

    private function pathTo($id)
    {
        return $this->storageDirectory.$id.'.json';
    }
}

Fix formatting of previous merge

Fix formatting of previous merge


<?php
$subject = $this->email->getHeaderValue('Subject', '<Empty Subject>');
$this->title($subject);
?>

    <a href="<?= $this->escape()->attr($this->route('list')); ?>">Outgoing emails - listing >
    <?= $this->escape()->html($subject);?>

        <?php
        foreach ($this->email->getHeaders() as $header) {
            echo "
", $this->escape()->html($header->getName()), "
\r\n";
            echo "
", $this->escape()->html($header->getValue()), "
\r\n";
        }
        ?>

        <a href="<?= $this->escape()->attr($this->route('list')); ?>">Back to email list

    <?php
    $html = $this->email->getHtmlContent();
    if ($html !== null) {
        echo preg_replace('/.*?(.*?)<\/body>.*?/ims', '$1', $html);
    } else {
        echo nl2br($this->escape()->html($this->email->getTextContent()));
    }
    ?>

Add   to header values to force a value

Add   to header values to force a value


<?php
require_once __DIR__ . '/base.php';
require_once __DIR__ . '/labeled-input.php';
require_once __DIR__ . '/text-button.php';
require_once __DIR__ . '/../../lib/utils.php';

class LoginForm extends RawDataContainer implements Component {
  public function render(): Component {
    $action = $this->getDefault('action', '.');
    $signup = $this->getDefault('sign-up', '.');

    return HtmlElement::emmetTop('form', [
      'action' => $action,
      HtmlElement::emmetTop('.input-container', [
        LabeledInput::text('username', 'Tên đăng nhập'),
        LabeledInput::text('password', 'Mật khẩu'),
      ]),
      HtmlElement::emmetTop('.button-container', [
        new PrimaryButton([
          'type' => 'submit',
          'Đăng nhập',
        ]),
        new PrimaryButton([
          'type' => 'reset',
          'Xóa',
        ]),
        HtmlElement::emmetTop('a#sign-up-anchor.sign-up', [
          'href' => $signup,
          'Tạo tài khoản',
        ]),
      ]),
    ]);
  }
}
?>

<?php
require_once __DIR__ . '/base.php';
require_once __DIR__ . '/labeled-input.php';
require_once __DIR__ . '/text-button.php';
require_once __DIR__ . '/../../lib/utils.php';

class LoginForm extends RawDataContainer implements Component {
  public function render(): Component {
    $action = $this->getDefault('action', '.');
    $signup = $this->getDefault('sign-up', null);

    return HtmlElement::emmetTop('form', [
      'action' => $action,
      HtmlElement::emmetTop('.input-container', [
        LabeledInput::text('username', 'Tên đăng nhập'),
        LabeledInput::text('password', 'Mật khẩu'),
      ]),
      HtmlElement::emmetTop('.button-container', [
        new PrimaryButton([
          'type' => 'submit',
          'Đăng nhập',
        ]),
        new PrimaryButton([
          'type' => 'reset',
          'Xóa',
        ]),
        $signup === null
          ? ''
          : HtmlElement::emmetTop('a#sign-up-anchor.sign-up', [
            'href' => $signup,
            'Tạo tài khoản',
          ])
        ,
      ]),
    ]);
  }
}
?>

Create option to not render sign up link


<?php

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

namespace Symfony\Component\VarDumper\Tests\Command;

use PHPUnit\Framework\TestCase;
use Symfony\Component\Console\Tester\CommandCompletionTester;
use Symfony\Component\VarDumper\Command\ServerDumpCommand;
use Symfony\Component\VarDumper\Server\DumpServer;

class ServerDumpCommandTest extends TestCase
{
    /**
     * @dataProvider provideCompletionSuggestions
     */
    public function testComplete(array $input, array $expectedSuggestions)
    {
        if (!class_exists(CommandCompletionTester::class)) {
            $this->markTestSkipped('Test command completion requires symfony/console 5.4+.');
        }

        $tester = new CommandCompletionTester($this->createCommand());

        $this->assertSame($expectedSuggestions, $tester->complete($input));
    }

    public function provideCompletionSuggestions()
    {
        yield 'option --format' => [
            ['--format', ''],
            ['cli', 'html'],
        ];
    }

    private function createCommand(): ServerDumpCommand
    {
        return new ServerDumpCommand($this->createMock(DumpServer::class));
    }
}

<?php

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

namespace Symfony\Component\VarDumper\Tests\Command;

use PHPUnit\Framework\TestCase;
use Symfony\Component\Console\Tester\CommandCompletionTester;
use Symfony\Component\VarDumper\Command\ServerDumpCommand;
use Symfony\Component\VarDumper\Server\DumpServer;

class ServerDumpCommandTest extends TestCase
{
    /**
     * @dataProvider provideCompletionSuggestions
     */
    public function testComplete(array $input, array $expectedSuggestions)
    {
        $tester = new CommandCompletionTester($this->createCommand());

        $this->assertSame($expectedSuggestions, $tester->complete($input));
    }

    public function provideCompletionSuggestions()
    {
        yield 'option --format' => [
            ['--format', ''],
            ['cli', 'html'],
        ];
    }

    private function createCommand(): ServerDumpCommand
    {
        return new ServerDumpCommand($this->createMock(DumpServer::class));
    }
}

Clean skippable tests that are never skipped


<?php
namespace Gt\Dom;

/**
 * Represents any web page loaded in the browser and serves as an entry point
 * into the web page's content, the DOM tree (including elements such as
 * <body> or <table>).
 */
class Document extends \DOMDocument {
use LiveProperty, ParentNode;

public function __construct($document = null) {
	parent::__construct("1.0", "utf-8");
	$this->registerNodeClass("\\DOMNode", Node::class);
	$this->registerNodeClass("\\DOMElement", Element::class);
	$this->registerNodeClass("\\DOMAttr", Attr::class);
	$this->registerNodeClass("\\DOMDocumentFragment", DocumentFragment::class);
	$this->registerNodeClass("\\DOMDocumentType", DocumentType::class);
	$this->registerNodeClass("\\DOMCharacterData", CharacterData::class);
	$this->registerNodeClass("\\DOMText", Text::class);
	$this->registerNodeClass("\\DOMComment", Comment::class);

	if ($document instanceof \DOMDocument) {
		$node = $this->importNode($document->documentElement, true);
		$this->appendChild($node);
		return;
	}
}

protected  function getRootDocument(): \DOMDocument {
	return $this;
}

}#

<?php
namespace Gt\Dom;
use DOMNode;

/**
 * Represents any web page loaded in the browser and serves as an entry point
 * into the web page's content, the DOM tree (including elements such as
 * <body> or <table>).
 *
 * @method Node importNode(DOMNode $importedNode, bool $deep = false)
 */
class Document extends \DOMDocument {
use LiveProperty, ParentNode;

public function __construct($document = null) {
	parent::__construct("1.0", "utf-8");
	$this->registerNodeClass("\\DOMNode", Node::class);
	$this->registerNodeClass("\\DOMElement", Element::class);
	$this->registerNodeClass("\\DOMAttr", Attr::class);
	$this->registerNodeClass("\\DOMDocumentFragment", DocumentFragment::class);
	$this->registerNodeClass("\\DOMDocumentType", DocumentType::class);
	$this->registerNodeClass("\\DOMCharacterData", CharacterData::class);
	$this->registerNodeClass("\\DOMText", Text::class);
	$this->registerNodeClass("\\DOMComment", Comment::class);

	if ($document instanceof \DOMDocument) {
		$node = $this->importNode($document->documentElement, true);
		$this->appendChild($node);
		return;
	}
}

protected  function getRootDocument(): \DOMDocument {
	return $this;
}

}#

Define Node properties and methods

Define Node properties and methods


<?php namespace CodeIgniter\Config;

use Config\Email;

class ConfigTest extends \CIUnitTestCase
{

	public function testCreateSingleInstance()
	{
		$Config          = Config::get('Format', false);
		$NamespaceConfig = Config::get('Config\\Format', false);

		$this->assertInstanceOf(Email::class, $Config);
		$this->assertInstanceOf(Email::class, $NamespaceConfig);
	}

	public function testCreateInvalidInstance()
	{
		$Config = Config::get('gfnusvjai', false);

		$this->assertNull($Config);
	}

	public function testCreateSharedInstance()
	{
		$Config  = Config::get('Format' );
		$Config2 = Config::get('Config\\Format');

		$this->assertTrue($Config === $Config2);
	}

	public function testCreateNonConfig()
	{
		$Config = Config::get('Constants', false);

		$this->assertNull($Config);
	}
}

<?php namespace CodeIgniter\Config;

use Config\Email;

class ConfigTest extends \CIUnitTestCase
{

	public function testCreateSingleInstance()
	{
		$Config          = Config::get('Format', false);
		$NamespaceConfig = Config::get('Config\\Format', false);

		$this->assertInstanceOf(Format::class, $Config);
		$this->assertInstanceOf(Format::class, $NamespaceConfig);
	}

	public function testCreateInvalidInstance()
	{
		$Config = Config::get('gfnusvjai', false);

		$this->assertNull($Config);
	}

	public function testCreateSharedInstance()
	{
		$Config  = Config::get('Format' );
		$Config2 = Config::get('Config\\Format');

		$this->assertTrue($Config === $Config2);
	}

	public function testCreateNonConfig()
	{
		$Config = Config::get('Constants', false);

		$this->assertNull($Config);
	}
}

Remove Email module - missed tests

Remove Email module - missed tests


<?php

namespace App\Entities;

use Illuminate\Database\Eloquent\Model as Model;

class Lead extends Model
{

    protected $table = 'leads';

    public $timestamps = false;

    public function getFullNameAttribute($value)
    {
        return $this->attributes['name'];
    }
}

<?php

namespace App\Entities;

use Illuminate\Database\Eloquent\Model as Model;

class Lead extends Model
{

    protected $table = 'leads';

    public $timestamps = false;

    public function getFullNameAttribute($value)
    {
        return $this->attributes['name'];
    }

    public function isRegistered($email)
    {
        return $this->where('email', '=', $email)->first();
    }

}

Add isRegistered method to lead entity

Add isRegistered method to lead entity


<?= t('Change category for the task "%s"', $values['title']) ?>

        <form method="post" action="<?= $this->url->href('board', 'updateCategory', array('task_id' => $values['id'], 'project_id' => $values['project_id'])) ?>">

            <?= $this->form->csrf() ?>

            <?= $this->form->hidden('id', $values) ?>
            <?= $this->form->hidden('project_id', $values) ?>

            <?= $this->form->label(t('Category'), 'category_id') ?>
            <?= $this->form->select('category_id', $categories_list, $values) ?>

                <input type="submit" value="<?= t('Save') ?>" class="btn btn-blue"/>
                <?= t('or') ?>
                <?= $this->url->link(t('cancel'), 'board', 'show', array('project_id' => $project['id']), false, 'close-popover') ?>

        </form>

<?= t('Change category for the task "%s"', $values['title']) ?>

        <form method="post" action="<?= $this->url->href('board', 'updateCategory', array('task_id' => $values['id'], 'project_id' => $values['project_id'])) ?>">

            <?= $this->form->csrf() ?>

            <?= $this->form->hidden('id', $values) ?>
            <?= $this->form->hidden('project_id', $values) ?>

            <?= $this->form->label(t('Category'), 'category_id') ?>
            <?= $this->form->select('category_id', $categories_list, $values, array(), array('autofocus')) ?>

                <input type="submit" value="<?= t('Save') ?>" class="btn btn-blue"/>
                <?= t('or') ?>
                <?= $this->url->link(t('cancel'), 'board', 'show', array('project_id' => $project['id']), false, 'close-popover') ?>

        </form>

Set focus on the dropdown for category popover


<?php
namespace SmoothPhp\CommandBus;

use Rhumsaa\Uuid\Uuid;
use SmoothPhp\Contracts\CommandBus\Command;

/**
 * Class Command
 * @package SmoothPhp\CommandBus
 * @author Simon Bennett <simon.bennett@smoothphp.com>
 */
abstract class BaseCommand implements Command
{
    /**
     * @var string
     */
    public $commandId;

    /**
     * Give the command a Uuid, Used to logging and auditing
     */
    public function __construct()
    {
        $this->commandId = (string)Uuid::uuid4();
    }

    /**
     * @return string
     */
    public function __toString()
    {
        return get_class($this) . ':' . $this->commandId;
    }
}

<?php
namespace SmoothPhp\CommandBus;

use Ramsey\Uuid\Uuid;
use SmoothPhp\Contracts\CommandBus\Command;

/**
 * Class Command
 * @package SmoothPhp\CommandBus
 * @author Simon Bennett <simon.bennett@smoothphp.com>
 */
abstract class BaseCommand implements Command
{
    /**
     * @var string
     */
    public $commandId;

    /**
     * Give the command a Uuid, Used to logging and auditing
     */
    public function __construct()
    {
        $this->commandId = (string)Uuid::uuid4();
    }

    /**
     * @return string
     */
    public function __toString()
    {
        return get_class($this) . ':' . $this->commandId;
    }
}

Swap to the correct Uuid library

Swap to the correct Uuid library


<?php

namespace Pinq\Tests\Integration\Collection;

class ApplyTest extends CollectionTest
{
    /**
     * @dataProvider Everything
     */
    public function testThatExecutionIsNotDeferred(\Pinq\ICollection $Collection, array $Data)
    {
        if(count($Data) > 0) {
            $this->AssertThatExecutionIsNotDeferred([$Collection, 'Apply']);
        }
    }

    /**
     * @dataProvider AssocOneToTen
     */
    public function testThatCollectionApplyOperatesOnTheSameCollection(\Pinq\ICollection $Collection, array $Data)
    {
        static $Count = 0;
        $Count++;
        var_dump($Count);
        $Multiply = function (&$I) { $I = "\\r" . $I * 10 . PHP_EOL; };
        $Collection->Apply($Multiply);

        array_walk($Data, $Multiply);
        $this->AssertMatches($Collection, $Data);
    }
}

<?php

namespace Pinq\Tests\Integration\Collection;

class ApplyTest extends CollectionTest
{
    /**
     * @dataProvider Everything
     */
    public function testThatExecutionIsNotDeferred(\Pinq\ICollection $Collection, array $Data)
    {
        if(count($Data) > 0) {
            $this->AssertThatExecutionIsNotDeferred([$Collection, 'Apply']);
        }
    }

    /**
     * @dataProvider AssocOneToTen
     */
    public function testThatCollectionApplyOperatesOnTheSameCollection(\Pinq\ICollection $Collection, array $Data)
    {
        $Multiply = function (&$I) { $I *= 10; };
        $Collection->Apply($Multiply);

        array_walk($Data, $Multiply);
        $this->AssertMatches($Collection, $Data);
    }
}

Remove whatever was causing HHVM segfault


<?php
declare(strict_types=1);

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

/**
 * Class ChangesForV540
 */
class ChangesForV540 extends Migration
{
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down(): void
    {
        Schema::table(
            'accounts', static function (Blueprint $table) {
            $table->dropColumn('order');
        }
        );
    }

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up(): void
    {
        Schema::table(
            'accounts', static function (Blueprint $table) {
            $table->integer('order', false, true)->default(0);
        }
        );
    }
}

<?php
declare(strict_types=1);

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

/**
 * Class ChangesForV540
 */
class ChangesForV540 extends Migration
{
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down(): void
    {
        Schema::table(
            'oauth_clients', static function (Blueprint $table) {
            $table->dropColumn('order');
        }
        );

        Schema::table(
            'accounts', static function (Blueprint $table) {
            $table->dropColumn('provider');
        }
        );
    }

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up(): void
    {
        Schema::table(
            'accounts', static function (Blueprint $table) {
            $table->integer('order', false, true)->default(0);
        }
        );
        Schema::table(
            'oauth_clients', static function (Blueprint $table) {
            $table->string('provider')->nullable();
        }
        );

    }
}

Add column for new OAuth thing.

Add column for new OAuth thing.


<?php

use SensioLabs\Behat\PageObjectExtension\PageObject\Page;

class AddAssessment extends Page
{
    protected $path = "/assessments/add";
}

<?php

use SensioLabs\Behat\PageObjectExtension\PageObject\Page;

class AddAssessment extends Page
{
    protected $path = "/assessments/new";
}

Rename path for assessment add form

Rename path for assessment add form


<?php

declare(strict_types=1);

namespace Orchid\Screen\Traits;

use Illuminate\Support\Arr;

/**
 * Trait AsSource.
 */
trait AsSource
{
    /**
     * @var array|null
     */
    protected $contentCache;

    /**
     * @param string $field
     *
     * @return mixed|null
     */
    public function getContent(string $field)
    {
        /** @var self \Illuminate\Database\Eloquent\Model */
        $model = $this->contentCache ?? $this->toArray();

        return Arr::get($model, $field) ?? Arr::get($this->getRelations(), $field);
    }
}

<?php

declare(strict_types=1);

namespace Orchid\Screen\Traits;

use Illuminate\Support\Arr;

/**
 * Trait AsSource.
 */
trait AsSource
{
    /**
     * @param string $field
     *
     * @return mixed|null
     */
    public function getContent(string $field)
    {
        return Arr::get($this->toArray(), $field) ?? Arr::get($this->getRelations(), $field);
    }
}

Remove cache for source trait

Remove cache for source trait


// Add featured images support
add_theme_support('post-thumbnails');

// Image dimensions
add_image_size('random-profile', 200, 200, true);
add_image_size('program-detail', 1400, 460, true);

Add second image thumbnail example

Add second image thumbnail example


      <a class="brand" href="<?php echo home_url(); ?>/"><?php bloginfo('name'); ?>

        <?php
          if (has_nav_menu('primary_navigation')) :
            wp_nav_menu(array('theme_location' => 'primary_navigation', 'menu_class' => 'nav nav-pills'));
          endif;
        ?>

      <a class="brand" href="<?php echo home_url('/') ?>"><?php bloginfo('name'); ?>

        <?php
          if (has_nav_menu('primary_navigation')) :
            wp_nav_menu(array('theme_location' => 'primary_navigation', 'menu_class' => 'nav nav-pills'));
          endif;
        ?>

Add trailing slash using the $path parameter


<?php

/*
 * Include the composer autoload file.
 */

include('../vendor/autoload.php');

/*
 * Load in the configuration information.
 * Make sure to replace the keys with your own.
 */

$configuration = new \Ziftr\ApiClient\Configuration();

$configuration->load_from_array(array(
  'host' => 'sandbox.fpa.bz',
  'port' => 443,
  'private_key' => '...',
  'publishable_key' => '...'
));

/*
 * Create a new order request.
 */

$order = new \Ziftr\ApiClient\Request('/orders/', $configuration, false);

try {

  /*
   * POST the request with the order data.
   * See the documentation for possible fields.
   */

  $order = $order->post(
    array(
      'order' => array(
        'currency_code' => 'USD',
        'is_shipping_required' => true
      )
    )
  );

  print_r($order->getResponse());

  /*
   * Create a new request object for the items endpoint.
   * This method is preffered to creating a URL directly.
   */

  $itemsReq = $order->linkRequest('items');

  /*
   * Add an order item.
   */

  $itemsReq->post(array(
    'order_item' => array(
      'name' => 'Test Item',
      'price' => 100,
      'quantity' => 1,
      'currency_code' => 'USD'
    )
  ));

  print_r($itemsReq->getResponse());

} catch( Exception $e ) {
}

<?php

/*
 * Include the composer autoload file.
 */

include('../vendor/autoload.php');

/*
 * Load in the configuration information.
 * Make sure to replace the keys with your own.
 */

$configuration = new \Ziftr\ApiClient\Configuration();

$configuration->load_from_array(array(
  'host' => 'sandbox.fpa.bz',
  'port' => 443,
  'private_key' => '...',
  'publishable_key' => '...'
));

/*
 * Create a new order request.
 */

$order = new \Ziftr\ApiClient\Request('/orders/', $configuration);

try {

  /*
   * POST the request with the order data.
   * See the documentation for possible fields.
   */

  $order = $order->post(
    array(
      'order' => array(
        'currency_code' => 'USD',
        'is_shipping_required' => true
      )
    )
  );

  print_r($order->getResponse());

  /*
   * Create a new request object for the items endpoint.
   * This method is preffered to creating a URL directly.
   */

  $itemsReq = $order->linkRequest('items');

  /*
   * Add an order item.
   */

  $itemsReq->post(array(
    'order_item' => array(
      'name' => 'Test Item',
      'price' => 100,
      'quantity' => 1,
      'currency_code' => 'USD'
    )
  ));

  print_r($itemsReq->getResponse());

} catch( Exception $e ) {
}

Exclude secure false from example

Exclude secure false from example


<?php

class GitRepository
{
    public $path;

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

    public function git_upload_pack()
    {

    }

    public function git_receive_pack()
    {

    }
}

?>

<?php

class GitRepository
{
    public $path;

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

?>

Remove git_upload/receive_pack() methods from GitRepository class---not planned for this class anymore


<?php

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

class CreateMediaEndpointTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('media_endpoint', function (Blueprint $table) {
            $table->increments('id');
            $table->text('token')->nullable();
            $table->varchar('path');
            $table->unsignedInteger('note_id')->nullable();
            $table->timestamps();

            $table->primary('id');
            $table->index('token');
            $table->foreign('note_id')->references('id')->on('notes');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Scheme::table('media_endpoint', function (Blueprint $table) {
            $table->dropForeign(['note_id']);
        });
        Schema::dropIfExists('media_endpoint');
    }
}

<?php

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

class CreateMediaEndpointTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('media_endpoint', function (Blueprint $table) {
            $table->increments('id');
            $table->text('token')->nullable();
            $table->string('path');
            $table->unsignedInteger('note_id')->nullable();
            $table->timestamps();

            $table->primary('id');
            $table->index('token');
            $table->foreign('note_id')->references('id')->on('notes');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Scheme::table('media_endpoint', function (Blueprint $table) {
            $table->dropForeign(['note_id']);
        });
        Schema::dropIfExists('media_endpoint');
    }
}

Use the correct method for a VARCHAR column


<?php
/*
 * WellCommerce Open-Source E-Commerce Platform
 *
 * This file is part of the WellCommerce package.
 *
 * (c) Adam Piotrowski <adam@wellcommerce.org>
 *
 * For the full copyright and license information,
 * please view the LICENSE file that was distributed with this source code.
 */

namespace WellCommerce\Bundle\LocaleBundle\Tests\Manager\Admin;

use WellCommerce\Bundle\CoreBundle\Test\Manager\AbstractManagerTestCase;

/**
 * Class LocaleManagerTest
 *
 * @author  Adam Piotrowski <adam@wellcommerce.org>
 */
class LocaleManagerTest extends AbstractManagerTestCase
{
    protected function get()
    {
        return $this->container->get('locale.manager');
    }
}

<?php
/*
 * WellCommerce Open-Source E-Commerce Platform
 *
 * This file is part of the WellCommerce package.
 *
 * (c) Adam Piotrowski <adam@wellcommerce.org>
 *
 * For the full copyright and license information,
 * please view the LICENSE file that was distributed with this source code.
 */

namespace WellCommerce\Bundle\LocaleBundle\Tests\Manager\Admin;

use WellCommerce\Bundle\CoreBundle\Test\Manager\AbstractManagerTestCase;
use WellCommerce\Bundle\DoctrineBundle\Manager\ManagerInterface;

/**
 * Class LocaleManagerTest
 *
 * @author  Adam Piotrowski <adam@wellcommerce.org>
 */
class LocaleManagerTest extends AbstractManagerTestCase
{
    protected function get() : ManagerInterface
    {
        return $this->container->get('locale.manager');
    }
}

Return types in manager tests

Return types in manager tests


<?php
namespace Craft;

use Carbon\Carbon;

class FeedMeDateHelper
{
    // Public Methods
    // =========================================================================

    public static function parseString($date)
    {
        $parsedDate = null;

        if (is_array($date)) {
            return $date;
        }

        try {
            $timestamp = FeedMeDateHelper::isTimestamp($date);

            if ($timestamp) {
                $date = '@' . $date;
            }

            $dt = Carbon::parse($date);

            if ($dt) {
                $dateTimeString = $dt->toDateTimeString();

                $parsedDate = DateTime::createFromString($dateTimeString, craft()->timezone);
            }
        } catch (\Exception $e) {
            FeedMePlugin::log('Date parse error: ' . $date . ' - ' . $e->getMessage(), LogLevel::Error, true);
        }

        return $parsedDate;
    }

    public static function isTimestamp($string)
    {
        try {
            new DateTime('@' . $string);
        } catch(\Exception $e) {
            FeedMePlugin::log('Date parse error: ' . $string . ' - ' . $e->getMessage(), LogLevel::Error, true);

            return false;
        }

        return true;
    }

}

<?php
namespace Craft;

use Carbon\Carbon;

class FeedMeDateHelper
{
    // Public Methods
    // =========================================================================

    public static function parseString($date)
    {
        $parsedDate = null;

        if (is_array($date)) {
            return $date;
        }

        try {
            $timestamp = FeedMeDateHelper::isTimestamp($date);

            if ($timestamp) {
                $date = '@' . $date;
            }

            $dt = Carbon::parse($date);

            if ($dt) {
                $dateTimeString = $dt->toDateTimeString();

                $parsedDate = DateTime::createFromString($dateTimeString, craft()->timezone);
            }
        } catch (\Exception $e) {
            FeedMePlugin::log('Date parse error: ' . $date . ' - ' . $e->getMessage(), LogLevel::Error, true);
        }

        return $parsedDate;
    }

    public static function isTimestamp($string)
    {
        try {
            new DateTime('@' . $string);
        } catch(\Exception $e) {
            return false;
        }

        return true;
    }

}

Remove unnesearry log when testing for timestamp