<?php

namespace EmergencyExplorer;

use Illuminate\Database\Eloquent\Model;

class Project extends Model
{
    const PROJECT_ROLE_NONE = 0;
    const PROJECT_ROLE_WATCHER = 1;
    const PROJECT_ROLE_MEMBER = 2;
    const PROJECT_ROLE_ADMIN = 3;

    protected $fillable = [
        'name', 'description', 'status',
    ];

    function game() {
        return $this->belongsTo(Game::class);
    }

    function users() {
        return $this->belongsToMany(User::class)->withPivot('role');
    }

    function admins() {
        return $this->users()->wherePivot('role', self::PROJECT_ROLE_ADMIN);
    }

    function watchers() {
        return $this->users()->wherePivot('role', self::PROJECT_ROLE_WATCHER);
    }

    function members() {
        return $this->users()->wherePivot('role', self::PROJECT_ROLE_ADMIN)
        ->orWherePivot('role', self::PROJECT_ROLE_MEMBER);
    }

    function media() {
        return $this->belongsToMany(Media::class);
    }
}

<?php

namespace EmergencyExplorer;

use Illuminate\Database\Eloquent\Model;

class Project extends Model
{
    const PROJECT_ROLE_NONE = 0;
    const PROJECT_ROLE_WATCHER = 1;
    const PROJECT_ROLE_MEMBER = 2;
    const PROJECT_ROLE_ADMIN = 3;

    protected $fillable = [
        'name', 'description', 'status', 'game_id', 'visible'
    ];

    function game() {
        return $this->belongsTo(Game::class);
    }

    function users() {
        return $this->belongsToMany(User::class)->withPivot('role');
    }

    function admins() {
        return $this->users()->wherePivot('role', self::PROJECT_ROLE_ADMIN);
    }

    function watchers() {
        return $this->users()->wherePivot('role', self::PROJECT_ROLE_WATCHER);
    }

    function members() {
        return $this->users()->whereIn('project_user.role', [self::PROJECT_ROLE_MEMBER, self::PROJECT_ROLE_ADMIN]);
    }

    function media() {
        return $this->belongsToMany(Media::class);
    }
}

Fix a critical bug where the project member query would return wrong members

Durch einen Fehler in der orWhere() Logik von Laravel konnte die project_id ignoriert werden


<?php

namespace PHPUnit\Framework {

    if (!class_exists(TestCase::class)) {
        /*
         * Forward compatibility for PHPUnit 4.x (Magento 2.1)
         */
        abstract class TestCase extends \PHPUnit_Framework_TestCase
        {
            public function expectException($exceptionName)
            {
                $this->setExpectedException($exceptionName);
            }
        }
    }
}

<?php

namespace PHPUnit\Framework {

    /*
     * TestCase::class cannot be used because it would break code generation in Magento 2.1
     * where the code scanner looks for the first "class" keyword.
     */
    if (!class_exists('\PHPUnit\Framework\TestCase')) {
        /*
         * Forward compatibility for PHPUnit 4.x (Magento 2.1)
         */
        abstract class TestCase extends \PHPUnit_Framework_TestCase
        {
            public function expectException($exceptionName)
            {
                $this->setExpectedException($exceptionName);
            }
        }
    }
}

Fix compilation error in Magento 2.1

Fix compilation error in Magento 2.1


<?php

namespace habil\ResellerClub\APIs;

use habil\ResellerClub\Helper;

class Orders
{
    use Helper;

    /**
     * @var string
     */
    protected $api = 'orders';

    public function suspend($orderId, $reason)
    {
        return $this->get('suspend', [
            'order-id'  => $orderId,
            'reason'    => $reason
        ]);
    }

    public function unsuspend($orderId, $reason)
    {
        return $this->get('unsuspend', [
            'order-id'  => $orderId,
            'reason'    => $reason
        ]);
    }
}

<?php

namespace habil\ResellerClub\APIs;

use habil\ResellerClub\Helper;

class Orders
{
    use Helper;

    /**
     * @var string
     */
    protected $api = 'orders';

    public function suspend($orderId, $reason)
    {
        return $this->post('suspend', [
            'order-id'  => $orderId,
            'reason'    => $reason
        ]);
    }

    public function unsuspend($orderId, $reason)
    {
        return $this->post('unsuspend', [
            'order-id'  => $orderId,
            'reason'    => $reason
        ]);
    }
}

Fix Order suspend/unsuspend HTTP method

Fix Order suspend/unsuspend HTTP method

@see
https://manage.resellerclub.com/kb/answer/1077
https://manage.resellerclub.com/kb/node/1452


<?php
/**
 * This file is part of the TelegramBot package.
 *
 * (c) Avtandil Kikabidze aka LONGMAN <akalongman@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Longman\TelegramBot\Commands;

use Longman\TelegramBot\Entities\ServerResponse;

/**
 * Abstract System Command Class
 */
abstract class SystemCommand extends Command
{
    /**
     * A system command just executes
     *
     * Although system commands should just work and return a successful ServerResponse,
     * each system command can override this method to add custom functionality.
     *
     * @return Entities\ServerResponse
     */
    public function execute()
    {
        //System command, return successful ServerResponse
        return new ServerResponse(['ok' => true, 'result' => true], null);
    }
}

<?php
/**
 * This file is part of the TelegramBot package.
 *
 * (c) Avtandil Kikabidze aka LONGMAN <akalongman@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Longman\TelegramBot\Commands;

use Longman\TelegramBot\Request;

/**
 * Abstract System Command Class
 */
abstract class SystemCommand extends Command
{
    /**
     * A system command just executes
     *
     * Although system commands should just work and return a successful ServerResponse,
     * each system command can override this method to add custom functionality.
     *
     * @return Entities\ServerResponse
     */
    public function execute()
    {
        //System command, return empty ServerResponse
        return Request::emptyResponse();
    }
}

Use the new emptyResponse() method for returning an empty AdminCommand response.


<?php
namespace App\Entity\Fixture;

use App\Radio\Adapters;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\Persistence\ObjectManager;
use App\Entity;

class Station extends AbstractFixture
{
    public function load(ObjectManager $em)
    {
        $station = new Entity\Station;
        $station->setName('AzuraTest Radio');
        $station->setDescription('A test radio station.');
        $station->setFrontendType(Adapters::FRONTEND_ICECAST);
        $station->setBackendType(Adapters::BACKEND_LIQUIDSOAP);
        $station->setRadioBaseDir('/var/azuracast/stations/azuratest_radio');

        // Ensure all directories exist.
        $radio_dirs = [
            $station->getRadioBaseDir(),
            $station->getRadioMediaDir(),
            $station->getRadioAlbumArtDir(),
            $station->getRadioPlaylistsDir(),
            $station->getRadioConfigDir(),
            $station->getRadioTempDir(),
        ];
        foreach ($radio_dirs as $radio_dir) {
            if (!file_exists($radio_dir) && !mkdir($radio_dir, 0777) && !is_dir($radio_dir)) {
                throw new \RuntimeException(sprintf('Directory "%s" was not created', $radio_dir));
            }
        }

        $station_quota = getenv('INIT_STATION_QUOTA');
        if (!empty($station_quota)) {
            $station->setStorageQuota($station_quota);
        }

        $em->persist($station);
        $em->flush();

        $this->addReference('station', $station);
    }
}

<?php
namespace App\Entity\Fixture;

use App\Radio\Adapters;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\Persistence\ObjectManager;
use App\Entity;

class Station extends AbstractFixture
{
    public function load(ObjectManager $em)
    {
        $station = new Entity\Station;
        $station->setName('AzuraTest Radio');
        $station->setDescription('A test radio station.');
        $station->setEnableRequests(true);
        $station->setFrontendType(Adapters::FRONTEND_ICECAST);
        $station->setBackendType(Adapters::BACKEND_LIQUIDSOAP);
        $station->setRadioBaseDir('/var/azuracast/stations/azuratest_radio');

        // Ensure all directories exist.
        $radio_dirs = [
            $station->getRadioBaseDir(),
            $station->getRadioMediaDir(),
            $station->getRadioAlbumArtDir(),
            $station->getRadioPlaylistsDir(),
            $station->getRadioConfigDir(),
            $station->getRadioTempDir(),
        ];
        foreach ($radio_dirs as $radio_dir) {
            if (!file_exists($radio_dir) && !mkdir($radio_dir, 0777) && !is_dir($radio_dir)) {
                throw new \RuntimeException(sprintf('Directory "%s" was not created', $radio_dir));
            }
        }

        $station_quota = getenv('INIT_STATION_QUOTA');
        if (!empty($station_quota)) {
            $station->setStorageQuota($station_quota);
        }

        $em->persist($station);
        $em->flush();

        $this->addReference('station', $station);
    }
}

Enable requests on fixture station.

Enable requests on fixture station.


<?php

namespace XeroPHP\Remote\OAuth\SignatureMethod;

use XeroPHP\Remote\OAuth\Exception;

class RSASHA1 implements SignatureMethodInterface {

    public static function generateSignature(array $config, $sbs, $secret) {
        // Fetch the private key
        if(false === $private_key_id = openssl_pkey_get_private($config['rsa_private_key']))
            throw new Exception('Cannot access private key for signing');

        // Sign using the key
        if(false === openssl_sign($sbs, $signature, $private_key_id)) {
            throw new Exception('Cannot sign signature base string.');
        }

        // Release the key resource
        openssl_free_key($private_key_id);

        return base64_encode($signature);
    }

}

<?php

namespace XeroPHP\Remote\OAuth\SignatureMethod;

use XeroPHP\Remote\OAuth\Exception;

class RSASHA1 implements SignatureMethodInterface {

    public static function generateSignature(array $config, $sbs, $secret) {
        // Fetch the private key
        if(false === $private_key_id = openssl_pkey_get_private($config['rsa_private_key'])){
            throw new Exception("Cannot access private key for signing: openssl_pkey_get_private('${config['rsa_private_key']}') returned false");
        }

        // Sign using the key
        if(false === openssl_sign($sbs, $signature, $private_key_id)) {
            throw new Exception('Cannot sign signature base string.');
        }

        // Release the key resource
        openssl_free_key($private_key_id);

        return base64_encode($signature);
    }

}

Make inaccessable private key exception more informative

Perviously setting $config['rsa_private_key'] = 'file://full/path/to/key.pem' (note two slashes instead of three) or other variations that are incompatitible with openssl_pkey_private(), would just give the user "Cannot access private key for signing", for a file that is very much accessable. The additional info I've added allows the user to go straight to the manual instead of spending time thinking it's a permissions issue.


<?php

namespace Dash;

/**
 * @see all
 * @codeCoverageIgnore
 */
function every($iterable, $predicate)
{
	return all($iterable, $predicate);
}

<?php

namespace Dash;

/**
 * @see all
 * @codingStandardsIgnoreFile
 * @codeCoverageIgnore
 */
function every($iterable, $predicate)
{
	return all($iterable, $predicate);
}

Exclude alias functions from phpcs

Exclude alias functions from phpcs


<?php namespace Flarum\Sticky\Handlers;

use Flarum\Core\Events\DiscussionSearchWillBePerformed;
use Flarum\Categories\CategoryGambit;

class StickySearchModifier
{
    public function subscribe($events)
    {
        $events->listen('Flarum\Core\Events\DiscussionSearchWillBePerformed', __CLASS__.'@reorderSearch');
    }

    public function reorderSearch(DiscussionSearchWillBePerformed $event)
    {
        if ($event->criteria->sort === null) {
            $query = $event->searcher->query();

            foreach ($event->searcher->getActiveGambits() as $gambit) {
                if ($gambit instanceof CategoryGambit) {
                    array_unshift($query->orders, ['column' => 'is_sticky', 'direction' => 'desc']);
                    return;
                }
            }

            $query->leftJoin('users_discussions', function ($join) use ($event) {
                $join->on('users_discussions.discussion_id', '=', 'discussions.id')
                     ->where('discussions.is_sticky', '=', true)
                     ->where('users_discussions.user_id', '=', $event->criteria->user->id);
            });
            // might be quicker to do a subquery in the order clause than a join?
            array_unshift(
                $query->orders,
                ['type' => 'raw', 'sql' => '(is_sticky AND (users_discussions.read_number IS NULL OR discussions.last_post_number > users_discussions.read_number)) desc']
            );
        }
    }
}

<?php namespace Flarum\Sticky\Handlers;

use Flarum\Core\Events\DiscussionSearchWillBePerformed;
use Flarum\Categories\CategoryGambit;

class StickySearchModifier
{
    public function subscribe($events)
    {
        $events->listen('Flarum\Core\Events\DiscussionSearchWillBePerformed', __CLASS__.'@reorderSearch');
    }

    public function reorderSearch(DiscussionSearchWillBePerformed $event)
    {
        if ($event->criteria->sort === null) {
            $query = $event->searcher->query();

            if (!is_array($query->orders)) {
                $query->orders = [];
            }

            foreach ($event->searcher->getActiveGambits() as $gambit) {
                if ($gambit instanceof CategoryGambit) {
                    array_unshift($query->orders, ['column' => 'is_sticky', 'direction' => 'desc']);
                    return;
                }
            }

            $query->leftJoin('users_discussions', function ($join) use ($event) {
                $join->on('users_discussions.discussion_id', '=', 'discussions.id')
                     ->where('discussions.is_sticky', '=', true)
                     ->where('users_discussions.user_id', '=', $event->criteria->user->id);
            });
            // might be quicker to do a subquery in the order clause than a join?
            array_unshift(
                $query->orders,
                ['type' => 'raw', 'sql' => '(is_sticky AND (users_discussions.read_number IS NULL OR discussions.last_post_number > users_discussions.read_number)) desc']
            );
        }
    }
}

Fix error when there are no orders on the query


<?php

namespace Actuallymab\LaravelComment;

use Illuminate\Support\ServiceProvider;

class LaravelCommentServiceProvider extends ServiceProvider
{
    protected $defer = false;

    /**
     * Perform post-registration booting of services.
     *
     * @return void
     */
    public function boot()
    {
        $this->publishes([
            __DIR__.'/../database/migrations/' => database_path('migrations')
        ], 'migrations');
    }

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

<?php

namespace Actuallymab\LaravelComment;

use Illuminate\Support\ServiceProvider;

class LaravelCommentServiceProvider extends ServiceProvider
{
    protected $defer = false;

    /**
     * Perform post-registration booting of services.
     *
     * @return void
     */
    public function boot()
    {
        $timestamp = date('Y_m_d_His', time());

        $this->publishes([
            __DIR__ . '/../database/migrations/create_comments_table.php.stub' => $this->app->databasePath()
                . "/migrations/{$timestamp}_create_comments_table.php",
        ], 'migrations');
    }

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

Add date generation while publishing migrations

Uses the migration stub and prefixes it with the current timestamp.


<?php

namespace Kunstmaan\DashboardBundle\DependencyInjection;

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

/**
 * This is the class that loads and manages your bundle configuration
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
 */
class KunstmaanDashboardExtension extends Extension
{
    /**
     * {@inheritdoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $configuration = new Configuration();
        $this->processConfiguration($configuration, $configs);

        $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));
        $loader->load('services.yml');
        $loader->load('commands.yml');
    }
}

<?php

namespace Kunstmaan\DashboardBundle\DependencyInjection;

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

/**
 * This is the class that loads and manages your bundle configuration
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
 */
class KunstmaanDashboardExtension extends Extension implements PrependExtensionInterface
{
    /**
     * {@inheritdoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $configuration = new Configuration();
        $this->processConfiguration($configuration, $configs);

        $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));
        $loader->load('services.yml');
        $loader->load('commands.yml');
    }

    public function prepend(ContainerBuilder $container)
    {
        $container->prependExtensionConfig('framework', ['esi' => ['enabled' => true]]);
    }
}

[DashboardBundle] Enable esi by default for the dashboard bundle


<?php
namespace phpgt\dom;

/**
 * Contains methods that are particular to Node objects that can have a parent.
 *
 * This trait is used by the following classes:
 *  - Element
 *  - DocumentType
 *  - CharacterData
 */
trait ChildNode {

/**
 * Removes this ChildNode from the children list of its parent.
 * @return void
 */
public function remove() {
	$this->parentNode->removeChild($this);
}

/**
 * Inserts a Node into the children list of this ChildNode's parent,
 * just before this ChildNode.
 * @return void
 */
public function before(Node $node) {
	$this->parentNode->insertBefore($node, $this);
}

/**
 * Inserts a Node into the children list of this ChildNode's parent,
 * just after this ChildNode.
 * @return void
 */
public function after(Node $node) {
	$this->parentNode->insertBefore($node, $this->nextSibling);
}

/**
 * Replace this ChildNode in the children list of its parent.
 *
 * @param Node $replacement
 * @return void
 */
public function replaceWith(Node $replacement) {
	$this->parentNode->insertBefore($replacement, $this);
	$this->remove();
}

}#

<?php
namespace phpgt\dom;

/**
 * Contains methods that are particular to Node objects that can have a parent.
 *
 * This trait is used by the following classes:
 *  - Element
 *  - DocumentType
 *  - CharacterData
 */
trait ChildNode {

/**
 * Removes this ChildNode from the children list of its parent.
 * @return void
 */
public function remove() {
	$this->parentNode->removeChild($this);
}

/**
 * Inserts a Node into the children list of this ChildNode's parent,
 * just before this ChildNode.
 * @return void
 */
public function before(\DOMNode $node) {
	$this->parentNode->insertBefore($node, $this);
}

/**
 * Inserts a Node into the children list of this ChildNode's parent,
 * just after this ChildNode.
 * @return void
 */
public function after(\DOMNode $node) {
	$this->parentNode->insertBefore($node, $this->nextSibling);
}

/**
 * Replace this ChildNode in the children list of its parent.
 *
 * @param Node $replacement
 * @return void
 */
public function replaceWith(\DOMNode $replacement) {
	$this->parentNode->insertBefore($replacement, $this);
	$this->remove();
}

}#

Allow any DOMNode to be passed as parameters


<?php

namespace Inspector;

use Inspector\Inspection\InspectionInterface;

use ReflectionClass;

class Inspector implements InspectorInterface
{
    private $inspections = array();
    private $container;

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

    public function addInspection(InspectionInterface $inspection)
    {
        $this->inspections[] = $inspection;
    }
    public function getInspections()
    {
        return $this->inspections;
    }

    public function runInspection(InspectionInterface $inspection)
    {
        $className = $inspection->getClassName();
        $methodName = $inspection->getMethodName();

        $reflector = new ReflectionClass($className);
        $method = $reflector->getConstructor();
        $arguments = array();

        // Inject requested constructor arguments
        if ($method) {
            foreach ($method->getParameters() as $p) {
                if ($p->getName() == 'db') {
                    $arguments[] = $this->container['db'];
                }
            }
        }
        $instance = $reflector->newInstanceArgs($arguments);

        foreach ($reflector->getMethods() as $method) {
            if ($method->getName()==$methodName) {
                if ($method->isPublic()) {
                    $instance->$methodName($inspection);
                }
            }
        }
    }

    public function run()
    {
        foreach ($this->inspections as $inspection) {
            $this->runInspection($inspection);
        }
    }
}

<?php

namespace Inspector;

use Inspector\Inspection\InspectionInterface;

use ReflectionClass;

class Inspector implements InspectorInterface
{
    private $inspections = array();
    private $container;

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

    public function addInspection(InspectionInterface $inspection)
    {
        $this->inspections[] = $inspection;
    }
    public function getInspections()
    {
        return $this->inspections;
    }

    public function runInspection(InspectionInterface $inspection)
    {
        $className = $inspection->getClassName();
        $methodName = $inspection->getMethodName();

        $reflector = new ReflectionClass($className);
        $method = $reflector->getConstructor();
        $arguments = array();

        // Inject requested constructor arguments
        if ($method) {
            foreach ($method->getParameters() as $p) {
                if ($p->getName() == 'db') {
                    $arguments[] = $this->container['db'];
                }
                if ($p->getName() == 'pdo') {
                    $arguments[] = $this->container['pdo'];
                }
            }
        }
        $instance = $reflector->newInstanceArgs($arguments);

        foreach ($reflector->getMethods() as $method) {
            if ($method->getName()==$methodName) {
                if ($method->isPublic()) {
                    $instance->$methodName($inspection);
                }
            }
        }
    }

    public function run()
    {
        foreach ($this->inspections as $inspection) {
            $this->runInspection($inspection);
        }
    }
}

Support pdo key in container

Support pdo key in container


<?php

namespace duncan3dc\OAuth;

use duncan3dc\Helpers\Helper;
use duncan3dc\Serial\Json;

class Instagram extends OAuth2
{

    public function __construct(array $options)
    {
        $options = Helper::getOptions($options, [
            "client"    =>  "",
            "secret"    =>  "",
            "username"  =>  "",
        ]);

        parent::__construct([
            "type"          =>  "instagram",
            "client"        =>  $options["client"],
            "secret"        =>  $options["secret"],
            "username"      =>  $options["username"],
            "authoriseUrl"  =>  "https://api.instagram.com/oauth/authorize",
            "redirectUrl"   =>  "https://api.instagram.com/oauth/redirect",
            "accessUrl"     =>  "https://api.instagram.com/oauth/access_token",
        ]);
    }

    public function timeline(array $options = null)
    {
        $options = Helper::getOptions($options, [
            "min"   =>  false,
            "limit" =>  200,
        ]);

        $url = "https://api.instagram.com/v1/users/self/feed";

        $params = [];
        if ($val = $options["min"]) {
            $params["min_id"] = $val;
        }
        if ($val = $options["limit"]) {
            $params["count"] = $val;
        }

        return $this->fetch($url, $params);
    }
}

<?php

namespace duncan3dc\OAuth;

use duncan3dc\Helpers\Helper;
use duncan3dc\Serial\Json;

class Instagram extends OAuth2
{

    public function __construct(array $options)
    {
        $options = Helper::getOptions($options, [
            "client"    =>  "",
            "secret"    =>  "",
            "username"  =>  "",
        ]);

        parent::__construct([
            "type"          =>  "instagram",
            "client"        =>  $options["client"],
            "secret"        =>  $options["secret"],
            "username"      =>  $options["username"],
            "authoriseUrl"  =>  "https://api.instagram.com/oauth/authorize",
            "redirectUrl"   =>  "https://api.instagram.com/oauth/redirect",
            "accessUrl"     =>  "https://api.instagram.com/oauth/access_token",
        ]);
    }

    public function timeline(array $options = null)
    {
        $options = Helper::getOptions($options, [
            "min"   =>  false,
            "limit" =>  200,
        ]);

        $url = "https://api.instagram.com/v1/users/self/media/recent";

        $params = [];
        if ($val = $options["min"]) {
            $params["min_id"] = $val;
        }
        if ($val = $options["limit"]) {
            $params["count"] = $val;
        }

        return $this->fetch($url, $params);
    }
}

Update the timeline endpoint for instagram


@section("content")

Last Played

			@foreach ($lastplayed as $lp)

					{{{ date("H:m:i", $lp["time"]) }}}
					{{{ $lp["meta"] }}}

			@endforeach

			{{ $lastplayed->links() }}

@stop

@section("content")

Last Played

			@foreach ($lastplayed as $lp)

					{{{ date("H:i:s", $lp["time"]) }}}
					{{{ $lp["meta"] }}}

			@endforeach

			{{ $lastplayed->links() }}

@stop

Change the date formatting on lastplayed


<?php

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

class AlterTableIncidentsRemoveDefaultComponent extends Migration
{

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('incidents', function (Blueprint $table) {
            DB::statement("ALTER TABLE `incidents` CHANGE `component_id` `component_id` TINYINT(4)  NOT NULL  DEFAULT '0';");
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('incidents', function (Blueprint $table) {
            DB::statement("ALTER TABLE `incidents` CHANGE `component_id` `component_id` TINYINT(4)  NOT NULL  DEFAULT '1';");
        });
    }
}

<?php

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

class AlterTableIncidentsRemoveDefaultComponent extends Migration
{

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('incidents', function (Blueprint $table) {
            DB::statement("ALTER TABLE incidents CHANGE component_id component_id TINYINT(4)  NOT NULL  DEFAULT '0';");
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('incidents', function (Blueprint $table) {
            DB::statement("ALTER TABLE incidents CHANGE component_id component_id TINYINT(4)  NOT NULL  DEFAULT '1';");
        });
    }
}

Remove incompatible backticks from migration. Closes GH-90


@if (method_exists($modelAdmin, 'tableTbodyRow'))
    {{ $modelAdmin->tableTbodyRow($modelItem) }}
@else

        @foreach ($modelAdmin->getColumns() as $key => $field)

                {!! $modelAdmin->getAttribute($key, $modelItem) !!}

        @endforeach

            @include('flare::admin.modeladmin.includes.table.actions.before')

            @if ($modelAdmin->hasViewing())
                @include('flare::admin.modeladmin.includes.table.actions.view')
            @endif
            @if ($modelAdmin->hasEditting())
                @include('flare::admin.modeladmin.includes.table.actions.edit')
            @endif
            @if ($modelAdmin->hasDeleting() && ($modelAdmin->hasSoftDeleting() && $modelItem->trashed()))
                @include('flare::admin.modeladmin.includes.table.actions.restore')
            @elseif ($modelAdmin->hasCloning())
                @include('flare::admin.modeladmin.includes.table.actions.clone')
            @endif
            @if ($modelAdmin->hasDeleting())
                @include('flare::admin.modeladmin.includes.table.actions.delete')
            @endif

            @include('flare::admin.modeladmin.includes.table.actions.after')

@endif

Fix whitespace issue with Admin Panel ModelAdmin columns


<?php

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

class MakeBucketAndDetailsColumnsNullable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('posts', function (Blueprint $table) {
            $table->string('action_bucket')->nullable()->change();
            $table->text('details')->nullable()->change();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('posts', function (Blueprint $table) {
            $table->string('action_bucket')->nullable(false)->change();
            $table->text('details')->nullable(false)->change();
        });
    }
}

<?php

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

class MakeBucketAndDetailsColumnsNullable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('posts', function (Blueprint $table) {
            $table->text('details')->nullable()->change();
            $table->dropColumn('action_bucket');
            $table->string('action')->index()->after('type')->default('default')->comment('Describes the bucket the action is tied to. A campaign could ask for multiple types of actions throught the life of the campaign.');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('posts', function (Blueprint $table) {
            $table->text('details')->nullable(false)->change();
            $table->string('action_bucket')->index()->after('type')->comment('Describes the bucket the action is tied to. A campaign could ask for multiple types of actions throught the life of the campaign.');
            $table->dropColumn('action');
        });
    }
}

Update action_bucket column with new name and default value


<?php

namespace Oro\Bundle\SearchBundle\Engine;

interface IndexerInterface
{
    /**
     * Save one of several entities to search index
     *
     * @param object|array $entity
     * @param array        $context
     *
     * @return bool
     */
    public function save($entity, $context = []);

    /**
     * Delete one or several entities from search index
     *
     * @param object|array $entity
     * @param array        $context
     *
     * @return bool
     */
    public function delete($entity, $context = []);

    /**
     * Returns classes required to reindex for one or several classes
     * Returns all indexed classes if $class is null
     *
     * @param string|string[] $class
     * @param array           $context
     *
     * @return string[]
     */
    public function getClassesForReindex($class = null, $context = []);

    /**
     * Resets data for one or several classes in index
     * Resets data for all indexed classes if $class is null
     *
     * @param string|string[] $class
     * @param array           $context
     */
    public function resetIndex($class = null, $context = []);

    /**
     * Reindex data for one or several classes in index
     * Reindex data for all indexed classes if $class is null
     *
     * @param string|string[] $class
     * @param array           $context
     */
    public function reindex($class = null, $context = []);
}

<?php

namespace Oro\Bundle\SearchBundle\Engine;

interface IndexerInterface
{
    /**
     * Save one of several entities to search index
     *
     * @param object|array $entity
     * @param array        $context
     *
     * @return bool
     */
    public function save($entity, array $context = []);

    /**
     * Delete one or several entities from search index
     *
     * @param object|array $entity
     * @param array        $context
     *
     * @return bool
     */
    public function delete($entity, array $context = []);

    /**
     * Returns classes required to reindex for one or several classes
     * Returns all indexed classes if $class is null
     *
     * @param string|string[] $class
     * @param array           $context
     *
     * @return string[]
     */
    public function getClassesForReindex($class = null, array $context = []);

    /**
     * Resets data for one or several classes in index
     * Resets data for all indexed classes if $class is null
     *
     * @param string|string[] $class
     * @param array           $context
     */
    public function resetIndex($class = null, array $context = []);

    /**
     * Reindex data for one or several classes in index
     * Reindex data for all indexed classes if $class is null
     *
     * @param string|string[] $class
     * @param array           $context
     *
     * @return int Number of reindexed entities
     */
    public function reindex($class = null, array $context = []);
}

BB-4080: Add CLI command to perform product reindex
 - cr fixes


<?php

namespace App\Http\Controllers\Files;

use Storage;

use App\Http\Controllers\Controller;
use App\File;

use Illuminate\Http\Request;

class UploadController extends Controller
{
    /**
     * Create a new upload controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('verify.key');
    }

    /**
     * POST function
     *
     * @param  \Illuminate\Http\Request $request
     */
    public function post(Request $request)
    {
        // Decode the file
        $contents = base64_decode($request['contents']);
        $hash = File::hash();

        // Save the file in the database
        $file        = new File;
        $file->name  = $request['file'];
        $file->type  = $request['type'];
        $file->hash  = $hash;
        $file->owner = Session::get('user')->id;
        $file->save();

        // Put the file at $hash
        Storage::put($hash, $contents);

        // Return the url of where the file is
        return 'http://dl.' . env('APP_URL') . '/' . $hash;
    }

}

<?php

namespace App\Http\Controllers\Files;

use Storage;
use Session;

use App\Http\Controllers\Controller;
use App\File;

use Illuminate\Http\Request;

class UploadController extends Controller
{
    /**
     * Create a new upload controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('verify.key');
    }

    /**
     * POST function
     *
     * @param  \Illuminate\Http\Request $request
     */
    public function post(Request $request)
    {
        // Decode the file
        $contents = base64_decode($request['contents']);
        $hash = File::hash();

        // Save the file in the database
        $file        = new File;
        $file->name  = $request['file'];
        $file->type  = $request['type'];
        $file->hash  = $hash;
        $file->owner = Session::get('user')->id;
        $file->save();

        // Put the file at $hash
        Storage::put($hash, $contents);

        // Return the url of where the file is
        return 'http://dl.' . env('APP_URL') . '/' . $hash;
    }

}

Use Session class in upload controller

Use Session class in upload controller


<?php header("Content-Type: application/json; charset=utf-8"); ?>
<?php echo json_encode($json); ?>

<?php
if(!headers_sent()) {
  header("Content-Type: application/json; charset=utf-8");
}
?>
<?php echo json_encode($json); ?>

Improve test support: avoid send header when header sent.


<?php
namespace wcf\system\user\activity\event;
use wcf\data\user\UserList;
use wcf\system\SingletonFactory;
use wcf\system\WCF;

/**
 * User activity event implementation for follows.
 *
 * @author	Alexander Ebert
 * @copyright	2001-2017 WoltLab GmbH
 * @license	GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package	WoltLabSuite\Core\System\User\Activity\Event
 */
class FollowUserActivityEvent extends SingletonFactory implements IUserActivityEvent {
	/**
	 * @inheritDoc
	 */
	public function prepare(array $events) {
		$objectIDs = [];
		foreach ($events as $event) {
			$objectIDs[] = $event->objectID;
		}

		// fetch user id and username
		$userList = new UserList();
		$userList->setObjectIDs($objectIDs);
		$userList->readObjects();
		$users = $userList->getObjects();

		// set message
		foreach ($events as $event) {
			if (isset($users[$event->objectID])) {
				$event->setIsAccessible();

				$text = WCF::getLanguage()->getDynamicVariable('wcf.user.profile.recentActivity.follow', ['user' => $users[$event->objectID]]);
				$event->setTitle($text);
			}
			else {
				$event->setIsOrphaned();
			}
		}
	}
}

<?php
namespace wcf\system\user\activity\event;
use wcf\data\user\UserList;
use wcf\system\SingletonFactory;
use wcf\system\WCF;

/**
 * User activity event implementation for follows.
 *
 * @author	Alexander Ebert
 * @copyright	2001-2017 WoltLab GmbH
 * @license	GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package	WoltLabSuite\Core\System\User\Activity\Event
 */
class FollowUserActivityEvent extends SingletonFactory implements IUserActivityEvent {
	/**
	 * @inheritDoc
	 */
	public function prepare(array $events) {
		if (!WCF::getSession()->getPermission('user.profile.canViewUserProfile')) {
			return;
		}

		$objectIDs = [];
		foreach ($events as $event) {
			$objectIDs[] = $event->objectID;
		}

		// fetch user id and username
		$userList = new UserList();
		$userList->setObjectIDs($objectIDs);
		$userList->readObjects();
		$users = $userList->getObjects();

		// set message
		foreach ($events as $event) {
			if (isset($users[$event->objectID])) {
				$event->setIsAccessible();

				$text = WCF::getLanguage()->getDynamicVariable('wcf.user.profile.recentActivity.follow', ['user' => $users[$event->objectID]]);
				$event->setTitle($text);
			}
			else {
				$event->setIsOrphaned();
			}
		}
	}
}

Hide follow events if the user may not view profiles


<?php

use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Event;
use Orchestra\Support\Messages;
use Orchestra\Foundation\Services\UserMetaRepository;

App::make('orchestra.memory')->extend('user', function ($app, $name)
{
	return new UserMetaRepository($app, $name);
});

/*
|--------------------------------------------------------------------------
| Bind Installation Interface
|--------------------------------------------------------------------------
|
| These interface allow Orchestra Platform installation process to be
| customized by the application when there a requirement for it.
|
*/

App::bind('Orchestra\Foundation\Installation\InstallerInterface', function ()
{
	return new Orchestra\Foundation\Installation\Installer(App::make('app'));
});

App::bind('Orchestra\Foundation\Installation\RequirementInterface', function ()
{
	return new Orchestra\Foundation\Installation\Requirement(App::make('app'));
});

/*
|--------------------------------------------------------------------------
| Inject Safe Mode Notification
|--------------------------------------------------------------------------
|
| This event listener would allow Orchestra Platform to display notification
| if the application is running on safe mode.
|
*/

Event::listen('composing: *', function ()
{
	if ('on' === App::make('session')->get('orchestra.safemode'))
	{
		$messages = App::make('orchestra.messages')->retrieve();

		($messages instanceof Messages) or $messages = new Messages;

		$messages->add('info', trans('orchestra/foundation::response.safe-mode'));
		$messages->save();
	}
});

<?php

use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Event;
use Orchestra\Support\Messages;
use Orchestra\Foundation\Services\UserMetaRepository;

App::make('orchestra.memory')->extend('user', function ($app, $name)
{
	return new UserMetaRepository($app, $name);
});

/*
|--------------------------------------------------------------------------
| Bind Installation Interface
|--------------------------------------------------------------------------
|
| These interface allow Orchestra Platform installation process to be
| customized by the application when there a requirement for it.
|
*/

App::bind('Orchestra\Foundation\Installation\InstallerInterface', function ()
{
	return new Orchestra\Foundation\Installation\Installer(App::make('app'));
});

App::bind('Orchestra\Foundation\Installation\RequirementInterface', function ()
{
	return new Orchestra\Foundation\Installation\Requirement(App::make('app'));
});

/*
|--------------------------------------------------------------------------
| Inject Safe Mode Notification
|--------------------------------------------------------------------------
|
| This event listener would allow Orchestra Platform to display notification
| if the application is running on safe mode.
|
*/

Event::listen('composing: *', function ()
{
	if ('on' === App::make('session')->get('orchestra.safemode'))
	{
		App::make('orchestra.messages')->extend(function ($messages)
		{
			$messages->add('info', trans('orchestra/foundation::response.safe-mode'));
		});
	}
});

Improve safe mode notification using the new Orchestra\Messages::extend() API

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


<?php

namespace App\Traits;

use App\Notifications\UsernameMentioned;
use App\User;
use Auth;

trait UsernameMentions
{
    /**
     * Handles all the mentions in the comment. (sends notifications to mentioned usernames).
     *
     * @param \App\Comment    $comment
     * @param \App\Submission $submission
     * @param \App\User       $notifiableUser
     *
     * @return void
     */
    protected function handleMentions($comment, $submission, $notifiableUser = null)
    {
        if (!preg_match_all('/@([A-Za-z0-9\._]+)/', $comment->body, $mentionedUsernames)) {
            return;
        }

        foreach ($mentionedUsernames[1] as $key => $username) {
            // set a limit so they can't just mention the whole website!
            if ($key === 5) {
                return;
            }

            if ($user = User::whereUsername($username)->first()) {
                if ($notifiableUser->id === $user->id) {
                    continue;
                }

                $user->notify(new UsernameMentioned(Auth::user(), $submission));
            }
        }
    }
}

<?php

namespace App\Traits;

use App\Notifications\UsernameMentioned;
use App\User;
use Auth;

trait UsernameMentions
{
    /**
     * Handles all the mentions in the comment. (sends notifications to mentioned usernames).
     *
     * @param \App\Comment    $comment
     * @param \App\Submission $submission
     * @param \App\User       $notifiableUser
     *
     * @return void
     */
    protected function handleMentions($comment, $submission, $notifiableUser = null)
    {
        if (!preg_match_all('/@([A-Za-z0-9\._]+)/', $comment->body, $mentionedUsernames)) {
            return;
        }

        foreach ($mentionedUsernames[1] as $key => $username) {
            // set a limit so they can't just mention the whole website!
            if ($key === 5) {
                return;
            }

            if ($user = User::whereUsername($username)->first()) {
                if (optional($notifiableUser)->id === $user->id) {
                    continue;
                }

                $user->notify(new UsernameMentioned(Auth::user(), $submission));
            }
        }
    }
}

Fix "Trying to get property of non-object" when mentioning at your own submission


<?php

/*
 * This file is part of the DataGridBundle.
 *
 * (c) Stanislav Turza <sorien@mail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Sorien\DataGridBundle\Grid\Column;

use Sorien\DataGridBundle\Grid\Action\RowAction;

class ActionsColumn extends Column
{
    private $rowActions;

    public function __construct($column, $title, array $rowActions = array())
    {
        $this->rowActions = $rowActions;
        parent::__construct(array('id' => $column, 'title' => $title, 'sortable' => false, 'source' => false));
    }

    public function getRouteParameters($row, $action)
    {
        $actionParameters = $action->getRouteParameters();
        if(!empty($actionParameters)){
            $routeParameters = array();
            foreach ($actionParameters as $name => $parameter) {
                if(is_numeric($name)){
                    $routeParameters[$parameter] = $row->getField($parameter);
                } else {
                    $routeParameters[$name] = $parameter;
                }
            }
            return $routeParameters;
        }

        $routeParameters = array_merge(
            array($row->getPrimaryField() => $row->getPrimaryFieldValue()),
            $action->getRouteParameters()
        );

        return $routeParameters;
    }

    public function getRowActions()
    {
        return $this->rowActions;
    }

    public function setRowActions(array $rowActions) {
        $this->rowActions = $rowActions;
    }

    public function getType()
    {
        return 'actions';
    }
}

<?php

/*
 * This file is part of the DataGridBundle.
 *
 * (c) Stanislav Turza <sorien@mail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Sorien\DataGridBundle\Grid\Column;

use Sorien\DataGridBundle\Grid\Action\RowAction;

class ActionsColumn extends Column
{
    private $rowActions;

    public function __construct($column, $title, array $rowActions = array())
    {
        $this->rowActions = $rowActions;
        parent::__construct(array('id' => $column, 'title' => $title, 'sortable' => false, 'source' => false));
    }

    public function getRouteParameters($row, $action)
    {
        $actionParameters = $action->getRouteParameters();
        if(!empty($actionParameters)){
            $routeParameters = array();
            foreach ($actionParameters as $name => $parameter) {
                if(is_numeric($name)){
                    $routeParameters[$parameter] = $row->getField($parameter);
                } else {
                    $routeParameters[$name] = $parameter;
                }
            }
        }

        return array_merge(
            array($row->getPrimaryField() => $row->getPrimaryFieldValue()),
            $routeParameters
        );
    }

    public function getRowActions()
    {
        return $this->rowActions;
    }

    public function setRowActions(array $rowActions) {
        $this->rowActions = $rowActions;
    }

    public function getType()
    {
        return 'actions';
    }
}

Fix route parameters for a row action

Fix route parameters for a row action


<?php

/**
 * CheckoutApi_Client_Constant
 * A final class that manage constant value for all CheckoutApi_Client_Client instance
 * @package     CheckoutApi_Client
 * @category     Api
 * @author       Dhiraj Gangoosirdar <dhiraj.gangoosirdar@checkout.com>
 * @copyright 2014 Integration team (http://www.checkout.com)
 */
final class CheckoutApi_Client_Constant
{
	const APIGW3_URI_PREFIX_PREPOD = 'http://preprod.checkout.com/api2/';
	const APIGW3_URI_PREFIX_DEV= 'http://dev.checkout.com/api2/';
	const APIGW3_URI_PREFIX_SANDBOX= 'http://sandbox.checkout.com/api2/';
	const APIGW3_URI_PREFIX_LIVE = 'https://api2.checkout.com/';
	const ADAPTER_CLASS_GROUP = 'CheckoutApi_Client_Adapter_';
	const PARSER_CLASS_GROUP = 'CheckoutApi_Parser_';
	const CHARGE_TYPE = 'card';
	const LOCALPAYMENT_CHARGE_TYPE = 'localPayment';
	const TOKEN_CARD_TYPE = 'cardToken';
	const TOKEN_SESSION_TYPE = 'sessionToken';
	const AUTOCAPUTURE_CAPTURE = 'y';
	const AUTOCAPUTURE_AUTH = 'n';
	const VERSION = 'v2';
    const STATUS_CAPTURE = 'Captured';
    const LIB_VERSION = 'v1.2.5';

}

<?php

/**
 * CheckoutApi_Client_Constant
 * A final class that manage constant value for all CheckoutApi_Client_Client instance
 * @package     CheckoutApi_Client
 * @category     Api
 * @author       Dhiraj Gangoosirdar <dhiraj.gangoosirdar@checkout.com>
 * @copyright 2014 Integration team (http://www.checkout.com)
 */
final class CheckoutApi_Client_Constant
{
	const APIGW3_URI_PREFIX_PREPOD = 'http://preprod.checkout.com/api2/';
	const APIGW3_URI_PREFIX_DEV= 'http://dev.checkout.com/api2/';
	const APIGW3_URI_PREFIX_SANDBOX= 'http://sandbox.checkout.com/api2/';
	const APIGW3_URI_PREFIX_LIVE = 'https://api2.checkout.com/';
	const ADAPTER_CLASS_GROUP = 'CheckoutApi_Client_Adapter_';
	const PARSER_CLASS_GROUP = 'CheckoutApi_Parser_';
	const CHARGE_TYPE = 'card';
	const LOCALPAYMENT_CHARGE_TYPE = 'localPayment';
	const TOKEN_CARD_TYPE = 'cardToken';
	const TOKEN_SESSION_TYPE = 'sessionToken';
	const AUTOCAPUTURE_CAPTURE = 'y';
	const AUTOCAPUTURE_AUTH = 'n';
	const VERSION = 'v2';
    const STATUS_CAPTURE = 'Captured';
    const LIB_VERSION = 'v1.2.4';

}

Revert "Update version inside constant.php"

This reverts commit ad751383f50b96b48a915e1d022c912f1114d166.


<?php

namespace Bolt\Extension;

use Silex\Application;

/**
 * Management class for extensions.
 *
 * @author Gawain Lynch <gawain.lynch@gmail.com>
 */
class Manager
{
    /** @var Application */
    private $app;

    /**
     * Constructor.
     *
     * @param Application $app
     */
    public function __construct(Application $app)
    {
        $this->app = $app;
    }
}

<?php

namespace Bolt\Extension;

use Silex\Application;

/**
 * Management class for extensions.
 *
 * @author Gawain Lynch <gawain.lynch@gmail.com>
 */
class Manager
{
    /** @var \Bolt\Composer\ExtensionAutoloader */
    protected $autoloader;
    /** @var ExtensionInterface[] */
    protected $extensions;

    /** @var Application */
    private $app;

    /**
     * Constructor.
     *
     * @param Application $app
     */
    public function __construct(Application $app)
    {
        $this->app = $app;
        $this->autoloader = $app['extensions.autoload'];
    }

    /**
     * Load and fetch the extension classes.
     */
    public function load()
    {
        $this->extensions = $this->autoloader->load();
    }
}

Load and fetch the extension classes

Load and fetch the extension classes


<?php

namespace Romans\Filter;

use Romans\Grammar\Grammar;
use Romans\Grammar\GrammarAwareTrait;

/**
 * Int to Roman
 */
class IntToRoman
{
    use GrammarAwareTrait;

    /**
     * Default Constructor
     *
     * @param Grammar $grammar Grammar Object
     */
    public function __construct(Grammar $grammar = null)
    {
        if (! isset($grammar)) {
            $grammar = new Grammar();
        }

        $this->setGrammar($grammar);
    }

    /**
     * Filter Integer to Roman Number
     *
     * @param  int    Integer
     * @return string Roman Number Result
     */
    public function filter(int $value) : string
    {
        if ($value < 0) {
            throw new Exception(sprintf('Invalid integer: %d', $value), Exception::INVALID_INTEGER);
        }

        $tokens = $this->getGrammar()->getTokens();
        $values = array_reverse($this->getGrammar()->getValues());

        if ($value === 0) {
            $token = array_search(0, $values);

            return $tokens[$token];
        }

        $result = '';

        foreach ($values as $token => $current) {
            while ($current > 0 && $value >= $current) {
                $value  = $value - $current;
                $result = $result . $tokens[$token];
            }
        }

        return $result;
    }
}

<?php

namespace Romans\Filter;

use Romans\Grammar\Grammar;
use Romans\Grammar\GrammarAwareTrait;

/**
 * Int to Roman
 */
class IntToRoman
{
    use GrammarAwareTrait;

    /**
     * Default Constructor
     *
     * @param Grammar $grammar Grammar Object
     */
    public function __construct(Grammar $grammar = null)
    {
        if (! isset($grammar)) {
            $grammar = new Grammar();
        }

        $this->setGrammar($grammar);
    }

    /**
     * Filter Integer to Roman Number
     *
     * @param  int    Integer
     * @return string Roman Number Result
     */
    public function filter(int $value) : string
    {
        if ($value < 0) {
            throw new Exception(sprintf('Invalid integer: %d', $value), Exception::INVALID_INTEGER);
        }

        $tokens = $this->getGrammar()->getTokens();
        $values = array_reverse($this->getGrammar()->getValuesWithModifiers(), true /* preserve keys */);
        $result = '';

        if ($value === 0) {
            $dataset = $values[0];

            foreach ($dataset as $token) {
                $result = $result . $tokens[$token];
            }

            return $result;
        }

        foreach ($values as $current => $dataset) {
            while ($current > 0 && $value >= $current) {
                $value = $value - $current;
                foreach ($dataset as $token) {
                    $result = $result . $tokens[$token];
                }
            }
        }

        return $result;
    }
}

Update filter to use Grammar modifiers

Update filter to use Grammar modifiers


<?php

namespace AppendedArrayItem;

// inferred from literal array
$integers = [1, 2, 3];
$integers[] = 4;
$integers['foo'] = 5;

$integers[] = 'foo';
$integers['bar'] = 'baz';

class Foo
{

	/**
	 * @param int[] $integers
	 * @param callable[] $callables
	 */
	public function doFoo(
		array $integers,
		array $callables
	)
	{
		$integers[] = 4;
		$integers['foo'] = 5;

		$integers[] = 'foo';
		$integers['bar'] = 'baz'; // already mixed[] here

		$callables[] = [$this, 'doFoo'];
		$callables[] = [1, 2, 3];

		/** @var callable[] $otherCallables */
		$otherCallables = $callables;
		$otherCallables[] = ['Foo', 'doFoo'];

		/** @var callable[] $anotherCallables */
		$anotherCallables = $callables;
		$anotherCallables[] = 'doFoo';
	}

}

<?php

namespace AppendedArrayItem;

// inferred from literal array
$integers = [1, 2, 3];
$integers[] = 4;
$integers['foo'] = 5;

$integers[] = 'foo';
$integers['bar'] = 'baz';

class Foo
{

	/**
	 * @param int[] $integers
	 * @param callable[] $callables
	 */
	public function doFoo(
		array $integers,
		array $callables
	)
	{
		$integers[] = 4;
		$integers['foo'] = 5;

		$integers[] = 'foo';
		$integers['bar'] = 'baz'; // already mixed[] here

		$callables[] = [$this, 'doFoo'];
		$callables[] = [1, 2, 3];

		/** @var callable[] $otherCallables */
		$otherCallables = $callables;
		$otherCallables[] = ['Foo', 'doFoo'];

		/** @var callable[] $anotherCallables */
		$anotherCallables = $callables;
		$anotherCallables[] = 'doFoo';

		/** @var callable[] $yetAnotherCallables */
		$yetAnotherCallables = $callables;
		$yetAnotherCallables[] = [__CLASS__, 'classMethod'];
	}

}

Test for possible array callable with a magic constant


<?php
App::uses('AppModel', 'Model');

/**
 * Product model
 */
class ProductSuggestion extends AppModel
{
	public $belongsTo = array(
		'Person',
		'Product'
	);
}

<?php
App::uses('AppModel', 'Model');

/**
 * Product model
 */
class ProductSuggestion extends AppModel
{
	public $belongsTo = array(
		'Person',
		'Product',
		'Recommender' => array(
			'className' => 'Person',
			'foreignKey' => 'recommender_id'
		)
	);
}

Define the recommender of a product.

Define the recommender of a product.


<?php

namespace Omnipay\SecureTrading\Test\Message;

use Omnipay\SecureTrading\Message\AbstractRequest;
use Omnipay\Tests\TestCase;

abstract class AbstractRequestTest extends TestCase
{
    /**
     * @var AbstractRequest
     */
    protected $request;

    protected function getTestAuthorizationData()
    {
        return array(
            'siteReference' => 'test-site-reference',
            'username'      => 'test-username',
            'password'      => 'test-password',
            'transactionId' => 'test-1234',
        );
    }

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

        $this->assertSame('test-username', (string)$data->alias);
        $this->assertSame('test-site-reference', (string)$data->request->operation->sitereference);
        $this->assertSame('test-1234', (string)$data->request->merchant->orderreference);
        $this->assertSame('test-password', $this->request->getPassword());
    }
}

<?php

namespace Omnipay\SecureTrading\Test\Message;

use Omnipay\SecureTrading\Message\AbstractRequest;
use Omnipay\Tests\TestCase;

abstract class AbstractRequestTest extends TestCase
{
    /**
     * @var AbstractRequest
     */
    protected $request;

    protected function getTestAuthorizationData()
    {
        return array(
            'siteReference' => 'test-site-reference',
            'username'      => 'test-username',
            'password'      => 'test-password',
            'transactionId' => 'test-1234',
            'accountType'   => 'ECOM',
        );
    }

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

        $this->assertSame('test-username', (string)$data->alias);
        $this->assertSame('test-site-reference', (string)$data->request->operation->sitereference);
        $this->assertSame('test-1234', (string)$data->request->merchant->orderreference);
        $this->assertSame('test-password', $this->request->getPassword());
        $this->assertSame('ECOM', $this->request->getAccountType());
    }
}

Add Abstract Request tests for Account Type


<?php

namespace Phug\Test\Profiler;

use PHPUnit\Framework\TestCase;
use Phug\Renderer\Profiler\EventList;

/**
 * @coversDefaultClass \Phug\Renderer\Profiler\EventList
 */
class EventListTest extends TestCase
{
    /**
     * @covers ::<public>
     */
    public function testLock()
    {
        $list = new EventList();

        self::assertFalse($list->isLocked());
        self::assertSame($list, $list->lock());
        self::assertTrue($list->isLocked());
        self::assertSame($list, $list->unlock());
        self::assertFalse($list->isLocked());
    }
}

<?php

namespace Phug\Test\Profiler;

use PHPUnit\Framework\TestCase;
use Phug\Renderer\Profiler\EventList;

/**
 * @coversDefaultClass \Phug\Renderer\Profiler\EventList
 */
class EventListTest extends TestCase
{
    /**
     * @covers ::<public>
     */
    public function testLock()
    {
        $list = new EventList();

        self::assertFalse($list->isLocked());
        self::assertSame($list, $list->lock());
        self::assertTrue($list->isLocked());
        self::assertSame($list, $list->unlock());
        self::assertFalse($list->isLocked());
    }

    /**
     * @covers ::<public>
     */
    public function testReset()
    {
        $list = new EventList();
        $list[] = 5;
        $list[] = 'foo';

        self::assertSame(2, count($list));
        self::assertSame('foo', $list[1]);

        $list->reset();

        self::assertSame(0, count($list));
        self::assertFalse(isset($list[1]));

        $list->lock();

        self::assertTrue($list->isLocked());

        $list->reset();

        self::assertFalse($list->isLocked());
    }
}

Add test for the method EventLists::reset


<?php

require_once 'Swat/SwatCellRenderer.php';

/**
 * A text cell renderer
 *
 * @package   Swat
 * @copyright 2004-2005 silverorange
 * @license   http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
 */
class SwatTextCellRenderer extends SwatCellRenderer
{
	/**
	 * Cell value
	 *
	 * The textual content to place within this cell.
	 *
	 * @var string
	 */
	public $value = '';

	/**
	 * Renders the contents of this cell
	 *
	 * @see swatcellrenderer::render()
	 */
	public function render()
	{
		echo $this->value;
	}
}

?>

<?php

require_once 'Swat/SwatCellRenderer.php';

/**
 * A text cell renderer
 *
 * @package   Swat
 * @copyright 2004-2005 silverorange
 * @license   http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
 */
class SwatTextCellRenderer extends SwatCellRenderer
{
	/**
	 * Cell content
	 *
	 * The textual content to place within this cell.
	 *
	 * @var string
	 */
	public $text = '';

	/**
	 * A value to substitute into the text of this cell
	 *
	 * The value is substituted using a call to printf. For example, if the
	 * {@link SwatCellRendererText::$text} property is set to 'My %s example'
	 * and the value property is set to 'awesome' the cell renderer will render
	 * as 'My aswesome example'.
	 *
	 * @var string
	 */
	public $value = null;

	/**
	 * Renders the contents of this cell
	 *
	 * @see swatcellrenderer::render()
	 */
	public function render()
	{
		if ($this->value === null)
			echo $this->text;
		else
			printf($this->text, $this->value);
	}
}

?>

Make it possible to do text substitution with this renderer.

svn commit r2278


<?php

namespace Auth0\Login;

use Session;
use Auth0\SDK\Store\StoreInterface;

class LaravelSessionStore implements StoreInterface
{
    const BASE_NAME = 'auth0_';

    /**
     * Persists $value on $_SESSION, identified by $key.
     *
     * @see Auth0SDK\BaseAuth0
     *
     * @param string $key
     * @param mixed  $value
     */
    public function set($key, $value)
    {
        $key_name = $this->getSessionKeyName($key);
        Session::put($key_name, $value);
        Session::save();
    }

    /**
     * @param $key
     * @param null $default
     *
     * @return mixed
     */
    public function get($key, $default = null)
    {
        $key_name = $this->getSessionKeyName($key);

        return Session::get($key_name, $default);
    }

    /**
     * Removes a persisted value identified by $key.
     *
     * @see Auth0SDK\BaseAuth0
     *
     * @param string $key
     */
    public function delete($key)
    {
        $key_name = $this->getSessionKeyName($key);

        Session::forget($key_name);
    }

    /**
     * Constructs a session var name.
     *
     * @param string $key
     *
     * @return string
     */
    public function getSessionKeyName($key)
    {
        return self::BASE_NAME.'_'.$key;
    }
}

<?php

namespace Auth0\Login;

use Session;
use Auth0\SDK\Store\StoreInterface;

class LaravelSessionStore implements StoreInterface
{
    const BASE_NAME = 'auth0_';

    /**
     * Persists $value on $_SESSION, identified by $key.
     *
     * @see Auth0SDK\BaseAuth0
     *
     * @param string $key
     * @param mixed  $value
     */
    public function set($key, $value)
    {
        $key_name = $this->getSessionKeyName($key);
        Session::put($key_name, $value);

        // The Auth0 SDK might decide to redirect and exit the PHP execution
        // before the Laravel middleware can write the changes.
        // thus we have to persist our changes early
        Session::save();
    }

    /**
     * @param $key
     * @param null $default
     *
     * @return mixed
     */
    public function get($key, $default = null)
    {
        $key_name = $this->getSessionKeyName($key);

        return Session::get($key_name, $default);
    }

    /**
     * Removes a persisted value identified by $key.
     *
     * @see Auth0SDK\BaseAuth0
     *
     * @param string $key
     */
    public function delete($key)
    {
        $key_name = $this->getSessionKeyName($key);

        Session::forget($key_name);
    }

    /**
     * Constructs a session var name.
     *
     * @param string $key
     *
     * @return string
     */
    public function getSessionKeyName($key)
    {
        return self::BASE_NAME.'_'.$key;
    }
}

Add comment why we are manually saving the session


<?php

namespace App\Http\Middleware;

use Illuminate\Http\Request;
use Fideloper\Proxy\TrustProxies as Middleware;

class TrustProxies extends Middleware
{
    /**
     * The trusted proxies for this application.
     *
     * @var array
     */
    protected $proxies = '*';

    /**
     * The headers that should be used to detect proxies.
     *
     * @var string
     */
    protected $headers = Request::HEADER_X_FORWARDED_ALL;
}

<?php

namespace App\Http\Middleware;

use Illuminate\Http\Request;
use Fideloper\Proxy\TrustProxies as Middleware;

class TrustProxies extends Middleware
{
    /**
     * The trusted proxies for this application.
     *
     * @var array
     */
    protected $proxies = '*';

    /**
     * The headers that should be used to detect proxies.
     *
     * @var string
     */
    protected $headers = Request::HEADER_X_FORWARDED_AWS_ELB;
}

Update header for proxy midleware

Update header for proxy midleware [WEB-889]


<?php

require_once(__DIR__ . '/../GitHubObject.php');

class GitHubBranch extends GitHubObject
{
	/* (non-PHPdoc)
	 * @see GitHubObject::getAttributes()
	 */
	protected function getAttributes()
	{
		return array_merge(parent::getAttributes(), array(
		));
	}

}

<?php

require_once(__DIR__ . '/../GitHubObject.php');

class GitHubBranch extends GitHubObject
{
	/* (non-PHPdoc)
	 * @see GitHubObject::getAttributes()
	 */
	protected function getAttributes()
	{
		return array_merge(parent::getAttributes(), array(
			'name' => 'string'
		));
	}

	/**
	 * @var string
	 */
	protected $name;

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

Add name accessor for Branch object

Add name accessor for Branch object


<?php

namespace Knplabs\MenuBundle\Twig;

use Knplabs\MenuBundle\Templating\Helper\MenuHelper;

class MenuExtension extends \Twig_Extension
{
    /**
     * @var MenuHelper
     */
    protected $provider;

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

    /**
     * @return array
     */
    public function getFunctions()
    {
        return array(
            'menu' => new \Twig_Function_Method($this, 'render', array(
                'is_safe' => array('html'),
            )),
            'menu_get' => new \Twig_Function_Method($this, 'get', array(
                'is_safe' => array('html'),
            )),
        );
    }

    /**
     * @param string $name
     * @return \Knplabs\MenuBundle\Menu
     * @throws \InvalidArgumentException
     */
    public function get($name)
    {
        return $this->helper->get($name);
    }

    /**
     * @param string $name
     * @param integer $depth (optional)
     * @return string
     */
    public function render($name, $path = null, $depth = null, $template = null)
    {
        return $this->helper->render($name, $path, $depth, $template);
    }

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

<?php

namespace Knplabs\MenuBundle\Twig;

use Knplabs\MenuBundle\Templating\Helper\MenuHelper;

class MenuExtension extends \Twig_Extension
{
    /**
     * @var MenuHelper
     */
    protected $helper;

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

    /**
     * @return array
     */
    public function getFunctions()
    {
        return array(
            'menu' => new \Twig_Function_Method($this, 'render', array(
                'is_safe' => array('html'),
            )),
            'menu_get' => new \Twig_Function_Method($this, 'get', array(
                'is_safe' => array('html'),
            )),
        );
    }

    /**
     * @param string $name
     * @return \Knplabs\MenuBundle\Menu
     * @throws \InvalidArgumentException
     */
    public function get($name)
    {
        return $this->helper->get($name);
    }

    /**
     * @param string $name
     * @param integer $depth (optional)
     * @return string
     */
    public function render($name, $path = null, $depth = null, $template = null)
    {
        return $this->helper->render($name, $path, $depth, $template);
    }

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

Fix property name in twig extension

Fix property name in twig extension


<?= $this->get('game')->name; ?>
<a href="<?= $this->get('edit-link'); ?>">Edit

    Created at: <?= $this->get('game')->created; ?>

    Last modified: <?= $this->get('game')->updated; ?>

Fix edit link outside the header

Fix edit link outside the header


<?php

namespace Http;

interface Request
{
    public function getParameter($key, $defaultValue = null);
    public function getFile($key, $defaultValue = null);
    public function getCookie($key, $defaultValue = null);
    public function getParameters();
    public function getCookies();
    public function getFiles();
    public function getMethod();
    public function getHttpAccept();
    public function getReferer();
    public function getUserAgent();
    public function getIpAddress();
    public function isSecure();
    public function getQueryString();
}

<?php

namespace Http;

interface Request
{
    public function getParameter($key, $defaultValue = null);
    public function getFile($key, $defaultValue = null);
    public function getCookie($key, $defaultValue = null);
    public function getParameters();
    public function getCookies();
    public function getFiles();
    public function getUri();
    public function getPath();
    public function getMethod();
    public function getHttpAccept();
    public function getReferer();
    public function getUserAgent();
    public function getIpAddress();
    public function isSecure();
    public function getQueryString();
}

Add getPath(), getUri() in the request intereface


<?php

namespace Thumbor;

class UrlTest extends \PHPUnit_Framework_TestCase
{
    public function testSign()
    {
        $this->assertEquals(
            'bDv76lTvUdX6vORS96scx7P185c=',
            Url::sign(
                'fit-in/560x420/filters:fill(green)/my/big/image.jpg',
                'MY_SECURE_KEY'
            )
        );
    }

    public function testToString()
    {
        $url = new Url(
            'my/big/image.jpg',
            array('fit-in', '560x420', 'filters:fill(green)'),
            'http://thumbor-server:8888',
            'MY_SECURE_KEY'
        );

        $this->assertEquals(
            'http://thumbor-server:8888/bDv76lTvUdX6vORS96scx7P185c=/fit-in/560x420/filters:fill(green)/my%2Fbig%2Fimage.jpg',
            "$url"
        );
    }
}

<?php

namespace Thumbor;

class UrlTest extends \PHPUnit_Framework_TestCase
{
    public function testSign()
    {
        $this->assertEquals(
            '-qITCsYPvj2Lt0ivIX1eXHhGFOM=',
            Url::sign(
                'fit-in/560x420/filters:fill(green)/my%2Fbig%2Fimage.jpg',
                'MY_SECURE_KEY'
            )
        );
    }

    public function testToString()
    {
        $url = new Url(
            'my/big/image.jpg',
            array('fit-in', '560x420', 'filters:fill(green)'),
            'http://thumbor-server:8888',
            'MY_SECURE_KEY'
        );

        $this->assertEquals(
            'http://thumbor-server:8888/-qITCsYPvj2Lt0ivIX1eXHhGFOM=/fit-in/560x420/filters:fill(green)/my%2Fbig%2Fimage.jpg',
            "$url"
        );
    }
}

Update tests to reflect c03ba5c

Update tests to reflect c03ba5c


<?php
namespace wcf\system\page\handler;

/**
 * Menu page handler for the user profile page.
 *
 * @author	Matthias Schmidt
 * @copyright	2001-2016 WoltLab GmbH
 * @license	GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package	WoltLabSuite\Core\System\Page\Handler
 * @since	3.0
 */
class UserPageHandler extends AbstractMenuPageHandler implements IOnlineLocationPageHandler {
	use TUserOnlineLocationPageHandler;
}

<?php
namespace wcf\system\page\handler;
use wcf\system\cache\runtime\UserRuntimeCache;

/**
 * Menu page handler for the user profile page.
 *
 * @author	Matthias Schmidt
 * @copyright	2001-2016 WoltLab GmbH
 * @license	GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package	WoltLabSuite\Core\System\Page\Handler
 * @since	3.0
 */
class UserPageHandler extends AbstractLookupPageHandler implements IOnlineLocationPageHandler {
	use TUserOnlineLocationPageHandler;
	use TUserLookupPageHandler;

	/**
	 * @inheritDoc
	 */
	public function getLink($objectID) {
		return UserRuntimeCache::getInstance()->getObject($objectID)->getLink();
	}
}

Add lookup support for user profile page


<?php

class EngineBlock_Test_Saml2_AuthnRequestAnnotationDecoratorTest extends PHPUnit_Framework_TestCase
{
    public function testToString()
    {
        $request = new SAML2_AuthnRequest();
        $request->setId('TEST123');
        $request->setIssueInstant(0);

        $annotatedRequest = new EngineBlock_Saml2_AuthnRequestAnnotationDecorator($request);
        $annotatedRequest->setDebug();

        $this->assertEquals(
            '{'.
                '"sspMessage":"<?xml version=\"1.0\"?>\n'.
                    '<samlp:AuthnRequest xmlns:samlp=\"urn:oasis:names:tc:SAML:2.0:protocol\" '.
                                        'xmlns:saml=\"urn:oasis:names:tc:SAML:2.0:assertion\" '.
                                        'ID=\"TEST123\" '.
                                        'Version=\"2.0\" '.
                                        'IssueInstant=\"1970-01-01T00:00:00Z\"\/>\n",'.
                '"keyId":null,'.
                '"wasSigned":false,'.
                '"debug":true,'.
                '"unsolicited":false,'.
                '"transparent":false,'.
                '"deliverByBinding":null'.
            '}',
            $annotatedRequest->__toString()
        );
    }
}

<?php

class EngineBlock_Test_Saml2_AuthnRequestAnnotationDecoratorTest extends PHPUnit_Framework_TestCase
{
    public function testToString()
    {
        $request = new SAML2_AuthnRequest();
        $request->setId('TEST123');
        $request->setIssueInstant(0);

        $annotatedRequest = new EngineBlock_Saml2_AuthnRequestAnnotationDecorator($request);
        $annotatedRequest->setDebug();

        $this->assertEquals(
            '{"sspMessage":"<?xml version=\"1.0\"?>\n<samlp:AuthnRequest xmlns:samlp=\"urn:oasis:names:tc:SAML:2.0:protocol\" xmlns:saml=\"urn:oasis:names:tc:SAML:2.0:assertion\" ID=\"TEST123\" Version=\"2.0\" IssueInstant=\"1970-01-01T00:00:00Z\"\/>\n","voContext":null,"keyId":null,"explicitVoContext":true,"wasSigned":false,"debug":true,"unsolicited":false,"transparent":false,"deliverByBinding":null}',
            $annotatedRequest->__toString()
        );
    }
}

Revert "Fixed broken test and improved indentation of test."

This reverts commit b559c557c5f64c7df4a5e9d20759f3e09e8d3974.


<?php

function checkVersion() {
	$current = explode("-", file_get_contents("version"));
	$latest = explode("-", file_get_contents("https://raw.github.com/VeoPVM/LinMon/master/slave/version"));

	if ($current[0] != $latest[0]) {
		$current = $current[1];
		$latest = $latest[1];
		return "A new version of the slave is available!
		Your version: ".$current."
		Latest version: ".$latest." \n";
	}
}

?>

<?php

function checkVersion() {
	$current = explode("-", file_get_contents("version"));
	$latest = explode("-", file_get_contents("https://raw.github.com/VeoPVM/LinMon/master/slave/version"));

	if ($current[0] != $latest[0]) {
		$current = $current[1];
		$latest = $latest[1];
		return "A new version of the slave is available! \n Your version: ".$current." \n Latest version: ".$latest." \n";
	}
}

?>

Correct line spacing in update checker

Correct line spacing in update checker


<?php

return array(

    /*
    |--------------------------------------------------------------------------
    | Database Connections
    |--------------------------------------------------------------------------
    |
    | Here are each of the database connections setup for your application.
    | Of course, examples of configuring each database platform that is
    | supported by Laravel is shown below to make development simple.
    |
    |
    | All database work in Laravel is done through the PHP PDO facilities
    | so make sure you have the driver for your particular database of
    | choice installed on your machine before you begin development.
    |
    */
	'default' => $_ENV["DATABASE_TYPE"],

    'connections' => array(

        'mysql' => array(
            'driver'    => 'mysql',
            'host'      => 'localhost',
            'database'  => $_ENV['DATABASE_NAME'],
            'username'  => $_ENV['DATABASE_USER'],
            'password'  => $_ENV['DATABASE_PASSWORD'],
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
        ),

        'pgsql' => array(
            'driver'   => 'pgsql',
            'host'     => 'localhost',
            'database' => 'homestead',
            'username' => 'homestead',
            'password' => 'secret',
            'charset'  => 'utf8',
            'prefix'   => '',
            'schema'   => 'public',
        ),

    ),

);

<?php

return array(

    /*
    |--------------------------------------------------------------------------
    | Database Connections
    |--------------------------------------------------------------------------
    |
    | Here are each of the database connections setup for your application.
    | Of course, examples of configuring each database platform that is
    | supported by Laravel is shown below to make development simple.
    |
    |
    | All database work in Laravel is done through the PHP PDO facilities
    | so make sure you have the driver for your particular database of
    | choice installed on your machine before you begin development.
    |
    */
    'default' => array_get($_ENV, "DATABASE_TYPE", "sqlite"),

    'connections' => array(

        'mysql' => array(
            'driver'    => 'mysql',
            'host'      => 'localhost',
            'database'  => array_get($_ENV, "DATABASE_NAME"),
            'username'  => array_get($_ENV, "DATABASE_USER"),
            'password'  => array_get($_ENV, "DATABASE_PASS"),
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
        ),

        'pgsql' => array(
            'driver'   => 'pgsql',
            'host'     => 'localhost',
            'database' => 'homestead',
            'username' => 'homestead',
            'password' => 'secret',
            'charset'  => 'utf8',
            'prefix'   => '',
            'schema'   => 'public',
        ),

    ),

);

Use array_get to prevent undefined index warnings


<?php

namespace Listabierta\Bundle\MunicipalesBundle\Form\Type;

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

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

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
    }

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

<?php

namespace Listabierta\Bundle\MunicipalesBundle\Form\Type;

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

class CandidateStep3Type extends AbstractType
{
	public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('academic_level', 'choice', array(
			     	'choices' => array(
			     			'1' => 'Sin estudios',
			     			'2' => 'Estudios primarios o equivalentes',
			     			'3' => 'Enseñanza general secundaria, 1er ciclo',
			     			'4' => 'Enseñanza Profesional de 2º grado, 2º ciclo',
			     			'5' => 'Enseñanza general secundaria, 2º ciclo',
			     			'6' => 'Enseñanzas profesionales superiores',
			     			'7' => 'Estudios universitarios o equivalentes',
			     			'8' => 'Máster universitario o doctorado',
			     	),
			     ))
			     ->add('languages', 'choice', array(
			     		'multiple' => TRUE,
			     		'expanded' => TRUE,
			     		'choices' => array(
			     				'1' => 'Inglés',
			     				'2' => 'Francés',
			     				'3' => 'Alemán',
			     				'4' => 'Italiano',
			     				'5' => 'Chino',
			     				'6' => 'Árabe',
			     				'7' => 'Otro',
			     		),
			     ))
	            ->add('continue', 'submit', array('attr' => array('class' => 'submit')));
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
    }

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

Add academic level and language questions to step 3 form


<?php

// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
// See the LICENCE file in the repository root for full licence text.

namespace App\Transformers\Multiplayer;

use App\Models\Multiplayer\PlaylistItem;
use App\Transformers\BeatmapCompactTransformer;
use App\Transformers\TransformerAbstract;

class PlaylistItemTransformer extends TransformerAbstract
{
    protected $availableIncludes = [
        'beatmap',
    ];

    public function transform(PlaylistItem $item)
    {
        return [
            'id' => $item->id,
            'room_id' => $item->room_id,
            'beatmap_id' => $item->beatmap_id,
            'ruleset_id' => $item->ruleset_id,
            'allowed_mods' => $item->allowed_mods,
            'required_mods' => $item->required_mods,
            'expired' => $item->expired,
        ];
    }

    public function includeBeatmap(PlaylistItem $item)
    {
        return $this->item(
            $item->beatmap,
            new BeatmapCompactTransformer()
        );
    }
}

<?php

// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
// See the LICENCE file in the repository root for full licence text.

namespace App\Transformers\Multiplayer;

use App\Models\Multiplayer\PlaylistItem;
use App\Transformers\BeatmapCompactTransformer;
use App\Transformers\TransformerAbstract;

class PlaylistItemTransformer extends TransformerAbstract
{
    protected $availableIncludes = [
        'beatmap',
    ];

    public function transform(PlaylistItem $item)
    {
        return [
            'id' => $item->id,
            'room_id' => $item->room_id,
            'beatmap_id' => $item->beatmap_id,
            'ruleset_id' => $item->ruleset_id,
            'allowed_mods' => $item->allowed_mods,
            'required_mods' => $item->required_mods,
            'expired' => $item->expired,
            'user_id' => $item->user_id,
        ];
    }

    public function includeBeatmap(PlaylistItem $item)
    {
        return $this->item(
            $item->beatmap,
            new BeatmapCompactTransformer()
        );
    }
}

Add user_id to playlist item transformer


<?php

namespace Orbt\ResourceMirror\Tests\Resource;

use Orbt\ResourceMirror\Resource\GenericResource;

class GenericResourceTest extends \PHPUnit_Framework_TestCase
{
    /**
     * A generic resource can be instantiated.
     */
    public function testCreate()
    {
        $resource = new GenericResource('test');
        $this->assertInstanceOf('Orbt\ResourceMirror\Resource\GenericResource', $resource);
    }

    /**
     * A generic resource returns the resource path.
     *
     * @depends testCreate
     */
    public function testGetPath()
    {
        $resource = new GenericResource('test');
        $this->assertEquals('test', $resource->getPath());
    }
}

<?php

namespace Orbt\ResourceMirror\Tests\Resource;

use Orbt\ResourceMirror\Resource\GenericResource;

class GenericResourceTest extends \PHPUnit_Framework_TestCase
{
    /**
     * A generic resource can be instantiated.
     */
    public function testCreate()
    {
        $resource = new GenericResource('test');
        $this->assertInstanceOf('Orbt\ResourceMirror\Resource\GenericResource', $resource);
    }

    /**
     * A generic resource is not created for an empty path.
     *
     * @expectedException \InvalidArgumentException
     */
    public function testCreateEmptyPath()
    {
        new GenericResource('');
    }

    /**
     * A generic resource is not created for an absolute path.
     *
     * @expectedException \InvalidArgumentException
     */
    public function testCreateAbsolutePath()
    {
        new GenericResource('/path');
    }

    /**
     * A generic resource is not created for denormalized path.
     *
     * @expectedException \InvalidArgumentException
     */
    public function testCreateDenormalizedPath()
    {
        new GenericResource('a/../b');
    }

    /**
     * A generic resource returns the resource path.
     *
     * @depends testCreate
     */
    public function testGetPath()
    {
        $resource = new GenericResource('test');
        $this->assertEquals('test', $resource->getPath());
    }
}

Test path exception for generic resource.


<?php namespace App\Exceptions;

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

class Handler extends ExceptionHandler {

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

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

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

}

<?php namespace App\Exceptions;

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

class Handler extends ExceptionHandler {

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

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

	/**
	 * Render an exception into an HTTP response.
	 *
	 * @param  \Illuminate\Http\Request  $request
	 * @param  \Exception  $e
	 * @return \Illuminate\Http\Response
	 */
	public function render($request, Exception $e)
	{
    if (\App::environment() == 'testing') {
      throw $e;
    } else {
  		return parent::render($request, $e);
    }
	}

}

Throw exceptions properly when running tests


<?php

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

class AppKernel extends Kernel
{
    public function registerBundles()
    {
        $bundles = [
            new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
            new Symfony\Bundle\SecurityBundle\SecurityBundle(),
            new Symfony\Bundle\TwigBundle\TwigBundle(),
            new Symfony\Bundle\MonologBundle\MonologBundle(),
            new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
            new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
            new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
            new AppBundle\AppBundle(),
        ];

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

        return $bundles;
    }

    public function getRootDir()
    {
        return __DIR__;
    }

    public function getCacheDir()
    {
        return dirname(__DIR__).'/var/cache/'.$this->getEnvironment();
    }

    public function getLogDir()
    {
        return dirname(__DIR__).'/var/logs';
    }

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

<?php

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

class AppKernel extends Kernel
{
    public function registerBundles()
    {
        $bundles = [
            new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
            new Symfony\Bundle\SecurityBundle\SecurityBundle(),
            new Symfony\Bundle\TwigBundle\TwigBundle(),
            new Symfony\Bundle\MonologBundle\MonologBundle(),
            new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
            new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
            new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
            new AppBundle\AppBundle(),
            new TheGame\MapsBundle\TheGameMapsBundle(),
        ];

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

        return $bundles;
    }

    public function getRootDir()
    {
        return __DIR__;
    }

    public function getCacheDir()
    {
        return dirname(__DIR__).'/var/cache/'.$this->getEnvironment();
    }

    public function getLogDir()
    {
        return dirname(__DIR__).'/var/logs';
    }

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

Update to include the TheGame:MapBundle controller


<?php

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

class DropNetworthColumnFromDominionsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('dominions', function (Blueprint $table) {
            $table->dropColumn('networth');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('dominions', function (Blueprint $table) {
            $table->integer('networth')->default(0)->after('name');
        });
    }
}

<?php

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

class DropNetworthColumnFromDominionsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('dominions', function (Blueprint $table) {
            $table->dropColumn('networth');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('dominions', function (Blueprint $table) {
            $table->integer('networth')->nullable()->after('name');
        });
    }
}

Make networth rollback column nullable

Make networth rollback column nullable


<?php

namespace Paulboco\Powerball\Drawings;

class DrawingFacade
{
    /**
     * The file handler instance.
     *
     * @var Paulboco\Powerball\Drawings\FileHandler
     */
    private $handler;

    /**
     * The file handler instance.
     *
     * @var Paulboco\Powerball\Drawings\FileParser
     */
    private $parser;

    /**
     * Create a new drawings facade instance.
     *
     * @param  string|null  $url
     * @return void
     */
    public function __construct($url = null)
    {
        $this->handler = $this->getHandler($url);
        $this->parser = new FileParser;
    }

    /**
     * Get all drawings as an array of drawing objects.
     *
     * @return array
     */
    public function all()
    {
        $contents = $this->handler->getContents();

        return $this->parser->parse($contents);
    }

    /**
     * Get the content length of the winning numbers file.
     *
     * @return integer
     */
    public function length()
    {
        return $this->handler->getContentLength();
    }

    /**
     * Get a new file handler instance.
     *
     * @return Paulboco\Powerball\Drawings\FileHandler
     */
    private function getHandler($url)
    {
        return new FileHandler(new FileValidator, new FileSizer, $url);
    }
}

Add newline to end of file

Add newline to end of file


<?php

namespace App\Entity\Fixture;

use App\Entity;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\DependentFixtureInterface;
use Doctrine\Persistence\ObjectManager;

class ApiKey extends AbstractFixture implements DependentFixtureInterface
{
    public function load(ObjectManager $em): void
    {
        $demo_api_key = getenv('INIT_DEMO_API_KEY');

        if (!empty($demo_api_key) && $this->hasReference('demo_user')) {
            /** @var Entity\User $demo_user */
            $demo_user = $this->getReference('demo_user');

            $api_key = new Entity\ApiKey($demo_user, $demo_api_key);
            $api_key->setComment('Demo User');

            $em->persist($api_key);
        }

        $admin_api_key = getenv('INIT_ADMIN_API_KEY');

        if (!empty($admin_api_key) && $this->hasReference('admin_user')) {
            /** @var Entity\User $admin_user */
            $admin_user = $this->getReference('admin_user');

            $api_key = new Entity\ApiKey($admin_user, $admin_api_key);
            $api_key->setComment('Administrator');

            $em->persist($api_key);
        }

        $em->flush();
    }

    /**
     * @return string[]
     */
    public function getDependencies(): array
    {
        return [
            User::class,
        ];
    }
}

<?php

namespace App\Entity\Fixture;

use App\Entity;
use App\Security\SplitToken;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\DependentFixtureInterface;
use Doctrine\Persistence\ObjectManager;

class ApiKey extends AbstractFixture implements DependentFixtureInterface
{
    public function load(ObjectManager $em): void
    {
        $demo_api_key = getenv('INIT_DEMO_API_KEY');

        if (!empty($demo_api_key) && $this->hasReference('demo_user')) {
            /** @var Entity\User $demo_user */
            $demo_user = $this->getReference('demo_user');

            $api_key = new Entity\ApiKey($demo_user, SplitToken::fromKeyString($demo_api_key));
            $api_key->setComment('Demo User');

            $em->persist($api_key);
        }

        $admin_api_key = getenv('INIT_ADMIN_API_KEY');

        if (!empty($admin_api_key) && $this->hasReference('admin_user')) {
            /** @var Entity\User $admin_user */
            $admin_user = $this->getReference('admin_user');

            $api_key = new Entity\ApiKey($admin_user, SplitToken::fromKeyString($admin_api_key));
            $api_key->setComment('Administrator');

            $em->persist($api_key);
        }

        $em->flush();
    }

    /**
     * @return string[]
     */
    public function getDependencies(): array
    {
        return [
            User::class,
        ];
    }
}

Fix fixture loading with API keys.

Fix fixture loading with API keys.


<?php

use Elasticsearch\Client;

trait AdminSearch {

	public function getSearch($index = null) {

		if ($index) {

			$document = $this->search($index, "track", "song-database");

			View::share("index", $document["hits"]["hits"]);
		}

		$this->layout->content = View::make("admin.search");

	}

	// rebuild
	public function putSearch() {

		$load = DB::table("tracks")->get();

		try {
			foreach ($load as $track) {
				$this->index($track);
			}

			return;
		} catch (Exception $e) {
			return ["error" => $e->getTraceAsString(), "message" => $e->getMessage()];
		}
	}

	// wipe
	public function deleteSearch() {

		$this->client->indices()->delete(["index" => "song-database"]);
	}

	// query
	public function postSearch() {

	}
}

<?php

use Elasticsearch\Client;

trait AdminSearch {

	public function getSearch($index = null) {

		if ($index) {

			$document = $this->search($index, "track", "song-database");

			View::share("index", $document["hits"]["hits"]);
		}

		$this->layout->content = View::make("admin.search");

	}

	// rebuild
	public function putSearch() {

		$load = DB::table("tracks")->get();

		try {

			$this->deleteSearch();

			foreach ($load as $track) {
				$this->index($track);
			}

			return;
		} catch (Exception $e) {
			return ["error" => $e->getTraceAsString(), "message" => $e->getMessage()];
		}
	}

	// wipe
	public function deleteSearch() {

		$this->client->indices()->delete(["index" => "song-database"]);
	}

	// query
	public function postSearch() {

	}
}

Clear the song index before re-indexing the entire database