<?php
namespace Ob_Ivan\Cache\Driver;

use DateTime;
use Ob_Ivan\Cache\StorageInterface;

class MemoryDriver implements StorageInterface
{
    const KEY_EXPIRE = __LINE__;
    const KEY_VALUE  = __LINE__;

    /**
     *  @var [
     *      <string key> => [
     *          KEY_EXPIRE  => <DateTime Expiration date>,
     *          KEY_VALUE   => <mixed    Stored value>,
     *      ],
     *      ...
     *  ]
    **/
    protected $storage = [];

    public function delete($key)
    {
        unset($storage[$key]);
        return true;
    }

    public function get($key)
    {
        if (isset($storage[$key])) {
            if ($storage[$key][static::KEY_EXPIRE] < (new DateTime)) {
                unset($storage[$key]);
            } else {
                return $storage[$key][static::KEY_VALUE];
            }
        }
        return null;
    }

    public function set($key, $value, $duration = null)
    {
        if ($duration < 0) {
            return false;
        }
        $storage[$key] = [
            static::KEY_EXPIRE  => new DateTime(
                $duration > 0
                    ? '+' . intval($duration) . 'sec'
                    : '+10000years'
            ),
            static::KEY_VALUE   => $value,
        ];
        return true;
    }
}

<?php
namespace Ob_Ivan\Cache\Driver;

use DateTime;
use Ob_Ivan\Cache\StorageInterface;

class MemoryDriver implements StorageInterface
{
    const KEY_EXPIRE = __LINE__;
    const KEY_VALUE  = __LINE__;

    /**
     *  @var [
     *      <string key> => [
     *          KEY_EXPIRE  => <DateTime Expiration date>,
     *          KEY_VALUE   => <mixed    Stored value>,
     *      ],
     *      ...
     *  ]
    **/
    protected $storage = [];

    public function delete($key)
    {
        unset($this->storage[$key]);
        return true;
    }

    public function get($key)
    {
        if (isset($this->storage[$key])) {
            if ($this->storage[$key][static::KEY_EXPIRE] < (new DateTime)) {
                unset($this->storage[$key]);
            } else {
                return $this->storage[$key][static::KEY_VALUE];
            }
        }
        return null;
    }

    public function set($key, $value, $duration = null)
    {
        if ($duration < 0) {
            return false;
        }
        $this->storage[$key] = [
            static::KEY_EXPIRE  => new DateTime(
                $duration > 0
                    ? '+' . intval($duration) . 'sec'
                    : '+10000years'
            ),
            static::KEY_VALUE   => $value,
        ];
        return true;
    }
}

Fix typo: it is $this->storage, not just any local $storage


<?php

namespace WyriHaximus\Ratchet\Tests\Event;

abstract class AbstractEventTest extends \PHPUnit_Framework_TestCase
{
    public function testEventConst()
    {
        $fqcn = static::FQCN;
        $this->assertInternalType('string', $fqcn::EVENT);
        $this->assertTrue(strlen($fqcn::EVENT) > 0);
    }
}

<?php

namespace WyriHaximus\Ratchet\Tests\Event;

abstract class AbstractEventTest extends \PHPUnit_Framework_TestCase
{
    public function testEventConst()
    {
        $fqcn = static::FQCN;
        $this->assertInternalType('string', $fqcn::EVENT);
        $this->assertTrue(strlen($fqcn::EVENT) > 0);
    }

    public function testExtendsEvent()
    {
        $this->assertSame('Cake\Event\Event', (new \ReflectionClass(static::FQCN))->getParentClass()->getName());
    }
}

Make sure all events extend Event

Make sure all events extend Event


<?php
namespace Fsv\TypographyBundle\Tests\Form\Extension;

use Fsv\TypographyBundle\Form\Extension\TextareaTypeExtension;
use Fsv\TypographyBundle\Typograph\MdashTypograph;
use Symfony\Component\Form\PreloadedExtension;
use Symfony\Component\Form\Test\TypeTestCase;

class TextareaTypeExtensionTest extends TypeTestCase
{
    public function testSubmitWithTypography()
    {
        $form = $this->factory->create('Symfony\Component\Form\Extension\Core\Type\TextareaType', null, array(
            'typography' => true
        ));
        $form->submit('Типограф - это здорово!');

        $this->assertEquals('Типограф — это здорово!', $form->getData());
    }

    public function testSubmitWithoutTypography()
    {
        $form = $this->factory->create('Symfony\Component\Form\Extension\Core\Type\TextareaType', null);
        $form->submit('Типограф - это здорово!');

        $this->assertEquals('Типограф - это здорово!', $form->getData());
    }

    protected function getExtensions()
    {
        return array(
            new PreloadedExtension(
                array(),
                array(
                    'Symfony\Component\Form\Extension\Core\Type\TextareaType' => array(
                        new TextareaTypeExtension(new MdashTypograph(array('Text.paragraphs' => 'off')))
                    )
                )
            )
        );
    }
}

<?php
namespace Fsv\TypographyBundle\Tests\Form\Extension;

use Fsv\TypographyBundle\Form\Extension\TextareaTypeExtension;
use Fsv\TypographyBundle\Typograph\MdashTypograph;
use Symfony\Component\Form\PreloadedExtension;
use Symfony\Component\Form\Test\TypeTestCase;

class TextareaTypeExtensionTest extends TypeTestCase
{
    public function testSubmitWithTypography()
    {
        $form = $this->factory->create('textarea', null, array(
            'typography' => true
        ));
        $form->submit('Типограф - это здорово!');

        $this->assertEquals('Типограф — это здорово!', $form->getData());
    }

    public function testSubmitWithoutTypography()
    {
        $form = $this->factory->create('textarea');
        $form->submit('Типограф - это здорово!');

        $this->assertEquals('Типограф - это здорово!', $form->getData());
    }

    protected function getExtensions()
    {
        return array(
            new PreloadedExtension(
                array(),
                array(
                    'textarea' => array(
                        new TextareaTypeExtension(new MdashTypograph(array('Text.paragraphs' => 'off')))
                    )
                )
            )
        );
    }
}

Fix tests for symfony 2.7

Fix tests for symfony 2.7


<?php

/*
 * This file is part of the Active Collab DatabaseStructure project.
 *
 * (c) A51 doo <info@activecollab.com>. All rights reserved.
 */

declare(strict_types=1);

namespace ActiveCollab\DatabaseStructure\Behaviour\ParentInterface;

use ActiveCollab\DatabaseObject\Entity\EntityInterface;
use ActiveCollab\DatabaseStructure\Behaviour\ParentInterface;
use LogicException;

/**
 * @property \ActiveCollab\DatabaseObject\PoolInterface $pool
 */
trait OptionalImplementation
{
    public function getParent(bool $use_cache = true): ?EntityInterface
    {
        if ($id = $this->getParentId()) {
            return $this->pool->getById($this->getParentType(), $id, $use_cache);
        } else {
            return null;
        }
    }

    /**
     * @param  EntityInterface|null $value
     * @return ParentInterface|$this
     */
    public function &setParent(?EntityInterface $value): ParentInterface
    {
        if ($value === null) {
            $this->setParentType(null);
            $this->setParentId(null);
        } else {
            if (!$value->isLoaded()) {
                throw new LogicException('Parent needs to be saved to the database.');
            }

            $this->setParentType(get_class($value));
            $this->setParentId($value->getId());
        }

        return $this;
    }

    abstract public function getParentType(): ?string;

    abstract public function &setParentType(?string $value);

    abstract public function getParentId(): ?int;

    abstract public function &setParentId(?int $value);
}

Fix code style in optional parent interface implementation


<?php

namespace App\Providers;

use Laravel\Telescope\Telescope;
use Illuminate\Support\Facades\Gate;
use Laravel\Telescope\IncomingEntry;
use Laravel\Telescope\TelescopeApplicationServiceProvider;

class TelescopeServiceProvider extends TelescopeApplicationServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        // Telescope::night();

        $this->hideSensitiveRequestDetails();

        Telescope::filter(function (IncomingEntry $entry) {
            if ($this->app->isLocal()) {
                return true;
            }

            return $entry->isReportableException() ||
                   $entry->isFailedJob() ||
                   $entry->isScheduledTask() ||
                   $entry->hasMonitoredTag();
        });
    }

    /**
     * Prevent sensitive request details from being logged by Telescope.
     *
     * @return void
     */
    protected function hideSensitiveRequestDetails()
    {
        if ($this->app->isLocal()) {
            return;
        }

        Telescope::hideRequestParameters(['_token']);

        Telescope::hideRequestHeaders([
            'cookie',
            'x-csrf-token',
            'x-xsrf-token',
        ]);
    }

    /**
     * Register the Telescope gate.
     *
     * This gate determines who can access Telescope in non-local environments.
     *
     * @return void
     */
    protected function gate()
    {
        Gate::define('viewTelescope', function ($user) {
            return in_array($user->name, [
                'jonny',
            ]);
        });
    }
}

<?php

namespace App\Providers;

use Laravel\Telescope\Telescope;
use Illuminate\Support\Facades\Gate;
use Laravel\Telescope\IncomingEntry;
use Laravel\Telescope\TelescopeApplicationServiceProvider;

class TelescopeServiceProvider extends TelescopeApplicationServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        Telescope::night();

        $this->hideSensitiveRequestDetails();

        Telescope::filter(function (IncomingEntry $entry) {
            if ($this->app->isLocal()) {
                return true;
            }

            return $entry->isReportableException() ||
                   $entry->isFailedJob() ||
                   $entry->isScheduledTask() ||
                   $entry->hasMonitoredTag();
        });
    }

    /**
     * Prevent sensitive request details from being logged by Telescope.
     *
     * @return void
     */
    protected function hideSensitiveRequestDetails()
    {
        if ($this->app->isLocal()) {
            return;
        }

        Telescope::hideRequestParameters(['_token']);

        Telescope::hideRequestHeaders([
            'cookie',
            'x-csrf-token',
            'x-xsrf-token',
        ]);
    }

    /**
     * Register the Telescope gate.
     *
     * This gate determines who can access Telescope in non-local environments.
     *
     * @return void
     */
    protected function gate()
    {
        Gate::define('viewTelescope', function ($user) {
            return in_array($user->name, [
                'jonny',
            ]);
        });
    }
}

Enable dark mode in Telescope

Enable dark mode in Telescope


<?php

/*
 * 이 컨트롤러를 상속받아 구현하는 컨트롤러는 Twig 템플릿 엔진을 기본으로 로드함
 */

class MY_Controller extends CI_Controller {
    public function __construct() {
        parent::__construct();
        $this->load->library('twig');
        $this->load->helper('url');
        // Twig 관련 글로벌 설정은 이곳 또는 application/libraries/Twig.php 에 작성
        $this->twig->addGlobal('session', $_SESSION);

        if ($this->accountlib->is_login() === false) {
            redirect('/account/login');
        } elseif ($this->accountlib->is_auth() === false) {
            redirect('/account/not_authenticated');
        }
    }
}

if (!class_exists('API_Controller')) {
    require_once APPPATH . 'core/API_Controller.php';
}

<?php

/*
 * 이 컨트롤러를 상속받아 구현하는 컨트롤러는 Twig 템플릿 엔진을 기본으로 로드함
 */

class MY_Controller extends CI_Controller {
    public function __construct() {
        parent::__construct();
        $this->load->library('twig');
        $this->load->helper('url');
        $this->config->load('facebook');
        // Twig 관련 글로벌 설정은 이곳 또는 application/libraries/Twig.php 에 작성
        $this->twig->addGlobal('session', $_SESSION);
        $this->twig->addGlobal('facebook_app_id', $this->config->item('app_id'));

        if ($this->accountlib->is_login() === false) {
            redirect('/account/login');
        } elseif ($this->accountlib->is_auth() === false) {
            redirect('/account/not_authenticated');
        }
    }
}

if (!class_exists('API_Controller')) {
    require_once APPPATH . 'core/API_Controller.php';
}

Add twig global var Facebook app id info


<?php

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

class CreateOauthRefreshTokensTable extends Migration
{
    /**
     * The database schema.
     *
     * @var \Illuminate\Database\Schema\Builder
     */
    protected $schema;

    /**
     * Create a new migration instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->schema = Schema::connection($this->getConnection());
    }

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        $this->schema->create('oauth_refresh_tokens', function (Blueprint $table) {
            $table->string('id', 100)->primary();
            $table->string('access_token_id', 100);
            $table->boolean('revoked');
            $table->dateTime('expires_at')->nullable();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        $this->schema->dropIfExists('oauth_refresh_tokens');
    }

    /**
     * Get the migration connection name.
     *
     * @return string|null
     */
    public function getConnection()
    {
        return config('passport.storage.database.connection');
    }
}

<?php

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

class CreateOauthRefreshTokensTable extends Migration
{
    /**
     * The database schema.
     *
     * @var \Illuminate\Database\Schema\Builder
     */
    protected $schema;

    /**
     * Create a new migration instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->schema = Schema::connection($this->getConnection());
    }

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        $this->schema->create('oauth_refresh_tokens', function (Blueprint $table) {
            $table->string('id', 100)->primary();
            $table->string('access_token_id', 100)->index();
            $table->boolean('revoked');
            $table->dateTime('expires_at')->nullable();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        $this->schema->dropIfExists('oauth_refresh_tokens');
    }

    /**
     * Get the migration connection name.
     *
     * @return string|null
     */
    public function getConnection()
    {
        return config('passport.storage.database.connection');
    }
}

Add index to access_token_id column

Add index to access_token_id column


<?php

namespace App\Containers\Debugger\Providers;

use App\Containers\Debugger\Tasks\QueryDebuggerTask;
use App\Ship\Parents\Providers\MainProvider;
use Jenssegers\Agent\AgentServiceProvider;
use Jenssegers\Agent\Facades\Agent;

/**
 * Class MainServiceProvider.
 *
 * The Main Service Provider of this container, it will be automatically registered in the framework.
 *
 * @author  Mahmoud Zalt <mahmoud@zalt.me>
 */
class MainServiceProvider extends MainProvider
{
    /**
     * Container Service Providers.
     */
    public array $serviceProviders = [
        AgentServiceProvider::class,
        MiddlewareServiceProvider::class,
    ];

    /**
     * Container Aliases
     */
    public array $aliases = [
        'Agent' => Agent::class,
    ];

    /**
     * Register anything in the container.
     */
    public function register(): void
    {
        parent::register();

        (new QueryDebuggerTask)->run();
    }
}

<?php

namespace App\Containers\Debugger\Providers;

use App\Containers\Debugger\Tasks\QueryDebuggerTask;
use App\Ship\Parents\Providers\MainProvider;
use Barryvdh\Debugbar\Facade as Debugbar;
use Barryvdh\Debugbar\ServiceProvider as DebugbarServiceProvider;
use Jenssegers\Agent\AgentServiceProvider;
use Jenssegers\Agent\Facades\Agent;

/**
 * Class MainServiceProvider.
 *
 * The Main Service Provider of this container, it will be automatically registered in the framework.
 *
 * @author  Mahmoud Zalt <mahmoud@zalt.me>
 */
class MainServiceProvider extends MainProvider
{
    /**
     * Container Service Providers.
     */
    public array $serviceProviders = [
        AgentServiceProvider::class,
        MiddlewareServiceProvider::class,
        DebugbarServiceProvider::class
    ];

    /**
     * Container Aliases
     */
    public array $aliases = [
        'Agent' => Agent::class,
        'Debugbar' => Debugbar::class,
    ];

    /**
     * Register anything in the container.
     */
    public function register(): void
    {
        parent::register();

        (new QueryDebuggerTask)->run();
    }
}

Add missing debugbar alias and serviceProvider


<?php

namespace Predis\Commands;

class ServerEval extends Command {
    public function getId() {
        return 'EVAL';
    }

    protected function canBeHashed() {
        return false;
    }
}

<?php

namespace Predis\Commands;

class ServerEval extends Command {
    public function getId() {
        return 'EVAL';
    }

    protected function onPrefixKeys(Array $arguments, $prefix) {
        $arguments = $this->getArguments();
        for ($i = 2; $i < $arguments[1] + 2; $i++) {
            $arguments[$i] = "$prefix{$arguments[$i]}";
        }
        return $arguments;
    }

    protected function canBeHashed() {
        return false;
    }
}

Add support for transparent key prefixing to EVAL and the Predis\Commands\ScriptedCommand class.


<?php

namespace Illuminate\Foundation\Testing\Concerns;

use Exception;
use Illuminate\Contracts\Debug\ExceptionHandler;
use Symfony\Component\Console\Application as ConsoleApplication;

trait InteractsWithExceptionHandling
{
    /**
     * The previous exception handler.
     *
     * @var ExceptionHandler|null
     */
    protected $previousExceptionHandler;

    /**
     * Restore exception handling.
     *
     * @return $this
     */
    protected function withExceptionHandling()
    {
        if ($this->previousExceptionHandler) {
            $this->app->instance(ExceptionHandler::class, $this->previousExceptionHandler);
        }

        return $this;
    }

    /**
     * Disable exception handling for the test.
     *
     * @return $this
     */
    protected function withoutExceptionHandling()
    {
        $this->previousExceptionHandler = app(ExceptionHandler::class);

        $this->app->instance(ExceptionHandler::class, new class implements ExceptionHandler {
            public function __construct()
            {
            }

            public function report(Exception $e)
            {
            }

            public function render($request, Exception $e)
            {
                throw $e;
            }

            public function renderForConsole($output, Exception $e)
            {
                (new ConsoleApplication)->renderException($e, $output);
            }
        });

        return $this;
    }
}

<?php

namespace Illuminate\Foundation\Testing\Concerns;

use Exception;
use Illuminate\Contracts\Debug\ExceptionHandler;
use Symfony\Component\Console\Application as ConsoleApplication;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

trait InteractsWithExceptionHandling
{
    /**
     * The previous exception handler.
     *
     * @var ExceptionHandler|null
     */
    protected $previousExceptionHandler;

    /**
     * Restore exception handling.
     *
     * @return $this
     */
    protected function withExceptionHandling()
    {
        if ($this->previousExceptionHandler) {
            $this->app->instance(ExceptionHandler::class, $this->previousExceptionHandler);
        }

        return $this;
    }

    /**
     * Disable exception handling for the test.
     *
     * @return $this
     */
    protected function withoutExceptionHandling()
    {
        $this->previousExceptionHandler = app(ExceptionHandler::class);

        $this->app->instance(ExceptionHandler::class, new class implements ExceptionHandler {
            public function __construct()
            {
            }

            public function report(Exception $e)
            {
            }

            public function render($request, Exception $e)
            {
                if ($e instanceof NotFoundHttpException) {
                    throw new NotFoundHttpException("{$request->method()} {$request->url()}", null, $e->getCode());
                } else {
                    throw $e;
                }
            }

            public function renderForConsole($output, Exception $e)
            {
                (new ConsoleApplication)->renderException($e, $output);
            }
        });

        return $this;
    }
}

Add 404 request method and url when using withoutExceptionHandling

Whenever a NotFoundHTTPException is thrown, it is helpful to see the request method and url. Helps to debug what route to look at instead of having to first look it up in the test file. I've been using this in my own tests and I love it.

Final result:

```
1) Tests\Feature\Backstage\PublishConcertTest::a_promoter_can_publish_their_own_concert
Symfony\Component\HttpKernel\Exception\NotFoundHttpException: POST http://ticketbeast.app/backstage/published-concerts
```


<?php

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

class CreateHospitalsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('hospitals', function (Blueprint $table) {
            $table->increments('id');
            $table->string('provider_id');
            $table->string('name');
            $table->string('address');
            $table->string('city');
            $table->string('state');
            $table->string('zipcode');
            $table->string('county');
            $table->string('phone');
            $table->string('type');
            $table->string('ownership');
            $table->boolean('emergency_services');
            $table->string('human_address')->default("");
            $table->decimal('latitude', 18, 15);
            $table->decimal('longitude', 18, 15);
            $table->timestamps();
        });
    }

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

<?php

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

class CreateHospitalsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('hospitals', function (Blueprint $table) {
            $table->increments('id');
            $table->string('provider_id')->nullable();
            $table->string('name')->nullable();
            $table->string('address')->nullable();
            $table->string('city')->nullable();
            $table->string('state')->nullable();
            $table->string('zipcode')->nullable();
            $table->string('county')->nullable();
            $table->string('phone')->nullable();
            $table->string('type')->nullable();
            $table->string('ownership')->nullable();
            $table->boolean('emergency_services')->nullable();
            $table->string('human_address')->nullable();
            $table->decimal('latitude', 18, 15)->nullable();
            $table->decimal('longitude', 18, 15)->nullable();
            $table->timestamps();
        });
    }

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

Allow nullable on all fields.

Allow nullable on all fields.


<?php
namespace HcCore\Options\Exception;

use HcCore\Exception\ExceptionInterface;

class DomainException extends \InvalidArgumentException implements ExceptionInterface {}

<?php
namespace HcBackend\Options\Exception;

use HcCore\Exception\ExceptionInterface;

class DomainException extends \InvalidArgumentException implements ExceptionInterface {}

Fix problem with incorrect namespace

Fix problem with incorrect namespace


<?php
namespace Respect\Foundation\InfoProviders;

use DirectoryIterator;

class VendorName extends AbstractProvider
{
    public function providerFolderStructure()
    {
        if (file_exists($libraryFolder = new LibraryFolder($this->projectFolder)))
            foreach (new DirectoryIterator($libraryFolder) as $vendor)
                    if (!$vendor->isDot() && $vendor->isDir()
                            && preg_match('/[A-Z].*/', $vendor->getFileName()))
                            return $vendor->getFileName();
    }

    public function providerDefault()
    {
        return ucfirst(preg_replace('/\W+/', '', new UserName($this->projectFolder)));
    }
}

<?php
namespace Respect\Foundation\InfoProviders;

use DirectoryIterator;

class VendorName extends AbstractProvider
{
    public function providerPackageIni()
    {
        $iniPath = realpath($this->projectFolder.'/package.ini');

        if (!file_exists($iniPath))
            return '';

        $ini = parse_ini_file($iniPath, true);

        return @$ini['package']['vendor'];
    }

    public function providerFolderStructure()
    {
        if (file_exists($libraryFolder = new LibraryFolder($this->projectFolder)))
            foreach (new DirectoryIterator($libraryFolder) as $vendor)
                    if (!$vendor->isDot() && $vendor->isDir()
                            && preg_match('/[A-Z].*/', $vendor->getFileName()))
                            return $vendor->getFileName();
    }

    public function providerDefault()
    {
        return ucfirst(preg_replace('/\W+/', '', new UserName($this->projectFolder)));
    }
}

Add vendor-name to package.ini as vendor.

Looking to find the vendor name based on a root src folder name may proof difficult at times.


<?php
namespace Grav\Common;

/**
 * Wrapper for Session
 */
class Session extends \RocketTheme\Toolbox\Session\Session
{
    protected $grav;
    protected $session;

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

    public function init()
    {
        /** @var Uri $uri */
        $uri = $this->grav['uri'];
        $config = $this->grav['config'];

        $session_timeout = $config->get('system.session.timeout', 1800);
        $session_path = $config->get('system.session.path', '/' . ltrim($uri->rootUrl(false), '/'));

        if ($config->get('system.session.enabled')) {
            // Define session service.
            parent::__construct(
                $session_timeout,
                $session_path
            );

            $site_identifier = $config->get('site.title', 'unkown');
            $this->setName($config->get('system.session.name', 'grav_site') . '_' . substr(md5($site_identifier), 0, 7));
            $this->start();
            setcookie(session_name(), session_id(), time() + $session_timeout, $session_path);
        }
    }
}

<?php
namespace Grav\Common;

/**
 * Wrapper for Session
 */
class Session extends \RocketTheme\Toolbox\Session\Session
{
    protected $grav;
    protected $session;

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

    public function init()
    {
        /** @var Uri $uri */
        $uri = $this->grav['uri'];
        $config = $this->grav['config'];

        if ($config->get('system.session.enabled')) {
            $session_timeout = $config->get('system.session.timeout', 1800);
            $session_path = $config->get('system.session.path', '/' . ltrim($uri->rootUrl(false), '/'));

            // Define session service.
            parent::__construct(
                $session_timeout,
                $session_path
            );

            $site_identifier = $config->get('site.title', 'unkown');
            $this->setName($config->get('system.session.name', 'grav_site') . '_' . substr(md5($site_identifier), 0, 7));
            $this->start();
            setcookie(session_name(), session_id(), time() + $session_timeout, $session_path);
        }
    }
}

Move $session_timeout & $session_path inside the if statement


<?php
return function(\Slim\Slim $app, array $holeModel, array $userModel, callable $loadAuth) {
    $app->get('/', $loadAuth, function() use($app, $holeModel, $userModel) {
        $holes = $holeModel['find'](['visibleBy' => $app->config('codegolf.user')]);

        $submissions = [];
        foreach ($holes as $hole) {
            $submissions = array_merge($submissions, $hole['submissions']);
        }

        usort($submissions, function($a, $b) {
            return $b['timestamp'] - $a['timestamp'];
        });

        $submissions = array_slice($submissions, 0, 20);

        $app->render(
            'home.html',
            ['holes' => $holes, 'users' => $userModel['find']([], $holes), 'user' => $app->config('codegolf.user'), 'submissions' => $submissions]
        );
    })->name('home');
};

<?php
return function(\Slim\Slim $app, array $holeModel, array $userModel, callable $loadAuth) {
    $app->get('/', $loadAuth, function() use($app, $holeModel, $userModel) {
        $user = $app->config('codegolf.user');
        $holes = $holeModel['find'](['visibleBy' => $user]);

        $submissions = [];
        foreach ($holes as $hole) {
            $submissions = array_merge($submissions, $hole['submissions']);
        }

        usort($submissions, function($a, $b) {
            return $b['timestamp'] - $a['timestamp'];
        });

        $submissions = array_slice($submissions, 0, 20);

        $users = $userModel['find']([], $holes);
        $app->render('home.html', ['holes' => $holes, 'users' => $users, 'user' => $user, 'submissions' => $submissions]);
    })->name('home');
};

Make code a little cleaner.

Make code a little cleaner.


<?php
namespace Mw\JsonMapping;

class MergeMapping extends ObjectMapping
{

    /**
     * @var ObjectMapping[]
     */
    private $innerMappings;

    /**
     * MergeMapping constructor.
     *
     * @param ObjectMapping[] ...$innerMappings
     */
    public function __construct(ObjectMapping ...$innerMappings)
    {
        $this->innerMappings = $innerMappings;
    }

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

        foreach ($this->innerMappings as $mapping) {
            $newMapped = $mapping->map($value);
            $mapped = array_replace_recursive($mapped, $newMapped);
        }

        return $mapped;
    }

    /**
     * @param array $fieldNames
     * @return MergeMapping
     */
    public function filter(array $fieldNames)
    {
        $newInnerMappings = [];
        foreach ($this->innerMappings as $innerMapping) {
            $newInnerMappings[] = $innerMapping->filter($fieldNames);
        }
        return new MergeMapping(...$newInnerMappings);
    }
}

<?php
namespace Mw\JsonMapping;

class MergeMapping extends ObjectMapping
{

    /**
     * @var ObjectMapping[]
     */
    private $innerMappings;

    /**
     * MergeMapping constructor.
     *
     * @param ObjectMapping[] ...$innerMappings
     */
    public function __construct(...$innerMappings)
    {
        $this->innerMappings = $innerMappings;
    }

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

        foreach ($this->innerMappings as $mapping) {
            $newMapped = $mapping->map($value);
            $mapped = array_replace_recursive($mapped, $newMapped);
        }

        return $mapped;
    }

    /**
     * @param array $fieldNames
     * @return MergeMapping
     */
    public function filter(array $fieldNames)
    {
        $newInnerMappings = [];
        foreach ($this->innerMappings as $innerMapping) {
            $newInnerMappings[] = $innerMapping->filter($fieldNames);
        }
        return new MergeMapping(...$newInnerMappings);
    }
}

Fix "Fatal error: Parameter $innerMappings is variadic and has a type constraint"


<?php

return array(

    'assets_user'       => 'Assets assigned to :name',
    'clone'             => 'Clone User',
    'contact_user'      => 'Contact :name',
    'edit'              => 'Edit User',
    'filetype_info'     => 'Allowed filetypes are png, gif, jpg, jpeg, doc, docx, pdf, txt, zip, and rar.',
    'history_user'      => 'History for :name',
    'last_login'        => 'Last Login',
    'ldap_config_text'  => 'LDAP configuration settings can be found in the app/config folder in a file called ldap.php',
    'ldap_text'         => 'Connect to LDAP and create users.  Passwords will be auto-generated.',
    'software_user'     => 'Software Checked out to :name',
    'view_user'         => 'View User :name',
    'usercsv'           => 'CSV file',
    );

<?php

return array(

    'assets_user'       => 'Assets assigned to :name',
    'clone'             => 'Clone User',
    'contact_user'      => 'Contact :name',
    'edit'              => 'Edit User',
    'filetype_info'     => 'Allowed filetypes are png, gif, jpg, jpeg, doc, docx, pdf, txt, zip, and rar.',
    'history_user'      => 'History for :name',
    'last_login'        => 'Last Login',
    'ldap_config_text'  => 'LDAP configuration settings can be found in the app/config folder in a file called ldap.php. The selected location will be set for all imported users. You will need to have at least one location set to use this feature.',
    'ldap_text'         => 'Connect to LDAP and create users.  Passwords will be auto-generated.',
    'software_user'     => 'Software Checked out to :name',
    'view_user'         => 'View User :name',
    'usercsv'           => 'CSV file',
    );

Add some explanation about the location field.


<?php

use Valet\PhpFpm;
use Illuminate\Container\Container;

class PhpFpmTest extends PHPUnit_Framework_TestCase
{
    public function setUp()
    {
        $_SERVER['SUDO_USER'] = user();

        Container::setInstance(new Container);
    }

    public function tearDown()
    {
        exec('rm -rf '.__DIR__.'/output');
        mkdir(__DIR__.'/output');
        touch(__DIR__.'/output/.gitkeep');

        Mockery::close();
    }

    public function test_fpm_is_configured_with_the_correct_user_group_and_port()
    {
        copy(__DIR__.'/files/fpm.conf', __DIR__.'/output/fpm.conf');
        resolve(StubForUpdatingFpmConfigFiles::class)->updateConfiguration();
        $contents = file_get_contents(__DIR__.'/output/fpm.conf');
        $this->assertContains(sprintf("\nuser = %s", user()), $contents);
        $this->assertContains("\ngroup = staff", $contents);
        $this->assertContains("\nlisten = /Users/".user()."/.valet/valet.sock", $contents);
    }
}

class StubForUpdatingFpmConfigFiles extends PhpFpm
{
    function fpmConfigPath()
    {
        return __DIR__.'/output/fpm.conf';
    }
}

<?php

use Valet\PhpFpm;
use Illuminate\Container\Container;

class PhpFpmTest extends PHPUnit_Framework_TestCase
{
    public function setUp()
    {
        $_SERVER['SUDO_USER'] = user();

        Container::setInstance(new Container);
    }

    public function tearDown()
    {
        exec('rm -rf '.__DIR__.'/output');
        mkdir(__DIR__.'/output');
        touch(__DIR__.'/output/.gitkeep');

        Mockery::close();
    }

    public function test_fpm_is_configured_with_the_correct_user_group_and_port()
    {
        copy(__DIR__.'/files/fpm.conf', __DIR__.'/output/fpm.conf');
        resolve(StubForUpdatingFpmConfigFiles::class)->updateConfiguration();
        $contents = file_get_contents(__DIR__.'/output/fpm.conf');
        $this->assertContains(sprintf("\nuser = %s", user()), $contents);
        $this->assertContains("\ngroup = staff", $contents);
        $this->assertContains("\nlisten = ".VALET_HOME_PATH."/valet.sock", $contents);
    }
}

class StubForUpdatingFpmConfigFiles extends PhpFpm
{
    function fpmConfigPath()
    {
        return __DIR__.'/output/fpm.conf';
    }
}

Fix test to run under Linux CI

Fix test to run under Linux CI


<?php
/**
 * Contains \jamesiarmes\PhpEws\Type\TransitionTargetType.
 */

namespace jamesiarmes\PhpEws\Type;

/**
 * Specifies the target of the time zone transition.
 *
 * The target is either a time zone period or a group of time zone transitions.
 *
 * @package php-ews\Type
 */
class TransitionTargetType extends StringType
{
    /**
     * Indicates whether the time zone transition target is a time zone period
     * or of a group of time zone transitions.
     *
     * @since Exchange 2010
     *
     * @var \jamesiarmes\PhpEws\Enumeration\TransitionTargetKindType
     */
    public $Kind;
}

<?php
/**
 * Contains \jamesiarmes\PhpEws\Type\TransitionTargetType.
 */

namespace jamesiarmes\PhpEws\Type;

/**
 * Specifies the target of the time zone transition.
 *
 * The target is either a time zone period or a group of time zone transitions.
 *
 * @package php-ews\Type
 */
class TransitionTargetType extends String
{
    /**
     * Indicates whether the time zone transition target is a time zone period
     * or of a group of time zone transitions.
     *
     * @since Exchange 2010
     *
     * @var \jamesiarmes\PhpEws\Enumeration\TransitionTargetKindType
     */
    public $Kind;
}

Revert "Minor fix for String"

Revert "Minor fix for String"

This reverts commit 6c3d312a9c944769ed2837f97b3653d92be254da.


<?php
namespace Concrete\Core\Filesystem\FileLocator;

use Concrete\Core\Package\PackageList;
use Concrete\Core\Page\Theme\Theme;
use Illuminate\Filesystem\Filesystem;

class ThemeLocation extends AbstractLocation
{

    protected $filesystem;
    protected $pkgHandle;
    protected $themeHandle;

    public function getCacheKey()
    {
        return array('theme', $this->themeHandle);
    }

    public function __construct(Theme $theme)
    {
        $this->themeHandle = $theme->getThemeHandle();
        $this->pkgHandle = $theme->getPackageHandle();
    }

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

    public function getPath()
    {
        if ($this->pkgHandle) {
            return DIR_PACKAGES
                . '/'
                . $this->pkgHandle
                . '/'
                . DIRNAME_THEMES
                . '/'
                . $this->themeHandle;
        } else {
            return DIR_APPLICATION . '/' . DIRNAME_THEMES . '/' . $this->themeHandle;
        }
    }

    public function getURL()
    {
        if ($this->pkgHandle) {
            return DIR_REL
            . '/'
            . $this->pkgHandle
            . '/'
            . DIRNAME_THEMES
            . $this->themeHandle;
        } else {
            return DIR_REL . '/' . DIRNAME_THEMES . '/' . $this->themeHandle;
        }
    }
}

<?php
namespace Concrete\Core\Filesystem\FileLocator;

use Concrete\Core\Package\PackageList;
use Concrete\Core\Page\Theme\Theme;
use Illuminate\Filesystem\Filesystem;

class ThemeLocation extends AbstractLocation
{

    protected $filesystem;
    protected $pkgHandle;
    protected $themeHandle;

    public function getCacheKey()
    {
        return array('theme', $this->themeHandle);
    }

    public function __construct(Theme $theme)
    {
        $this->themeHandle = $theme->getThemeHandle();
        $this->pkgHandle = $theme->getPackageHandle();
    }

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

    public function getPath()
    {
        if ($this->pkgHandle) {
            return DIR_PACKAGES
                . '/'
                . $this->pkgHandle
                . '/'
                . DIRNAME_THEMES
                . '/'
                . $this->themeHandle;
        } else {
            return DIR_APPLICATION . '/' . DIRNAME_THEMES . '/' . $this->themeHandle;
        }
    }

    public function getURL()
    {
        if ($this->pkgHandle) {
            return DIR_REL
            . '/'
            . DIRNAME_PACKAGES
            . '/'
            . $this->pkgHandle
            . '/'
            . DIRNAME_THEMES
            . '/'
            . $this->themeHandle;
        } else {
            return DIR_REL . '/' . DIRNAME_THEMES . '/' . $this->themeHandle;
        }
    }
}

Fix URL of locator records in packaged themes


<?php
/**
 * Created by Gary Hockin.
 * Date: 04/12/14
 * @GeeH
 */

namespace Application\Service;

use Zend\Log\Logger;

class ErrorHandlingService
{

    /**
     * @var Logger
     */
    protected $logger;

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

    public function logException(\Exception $e)
    {
        $trace = $e->getTraceAsString();
        $i     = 1;
        do {
            $messages[] = $i++ . ": " . $e->getMessage();
        } while ($e = $e->getPrevious());

        $log = "Exception:n" . implode("n", $messages);
        $log .= "nTrace:n" . $trace;

        $this->logger->err($log);
    }
}

<?php

namespace Application\Service;

use Zend\Log\Logger;

class ErrorHandlingService
{
    /**
     * @var Logger
     */
    private $logger;

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

    public function logException(\Exception $e)
    {
        $trace = $e->getTraceAsString();
        $i     = 1;
        do {
            $messages[] = $i++ . ": " . $e->getMessage();
        } while ($e = $e->getPrevious());

        $log = "Exception:n" . implode("n", $messages);
        $log .= "nTrace:n" . $trace;

        $this->logger->err($log);
    }
}

Fix: Reduce visibility of field to maximum needed


<?php

/*
 * This file is part of Rocketeer
 *
 * (c) Maxime Fabre <ehtnam6@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Rocketeer\Strategies\Dependencies;

use Rocketeer\Abstracts\Strategies\AbstractDependenciesStrategy;
use Rocketeer\Interfaces\Strategies\DependenciesStrategyInterface;

class NpmStrategy extends AbstractDependenciesStrategy implements DependenciesStrategyInterface
{
    /**
     * @var string
     */
    protected $description = 'Installs dependencies with NPM';

    /**
     * The name of the binary.
     *
     * @var string
     */
    protected $binary = 'npm';
}

<?php

/*
 * This file is part of Rocketeer
 *
 * (c) Maxime Fabre <ehtnam6@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Rocketeer\Strategies\Dependencies;

use Rocketeer\Abstracts\Strategies\AbstractDependenciesStrategy;
use Rocketeer\Interfaces\Strategies\DependenciesStrategyInterface;

class NpmStrategy extends AbstractDependenciesStrategy implements DependenciesStrategyInterface
{
    /**
     * @var string
     */
    protected $description = 'Installs dependencies with NPM';

    /**
     * The name of the binary.
     *
     * @var string
     */
    protected $binary = 'npm';

    /**
     * @var array
     */
    protected $options = [
        'flags.install' => '--no-progress',
    ];
}

Use no-progress flag for NPM

Use no-progress flag for NPM


<?php
/**
 * productupdater_ProductdataScriptDocumentElement
 * @package modules.productupdater.persistentdocument.import
 */
class productupdater_ProductdataScriptDocumentElement extends import_ScriptDocumentElement
{
    /**
     * @return productupdater_persistentdocument_productdata
     */
    protected function initPersistentDocument()
    {
    	return productupdater_ProductdataService::getInstance()->getNewDocumentInstance();
    }

    /**
	 * @return f_persistentdocument_PersistentDocumentModel
	 */
	protected function getDocumentModel()
	{
		return f_persistentdocument_PersistentDocumentModel::getInstanceFromDocumentModelName('modules_productupdater/productdata');
	}
}

<?php
/**
 * productupdater_ProductdataScriptDocumentElement
 * @package modules.productupdater.persistentdocument.import
 */
class productupdater_ProductdataScriptDocumentElement extends import_ScriptDocumentElement
{
    /**
     * @return productupdater_persistentdocument_productdata
     */
    protected function initPersistentDocument()
    {
    	return productupdater_ProductdataService::getInstance()->getNewDocumentInstance();
    }

    /**
	 * @return f_persistentdocument_PersistentDocumentModel
	 */
	protected function getDocumentModel()
	{
		return f_persistentdocument_PersistentDocumentModel::getInstanceFromDocumentModelName('modules_productupdater/productdata');
	}

	/**
	 * @return array
	 */
	protected function getDocumentProperties()
	{
		$properties = parent::getDocumentProperties();
		if (isset($properties['productQuery']))
		{
			$query = $this->replaceRefIdInString($properties['productQuery']) ;
			$properties['productQuery'] = $query;
		}
		return $properties;
	}
}

[NEW] Handle {ref-id:...} in XML import for query properties.


<?php

/**
 * Class LaralyticsTest
 */
class LaralyticsTest extends TestCase
{
    // @TODO: add PHPUnit command line
}

<?php

/**
 * Class LaralyticsTest
 */
class LaralyticsTest extends \Orchestra\Testbench\TestCase
{
    /**
     * Setup the test environment.
     */
    public function setUp()
    {
        parent::setUp();

        $this->artisan('migrate', [
            '--database' => 'test',
            '--realpath' => realpath(__DIR__ . '/../../publish/database/migrations'),
        ]);
    }

    /**
     * Define environment setup.
     *
     * @param  \Illuminate\Foundation\Application  $app
     *
     * @return void
     */
    protected function getEnvironmentSetUp($app)
    {
        $app['config']->set('database.default', 'test');
        $app['config']->set('database.migrations', 'migrations');
        $app['config']->set('database.connections.test', [
            'driver'   => 'sqlite',
            'database' => ':memory:',
            'prefix'   => '',
        ]);

        $app['config']->set('laralytics', require __DIR__ . '/../../publish/config/laralytics.php');
    }

    /**
     * Get package providers.
     *
     * @param  \Illuminate\Foundation\Application  $app
     *
     * @return array
     */
    protected function getPackageProviders($app)
    {
        return [
            'Bsharp\Laralytics\LaralyticsServiceProvider',
        ];
    }

    public function testDatabaseDriver()
    {
        // set database driver
        app('config')->set('laralytics.driver', 'database');

        $instance = new \Bsharp\Laralytics\Laralytics();

        $host = str_random(10);
        $path = '/' . str_random(10);

        $instance->url($host, $path, 'GET');

        $row = \DB::table('laralytics_url')->orderBy('id', 'DESC')->first();

        $this->assertEquals($host, $row->host);
        $this->assertEquals($path, $row->path);
    }
}

Refactor test using testbench, make first test for database driver


<?php

use SilverStripe\Core\Injector\Injector;
use Symbiote\QueuedJobs\Services\QueuedJobService;
use SilverStripe\CronTask\Interfaces\CronTask;

/**
 * These nightly updates can clean up anything that might have been missed by the other tasks
 */
class NightlyUpdatesCron implements CronTask
{

    /**
     * Run at 1am every morning
     *
     * @return string
     */
    public function getSchedule()
    {
        return "0 1 * * *";
    }

    /**
     * Run the build task to update addons
     * @return void
     */
    public function process()
    {
        $taskClasses = [
            [BuildAddonsTask::class, null], // rebuild all addons
        ];

        foreach ($taskClasses as $taskInfo) {
            list($taskClass, $taskQuerystring) = $taskInfo;
            $job = new RunBuildTaskJob($taskClass, $taskQuerystring);
            $jobID = Injector::inst()->get(QueuedJobService::class)->queueJob($job);
            echo 'Added ' . $taskClass . ' to job queue (job ID ' . $jobID . ")\n";
        }
    }
}

<?php

use SilverStripe\Core\Injector\Injector;
use Symbiote\QueuedJobs\Jobs\RunBuildTaskJob;
use Symbiote\QueuedJobs\Services\QueuedJobService;
use SilverStripe\CronTask\Interfaces\CronTask;

/**
 * These nightly updates can clean up anything that might have been missed by the other tasks
 */
class NightlyUpdatesCron implements CronTask
{

    /**
     * Run at 1am every morning
     *
     * @return string
     */
    public function getSchedule()
    {
        return "0 1 * * *";
    }

    /**
     * Run the build task to update addons
     * @return void
     */
    public function process()
    {
        $taskClasses = [
            [BuildAddonsTask::class, null], // rebuild all addons
        ];

        foreach ($taskClasses as $taskInfo) {
            list($taskClass, $taskQuerystring) = $taskInfo;
            $job = new RunBuildTaskJob($taskClass, $taskQuerystring);
            $jobID = Injector::inst()->get(QueuedJobService::class)->queueJob($job);
            echo 'Added ' . $taskClass . ' to job queue (job ID ' . $jobID . ")\n";
        }
    }
}

FIX Import RunBuildTaskJob namespace to fix undefined class error


<?php declare(strict_types=1);

namespace Symplify\Statie\Templating\FilterProvider;

use ParsedownExtra;
use Symplify\Statie\Contract\Templating\FilterProviderInterface;

final class MarkdownFilterProvider implements FilterProviderInterface
{
    /**
     * @var ParsedownExtra
     */
    private $parsedownExtra;

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

    /**
     * @return callable[]
     */
    public function provide(): array
    {
        return [
            // usage in Twig: {{ content|markdown }}
            // usage in Latte: {$content|markdown}
            'markdown' => function (string $content): string {
                return $this->parsedownExtra->parse($content);
            },
        ];
    }
}

<?php declare(strict_types=1);

namespace Symplify\Statie\Templating\FilterProvider;

use Nette\Utils\Strings;
use ParsedownExtra;
use Symplify\Statie\Contract\Templating\FilterProviderInterface;

final class MarkdownFilterProvider implements FilterProviderInterface
{
    /**
     * @var ParsedownExtra
     */
    private $parsedownExtra;

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

    /**
     * @return callable[]
     */
    public function provide(): array
    {
        return [
            // usage in Twig: {{ content|markdown }}
            // usage in Latte: {$content|markdown}
            'markdown' => function (string $content): string {
                $content = $this->parsedownExtra->parse($content);

                // remove

, it adds extra unwanted spaces
                $match = Strings::match($content, '#
(?<content>.*?)<\/p>#sm');
                if (isset($match['content'])) {
                    return $match['content'];
                }

                return $content;
            },
        ];
    }
}

Fix markdown filter extra spaces

[Statie] Fix markdown filter extra spaces


<?php namespace Felixkiss\UniqueWithValidator;

use Illuminate\Support\ServiceProvider;
use Illuminate\Validation\Factory;

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

    /**
     * Bootstrap the application events.
     *
     * @return void
     */
    public function boot()
    {
        $this->package('felixkiss/uniquewith-validator');

        // Registering the validator extension with the validator factory
        $this->app['validator']->resolver(function($translator, $data, $rules, $messages)
        {
            // Set custom validation error messages
            $messages['unique_with'] = $translator->get('uniquewith-validator::validation.unique_with');

            return new ValidatorExtension($translator, $data, $rules, $messages);
        });
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {

    }

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

<?php namespace Felixkiss\UniqueWithValidator;

use Illuminate\Support\ServiceProvider;
use Illuminate\Validation\Factory;

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

    /**
     * Bootstrap the application events.
     *
     * @return void
     */
    public function boot()
    {
        $this->package('felixkiss/uniquewith-validator');

        // Registering the validator extension with the validator factory
        $this->app['validator']->resolver(function($translator, $data, $rules, $messages)
        {
            // Set custom validation error messages
            if(!isset($messages['unique_with']))
            {
                $messages['unique_with'] = $translator->get(
                    'uniquewith-validator::validation.unique_with'
                );
            }

            return new ValidatorExtension($translator, $data, $rules, $messages);
        });
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {

    }

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

Allow error message to be overwritten inline

The error message for unique_with passed into Validator::make() was not used.
It was always overwritten by the error message defined in the language files.


<?php

namespace FullyBaked\Pslackr;

interface Transport
{
    public function send(FullyBaked\Pslackr\Messages\Message $message);
}

<?php

namespace FullyBaked\Pslackr;

interface Transport
{
    /**
     * must POST the $message to the Slack incoming-webhook
     */
    public function send(Messages\Message $message);
}

Fix namespacing of send() arg and add docblock


<?php

declare(strict_types = 1);

namespace App\Http;

use Interop\Http\Server\RequestHandlerInterface;
use Prooph\EventMachine\EventMachine;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\UriInterface;
use Zend\Diactoros\Response\JsonResponse;

final class MessageSchemaMiddleware implements RequestHandlerInterface
{
    /**
     * @var EventMachine
     */
    private $eventMachine;

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

    /**
     * Handle the request and return a response.
     *
     * @param ServerRequestInterface $request
     *
     * @return ResponseInterface
     */
    public function handle(ServerRequestInterface $request)
    {
        /** @var UriInterface $uri */
        $uri = $request->getAttribute('original_uri', $request->getUri());

        $messageBoxUri = $uri->withPath(str_replace('-schema', '', $uri->getPath()));

        return new JsonResponse(array_merge(
            ['messageBox' => (string)$messageBoxUri],
            $this->eventMachine->messageSchemas()
        ));
    }
}

<?php

declare(strict_types = 1);

namespace App\Http;

use Prooph\EventMachine\EventMachine;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\UriInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Zend\Diactoros\Response\JsonResponse;

final class MessageSchemaMiddleware implements RequestHandlerInterface
{
    /**
     * @var EventMachine
     */
    private $eventMachine;

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

    /**
     * Handle the request and return a response.
     *
     * @param ServerRequestInterface $request
     *
     * @return ResponseInterface
     */
    public function handle(ServerRequestInterface $request): ResponseInterface
    {
        /** @var UriInterface $uri */
        $uri = $request->getAttribute('original_uri', $request->getUri());

        $messageBoxUri = $uri->withPath(str_replace('-schema', '', $uri->getPath()));

        return new JsonResponse(array_merge(
            ['messageBox' => (string)$messageBoxUri],
            $this->eventMachine->messageSchemas()
        ));
    }
}

Update missed HTTP handler to PSR-15

Update missed HTTP handler to PSR-15


@extends('layouts.app')
@section('content')
    @if(count($animals) == 0)
        {{__('There are no animals.')}}
    @else

            {{__('Name')}}
            {{__('Dob')}}
            {{__('Own')}}
            {{__('Active')}}
            {{__('Options')}}

        @each('animal.index.item', $animals, 'animal')

    {{$animals->links()}}
    @endif
@stop

@extends('layouts.app')
@section('content')
    {{ __('Add animal') }}
    @if(count($animals) == 0)
        {{ __('There are no animals.') }}
    @else

            {{ __('Name') }}
            {{ __('Dob') }}
            {{ __('Own') }}
            {{ __('Active') }}
            {{ __('Options') }}

        @each('animal.index.item', $animals, 'animal')

    {{$animals->links()}}
    @endif
@stop

Add link for creating new animal.

Add link for creating new animal.


<?php

namespace ParaunitTestCase\TestCase;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Tester\CommandTester;

/**
 * Class ParaunitCommandTestCase
 * @package ParaunitTestCase\TestCase
 */
abstract class ParaunitCommandTestCase extends ParaunitWebTestCase
{
    /**
     * Runs a command and returns it output
     *
     * @param ContainerAwareCommand $command
     * @param array $input
     * @return string
     */
    public function runCommandTesterAndReturnOutput(ContainerAwareCommand $command, array $input = [])
    {
        $kernel = self::createKernel();
        $kernel->boot();

        $application = new Application($kernel);
        $application->add($command);

        $container = $kernel->getContainer();
        $this->injectManagersInContainer($container);
        $command->setContainer($container);

        $input['command'] = $command->getName();
        $input['--env'] = isset($input['--env']) ? $input['--env'] : 'test';

        $tester = new CommandTester($command);
        $tester->execute($input);

        return $tester->getDisplay();
    }
}

<?php

namespace ParaunitTestCase\TestCase;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Tester\CommandTester;

/**
 * Class ParaunitCommandTestCase
 * @package ParaunitTestCase\TestCase
 */
abstract class ParaunitCommandTestCase extends ParaunitWebTestCase
{
    /**
     * Runs a command and returns it output
     *
     * @param ContainerAwareCommand $command
     * @param array $input
     * @return string
     */
    public function runCommandTesterAndReturnOutput(ContainerAwareCommand $command, array $input = [])
    {
        $kernel = self::createKernel();
        $kernel->boot();

        $application = new Application($kernel);
        $application->add($command);

        $container = $kernel->getContainer();
        $this->injectManagersInContainer($container);
        $command->setContainer($container);

        $input['command'] = $command->getName();

        $tester = new CommandTester($command);
        $tester->execute($input);

        return $tester->getDisplay();
    }
}

Remove the --env default setting, it's not needed when testing a command


<?php

namespace App\Repository\Framework;

use App\Entity\Framework\LsDefFrameworkType;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Bridge\Doctrine\RegistryInterface;

/**
 * @method LsDefFrameworkType|null find($id, $lockMode = null, $lockVersion = null)
 * @method LsDefFrameworkType|null findOneBy(array $criteria, array $orderBy = null)
 * @method LsDefFrameworkType[]    findAll()
 * @method LsDefFrameworkType[]    findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
 */
class LsDefFrameworkTypeRepository extends ServiceEntityRepository
{
    public function __construct(RegistryInterface $registry)
    {
        parent::__construct($registry, LsDefFrameworkType::class);
    }

    /**
     * @return array|LsDefFrameworkType[]
     */
    public function getList()
    {
        $qBuilder = $this->createQueryBuilder('f', 'f.value')
            ->orderBy('f.value');

        return $qBuilder->getQuery()->getResult();
    }
}

<?php

namespace App\Repository\Framework;

use App\Entity\Framework\LsDefFrameworkType;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Symfony\Bridge\Doctrine\RegistryInterface;

/**
 * @method LsDefFrameworkType|null find($id, $lockMode = null, $lockVersion = null)
 * @method LsDefFrameworkType|null findOneBy(array $criteria, array $orderBy = null)
 * @method LsDefFrameworkType[]    findAll()
 * @method LsDefFrameworkType[]    findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
 */
class LsDefFrameworkTypeRepository extends ServiceEntityRepository
{
    public function __construct(RegistryInterface $registry)
    {
        parent::__construct($registry, LsDefFrameworkType::class);
    }

    /**
     * @return array|LsDefFrameworkType[]
     */
    public function getList()
    {
        $qBuilder = $this->createQueryBuilder('f', 'f.value')
            ->orderBy('f.value');

        return $qBuilder->getQuery()->getResult();
    }
}

Remove use call for ArrayCollection.

Remove use call for ArrayCollection.


<?php

namespace UKMNorge\DeltaBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class DefaultController extends Controller
{
    public function indexAction()
    {

/*	    $userService = $this->get('ukm_user');#->getCurrentUser();

		if( $userService->gotAccess('remembered', $userService->getCurrentUser() ) ) {
			return $this->redirect( $this->get('router')->generate('ukm_delta_ukmid_homepage') );
		}
*/
        return $this->render('UKMDeltaBundle:Default:index.html.twig', array());
    }
}

<?php

namespace UKMNorge\DeltaBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class DefaultController extends Controller
{
    public function indexAction()
    {
	    $is_granted_user = $this->get('security.authorization_checker')->isGranted('ROLE_USER');
	    if( $is_granted_user ) {
		    return $this->redirect( $this->get('router')->generate('ukm_delta_ukmid_homepage') );
	    }

        return $this->render('UKMDeltaBundle:Default:index.html.twig', array());
    }
}

Send bruker til hjem-område hvis logget inn

Close #97
Ikke spør om innlogging en gang til.. :)


<?php
/**
 * Convenience class- wraps the specific functionality of the api in a
 * friendlier interface.
 *
 * @author Sam Schmidt <samuel@dersam.net>
 * @since 2016-02-11
 */

namespace Dersam\RequestTracker;

class Client
{

}

<?php
/**
 * Convenience class- wraps the specific functionality of the api in a
 * friendlier interface.
 *
 * @author Sam Schmidt <samuel@dersam.net>
 * @since 2016-02-11
 */

namespace Dersam\RequestTracker;

class Client
{
    protected $connection;

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

Define connection in client constructor.


<?php
include '_CONFIG.php';

try {
		$dbh = new PDO("mysql:host=$CC_dbhost;dbname=$CC_database_name", $CC_dbusername, $CC_dbpasswd);

		 # MS SQL Server and Sybase with PDO_DBLIB
			#$dbh = new PDO("mssql:host=$CC_dbhost;dbname=$CC_database_name, $CC_dbusername, $CC_dbpasswd");
			#$dbh = new PDO("sybase:host=$CC_dbhost;dbname=$CC_database_name, $CC_dbusername, $CC_dbpasswd");

		# SQLite Database
			#$dbh = new PDO("sqlite:my/database/path/database.db");

    }
catch(PDOException $e)
    {
		echo $e->getMessage();
    }

<?php
include '_CONFIG.php';

try {
		$dbh = new PDO("mysql:host=$CC_dbhost;dbname=$CC_database_name", $CC_dbusername, $CC_dbpasswd);

		 // MS SQL Server and Sybase with PDO_DBLIB
			//$dbh = new PDO("mssql:host=$CC_dbhost;dbname=$CC_database_name, $CC_dbusername, $CC_dbpasswd");
			//$dbh = new PDO("sybase:host=$CC_dbhost;dbname=$CC_database_name, $CC_dbusername, $CC_dbpasswd");

		// SQLite Database
			#$dbh = new PDO("sqlite:my/database/path/database.db");

    }
catch(PDOException $e)
    {
		echo $e->getMessage();
    }

Add code for PDO connects to ms sql and sqlite, fix comments.

git-svn-id: 245d8f85226f8eeeaacc1269b037bb4851d63c96@858 54a900ba-8191-11dd-a5c9-f1483cedc3eb


<?php

final class DifferentialEditPolicyFieldSpecification
  extends DifferentialFieldSpecification {

  private $value;

  public function shouldAppearOnEdit() {
    return true;
  }

  protected function didSetRevision() {
    $this->value = $this->getRevision()->getEditPolicy();
  }

  public function setValueFromRequest(AphrontRequest $request) {
    $this->value = $request->getStr('editPolicy');
    return $this;
  }

  public function renderEditControl() {
    $viewer = $this->getUser();
    $revision = $this->getRevision();

    $policies = id(new PhabricatorPolicyQuery())
      ->setViewer($viewer)
      ->setObject($revision)
      ->execute();

    return id(new AphrontFormPolicyControl())
      ->setUser($viewer)
      ->setCapability(PhabricatorPolicyCapability::CAN_EDIT)
      ->setPolicyObject($revision)
      ->setPolicies($policies)
      ->setName('editPolicy')
      ->setCaption(
        pht(
          'NOTE: These policy features are not yet fully supported.'));
  }

  public function willWriteRevision(DifferentialRevisionEditor $editor) {
    $this->getRevision()->setEditPolicy($this->value);
  }

}

<?php

final class DifferentialEditPolicyFieldSpecification
  extends DifferentialFieldSpecification {

  private $value;

  public function shouldAppearOnEdit() {
    return true;
  }

  protected function didSetRevision() {
    $this->value = $this->getRevision()->getEditPolicy();
  }

  public function setValueFromRequest(AphrontRequest $request) {
    $this->value = $request->getStr('editPolicy');
    return $this;
  }

  public function renderEditControl() {
    $viewer = $this->getUser();
    $revision = $this->getRevision();

    $policies = id(new PhabricatorPolicyQuery())
      ->setViewer($viewer)
      ->setObject($revision)
      ->execute();

    return id(new AphrontFormPolicyControl())
      ->setUser($viewer)
      ->setCapability(PhabricatorPolicyCapability::CAN_EDIT)
      ->setPolicyObject($revision)
      ->setPolicies($policies)
      ->setName('editPolicy');
  }

  public function willWriteRevision(DifferentialRevisionEditor $editor) {
    $this->getRevision()->setEditPolicy($this->value);
  }

}

Remove policy caveat from Differential

Remove policy caveat from Differential

Summary: Policies are now fully supported in Differential.

Test Plan: Grepped for other caveats, looks like I've already removed htem all.

Reviewers: chad, btrahan

Reviewed By: chad

CC: aran

Differential Revision: https://secure.phabricator.com/D8095


<?php namespace Laravel\Database\Connectors; use PDO;

class MySQL extends Connector {

	/**
	 * Establish a PDO database connection for a given database configuration.
	 *
	 * @param  array  $config
	 * @return PDO
	 */
	public function connect($config)
	{
		$connection = new PDO($this->dsn($config), $config['username'], $config['password'], $this->options($config));

		if (isset($config['charset']))
		{
			$connection->prepare("SET NAMES '{$config['charset']}'")->execute();
		}

		return $connection;
	}

	/**
	 * Format the DSN connection string for a MySQL connection.
	 *
	 * @param  array   $config
	 * @return string
	 */
	protected function dsn($config)
	{
		// Format the initial MySQL PDO connection string. These options are required
		// for every MySQL connection that is established. The connection strings
		// have the following convention: "mysql:host=hostname;dbname=database"
		$dsn = sprintf('%s:host=%s;dbname=%s', $config['driver'], $config['host'], $config['database']);

		// Check for any optional MySQL PDO options. These options are not required
		// to establish a PDO connection; however, may be needed in certain server
		// or hosting environments used by the developer.
		foreach (array('port', 'unix_socket') as $key => $value)
		{
			if (isset($config[$key])) $dsn .= ";{$key}={$value}";
		}

		return $dsn;
	}

}

<?php namespace Laravel\Database\Connectors; use PDO;

class MySQL extends Connector {

	/**
	 * Establish a PDO database connection for a given database configuration.
	 *
	 * @param  array  $config
	 * @return PDO
	 */
	public function connect($config)
	{
		extract($config);

		// Format the initial MySQL PDO connection string. These options are required
		// for every MySQL connection that is established. The connection strings
		// have the following convention: "mysql:host=hostname;dbname=database"
		$dsn = sprintf('%s:host=%s;dbname=%s', $driver, $host, $database);

		// Check for any optional MySQL PDO options. These options are not required
		// to establish a PDO connection; however, may be needed in certain server
		// or hosting environments used by the developer.
		foreach (array('port', 'unix_socket') as $key => $value)
		{
			if (isset($config[$key]))
			{
				$dsn .= ";{$key}={$value}";
			}
		}

		$connection = new PDO($dsn, $username, $password, $this->options($config));

		if (isset($config['charset']))
		{
			$connection->prepare("SET NAMES '{$charset}'")->execute();
		}

		return $connection;
	}

}

Clean up the MySQL database connector.

Clean up the MySQL database connector.


<?php

return [
    'class' => 'yii\db\Connection',
    // 'dsn' => 'oci:host=103.13.28.239;dbname=103.13.28.239/XE;charset=UTF8',
    'dsn' => 'mysql:host=103.13.28.239;dbname=aci_dev;charset=UTF8',
    'username' => 'aci_dev',
    'password' => 'aci_2015',
    'charset' => 'utf8',
];

<?php

return [
    'class' => 'yii\db\Connection',
    //'dsn' => 'oci:host=103.13.28.239;dbname=103.13.28.239/XE;charset=UTF8',
    //'dsn' => 'mysql:host=103.13.28.239;dbname=aci_dev;charset=UTF8',
	'dsn' => 'mysql:host=122.155.175.5;dbname=chinnawat_aci;charset=UTF8',
    'username' => 'chinnawat_aci',
    'password' => 'aci_2015',
    'charset' => 'utf8',
];

Change Database pointer to PROD ENV

Change Database pointer to PROD ENV


Menu Maintenance - Editing

<form action="#" method="post">
    {fid}
    {fname}
    {fdescription}
    {fprice}
    {fpicture}
    {fcategory}
</form>

Menu Maintenance - Editing

<form action="/curd/save" method="post">
    {fid}
    {fname}
    {fdescription}
    {fprice}
    {fpicture}
    {fcategory}
    {zsubmit} Cancel
</form>

Update form view to show submit and cancel buttons


@extends('layouts.project')

@section('styles')
<link rel="stylesheet" href="{{ asset('css/bugtracker/issue.css') }}" />
@endsection

@section('scripts')

@endsection

@section('project-content')

{!! Breadcrumbs::render('issues', $project) !!}

        @if(!app('request')->input('closed_visible'))
         $project, 'closed_visible'=>true]) }}"> Show closed
        @else
         $project, 'closed_visible'=>false]) }}"> Hide closed
        @endif

@if(!$issues->isEmpty())

        @include('bugtracker.project.partials.issues-block')
        <button type="button" class="btn btn-info" data-toggle="modal" data-target="#create-issue-modal">@lang('projects.issue_create')</button>

@else

There is no issues yet, add one!

@endif

    {!! View::make('bugtracker.project.partials.issue_create_modal', ['project'=>$project])->render() !!}

@endsection

@extends('layouts.project')

@section('styles')
<link rel="stylesheet" href="{{ asset('css/bugtracker/issue.css') }}" />
@endsection

@section('scripts')

@endsection

@section('project-content')

{!! Breadcrumbs::render('issues', $project) !!}

        @if(!app('request')->input('closed_visible'))
         $project, 'closed_visible'=>true]) }}"> Show closed
        @else
         $project, 'closed_visible'=>false]) }}"> Hide closed
        @endif

@if(!$issues->isEmpty())

        @include('bugtracker.project.partials.issues-block')

@else

There is no issues yet, add one!

@endif
<button type="button" class="btn btn-info" data-toggle="modal" data-target="#create-issue-modal">@lang('projects.issue_create')</button>

    {!! View::make('bugtracker.project.partials.issue_create_modal', ['project'=>$project])->render() !!}

@endsection

Add issue button on issues page added

Add issue button on issues page added


<?php

/*
 * This file is part of the Fxp Composer Asset Plugin package.
 *
 * (c) François Pluchino <francois.pluchino@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Fxp\Composer\AssetPlugin\Package\Version;

use Composer\Package\Version\VersionParser as BaseVersionParser;

/**
 * Lazy loader for asset package.
 *
 * @author François Pluchino <francois.pluchino@gmail.com>
 */
class VersionParser extends BaseVersionParser
{
    /**
     * Returns the stability of a version
     *
     * @param string $version
     *
     * @return string
     */
    public static function parseStability($version)
    {
        $stability = parent::parseStability($version);

        return false !== strpos($version, '-patch') ? 'dev' : $stability;
    }
}

<?php

/*
 * This file is part of the Fxp Composer Asset Plugin package.
 *
 * (c) François Pluchino <francois.pluchino@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Fxp\Composer\AssetPlugin\Package\Version;

use Composer\Package\Version\VersionParser as BaseVersionParser;

/**
 * Lazy loader for asset package.
 *
 * @author François Pluchino <francois.pluchino@gmail.com>
 */
class VersionParser extends BaseVersionParser
{
    /**
     * Returns the stability of a version.
     *
     * @param string $version
     *
     * @return string
     */
    public static function parseStability($version)
    {
        $stability = parent::parseStability($version);

        return false !== strpos($version, '-patch') ? 'dev' : $stability;
    }
}

Fix php doc short description

Fix php doc short description


<?php

namespace Doctrine\Tests\ORM\Functional;

use Doctrine\ORM\Mapping\JoinColumn;

class MergeCompositeToOneKeyTest extends \Doctrine\Tests\OrmFunctionalTestCase
{
    protected function setUp()
    {
        parent::setUp();
        $this->_schemaTool->createSchema(array(
            $this->_em->getClassMetadata(__NAMESPACE__ . '\MergeCompositeToOneKeyCountry'),
            $this->_em->getClassMetadata(__NAMESPACE__ . '\MergeCompositeToOneKeyState'),
        ));
    }

    public function testIssue()
    {
        $country = new MergeCompositeToOneKeyCountry();
        $country->country = 'US';
        $state = new MergeCompositeToOneKeyState();
        $state->state = 'CA';
        $state->country = $country;

        $this->_em->merge($country);
        $this->_em->merge($state);
    }
}

/**
 * @Entity
 */
class MergeCompositeToOneKeyCountry
{
    /**
     * @Id
     * @Column(type="string", name="country")
     * @GeneratedValue(strategy="NONE")
     */
    public $country;
}

/**
 * @Entity
  */
class MergeCompositeToOneKeyState
{
    /**
     * @Id
     * @Column(type="string")
     * @GeneratedValue(strategy="NONE")
     */
    public $state;

    /**
     * @Id
     * @ManyToOne(targetEntity="MergeCompositeToOneKeyCountry")
     * @JoinColumn(name="country", referencedColumnName="country")
     */
    public $country;
}

<?php

namespace Doctrine\Tests\ORM\Functional;

use Doctrine\ORM\Mapping\JoinColumn;

class MergeCompositeToOneKeyTest extends \Doctrine\Tests\OrmFunctionalTestCase
{
    protected function setUp()
    {
        parent::setUp();
        $this->_schemaTool->createSchema(array(
            $this->_em->getClassMetadata(__NAMESPACE__ . '\MergeCompositeToOneKeyCountry'),
            $this->_em->getClassMetadata(__NAMESPACE__ . '\MergeCompositeToOneKeyState'),
        ));
    }

    public function testIssue()
    {
        $country = new MergeCompositeToOneKeyCountry();
        $country->country = 'US';
        $state = new MergeCompositeToOneKeyState();
        $state->state = 'CA';
        $state->country = $country;

        $this->_em->merge($state);
    }
}

/**
 * @Entity
 */
class MergeCompositeToOneKeyCountry
{
    /**
     * @Id
     * @Column(type="string", name="country")
     * @GeneratedValue(strategy="NONE")
     */
    public $country;
}

/**
 * @Entity
  */
class MergeCompositeToOneKeyState
{
    /**
     * @Id
     * @Column(type="string")
     * @GeneratedValue(strategy="NONE")
     */
    public $state;

    /**
     * @Id
     * @ManyToOne(targetEntity="MergeCompositeToOneKeyCountry", cascade={"MERGE"})
     * @JoinColumn(name="country", referencedColumnName="country")
     */
    public $country;
}

Update test to valid use case

Update test to valid use case


<?php

namespace App\Handler\Email;

class SendUserApprovedEmailHandler extends AbstractEmailHandler
{
    protected function configureMessage(\Swift_Message $email): void
    {
        $email
            ->setSubject('Your account has been activated')
            ->setBody('Thank you! Your account is active. You may login using your user name and password.')
        ;
    }
}

<?php

namespace App\Handler\Email;

class SendUserApprovedEmailHandler extends AbstractEmailHandler
{
    protected function configureMessage(\Swift_Message $email, AbstractSendEmailCommand $command): void
    {
        $email
            ->setSubject('Your account has been activated')
            ->setBody('Thank you! Your account is active. You may login using your user name and password.')
        ;
    }
}

Add abstract email command object as argument.


<?php

namespace Oro\Bundle\UserBundle\Migrations\Schema\v1_24;

use Doctrine\DBAL\Schema\Schema;

use Oro\Bundle\MigrationBundle\Migration\Migration;
use Oro\Bundle\MigrationBundle\Migration\QueryBag;

class AddDisableLogin implements Migration
{
    /**
     * {@inheritdoc}
     */
    public function up(Schema $schema, QueryBag $queries)
    {
        $table = $schema->getTable('oro_user');
        $table->dropColumn('login_disabled');
    }
}

<?php

namespace Oro\Bundle\UserBundle\Migrations\Schema\v1_24;

use Doctrine\DBAL\Schema\Schema;

use Oro\Bundle\EntityConfigBundle\Migration\RemoveFieldQuery;
use Oro\Bundle\MigrationBundle\Migration\Migration;
use Oro\Bundle\MigrationBundle\Migration\QueryBag;
use Oro\Bundle\UserBundle\Entity\User;

class RemoveDisableLogin implements Migration
{
    /**
     * {@inheritdoc}
     */
    public function up(Schema $schema, QueryBag $queries)
    {
        $table = $schema->getTable('oro_user');
        $table->dropColumn('login_disabled');

        $queries->addQuery(
            new RemoveFieldQuery(
                User::class,
                'loginDisabled'
            )
        );
    }
}

BB-5703: Create new release dump and create new build to test upgrade from latest release to master
- moved some migrations that had wrong versions
- fixed migrations that caused failures in tests


<?php

namespace Flosch\Bundle\StripeBundle\Stripe;

use Stripe\Stripe;

class StripeClient extends Stripe
{
    public function __construct($stripeApiKey)
    {
        self::setApiKey($stripeApiKey);

        return $this;
    }
}

<?php

namespace Flosch\Bundle\StripeBundle\Stripe;

use Stripe\Stripe,
    Stripe\Customer;

/**
 * An extension of the Stripe PHP SDK, including an API key parameter to automatically authenticate.
 *
 * This class will provide helper methods to use the Stripe SDK
 */
class StripeClient extends Stripe
{
    public function __construct($stripeApiKey)
    {
        self::setApiKey($stripeApiKey);

        return $this;
    }

    /**
     * Associate a new Customer object to an existing Plan.
     *
     * @throws HttpException:
     *     - If the planId is invalid (the plan does not exists...)
     *     - If the payment token is invalid (payment failed)
     *
     * @see https://stripe.com/docs/subscriptions/tutorial#create-subscription
     *
     * @param string $planId: The plan ID as defined in your Stripe dashboard
     * @param string $paymentToken: The payment token returned by the payment form
     * @param string $customerEmail: The customer email
     *
     * @return Customer
     */
    public function subscribeCustomerToPlan(string $planId, string $paymentToken, string $customerEmail)
    {
        return Customer::create([
            "plan" => $planId,
            "source" => $paymentToken,
            "email" => $customerEmail
        ]);
    }
}

[Plan] Add shortcut to subscribe a customer to a given plan.


<?php

namespace wcf\system\user\authentication\event;

use wcf\data\user\User;
use wcf\system\cache\runtime\UserRuntimeCache;
use wcf\system\event\IEvent;

/**
 * Indicates that the user actively logged in, i.e. that a user change happened in response
 * to a user's request based off proper authentication.
 *
 * This event specifically must not be used if the active user is changed for technical
 * reasons, e.g. when switching back to the real user after executing some logic with
 * guest permissions.
 *
 * @author  Tim Duesterhus
 * @copyright   2001-2021 WoltLab GmbH
 * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package WoltLabSuite\Core\System\User\Authentication\Event
 * @since   5.5
 */
final class UserLoggedIn implements IEvent
{
    /**
     * @var int
     */
    private $userID;

    public function __construct(User $user)
    {
        $this->userID = (int)$user->userID;
    }

    public function getUser(): User
    {
        return UserRuntimeCache::getInstance()->getObject($this->userID);
    }
}

<?php

namespace wcf\system\user\authentication\event;

use wcf\data\user\User;
use wcf\system\cache\runtime\UserRuntimeCache;
use wcf\system\event\IEvent;

/**
 * Indicates that the user actively logged in, i.e. that a user change happened in response
 * to a user's request based off proper authentication.
 *
 * This event specifically must not be used if the active user is changed for technical
 * reasons, e.g. when switching back to the real user after executing some logic with
 * guest permissions.
 *
 * @author  Tim Duesterhus
 * @copyright   2001-2021 WoltLab GmbH
 * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package WoltLabSuite\Core\System\User\Authentication\Event
 * @since   5.5
 */
final class UserLoggedIn implements IEvent
{
    private int $userID;

    public function __construct(User $user)
    {
        $this->userID = (int)$user->userID;
    }

    public function getUser(): User
    {
        return UserRuntimeCache::getInstance()->getObject($this->userID);
    }
}

Use typed property in UserLoggedIn event


<?php

/**
 * Stripe Create Subscription Request.
 */
namespace Omnipay\Stripe\Message;

/**
 * Stripe Create Subscription Request
 *
 * @see Omnipay\Stripe\Gateway
 * @link https://stripe.com/docs/api/php#create_subscription
 */
class CreateSubscriptionRequest extends AbstractRequest
{
    /**
     * Get the plan ID
     *
     * @return string
     */
    public function getPlan()
    {
        return $this->getParameter('plan');
    }

    /**
     * Set the plan ID
     *
     * @return CreateSubscriptionRequest provides a fluent interface.
     */
    public function setPlan($value)
    {
        return $this->setParameter('plan', $value);
    }

    public function getData()
    {
        $this->validate('customerReference', 'plan');

        $data = array(
            'plan' => $this->getPlan()
        );

        return $data;
    }

    public function getEndpoint()
    {
        return $this->endpoint.'/customers/'.$this->getCustomerReference().'/subscriptions';
    }
}

<?php

/**
 * Stripe Create Subscription Request.
 */
namespace Omnipay\Stripe\Message;

/**
 * Stripe Create Subscription Request
 *
 * @see Omnipay\Stripe\Gateway
 * @link https://stripe.com/docs/api/php#create_subscription
 */
class CreateSubscriptionRequest extends AbstractRequest
{
    /**
     * Get the plan ID
     *
     * @return string
     */
    public function getPlan()
    {
        return $this->getParameter('plan');
    }

    /**
     * Set the plan ID
     *
     * @return CreateSubscriptionRequest provides a fluent interface.
     */
    public function setPlan($value)
    {
        return $this->setParameter('plan', $value);
    }

    public function getData()
    {
        $this->validate('customerReference', 'plan');

        $data = array(
            'plan' => $this->getPlan()
        );

        if (isset($this->parameters->has('tax_percent'))) {
            $data['tax_percent'] = (float)$this->getParameter('tax_percent');
        }

        return $data;
    }

    public function getEndpoint()
    {
        return $this->endpoint.'/customers/'.$this->getCustomerReference().'/subscriptions';
    }
}

Add tax percent to stripe subscriptions

[FEATURE] Add tax percent to stripe subscriptions


<?php
namespace SmoothPhp\Tests\EventDispatcher;

use SmoothPhp\EventDispatcher\SimpleEventDispatcher;

/**
 * Class SimpleEventDispatcherTest
 * @package SmoothPhp\Tests\EventDispatcher
 * @author Simon Bennett <simon@smoothphp.com>
 */
final class SimpleEventDispatcherTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @test
     */
    public function check_dispatcher_runs()
    {
        $dispatcher = new SimpleEventDispatcher();

        $runCount = 0;
        $dispatcher->addListener('test',function()use(&$runCount)
        {
            $runCount ++;
        });

        $this->assertEquals(0,$runCount);

        $dispatcher->dispatch('test',[]);

        $this->assertEquals(1,$runCount);
    }
}

<?php
namespace SmoothPhp\Tests\EventDispatcher;

use SmoothPhp\EventDispatcher\SimpleEventDispatcher;

/**
 * Class SimpleEventDispatcherTest
 * @package SmoothPhp\Tests\EventDispatcher
 * @author Simon Bennett <simon@smoothphp.com>
 */
final class SimpleEventDispatcherTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @test
     */
    public function check_dispatcher_runs()
    {
        $dispatcher = new SimpleEventDispatcher();

        $runCount = 0;
        $dispatcher->addListener('test',function()use(&$runCount)
        {
            $runCount ++;
        });

        $this->assertEquals(0,$runCount);

        $dispatcher->dispatch('test',[]);

        $this->assertEquals(1,$runCount);
    }

    /**
     * @test
     */
    public function check_dispatcher_does_not_run()
    {
        $dispatcher = new SimpleEventDispatcher();

        $runCount = 0;
        $dispatcher->addListener('test',function()use(&$runCount)
        {
            $runCount ++;
        });
        $dispatcher->dispatch('test_does_not_run',[]);

        $this->assertEquals(0,$runCount);
    }
}

Add an addiction event dispatcher test

Add an addiction event dispatcher test


<?php
class ModelPaymentOmiseOffsite extends Model
{
    /**
     * Install a table that need to use in Omise Payment Gateway module
     * @return boolean
     */
    public function install()
    {
        $this->load->model('setting/setting');
        $this->model_setting_setting->editSetting($this->_group, array(
            'omise_offsite_status'        => 0,
            'omise_offsite_payment_title' => 'Internet Banking (Powered by Omise)'
        ));

        return true;
    }

    /**
     * Drop table when uninstall Omise Payment Gateway module
     * @return boolean
     */
    public function uninstall()
    {
        // ...
    }

    /**
     * Get config from table
     * @return array|boolean
     */
    public function getConfig()
    {
        try {
            $this->load->model('setting/setting');
            $this->model_setting_setting->getSetting($this->_group);
        } catch (Exception $e) {
            return false;
        }
    }
}

<?php
class ModelPaymentOmiseOffsite extends Model {
    private $_group = 'omise_offsite';

    /**
     * Install a table that need to use in Omise Payment Gateway module
     * @return boolean
     */
    public function install()
    {
        $this->load->model('setting/setting');
        $this->model_setting_setting->editSetting($this->_group, array(
            'omise_offsite_status'        => 0,
            'omise_offsite_payment_title' => 'Internet Banking (Powered by Omise)'
        ));

        return true;
    }

    /**
     * Drop table when uninstall Omise Payment Gateway module
     * @return boolean
     */
    public function uninstall()
    {
        // ...
    }

    /**
     * Get config from table
     * @return array|boolean
     */
    public function getConfig()
    {
        try {
            $this->load->model('setting/setting');
            $this->model_setting_setting->getSetting($this->_group);
        } catch (Exception $e) {
            return false;
        }
    }
}

Fix admin/model where bad config item was added on install


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

bcscale(2);

$txn_id= (int)$_REQUEST['txn'];
$id= (int)$_REQUEST['id'];

if (!$txn_id || !$id)
  die_jsonp("No transaction or payment specified.");

$txn= txn_load($db, $txn_id);

if ($txn['paid'])
  die_jsonp("Transaction is fully paid, can't remove payments.");

// add payment record
$q= "DELETE FROM payment WHERE id = $id AND txn = $txn_id";
$r= $db->query($q)
  or die_query($db, $q);

echo jsonp(array('txn' => txn_load($db, $id),
                          'payments' => txn_load_payments($db, $id)));

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

bcscale(2);

$txn_id= (int)$_REQUEST['txn'];
$id= (int)$_REQUEST['id'];

if (!$txn_id || !$id)
  die_jsonp("No transaction or payment specified.");

$txn= txn_load($db, $txn_id);

if ($txn['paid'])
  die_jsonp("Transaction is fully paid, can't remove payments.");

// add payment record
$q= "DELETE FROM payment WHERE id = $id AND txn = $txn_id";
$r= $db->query($q)
  or die_query($db, $q);

echo jsonp(array('txn' => txn_load($db, $txn_id),
                          'payments' => txn_load_payments($db, $txn_id)));

Fix response from payment removal API (using wrong ID for txn)


<?php

namespace App\Actions;

use App\Shell\Shell;

class InitializeGitRepo
{
    use LamboAction;

    protected $shell;

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

    public function __invoke()
    {
        $this->logStep('Initializing git repository');

        $this->shell->execInProject('git init');
        $this->shell->execInProject('git add .');
        $this->shell->execInProject('git commit -m "' . config('lambo.store.commit_message') . '"');
        $this->info('New git repository initialized.');
    }

}

<?php

namespace App\Actions;

use App\Shell\Shell;

class InitializeGitRepo
{
    use LamboAction;

    protected $shell;

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

    public function __invoke()
    {
        $this->logStep('Initializing git repository');

        $this->execAndCheck('git init');
        $this->execAndCheck('git add .');
        $this->execAndCheck('git commit -m "' . config('lambo.store.commit_message') . '"');
        $this->info('New git repository initialized.');
    }

    public function execAndCheck($command)
    {
        $process = $this->shell->execInProject($command);

        $this->abortIf(! $process->isSuccessful(), 'Initialization of git repository did not complete successfully.', $process);
    }
}

Stop if git commands fail.

Stop if git commands fail.


<?php

namespace Zeropingheroes\Lanager\Requests;

class StoreSlideRequest extends Request
{
    use LaravelValidation;

    /**
     * Whether the request is valid
     *
     * @return bool
     */
    public function valid(): bool
    {
        $this->validationRules = [
            'lan_id'             => ['required', 'numeric', 'exists:lans,id'],
            'name'               => ['required', 'max:255'],
            'content'            => ['required'],
            'position'           => ['integer'],
            'duration'           => ['integer'],
            'published'          => ['boolean'],
        ];

        if (!$this->laravelValidationPasses()) {
            return $this->setValid(false);
        }

        return $this->setValid(true);
    }
}

<?php

namespace Zeropingheroes\Lanager\Requests;

class StoreSlideRequest extends Request
{
    use LaravelValidation;

    /**
     * Whether the request is valid
     *
     * @return bool
     */
    public function valid(): bool
    {
        $this->validationRules = [
            'lan_id'             => ['required', 'numeric', 'exists:lans,id'],
            'name'               => ['required', 'max:255'],
            'content'            => ['required'],
            'position'           => ['integer', 'min:0', 'max:127'],
            'duration'           => ['integer', 'min:0', 'max:32767'],
            'published'          => ['boolean'],
        ];

        if (!$this->laravelValidationPasses()) {
            return $this->setValid(false);
        }

        return $this->setValid(true);
    }
}

Validate slide max position and duration


@section('js')

@endsection

@include('core::admin._buttons-form')

{!! BootForm::hidden('id') !!}

@include('core::admin._image-fieldset', ['field' => 'image'])

has('position'))has-error @endif">
        {!! BootForm::text(__('Position'), 'position') !!}

        {!! BootForm::text(__('Url'), 'url') !!}

{!! BootForm::select(__('Page'), 'page_id', Pages::allForSelect()) !!}

{!! TranslatableBootForm::hidden('status')->value(0) !!}
{!! TranslatableBootForm::checkbox(__('Published'), 'status') !!}
{!! TranslatableBootForm::textarea(__('Body'), 'body')->addClass('ckeditor') !!}

@section('js')

@endsection

@component('core::admin._buttons-form', ['model' => $model])
@endcomponent

{!! BootForm::hidden('id') !!}

@include('core::admin._image-fieldset', ['field' => 'image'])

has('position'))has-error @endif">
        {!! BootForm::text(__('Position'), 'position') !!}

        {!! BootForm::text(__('Url'), 'url') !!}

{!! BootForm::select(__('Page'), 'page_id', Pages::allForSelect()) !!}

{!! TranslatableBootForm::hidden('status')->value(0) !!}
{!! TranslatableBootForm::checkbox(__('Published'), 'status') !!}
{!! TranslatableBootForm::textarea(__('Body'), 'body')->addClass('ckeditor') !!}

Use of @component for buttons in form

Use of @component for buttons in form


<?php
/**
 * Description of Date
 *
 * @package Aktive Merchant
 * @author  Andreas Kollaros
 * @license http://www.opensource.org/licenses/mit-license.php
 */
class Merchant_Billing_ExpiryDate {

  private $year;
  private $month;

  public function  __construct($month, $year) {
    $this->year = $year;
    $this->month = (int) $month;
  }

  public function is_expired (){
    return ( time() > $this->expiration() ) ;
  }

  public function expiration (){
    return strtotime($this->year."-".$this->month."-".$this->month_days()."23:59:59");
  }

  private function month_days(){
    $mdays = array(null,31,28,31,30,31,30,31,31,30,31,30,31);
    if ( $this->is_leap() ) $mdays[2] = 29;
    return $mdays[$this->month];
  }

  private function is_leap(){
    $time = strtotime($this->year."-02-29");
    $time_array = localtime($time);
    if ( $time_array[4] == 1 ) return true;
    return false;
  }

}
?>

<?php
/**
 * Description of Date
 *
 * Usage:
 * <code>
 * $expire_date = new Merchant_Billing_ExpiryDate(5, 2010);
 * </code>
 * Public methods:
 * + is_expired() returns a boolean about expiration of given data
 * + expiration() returns expiration date as Unix timestamp
 *
 *
 *
 * @package Aktive Merchant
 * @author  Andreas Kollaros
 * @license http://www.opensource.org/licenses/mit-license.php
 */
class Merchant_Billing_ExpiryDate {

  private $year;
  private $month;

  public function  __construct($month, $year) {
    $this->year = $year;
    $this->month = (int) $month;
  }

  public function is_expired (){
    return ( time() > $this->expiration() ) ;
  }

  public function expiration (){
    return strtotime($this->year."-".$this->month."-".$this->month_days()." 23:59:59");
  }

  private function month_days(){
    $mdays = array(null,31,28,31,30,31,30,31,31,30,31,30,31);
    if ( $this->is_leap() ) $mdays[2] = 29;
    return $mdays[$this->month];
  }

  private function is_leap(){
    $time = strtotime($this->year."-02-29");
    $time_array = localtime($time);
    if ( $time_array[4] == 1 ) return true;
    return false;
  }

}
?>

Add description usage for ExpireDate class