<?php
namespace Tenet\Filter;

use Tenet\FilterInterface;
use Tenet\Accessor;

class AssociationToOneFilter extends AbstractAssociationFilter implements FilterInterface
{
	public function convertToSetterValue(Accessor $accessor, $object, $field, $value)
	{
		$manager         = $accessor->getObjectManager();
		$objectMetadata  = $manager->getClassMetadata(get_class($object));
		$mappedField     = $objectMetadata->getAssociationMappedByTargetField($field);
		$mappedClass     = $objectMetadata->getAssociationTargetClass($field);
		$relatedObject   = $this->makeObject($accessor, $object, $field, $value);

		if ($relatedObject && ($mappedField != $field || $mappledClass != get_class($object))) {
			$accessor->set($relatedObject, $mappedField, $object);
		}

		return $relatedObject;
	}

	public function convertToGetterValue(Accessor $accessor, $object, $field, $value)
	{
		return $value;
	}
}

<?php
namespace Tenet\Filter;

use Tenet\FilterInterface;
use Tenet\Accessor;

class AssociationToOneFilter extends AbstractAssociationFilter implements FilterInterface
{
	public function convertToSetterValue(Accessor $accessor, $object, $field, $value)
	{
		$manager         = $accessor->getObjectManager();
		$objectMetadata  = $manager->getClassMetadata(get_class($object));
		$mappedField     = $objectMetadata->getAssociationMappedByTargetField($field);
		$mappedClass     = $objectMetadata->getAssociationTargetClass($field);
		$relatedObject   = $this->makeObject($accessor, $object, $field, $value);

		if ($relatedObject && $mappedField && ($mappedField != $field || $mappledClass != get_class($object))) {
			$accessor->set($relatedObject, $mappedField, $object);
		}

		return $relatedObject;
	}

	public function convertToGetterValue(Accessor $accessor, $object, $field, $value)
	{
		return $value;
	}
}

Fix when no mapped field is available

Fix when no mapped field is available


<?php

namespace Onyx\Overwatch\Helpers\Game;
/**
 * Class Character
 * @package Onyx\Overwatch\Helpers\Game
 */
class Character
{
    public static function getValidCharacter(string $char) : string
    {
        switch ($char)
        {
            case 'reinhardt':
            case 'rein':
                return 'reinhardt';

            case 'mcree':
                return 'mcree';

            case 'winston':
                return 'winston';

            case 'pharah':
                return 'pharah';

            case 'roadhog':
            case 'road':
                return 'roadhog';

            case 'zarya':
                return 'zarya';

            case 'torbjorn':
            case 'torb':
                return 'torbjorn';

            case 'ana':
                return 'ana';

            case 'genji':
                return 'genji';

            case 'symmetra':
            case 'sim':
            case 'sym':
                return 'symmetra';

            case 'dva':
                return 'dva';

            case 'lucio':
                return 'lucio';

            case 'zen':
            case 'zenyatta':
                return 'zenyatta';

            case 'junkrat':
            case 'junk':
                return 'junkrat';

            case 'hanzo':
                return 'hanzo';

            case 'mercy':
                return 'mercy';

            case 'repear':
                return 'repear';

            case 'soldier76':
            case '76':
                return 'soldier76';

            case 'osira':
                return 'osira';

            default:
                return 'unknown';
        }
    }
}

<?php

namespace Onyx\Overwatch\Helpers\Game;
/**
 * Class Character
 * @package Onyx\Overwatch\Helpers\Game
 */
class Character
{
    public static function getValidCharacter(string $char) : string
    {
        switch ($char)
        {
            case 'reinhardt':
            case 'rein':
                return 'reinhardt';

            case 'mcree':
                return 'mcree';

            case 'winston':
                return 'winston';

            case 'pharah':
                return 'pharah';

            case 'roadhog':
            case 'road':
                return 'roadhog';

            case 'zarya':
                return 'zarya';

            case 'torbjorn':
            case 'torb':
                return 'torbjorn';

            case 'ana':
                return 'ana';

            case 'genji':
                return 'genji';

            case 'symmetra':
            case 'sim':
            case 'sym':
                return 'symmetra';

            case 'dva':
                return 'dva';

            case 'lucio':
                return 'lucio';

            case 'zen':
            case 'zenyatta':
                return 'zenyatta';

            case 'junkrat':
            case 'junk':
                return 'junkrat';

            case 'hanzo':
                return 'hanzo';

            case 'mercy':
                return 'mercy';

            case 'reaper':
                return 'reaper';

            case 'soldier76':
            case '76':
                return 'soldier76';

            case 'osira':
                return 'osira';

            case 'sombra':
                return 'sombra';

            default:
                return 'unknown';
        }
    }
}

[OW] Fix bad spelling of reaper and forgetting sombra

 - fixes #93


<?php

require_once 'Doctrine/Common/ClassLoader.php';

$classLoader = new \Doctrine\Common\ClassLoader('Doctrine');
$classLoader->register();

$configuration = new \Doctrine\Common\Cli\Configuration();

$cli = new \Doctrine\Common\Cli\CliController($configuration);
$cli->run($_SERVER['argv']);

<?php

require_once 'Doctrine/Common/ClassLoader.php';

$classLoader = new \Doctrine\Common\ClassLoader('Doctrine');
$classLoader->register();

$configFile = getcwd() . DIRECTORY_SEPARATOR . 'cli-config.php';
$configuration = new \Doctrine\Common\Cli\Configuration();

if (file_exists($configFile)) {
    if ( ! is_readable($configFile)) {
        trigger_error(
            'Configuration file [' . $configFile . '] does not have read permission.', E_ERROR
        );
    }

    require $configFile;

    foreach ($GLOBALS as $configCandidate) {
        if ($configCandidate instanceof \Doctrine\Common\Cli\Configuration) {
            $configuration = $configCandidate;
            break;
        }
    }
}

$cli = new \Doctrine\Common\Cli\CliController($configuration);
$cli->run($_SERVER['argv']);

[2.0] Fix for CLI Configuration and PEAR installer

git-svn-id: 6d62a1918bfbe91cfb3198953e3056b244989dd5@7064 2b2ae520-0f61-44a6-8c59-7e116ffd6265


<?php
/**
 * Application level Controller
 *
 * This file is application-wide controller file. You can put all
 * application-wide controller-related methods here.
 *
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link          http://cakephp.org CakePHP(tm) Project
 * @package       app.Controller
 * @since         CakePHP(tm) v 0.2.9
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
 */

App::uses('Controller', 'Controller');

/**
 * Application Controller
 *
 * Add your application-wide methods in the class below, your controllers
 * will inherit them.
 *
 * @package		app.Controller
 * @link		http://book.cakephp.org/2.0/en/controllers.html#the-app-controller
 */
class AppController extends Controller {
}

<?php
/**
 * Application level Controller
 *
 * This file is application-wide controller file. You can put all
 * application-wide controller-related methods here.
 *
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link          http://cakephp.org CakePHP(tm) Project
 * @package       app.Controller
 * @since         CakePHP(tm) v 0.2.9
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
 */

App::uses('Controller', 'Controller');

/**
 * Application Controller
 *
 * Add your application-wide methods in the class below, your controllers
 * will inherit them.
 *
 * @package		app.Controller
 * @link		http://book.cakephp.org/2.0/en/controllers.html#the-app-controller
 */
class AppController extends Controller {
    public function beforeRender()
    {
        $this->layout = 'user';
    }
}

Set before render or filter

Set before render or filter


<?php

use Illuminate\Http\RedirectResponse;

if (! function_exists('redirect_with_errors')) {
    /**
     * Redirect with input and errors.
     *
     * @param  string  $to
     * @param  \Illuminate\Contracts\Support\MessageBag|array  $errors
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    function redirect_with_errors(string $to, $errors): RedirectResponse
    {
        return redirect($to)->withInput()->withErrors($errors);
    }
}

if (! function_exists('redirect_with_message')) {
    /**
     * Queue notification and redirect.
     *
     * @param  string  $to
     * @param  string|null  $message
     * @param  string  $type
     *
     * @return mixed
     */
    function redirect_with_message(
        string $to,
        ?string $message = null,
        string $type = 'success'
    ): RedirectResponse {
        ! is_null($message) && app('orchestra.messages')->add($type, $message);

        return redirect($to);
    }
}

<?php

use Illuminate\Http\RedirectResponse;

if (! \function_exists('redirect_with_errors')) {
    /**
     * Redirect with input and errors.
     *
     * @param  string  $to
     * @param  \Illuminate\Contracts\Support\MessageBag|array  $errors
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    function redirect_with_errors(string $to, $errors): RedirectResponse
    {
        return \redirect($to)->withInput()->withErrors($errors);
    }
}

if (! \function_exists('redirect_with_message')) {
    /**
     * Queue notification and redirect.
     *
     * @param  string  $to
     * @param  string|null  $message
     * @param  string  $type
     *
     * @return mixed
     */
    function redirect_with_message(
        string $to,
        ?string $message = null,
        string $type = 'success'
    ): RedirectResponse {
        if (! \is_null($message)) {
            \app('orchestra.messages')->add($type, $message);
        }

        return \redirect($to);
    }
}

Update helper to use \ as prefix for global functions.

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


<?php

namespace Laravel\Scout;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;
use Laravel\Scout\Events\ModelsImported;
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;

class SearchableScope implements Scope
{
    /**
     * Apply the scope to a given Eloquent query builder.
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $builder
     * @param  \Illuminate\Database\Eloquent\Model  $model
     * @return void
     */
    public function apply(EloquentBuilder $builder, Model $model)
    {
        //
    }

    /**
     * Extend the query builder with the needed functions.
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $builder
     * @return void
     */
    public function extend(EloquentBuilder $builder)
    {
        $builder->macro('searchable', function (EloquentBuilder $builder) {
            $builder->chunk(100, function ($models) use ($builder) {
                $models->searchable();

                event(new ModelsImported($models));
            });
        });

        $builder->macro('unsearchable', function (EloquentBuilder $builder) {
            $builder->chunk(100, function ($models) use ($builder) {
                $models->unsearchable();
            });
        });
    }
}

<?php

namespace Laravel\Scout;

use Illuminate\Config\Repository as ConfigRepository;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;
use Laravel\Scout\Events\ModelsImported;
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;

class SearchableScope implements Scope
{
    /**
     * Apply the scope to a given Eloquent query builder.
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $builder
     * @param  \Illuminate\Database\Eloquent\Model  $model
     * @return void
     */
    public function apply(EloquentBuilder $builder, Model $model)
    {
        //
    }

    /**
     * Extend the query builder with the needed functions.
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $builder
     * @return void
     */
    public function extend(EloquentBuilder $builder)
    {
        $chunkSize = app(ConfigRepository::class)->get('scout.searchableChunkSize', 100);

        $builder->macro('searchable', function (EloquentBuilder $builder) use ($chunkSize) {
            $builder->chunk($chunkSize, function ($models) use ($builder) {
                $models->searchable();

                event(new ModelsImported($models));
            });
        });

        $builder->macro('unsearchable', function (EloquentBuilder $builder) use ($chunkSize) {
            $builder->chunk($chunkSize, function ($models) use ($builder) {
                $models->unsearchable();
            });
        });
    }
}

Allow for customizing searchable chunk size


<?php
/**
 * Copyright (C) 2014 Proximis
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */
namespace Rbs\Storeshipping\Blocks;

/**
 * @name \Rbs\Storeshipping\Blocks\ShortStoreInformation
 */
class ShortStoreInformation extends \Change\Presentation\Blocks\Information
{
	/**
	 * @param \Change\Events\Event $event
	 */
	public function onInformation(\Change\Events\Event $event)
	{
		parent::onInformation($event);
		$i18nManager = $event->getApplicationServices()->getI18nManager();
		$ucf = array('ucf');
		$this->setSection($i18nManager->trans('m.rbs.storeshipping.admin.module_name', $ucf));
		$this->setLabel($i18nManager->trans('m.rbs.storeshipping.admin.short_store_label', $ucf));

		// Declare your parameters here.
		$this->addInformationMeta('autoSelect', \Change\Documents\Property::TYPE_BOOLEAN, false, true)
			->setLabel($i18nManager->trans('m.rbs.storeshipping.admin.short_store_auto_select', $ucf));

	}
}

<?php
/**
 * Copyright (C) 2014 Proximis
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */
namespace Rbs\Storeshipping\Blocks;

/**
 * @name \Rbs\Storeshipping\Blocks\ShortStoreInformation
 */
class ShortStoreInformation extends \Change\Presentation\Blocks\Information
{
	/**
	 * @param \Change\Events\Event $event
	 */
	public function onInformation(\Change\Events\Event $event)
	{
		parent::onInformation($event);
		$i18nManager = $event->getApplicationServices()->getI18nManager();
		$ucf = array('ucf');
		$this->setSection($i18nManager->trans('m.rbs.storeshipping.admin.module_name', $ucf));
		$this->setLabel($i18nManager->trans('m.rbs.storeshipping.admin.short_store_label', $ucf));

		// Declare your parameters here.
		$this->addParameterInformation('autoSelect', \Change\Documents\Property::TYPE_BOOLEAN, false, true)
			->setLabel($i18nManager->trans('m.rbs.storeshipping.admin.short_store_auto_select', $ucf));

	}
}

Fix renamed functions in block information


<?php

class ContentTableSeeder extends Seeder {

    public function run()
    {
        DB::collection('contents')->delete();

        // Get list of user and group ids
        $groupIds = DB::collection('groups')->lists('_id');
        $userIds = DB::collection('users')->lists('_id');

        // Insert 50 elements filled with random data
        $faker = \Faker\Factory::create();

        for ($x = 0; $x < 50; $x++)
        {
            $randomUser = (string) $userIds[array_rand($userIds)];
            $randomGroup = (string) $groupIds[array_rand($groupIds)];

            Content::create([
                'created_at' => $faker->dateTimeThisDecade,
                'group_id' => $randomGroup,
                'title' => $faker->sentence(10),
                'description' => $faker->text(200),
                'user_id' => $randomUser,
                'url' => $faker->url,
            ]);
        }
    }

}

<?php

class ContentTableSeeder extends Seeder {

    public function run()
    {
        DB::collection('contents')->delete();

        // Get list of user and group ids
        $groupIds = DB::collection('groups')->lists('_id');
        $userIds = DB::collection('users')->lists('_id');

        $faker = \Faker\Factory::create();

        // Insert 50 elements filled with random data
        for ($x = 1; $x <= 50; $x++)
        {
            // Use static id generated by using first 6 chars of $x hash
            $id = substr(md5($x), 0, 6);

            $randomUser = (string) $userIds[array_rand($userIds)];
            $randomGroup = (string) $groupIds[array_rand($groupIds)];

            Content::create([
                '_id' => $id,
                'created_at' => $faker->dateTimeThisDecade,
                'group_id' => $randomGroup,
                'title' => $faker->sentence(10),
                'description' => $faker->text(200),
                'user_id' => $randomUser,
                'url' => $faker->url,
                'nsfw' => $faker->boolean,
                'eng' => $faker->boolean,
            ]);
        }
    }

}

Use static content ids in seeder

Use static content ids in seeder


<?php
 if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');

$suitecrm_version      = '7.4';
$suitecrm_timestamp    = '2015-10-30 17:00pm';

<?php
 if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');

$suitecrm_version      = '7.4.1';
$suitecrm_timestamp    = '2015-11-10 18:00pm';

Update SuiteCRM Version to 7.4.1.

Update SuiteCRM Version to 7.4.1.


<?php

namespace MetaSyntactical\Mime\Exception;

class FileNotFoundExceptionTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var FileNotFoundException
     */
    protected $object;

    /**
     * Sets up the fixture, for example, opens a network connection.
     * This method is called before a test is executed.
     */
    protected function setUp()
    {
        $this->object = new FileNotFoundException;
    }

    /**
     * Tears down the fixture, for example, closes a network connection.
     * This method is called after a test is executed.
     */
    protected function tearDown()
    {
    }

    public function testThatClassProvidesTheExpectedInterfaces()
    {
        self::assertInstanceOf('\\RuntimeException', $this->object);
        self::assertInstanceOf('\\MetaSyntactical\\Mime\\Exception\\Exception', $this->object);
    }
}

<?php

namespace MetaSyntactical\Mime\Exception;

use RuntimeException;

class FileNotFoundExceptionTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var FileNotFoundException
     */
    protected $object;

    /**
     * Sets up the fixture, for example, opens a network connection.
     * This method is called before a test is executed.
     */
    protected function setUp()
    {
        $this->object = new FileNotFoundException;
    }

    /**
     * Tears down the fixture, for example, closes a network connection.
     * This method is called after a test is executed.
     */
    protected function tearDown()
    {
    }

    public function testThatClassProvidesTheExpectedInterfaces()
    {
        self::assertInstanceOf(RuntimeException::class, $this->object);
        self::assertInstanceOf(Exception::class, $this->object);
    }
}

Update tests to not use deprecated methods as of phpunit 5.7


<?php
namespace CodeDay\Clear\Controllers\Api;

use \CodeDay\Clear\Models;
use \CodeDay\Clear\ModelContracts;

class Stats extends ApiController {
  public function getIndex(){
    $this->requirePermission(["internal"]);
    $registrations = Models\Batch\Event\Registration::count();

    return json_encode([
      "registrations_all_time" => $registrations
    ]);
  }
}

<?php
namespace CodeDay\Clear\Controllers\Api;

use \CodeDay\Clear\Models;
use \CodeDay\Clear\ModelContracts;

class Stats extends ApiController {
  public function getIndex(){
    $this->requirePermission(["internal"]);
    $registrations = Models\Batch\Event\Registration::count();
    $events = Models\Batch\Event::count();
    $batches = Models\Batch::count();

    return json_encode([
      "registrations_all_time" => $registrations,
      "events_all_time" => $events,
      "batches_all_time" => $batches
    ]);
  }
}

Add `events_all_time` and `batches_all_time` to /api/stats


<?php
namespace DL\AssetSync\Command;

/*
 * This file is part of the DL.AssetSync package.
 *
 * (c) Daniel Lienert 2017
 *
 * This package is Open Source Software. For the full copyright and license
 * information, please view the LICENSE file which was distributed with this
 * source code.
 */

use DL\AssetSync\Synchronization\Synchronizer;
use Neos\Flow\Annotations as Flow;
use Neos\Flow\Cli\CommandController;

/**
 * @Flow\Scope("singleton")
 */
class AssetSyncCommandController extends CommandController
{

    /**
     * @Flow\Inject
     * @var Synchronizer
     */
    protected $synchronizer;

    /**
     * @param string $sourceIdentifier The identifier of the source to synchronize.
     */
    public function syncCommand($sourceIdentifier)
    {
        $this->outputLine(sprintf('Syncing source <b>%s</b>', $sourceIdentifier));
        try {
            $this->synchronizer->syncAssetsBySourceIdentifier($sourceIdentifier);
        } catch (\Exception $exception) {
            $this->outputLine(sprintf("<error>Synchronization failed:\n%s (%s)</error>", $exception->getMessage(), $exception->getCode()));
        }
    }
}

<?php

namespace DL\AssetSync\Command;

/*
 * This file is part of the DL.AssetSync package.
 *
 * (c) Daniel Lienert 2017
 *
 * This package is Open Source Software. For the full copyright and license
 * information, please view the LICENSE file which was distributed with this
 * source code.
 */

use DL\AssetSync\Synchronization\Synchronizer;
use Neos\Flow\Annotations as Flow;
use Neos\Flow\Cli\CommandController;

/**
 * @Flow\Scope("singleton")
 */
class AssetSyncCommandController extends CommandController
{

    /**
     * @Flow\Inject
     * @var Synchronizer
     */
    protected $synchronizer;

    /**
     * @Flow\InjectConfiguration(path="sourceConfiguration")
     * @var array
     */
    protected $sourceConfiguration;

    /**
     * Synchronize a single defined source
     *
     * @param string $sourceIdentifier The identifier of the source to synchronize.
     */
    public function syncCommand($sourceIdentifier)
    {
        $this->synchronizeSource($sourceIdentifier);
    }

    /**
     * Synchronize all defined sources
     */
    public function syncAllCommand()
    {
        $this->outputLine('Syncing all available sources');
        foreach(array_keys($this->sourceConfiguration) as $sourceIdentifier) {
            $this->synchronizeSource($sourceIdentifier);
        }
    }

    /**
     * @param $sourceIdentifier
     */
    protected function synchronizeSource($sourceIdentifier) {
        $this->outputLine(sprintf('Syncing source <b>%s</b>', $sourceIdentifier));
        try {
            $this->synchronizer->syncAssetsBySourceIdentifier($sourceIdentifier);
        } catch (\Exception $exception) {
            $this->outputLine(sprintf("<error>Synchronization failed:\n%s (%s)</error>", $exception->getMessage(), $exception->getCode()));
        }
    }
}

FEATURE: Add a syncAll command to sync all sources at once


<?php

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

class CreateDiscussionsTable extends Migration
{
    public function up()
    {
        Schema::create('discussions', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->integer('user_id')->unsigned();
            $table->integer('topic_id')->unsigned();
            $table->string('title');
            $table->longText('body');
            //$table->string('slug');

            $table->timestamps();
            $table->softDeletes();
        });
    }

    public function down()
    {
        Schema::dropIfExists('discussions');
    }
}

<?php

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

class CreateDiscussionsTable extends Migration
{
    public function up()
    {
        Schema::create('discussions', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->integer('user_id')->unsigned();
            $table->integer('topic_id')->unsigned();
            $table->string('title');
            $table->longText('body');
            //$table->string('slug');
            $table->bigInteger('answer_id')->unsigned()->nullable();

            $table->timestamps();
            $table->softDeletes();
        });
    }

    public function down()
    {
        Schema::dropIfExists('discussions');
    }
}

Add the answer ID in

Add the answer ID in


<?php

namespace Api\Controller;

use Zend\View\Model\JsonModel;

class QuestionController extends AbstractRestfulController
{

    protected function getJsonConfig($questionnaire = null)
    {
        return array(
            'name',
            'category' => array(
                'name',
                'parent' => array(
                    'name',
                    'parent' => array(
                        'name',
                    ),
                ),
            ),
            // Here we use a closure to get the questions' answers, but only for the current questionnaire
            'answers' => function(AbstractRestfulController $controller, \Application\Model\Question $question) use($questionnaire) {
                $answerRepository = $controller->getEntityManager()->getRepository('Application\Model\Answer');
                $answers = $answerRepository->findBy(array(
                    'question' => $question,
                    'questionnaire' => $questionnaire,
                ));

                return $controller->arrayOfObjectsToArray($answers, array(
                            'valuePercent',
                            'valueAbsolute',
                            'questionnaire' => array(),
                            'part' => array(
                                'name',
                            )
                ));
            }
        );
    }

    public function getList()
    {
        $idQuestionnaire = $this->params('idQuestionnaire');
        $questionnaireRepository = $this->getEntityManager()->getRepository('Application\Model\Questionnaire');
        $questionnaire = $questionnaireRepository->find($idQuestionnaire);

        $questions = $this->getRepository()->findBy(array(
            'survey' => $questionnaire->getSurvey(),
        ));

        return new JsonModel($this->arrayOfObjectsToArray($questions, $this->getJsonConfig($questionnaire)));
    }

}

<?php

namespace Api\Controller;

use Zend\View\Model\JsonModel;

class QuestionController extends AbstractRestfulController
{

    protected function getJsonConfig($questionnaire = null)
    {
        return array(
            'name',
            'category' => array(
                'name',
                'parent' => array(
                    'name',
                    'parent' => array(
                        'name',
                    ),
                ),
            ),
            // Here we use a closure to get the questions' answers, but only for the current questionnaire
            'answers' => function(AbstractRestfulController $controller, \Application\Model\Question $question) use($questionnaire) {
                $answerRepository = $controller->getEntityManager()->getRepository('Application\Model\Answer');
                $answers = $answerRepository->findBy(array(
                    'question' => $question,
                    'questionnaire' => $questionnaire,
                ));

                return $controller->arrayOfObjectsToArray($answers, array(
                            'valuePercent',
                            'valueAbsolute',
                            'questionnaire' => array(),
                            'part' => array(
                                'name',
                            )
                ));
            }
        );
    }

    public function getList()
    {
        $idQuestionnaire = $this->params('idQuestionnaire');
        $questionnaireRepository = $this->getEntityManager()->getRepository('Application\Model\Questionnaire');
        $questionnaire = $questionnaireRepository->find($idQuestionnaire);

        if (!$questionnaire) {
            $this->getResponse()->setStatusCode(404);
            return;
        }

        $questions = $this->getRepository()->findBy(array(
            'survey' => $questionnaire->getSurvey(),
        ));

        return new JsonModel($this->arrayOfObjectsToArray($questions, $this->getJsonConfig($questionnaire)));
    }

}

Return 404 if questionnaire does not exist


// SYNTAX TEST "Packages/php-grammar/PHP.tmLanguage"
<?php

$double_quotes = "SELECT * FROM tbl";
//                  ^ source.sql keyword
//                       ^ source.sql keyword
//                          ^ source.sql keyword

$single_quotes = 'SELECT * FROM tbl';
//                  ^ source.sql keyword
//                          ^ source.sql keyword

$double_quotes = "UPDATE t1 SET col1 = col1 + 1, col2 = col1;";
//                  ^ source.sql keyword
//                          ^ source.sql keyword

$single_quotes = 'UPDATE t1 SET col1 = col1 + 1, col2 = col1;';
//                  ^ source.sql keyword
//                          ^ source.sql keyword

$double_quotes = "INSERT INTO tbl_name (col1, col2) VALUES (15, col1 * 2);";
//                  ^ source.sql keyword
//                          ^ source.sql keyword
//                                                  ^ source.sql keyword

$single_quotes = 'INSERT INTO tbl_name (col1, col2) VALUES (15, col1 * 2);';
//                  ^ source.sql keyword
//                          ^ source.sql keyword
//                                                      ^ source.sql keyword

$HERDOC = <<<SQL
SELECT * FROM users WHERE active;
// ^ source.sql keyword
//          ^ source.sql keyword
//                  ^ source.sql keyword
SQL;

Add heredoc sql interpolation test

Add heredoc sql interpolation test


<?php
/**
 *
 * PHP.Gt (http://php.gt)
 * @copyright Copyright Ⓒ 2014 Bright Flair Ltd. (http://brightflair.com)
 * @license Apache Version 2.0, January 2004. http://www.apache.org/licenses
 */
namespace Gt\Dispatcher;
use Gt\Request\Request;
use Gt\Response\Response;
use Gt\Api\ApiFactory;
use Gt\Database\DatabaseFactory;

class DispatcherFactory {

/**
 * @param Request $request Representing the HTTP request
 * @param Response $response Representing the HTTP response
 *
 * @param DatabaseFactory $database Database Access Layer
 * @return Dispatcher Either an ApiDispatcher or PageDispatcher
 */
public static function createDispatcher(Request $request, Response $response,
ApiFactory $apiFactory, DatabaseFactory $databaseFactory) {
	$type = $request->getType();

	switch($type) {
	case Request::TYPE_API:
		return new ApiDispatcher(
			$request,
			$response,
			$apiFactory,
			$databaseFactory
		);
		break;

	case Request::TYPE_PAGE:
		return new PageDispatcher(
			$request,
			$response,
			$apiFactory,
			$databaseFactory
		);
		break;

	default:
		break;
	}
}

}#

<?php
/**
 *
 * PHP.Gt (http://php.gt)
 * @copyright Copyright Ⓒ 2014 Bright Flair Ltd. (http://brightflair.com)
 * @license Apache Version 2.0, January 2004. http://www.apache.org/licenses
 */
namespace Gt\Dispatcher;
use Gt\Request\Request;
use Gt\Response\Response;
use Gt\Api\ApiFactory;
use Gt\Database\DatabaseFactory;

class DispatcherFactory {

/**
 * @param Request $request Representing the HTTP request
 * @param Response $response Representing the HTTP response
 *
 * @param DatabaseFactory $database Database Access Layer
 * @return Dispatcher Either an ApiDispatcher or PageDispatcher
 */
public static function createDispatcher(Request $request, Response $response,
ApiFactory $apiFactory, DatabaseFactory $databaseFactory) {
	$type = $request->getType();

	switch($type) {
	case Request::TYPE_API:
		return new ApiDispatcher(
			$request,
			$response,
			$apiFactory,
			$databaseFactory
		);

	case Request::TYPE_PAGE:
		return new PageDispatcher(
			$request,
			$response,
			$apiFactory,
			$databaseFactory
		);

	default:
		throw new \Gt\Core\Exception\InvalidAccessException();
	}
}

}#

Remove unreachable breaks, add InvalidAccessException


<?php

declare(strict_types=1);

namespace Cortex\Foundation\Console\Commands;

use Illuminate\Console\ConfirmableTrait;
use Cortex\Foundation\Traits\ConsoleMakeModuleCommand;
use Illuminate\Database\Console\Factories\FactoryMakeCommand as BaseFactoryMakeCommand;

class FactoryMakeCommand extends BaseFactoryMakeCommand
{
    use ConfirmableTrait;
    use ConsoleMakeModuleCommand;

    /**
     * Get the destination class path.
     *
     * @param string $name
     *
     * @throws \Exception
     *
     * @return string
     */
    protected function getPath($name): string
    {
        $name = str_replace_first($this->rootNamespace(), $this->moduleName().DIRECTORY_SEPARATOR.'database'.DIRECTORY_SEPARATOR.'factories', $name);

        if (! $this->files->exists($path = $this->laravel['path'].DIRECTORY_SEPARATOR.$this->moduleName().DIRECTORY_SEPARATOR.'database'.DIRECTORY_SEPARATOR.'factories')) {
            throw new \Exception("Invalid path: {$path}");
        }

        return $this->laravel['path'].DIRECTORY_SEPARATOR.str_replace('\\', DIRECTORY_SEPARATOR, $name).'.php';
    }
}

<?php

declare(strict_types=1);

namespace Cortex\Foundation\Console\Commands;

use Illuminate\Console\ConfirmableTrait;
use Cortex\Foundation\Traits\ConsoleMakeModuleCommand;
use Illuminate\Database\Console\Factories\FactoryMakeCommand as BaseFactoryMakeCommand;

class FactoryMakeCommand extends BaseFactoryMakeCommand
{
    use ConfirmableTrait;
    use ConsoleMakeModuleCommand;

    /**
     * Get the destination class path.
     *
     * @param string $name
     *
     * @throws \Exception
     *
     * @return string
     */
    protected function getPath($name): string
    {
        $name = str_replace_first($this->rootNamespace(), $this->moduleName().DIRECTORY_SEPARATOR.'database'.DIRECTORY_SEPARATOR.'factories', $name);

        if (! $this->files->exists($path = $this->laravel['path'].DIRECTORY_SEPARATOR.$this->moduleName().DIRECTORY_SEPARATOR)) {
            throw new \Exception("Invalid path: {$path}");
        }

        return $this->laravel['path'].DIRECTORY_SEPARATOR.str_replace('\\', DIRECTORY_SEPARATOR, $name).'.php';
    }
}

Fix artisan factory make command issue

Fix artisan factory make command issue


<?php

echo "An Overview of the Dinosaurs we Offer";

?>

<?php

echo "Here at R.A.W.R. we only offer herbivores. We have found that carnivores are much more aggressive,
 are not good for families, and require a lot of feeding with expensive meat. However, carnivores are available
 upon special request.";

print  '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

			<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

				<input id="btnBarosaurus" type="button" value="Barosaurus" align="center"></input>

				<input id="btnDiceratops" type="button" value="Biceratops" align="center"></input>

				<input id="btnErketu" type="button" value="Erketu" align="center"></input>

				<input id="btnGiraffatitan" type="button" value="Giraffatitan" align="center"></input>

				<input id="btnLaosaurus" type="button" value="Laosaurus" align="center"></input>

				<input id="btnManidens" type="button" value="Manidens" align="center"></input>

';

print '
';

?>

Work on Our Dinosaurs page

Work on Our Dinosaurs page


<?php

namespace SLLH\IsoCodesValidatorBundle\DependencyInjection\Compiler;

use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Finder\Finder;

/**
 * Register IsoCodesValidator translations files
 *
 * Files resources register method based on
 * Symfony\Bundle\FrameworkBundle\DependencyInjection\FrameworkExtension::registerTranslatorConfiguration
 *
 * @author Sullivan Senechal <soullivaneuh@gmail.com>
 */
class TranslationPass implements CompilerPassInterface
{
    /**
     * {@inheritdoc}
     */
    public function process(ContainerBuilder $container)
    {
        $translator = $container->findDefinition('translator.default');

        $r = new \ReflectionClass('SLLH\IsoCodesValidator\IsoCodesConstraintValidator');
        $translationsDir = dirname($r->getFilename()).'/Resources/translations';

        $finder = Finder::create()
            ->files()
            ->filter(function (\SplFileInfo $file) {
                return 2 === substr_count($file->getBasename(), '.') && preg_match('/\.\w+$/', $file->getBasename());
            })
            ->in($translationsDir)
        ;

        foreach ($finder as $file) {
            list($domain, $locale, $format) = explode('.', $file->getBasename(), 3);
            $translator->addMethodCall('addResource', array($format, (string) $file, $locale, $domain));
        }
    }
}

<?php

namespace SLLH\IsoCodesValidatorBundle\DependencyInjection\Compiler;

use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Finder\Finder;

/**
 * Register IsoCodesValidator translations files
 *
 * Files resources register method based on
 * Symfony\Bundle\FrameworkBundle\DependencyInjection\FrameworkExtension::registerTranslatorConfiguration
 *
 * @author Sullivan Senechal <soullivaneuh@gmail.com>
 */
class TranslationPass implements CompilerPassInterface
{
    /**
     * {@inheritdoc}
     */
    public function process(ContainerBuilder $container)
    {
        if (!$container->hasDefinition('translator.default')) {
            return;
        }

        $translator = $container->findDefinition('translator.default');

        $r = new \ReflectionClass('SLLH\IsoCodesValidator\IsoCodesConstraintValidator');
        $translationsDir = dirname($r->getFilename()).'/Resources/translations';

        $finder = Finder::create()
            ->files()
            ->filter(function (\SplFileInfo $file) {
                return 2 === substr_count($file->getBasename(), '.') && preg_match('/\.\w+$/', $file->getBasename());
            })
            ->in($translationsDir)
        ;

        foreach ($finder as $file) {
            list($domain, $locale, $format) = explode('.', $file->getBasename(), 3);
            $translator->addMethodCall('addResource', array($format, (string) $file, $locale, $domain));
        }
    }
}

Fix obtrusive compiler pass issue

Fix obtrusive compiler pass issue


<?PHP  // $Id$

    require("../config.php");

    if (empty($CFG->langmenu)) {
        $langmenu = "";
    } else {
        $currlang = current_language();
        $langs    = get_list_of_languages();
        $langmenu = popup_form ("$CFG->wwwroot/doc/?lang=", $langs, "chooselang", $currlang, "", "", "", true);
    }

    if (! $site = get_site()) {
        error("Site is misconfigured");
    }
    $strdocumentation = get_string("documentation");
    print_header("$site->shortname: $strdocumentation", "$site->fullname", "$strdocumentation", "", "", true, $langmenu, navmenu($site));

?>

<?PHP  // $Id$

    require("../config.php");

    if (empty($CFG->langmenu)) {
        $langmenu = "";
    } else {
        $currlang = current_language();
        $langs    = get_list_of_languages();
        $langmenu = popup_form ("$CFG->wwwroot/doc/?lang=", $langs, "chooselang", $currlang, "", "", "", true, "parent");
    }

    if (! $site = get_site()) {
        error("Site is misconfigured");
    }
    $strdocumentation = get_string("documentation");
    print_header("$site->shortname: $strdocumentation", "$site->fullname", "$strdocumentation", "", "", true, $langmenu, navmenu($site, NULL, "parent"));

?>

Fix for switching languages in documentation


<?php
namespace phorkie;
/**
 * security levels + login requirement:
 */

if (!isset($GLOBALS['phorkie']['auth']['secure'])) {
    //not set? highest level of security
    $GLOBALS['phorkie']['auth']['secure'] = 2;
}

if ($GLOBALS['phorkie']['auth']['secure'] == 0) {
    //everyone may do everything
    return;
}

$logged_in = false;
if (!isset($_SESSION['identity'])) {
    //not logged in
} else if ($GLOBALS['phorkie']['auth']['userlist']) {
    if (in_array($_SESSION['identity'], $GLOBALS['phorkie']['users'])) {
        $logged_in = true;
    }
} else {
    //session identity exists, no special checks required
    $logged_in = true;
}

if ($pageRequiresLogin >= $GLOBALS['phorkie']['auth']['secure']) {
    if ($logged_in) {
        return;
    }
} else {
    return;
}

// p / G / log_in = disp
// 0 / 1 / true   = return
// 0 / 1 / false  = block
// 0 / 2 / true   = return
// 0 / 2 / false  = return
// 1 / 1 / true   = return
// 1 / 1 / false  = block
// 1 / 2 / true   = return
// 1 / 2 / false  = block

require 'forbidden.php';
?>

<?php
namespace phorkie;
/**
 * security levels + login requirement:
 */

if (!isset($GLOBALS['phorkie']['auth']['secure'])) {
    //not set? highest level of security
    $GLOBALS['phorkie']['auth']['secure'] = 2;
}

if ($GLOBALS['phorkie']['auth']['secure'] == 0) {
    //everyone may do everything
    return;
}

$logged_in = false;
if (!isset($_SESSION['identity'])) {
    //not logged in
} else if ($GLOBALS['phorkie']['auth']['userlist']) {
    if (in_array($_SESSION['identity'], $GLOBALS['phorkie']['users'])) {
        $logged_in = true;
    }
} else {
    //session identity exists, no special checks required
    $logged_in = true;
}

if ($pageRequiresLogin >= $GLOBALS['phorkie']['auth']['secure']) {
    if ($logged_in) {
        return;
    }
} else {
    return;
}

// p / G / log_in = disp
// 0 / 1 / true   = return
// 0 / 1 / false  = block
// 0 / 2 / true   = return
// 0 / 2 / false  = return
// 1 / 1 / true   = return
// 1 / 1 / false  = block
// 1 / 2 / true   = return
// 1 / 2 / false  = block

$_SESSION['REQUEST_URI'] = $_SERVER['REQUEST_URI'];
require 'forbidden.php';
?>

FIX: Set REQUEST_URI to go back to page requested before logging in


@extends('app')

@section('content')

All Categories

These are all categories in the database. Categories will automatically show up in the site navigation
                above.

                Name
                Candidates

            @forelse($categories as $category)

                    {{ $category->name }}
                    {{ $category->candidates->count() }}
                    slug]) }}">view
                    slug]) }}">edit

            @empty

                    No winners... yet!

            @endforelse

            New Category

@stop

@extends('app')

@section('content')

All Categories

These are all categories in the database. Each candidate may be in one category.

                Name
                Candidates

            @forelse($categories as $category)

                    {{ $category->name }}
                    {{ $category->candidates->count() }}
                    slug]) }}">view
                    slug]) }}">edit

            @empty

                    No winners... yet!

            @endforelse

            New Category

@stop

Update category admin page copy.

Update category admin page copy.


<?php

namespace LonelyPullRequests\Domain;

use Assert\Assertion as Ensure;

final class RepositoryName
{
    /**
     * @var string
     */
    private $repositoryName;

    public static function fromString($string)
    {
        return new RepositoryName($string);
    }

    private function __construct($repositoryName)
    {
        Ensure::string($repositoryName);
        Ensure::notBlank($repositoryName);
        Ensure::contains($repositoryName, '/');

        $this->repositoryName = $repositoryName;
    }

    public function toString()
    {
        return $this->repositoryName;
    }

    public function __toString()
    {
        return $this->toString();
    }
}

<?php

namespace LonelyPullRequests\Domain;

use Assert\Assertion as Ensure;

final class RepositoryName
{
    /**
     * @var string
     */
    private $repositoryName;

    public static function fromString($string)
    {
        return new RepositoryName($string);
    }

    private function __construct($repositoryName)
    {
        Ensure::string($repositoryName);
        Ensure::notBlank($repositoryName);
        Ensure::regex($repositoryName, "/^[a-zA-Z0-9\-]+\/[a-zA-Z0-9\-\.]+$/");

        $this->repositoryName = $repositoryName;
    }

    public function toString()
    {
        return $this->repositoryName;
    }

    public function __toString()
    {
        return $this->toString();
    }
}

Use regex to be more fine grained

Use regex to be more fine grained


<script type="text/javascript" charset="utf-8">
    function loadScript(src) {
        var ref = window.document.getElementsByTagName('script')[0];
        var script = window.document.createElement('script');
        script.src = src; script.async = true;
        ref.parentNode.insertBefore(script, ref);
    }

    if ('querySelector' in document && 'addEventListener' in window) {
        loadScript('{{ asset('/js/bundle.js') }}');
    }
</script>

<script type="text/javascript" charset="utf-8">
    function loadScript(src) {
        var async = arguments[1] === undefined ? true : arguments[1];
        var ref = window.document.getElementsByTagName('script')[0];
        var script = window.document.createElement('script');
        script.src = src;
        if(async) script.async = async;
        ref.parentNode.insertBefore(script, ref);
    }

    var supportsMQ = window.matchMedia && window.matchMedia( "only all" ) !== null && window.matchMedia( "only all" ).matches;
    if (!supportsMQ) {
        loadScript('{{ asset('assets/vendor/respond.min.js') }}', false)
    }

    if ('querySelector' in document && 'addEventListener' in window) {
        loadScript('{{ asset('js/bundle.js') }}');
    }
</script>

<!--[if lte IE 8]>
    <script type="text/javascript" charset="utf-8" src="{{ asset('assets/vendor/html5shiv.min.js') }}"></script>
<![endif]-->

Load HTML5Shiv and RespondJS conditionally.


<?php

namespace ajax\details;

use \PDO as PDO;

/**
 * Web Service.
 * Returns Organisms with given ids
 */
class Organisms_to_traits extends \WebService {

    /**
     * @param $querydata[type_cvterm_id] array of trait type_cvterm_id
     * @returns array of organisms accoring to a specific trait type
     */
    public function execute($querydata) {
        global $db;

    }

}

?>

<?php

namespace ajax\details;

use \PDO as PDO;

/**
 * Web Service.
 * Returns Organisms with given ids
 */
class Organisms_to_traits extends \WebService {

    /**
     * @param $querydata[type_cvterm_id] array of trait type_cvterm_id
     * @returns array of organisms accoring to a specific trait type
     */
    public function execute($querydata) {
        global $db;
        $type_cvterm_id = $querydata['trait_id'];

        $query_get_organism_by_trait = <<<EOF
SELECT * FROM organism, (SELECT DISTINCT organism_id FROM trait_entry WHERE type_cvterm_id = :type_cvterm_id) AS ids WHERE organism.organism_id = ids.organism_id
EOF;
        $stm_get_organism_by_trait = $db->prepare($query_get_organism_by_trait);
        $stm_get_organism_by_trait->bindValue('type_cvterm_id', $type_cvterm_id);
        $stm_get_organism_by_trait->execute();

        $data = array();

        while ($row = $stm_get_organism_by_trait->fetch(PDO::FETCH_ASSOC)) {
            $result = array();
            $result['organism_id'] = $row['organism_id'];
            $result['scientific_name'] = $row['species'];
            $result['rank'] = $row['genus'];
            $result['common_name'] = $row['common_name'];
            if($row["abbreviation"]!=null){
                $result['rank']='species';
            }
            $data[] = $result;
        }
        return $data;

    }

}

?>

Select all organisms to a specific trait by its type_cvterm_id


<?php

namespace Spatie\YamlFrontMatter;

use Exception;
use Symfony\Component\Yaml\Yaml;

class Parser
{
    protected $yamlParser;

    public function __construct()
    {
        $this->yamlParser = new Yaml();
    }

    public function parse(string $content) : Document
    {
        // Parser regex borrowed from the `devster/frontmatter` package
        // https://github.com/devster/frontmatter/blob/bb5d2c7/src/Parser.php#L123
        $pattern = "/^\s*(?:---)[\n\r\s]*(.*?)[\n\r\s]*(?:---)[\s\n\r]*(.*)$/s";

        $parts = [];

        $match = preg_match($pattern, $content, $parts);

        if ($match === false) {
            throw new Exception('An error occurred while extracting the front matter from the contents');
        }

        if ($match === 0) {
            return new Document([], $content);
        }

        $matter = $this->yamlParser->parse($parts[1]);
        $body = $parts[2];

        return new Document($matter, $body);
    }
}

<?php

namespace Spatie\YamlFrontMatter;

use Exception;
use Symfony\Component\Yaml\Yaml;

class Parser
{

    protected $yamlParser;

    public function __construct()
    {
        $this->yamlParser = new Yaml();
    }

    public function parse(string $content) : Document
    {
        $pattern = '/[\s\r\n]---[\s\r\n]/s';

        $parts = preg_split($pattern, PHP_EOL . ltrim($content));

        if (count($parts) === 1) {
            return new Document([], $content);
        }
        $matter = $this->yamlParser->parse($parts[1]);
        $body = implode(PHP_EOL . "---" . PHP_EOL, array_slice($parts, 2));
        return new Document($matter, $body);
    }

}

Change delimiter detection to allow string "---" to appear in front matter


<?php

declare(strict_types=1);

namespace League\Flysystem\GoogleCloudStorage;

use Google\Cloud\Storage\StorageClient;
use League\Flysystem\AdapterTestUtilities\FilesystemAdapterTestCase;
use League\Flysystem\FilesystemAdapter;

class GoogleCloudStorageAdapterTest extends FilesystemAdapterTestCase
{
    /**
     * @var string
     */
    private static $adapterPrefix = 'ci';

    public static function setUpBeforeClass(): void
    {
        static::$adapterPrefix = 'ci/' . bin2hex(random_bytes(10));
    }

    protected static function createFilesystemAdapter(): FilesystemAdapter
    {
        if ( ! file_exists(__DIR__ . '/../../google-cloud-service-account.json')) {
            self::markTestSkipped("No google service account found in project root.");
        }

        $clientOptions = [
            'projectId' => 'flysystem-testing',
            'keyFilePath' => __DIR__ . '/../../google-cloud-service-account.json',
        ];
        $storageClient = new StorageClient($clientOptions);
        $bucket = $storageClient->bucket('flysystem');

        return new GoogleCloudStorageAdapter($bucket, static::$adapterPrefix);
    }
}

<?php

declare(strict_types=1);

namespace League\Flysystem\GoogleCloudStorage;

use Google\Cloud\Storage\StorageClient;
use League\Flysystem\AdapterTestUtilities\FilesystemAdapterTestCase;
use League\Flysystem\FilesystemAdapter;

/**
 * @group gcs
 */
class GoogleCloudStorageAdapterTest extends FilesystemAdapterTestCase
{
    /**
     * @var string
     */
    private static $adapterPrefix = 'ci';

    public static function setUpBeforeClass(): void
    {
        static::$adapterPrefix = 'ci/' . bin2hex(random_bytes(10));
    }

    protected static function createFilesystemAdapter(): FilesystemAdapter
    {
        if ( ! file_exists(__DIR__ . '/../../google-cloud-service-account.json')) {
            self::markTestSkipped("No google service account found in project root.");
        }

        $clientOptions = [
            'projectId' => 'flysystem-testing',
            'keyFilePath' => __DIR__ . '/../../google-cloud-service-account.json',
        ];
        $storageClient = new StorageClient($clientOptions);
        $bucket = $storageClient->bucket('flysystem');

        return new GoogleCloudStorageAdapter($bucket, static::$adapterPrefix);
    }
}

Create gcs group for test running

Create gcs group for test running


<?php

namespace OpenDominion\Console\Commands;

use Carbon\Carbon;
use Illuminate\Console\Command;
use OpenDominion\Models\Round;
use OpenDominion\Models\RoundLeague;

class RoundStartCommand extends Command
{
    protected $signature = 'round:start';

    protected $description = 'Starts a new round (dev only)';

    public function __construct()
    {
        parent::__construct();

        //
    }

    public function handle()
    {
        $this->output->writeln('<info>Attempting to start a new round</info>');

        $standardRoundLeague = RoundLeague::where('key', 'standard')
            ->firstOrFail();

        $lastRound = Round::where('round_league_id', $standardRoundLeague->id)
            ->orderBy('number', 'desc')
            ->firstOrFail();

        if ($lastRound->isActive()) {
            $this->output->writeln("<error>Did not create a new round because round {$lastRound->number} in {$standardRoundLeague->description} is still active!</error>");
            return false;
        }

        $newRound = Round::create([
            'round_league_id' => $standardRoundLeague->id,
            'number' => ($lastRound->number + 1),
            'name' => 'Development Round',
            'start_date' => new Carbon('tomorrow midnight'),
            'end_date' => new Carbon('+51 days midnight'),
        ]);

        $this->output->writeln("<info>Round {$newRound->number} created successfully</info>");
    }
}

<?php

namespace OpenDominion\Console\Commands;

use Carbon\Carbon;
use Illuminate\Console\Command;
use OpenDominion\Models\Round;
use OpenDominion\Models\RoundLeague;

class RoundStartCommand extends Command
{
    protected $signature = 'round:start';

    protected $description = 'Starts a new round (dev only)';

    public function __construct()
    {
        parent::__construct();

        //
    }

    public function handle()
    {
        $this->output->writeln('<info>Attempting to start a new round</info>');

        $standardRoundLeague = RoundLeague::where('key', 'standard')
            ->firstOrFail();

        $lastRound = Round::where('round_league_id', $standardRoundLeague->id)
            ->orderBy('number', 'desc')
            ->firstOrFail();

        if ($lastRound->isActive()) {
            $this->output->writeln("<error>Did not create a new round because round {$lastRound->number} in {$standardRoundLeague->description} is still active!</error>");
            return false;
        }

        $newRound = Round::create([
            'round_league_id' => $standardRoundLeague->id,
            'number' => ($lastRound->number + 1),
            'name' => 'Development Round',
            'start_date' => new Carbon('+5 days midnight'),
            'end_date' => new Carbon('+55 days midnight'),
        ]);

        $this->output->writeln("<info>Round {$newRound->number} created successfully</info>");
    }
}

Change round:start to +5 days

Change round:start to +5 days


<?php class Security_Config_Framework extends Config {
protected static $_remoteSetupWhitelist = array(
	"127.0.0.1"
);
protected static $_allowAllRemoteAdmin = true;
protected static $_remoteAdminWhiteList = array(
	"127.0.0.1"
);
protected static $_salt = "Php.Gt default salt - please change this!";
protected static $_domain;
protected static $_remoteIp;

public static function init() {
	if(!defined("APPSALT")) {
		define("APPSALT", hash("sha512", static::$_salt));
	}
	static::$_remoteIp = isset($_SERVER["REMOTE_ADDR"])
		? $_SERVER["REMOTE_ADDR"]
		: null;
	static::$_domain = isset(static::$_domain)
		? static::$_domain
		: isset($_SERVER["HTTP_HOST"])
			? $_SERVER["HTTP_HOST"]
			: null;
}

public static function getDomain() {
	return static::$_domain;
}

public static function isSetupAllowed() {
	return in_array(static::$_remoteIp, static::$_remoteSetupWhitelist);
}

public static function isAdminAllowed() {
	return in_array(static::$_remoteIp, static::$_remoteAdminWhiteList)
		|| static::$_allowAllRemoteAdmin;
}

}#

<?php class Security_Config_Framework extends Config {
protected static $_remoteSetupWhitelist = array(
	"127.0.0.1"
);
protected static $_allowAllRemoteAdmin = true;
protected static $_remoteAdminWhiteList = array(
	"127.0.0.1"
);
protected static $_salt = "Php.Gt default salt - please change this!";
protected static $_domain;
protected static $_remoteIp;

public static function init() {
	if(!defined("APPSALT")) {
		define("APPSALT", hash("sha512", static::$_salt));
	}
	static::$_remoteIp = isset($_SERVER["REMOTE_ADDR"])
		? $_SERVER["REMOTE_ADDR"]
		: null;
	static::$_domain = isset(static::$_domain)
		? static::$_domain
		: (isset($_SERVER["HTTP_HOST"])
			? $_SERVER["HTTP_HOST"]
			: null);
}

public static function getDomain() {
	return static::$_domain;
}

public static function isSetupAllowed() {
	return in_array(static::$_remoteIp, static::$_remoteSetupWhitelist);
}

public static function isAdminAllowed() {
	return in_array(static::$_remoteIp, static::$_remoteAdminWhiteList)
		|| static::$_allowAllRemoteAdmin;
}

}#

Fix deprecation re nested ternary

Fix deprecation re nested ternary


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

namespace WellCommerce\Bundle\ProductBundle\Entity;

use WellCommerce\Bundle\RoutingBundle\Entity\Route;
use WellCommerce\Bundle\RoutingBundle\Entity\RouteInterface;

/**
 * Class ProductRoute
 *
 * @author  Adam Piotrowski <adam@wellcommerce.org>
 */
class ProductRoute extends Route implements RouteInterface
{
    /**
     * @var ProductInterface
     */
    protected $identifier;

    /**
     * @return string
     */
    public function getType()
    {
        return 'product';
    }
}

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

namespace WellCommerce\Bundle\ProductBundle\Entity;

use WellCommerce\Bundle\RoutingBundle\Entity\Route;
use WellCommerce\Bundle\RoutingBundle\Entity\RouteInterface;

/**
 * Class ProductRoute
 *
 * @author  Adam Piotrowski <adam@wellcommerce.org>
 */
class ProductRoute extends Route implements RouteInterface
{
    /**
     * @var ProductInterface
     */
    protected $identifier;

    /**
     * @return string
     */
    public function getType() : string
    {
        return 'product';
    }
}

Return types in routing and news bundle

Return types in routing and news bundle


<?php

namespace Backend\Modules\Compression;

use Backend\Core\Engine\Base\Config as BaseConfig;

/**
 * This is the configuration-object for the Compressor module
 *
 * @author Jesse Dobbelaere <jesse@dobbelaere-ae.be>
 */
final class Config extends BaseConfig
{
    /**
     * The default action
     *
     * @var string
     */
    protected $defaultAction = 'Index';

    /**
     * The disabled actions
     *
     * @var array
     */
    protected $disabledActions = array();
}

<?php

namespace Backend\Modules\Compression;

use Backend\Core\Engine\Base\Config as BaseConfig;

/**
 * This is the configuration-object for the Compressor module
 *
 * @author Jesse Dobbelaere <jesse@dobbelaere-ae.be>
 */
final class Config extends BaseConfig
{
    /**
     * The default action
     *
     * @var string
     */
    protected $defaultAction = 'Settings';

    /**
     * The disabled actions
     *
     * @var array
     */
    protected $disabledActions = array();
}

Use Settings as default action

Use Settings as default action

Fixes #3


<?php namespace Orchestra\Html;

class HtmlServiceProvider extends \Illuminate\Html\HtmlServiceProvider {

	/**
	 * Register the HTML builder instance.
	 *
	 * @return void
	 */
	protected function registerHtmlBuilder()
	{
		$this->app['html'] = $this->app->share(function($app)
		{
			return new HtmlBuilder($app['url']);
		});

		$this->app['orchestra.form'] = $this->app->share(function($app)
		{
			return new Form\Environment;
		});

		$this->app['orchestra.table'] = $this->app->share(function($app)
		{
			return new Table\Environment;
		});
	}

	/**
	 * Bootstrap the application events.
	 *
	 * @return void
	 */
	public function boot()
	{
		$this->package('orchestra/html', 'orchestra/html');
	}
}

<?php namespace Orchestra\Html;

class HtmlServiceProvider extends \Illuminate\Html\HtmlServiceProvider {

	/**
	 * Register the HTML builder instance.
	 *
	 * @return void
	 */
	protected function registerHtmlBuilder()
	{
		$this->app['html'] = $this->app->share(function($app)
		{
			return new HtmlBuilder($app['url']);
		});

		$this->app['orchestra.form'] = $this->app->share(function($app)
		{
			return new Form\Environment;
		});

		$this->app['orchestra.table'] = $this->app->share(function($app)
		{
			return new Table\Environment;
		});
	}

	/**
	 * Bootstrap the application events.
	 *
	 * @return void
	 */
	public function boot()
	{
		$this->package('orchestra/html', 'orchestra/html');
	}

	/**
	 * Get the services provided by the provider.
	 *
	 * @return array
	 */
	public function provides()
	{
		return array('html', 'form', 'orchestra.form', 'orchestra.table');
	}
}

Add lists of provided services

Add lists of provided services

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


<?php

namespace Detail\Apigility\Rest\Resource;

use ZF\ApiProblem\ApiProblem;
use ZF\ApiProblem\ApiProblemResponse;
use ZF\Rest\Resource as BaseResource;

use Detail\Apigility\Exception;

class Resource extends BaseResource
{
    public function patchMultiple($ids, $data)
    {
        if (!is_array($ids)) {
            throw new Exception\InvalidArgumentException(
                sprintf(
                    'Data provided to %s must be an array of identifiers; received "%s"',
                    __FUNCTION__,
                    gettype($data)
                )
            );
        }

        if (is_array($data)) {
            $data = (object) $data;
        }

        if (!is_object($data)) {
            throw new Exception\InvalidArgumentException(
                sprintf(
                    'Data provided to create must be either an array or object; received "%s"',
                    gettype($data)
                )
            );
        }

        $events = $this->getEventManager();
        $event = $this->prepareEvent(__FUNCTION__, array('ids' => $ids, 'data' => $data));

        $results = $events->triggerUntil(
            $event,
            function ($result) {
                return ($result instanceof ApiProblem || $result instanceof ApiProblemResponse);
            }
        );

        $last = $results->last();

        if (!is_array($last) && !is_object($last)) {
            return $data;
        }

        return $last;
    }
}

<?php

namespace Detail\Apigility\Rest\Resource;

use ZF\ApiProblem\ApiProblem;
use ZF\ApiProblem\ApiProblemResponse;
use ZF\Rest\Resource as BaseResource;

use Detail\Apigility\Exception;

class Resource extends BaseResource
{
    public function patchMultiple($ids, $data)
    {
        if (!is_array($ids)) {
            throw new Exception\InvalidArgumentException(
                sprintf(
                    'Data provided to %s must be an array of identifiers; received "%s"',
                    __FUNCTION__,
                    gettype($data)
                )
            );
        }

        if (is_array($data)) {
            $data = (object) $data;
        }

        if (!is_object($data)) {
            throw new Exception\InvalidArgumentException(
                sprintf(
                    'Data provided to create must be either an array or object; received "%s"',
                    gettype($data)
                )
            );
        }

        $events = $this->getEventManager();
        $event = $this->prepareEvent(__FUNCTION__, array('ids' => $ids, 'data' => $data));

        $results = $events->trigger(
            $event,
            function ($result) {
                return ($result instanceof ApiProblem || $result instanceof ApiProblemResponse);
            }
        );

        $last = $results->last();

        if (!is_array($last) && !is_object($last)) {
            return $data;
        }

        return $last;
    }
}

Switch triggerUnti lfunction (deprecated) to trigger function


<?php
class Session
{
    const SESSION_STARTED = TRUE;
    const SESSION_STOPED = FALSE;

    private $sessionStatus = self::SESSION_STOPED;
    private static $instance;

    private function __construct() {}

    public static function getInstance()
    {
        if (!isset(self::$instance))
        {
            self::$instance = new self;
        }

        self::$instance->startSession();

        return self::$instance;
    }

    public function startSession()
    {
        if($this->sessionStatus == self::SESSION_STOPED)
        {
            $this->sessionStatus = session_start();
        }

        return $this->sessionStatus;
    }

    public function __set( $name , $value )
    {
        $_SESSION[$name] = $value;
    }

    public function __get( $name )
    {
        if(isset($_SESSION[$name]))
        {
            return $_SESSION[$name];
        }
    }

    public function __isset($name)
    {
        return isset($_SESSION[$name]);
    }

    public function __unset($name)
    {
        unset($_SESSION[$name]);
    }

    public function destroy()
    {
        if($this->sessionStatus == self::SESSION_STARTED)
        {
            $this->sessionStatus = session_destroy();
            unset($_SESSION);
            return $this->sessionStatus;
        }

        return FALSE;
    }

    public function restart()
    {
        if(self::$instance->destroy())
        {
		self::$instance->startSession();
        }
    }

    public function reset()
    {
        session_reset();
    }

}
?>

<?php
class Session
{
    const SESSION_STARTED = TRUE;
    const SESSION_STOPED = FALSE;

    private $sessionStatus = self::SESSION_STOPED;
    private static $instance;

    private function __construct() {}

    public static function getInstance()
    {
        if (!isset(self::$instance))
        {
            self::$instance = new self;
        }

        self::$instance->startSession();

        return self::$instance;
    }

    public function startSession()
    {
        $this->sessionStatus = session_start();

        return $this->sessionStatus;
    }

    public function __set( $name , $value )
    {
        $_SESSION[$name] = $value;
    }

    public function __get( $name )
    {
        if(isset($_SESSION[$name]))
        {
            return $_SESSION[$name];
        }
    }

    public function __isset($name)
    {
        return isset($_SESSION[$name]);
    }

    public function __unset($name)
    {
        unset($_SESSION[$name]);
    }

    public function destroy()
    {
        if($this->sessionStatus == self::SESSION_STARTED)
        {
            $this->sessionStatus = session_destroy();
            unset($_SESSION);
            return $this->sessionStatus;
        }

        return FALSE;
    }

    public function restart()
    {
        if(self::$instance->destroy())
        {
		self::$instance->startSession();
        }
    }

    public function reset()
    {
        session_reset();
    }

}
?>

Fix refresh session on navigate

Fix refresh session on navigate


<?php

namespace OpenDominion\Tests\Http;

use CoreDataSeeder;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use OpenDominion\Tests\AbstractHttpTestCase;

class HomeTest extends AbstractHttpTestCase
{
    use DatabaseMigrations;

    public function testIndex()
    {
        $this->get('/')
            ->assertStatus(200);
    }

    public function testRedirectLoggedWithoutSelectedDominionToDashboard()
    {
        $user = $this->createAndImpersonateUser();

        $this->actingAs($user)
            ->get('/')
            ->assertRedirect('/dashboard');
    }

    public function testRedirectLoggedWithSelectedDominionToStatus()
    {
        $this->seed(CoreDataSeeder::class);
        $user = $this->createAndImpersonateUser();
        $round = $this->createRound();
        $this->createAndSelectDominion($user, $round);

        $this->actingAs($user)
            ->get('/')
            ->assertRedirect('/dominion/status');
    }
}

<?php

namespace OpenDominion\Tests\Http;

use CoreDataSeeder;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use OpenDominion\Tests\AbstractHttpTestCase;

class HomeTest extends AbstractHttpTestCase
{
    use DatabaseMigrations;

    public function testIndex()
    {
        $this->get('/')
            ->assertStatus(200);
    }

    public function testRedirectLoggedUserWithoutSelectedDominionToDashboard()
    {
        $user = $this->createAndImpersonateUser();

        $this->actingAs($user)
            ->get('/')
            ->assertRedirect('/dashboard');
    }

    public function testRedirectLoggedUserWithSelectedDominionToStatus()
    {
        $this->seed(CoreDataSeeder::class);
        $user = $this->createAndImpersonateUser();
        $round = $this->createRound();
        $this->createAndSelectDominion($user, $round);

        $this->actingAs($user)
            ->get('/')
            ->assertRedirect('/dominion/status');
    }
}

Refactor home test method names

Refactor home test method names


<?php

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

namespace JsonSchema\Tests\Constraints;

class EnumTest extends BaseTestCase
{
    public function getInvalidTests()
    {
        return array(
            array(
                '{
                  "value":"Morango"
                }',
                '{
                  "type":"object",
                  "properties":{
                    "value":{"type":"string","enum":["Abacate","Manga","Pitanga"]}
                  },
                  "additionalProperties":false
                }'
            )
        );
    }

    public function getValidTests()
    {
        return array(
            array(
                '{
                  "value":"Abacate"
                }',
                '{
                  "type":"object",
                  "properties":{
                    "value":{"type":"string","enum":["Abacate","Manga","Pitanga"]}
                  },
                  "additionalProperties":false
                }'
            )
        );
    }
}

<?php

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

namespace JsonSchema\Tests\Constraints;

class EnumTest extends BaseTestCase
{
    public function getInvalidTests()
    {
        return array(
            array(
                '{
                  "value":"Morango"
                }',
                '{
                  "type":"object",
                  "properties":{
                    "value":{"type":"string","enum":["Abacate","Manga","Pitanga"]}
                  },
                  "additionalProperties":false
                }'
            ),
            array(
                '{}',
                '{
                  "type":"object",
                  "properties":{
                    "value":{
                      "type":"string",
                      "enum":["Abacate","Manga","Pitanga"],
                      "required":true
                    }
                  },
                  "additionalProperties":false
                }'
            )
        );
    }

    public function getValidTests()
    {
        return array(
            array(
                '{
                  "value":"Abacate"
                }',
                '{
                  "type":"object",
                  "properties":{
                    "value":{"type":"string","enum":["Abacate","Manga","Pitanga"]}
                  },
                  "additionalProperties":false
                }'
            ),
            array(
                '{}',
                '{
                  "type":"object",
                  "properties":{
                    "value":{"type":"string","enum":["Abacate","Manga","Pitanga"]}
                  },
                  "additionalProperties":false
                }'
            ),
            array(
                '{}',
                '{
                  "type":"object",
                  "properties":{
                    "value":{
                      "type":"string",
                      "enum":["Abacate","Manga","Pitanga"],
                      "required":false
                    }
                  },
                  "additionalProperties":false
                }'
            )
        );
    }
}

Add test cases for optional enums

Add test cases for optional enums

Added test cases where required is set as true and false,
with the attribute omitted.


<?php

namespace App\Transformers\Inbound\Membership;

use App\Transformers\Datum;
use App\Transformers\Inbound\MembershipTransformer;

class TicketedEvent extends MembershipTransformer
{

    protected function getExtraFields( Datum $datum )
    {

        return [
            'event_type_id' => $datum->date('type_id'),
            'start_at' => $datum->date('start_at'),
            'end_at' => $datum->date('end_at'),
        ];

    }

}

<?php

namespace App\Transformers\Inbound\Membership;

use App\Transformers\Datum;
use App\Transformers\Inbound\MembershipTransformer;

class TicketedEvent extends MembershipTransformer
{

    protected function getExtraFields( Datum $datum )
    {

        return [
            'event_type_id' => $datum->type_id,
            'start_at' => $datum->date('start_at'),
            'end_at' => $datum->date('end_at'),
        ];

    }

}

Fix `type_id` casting on ticketed event import


<?php

namespace Punkstar\SslTest;

use PHPUnit\Framework\TestCase;
use Punkstar\Ssl\Reader;

class IntegrationTest extends TestCase
{
    /**
     * @test
     * @dataProvider exampleCertsDataProvider
     */
    public function testExampleCerts($certFileName)
    {
        $reader = new Reader();
        $cert = $reader->readFromFile($certFileName);

        $this->assertInternalType('string', $cert->certName());
        $this->assertInternalType('string', $cert->toString());
        $this->assertInstanceOf('DateTime', $cert->validTo());
        $this->assertInstanceOf('DateTime', $cert->validFrom());
    }

    /**
     * @test
     * @dataProvider exampleCertsDataProvider
     */
    public function testRawCertificate($certFileName)
    {
        $reader = new Reader();
        $cert = $reader->readFromFile($certFileName);

        $rawCertFromFile = file_get_contents($certFileName);

        $this->assertEquals($rawCertFromFile, $cert->toString());
    }

    public function exampleCertsDataProvider()
    {
        $certs = glob(__DIR__ . "/../../../example_certs/*");
        $dataProvider = [];

        foreach ($certs as $cert) {
            $dataProvider[] = [$cert];
        }

        return $dataProvider;
    }
}

<?php

namespace Punkstar\SslTest;

use PHPUnit\Framework\TestCase;
use Punkstar\Ssl\Reader;

class IntegrationTest extends TestCase
{
    /**
     * @test
     * @dataProvider exampleCertsDataProvider
     */
    public function testExampleCerts($certFileName)
    {
        $reader = new Reader();
        $cert = $reader->readFromFile($certFileName);

        $this->assertInternalType('string', $cert->certName());
        $this->assertInternalType('string', $cert->toString());
        $this->assertInstanceOf('DateTime', $cert->validTo());
        $this->assertInstanceOf('DateTime', $cert->validFrom());
    }

    /**
     * @test
     * @dataProvider exampleCertsDataProvider
     */
    public function testRawCertificate($certFileName)
    {
        $reader = new Reader();
        $cert = $reader->readFromFile($certFileName);

        $rawCertFromFile = file_get_contents($certFileName);

        $this->assertEquals($rawCertFromFile, $cert->toString());
    }

    /**
     * @test
     */
    public function testUrlReading()
    {
        $reader = new Reader();
        $cert = $reader->readFromUrl("https://google.com");
        $this->assertInstanceOf("Punkstar\\Ssl\\Certificate", $cert);
    }

    public function exampleCertsDataProvider()
    {
        $certs = glob(__DIR__ . "/../../../example_certs/*");
        $dataProvider = [];

        foreach ($certs as $cert) {
            $dataProvider[] = [$cert];
        }

        return $dataProvider;
    }
}

Add a basic URL reading test

Add a basic URL reading test


<?
require_once "record.inc";
print $_lib['sess']->doctype
?>

<head>
  <title>Empatix - Altinn lønnslipper</title>
  <? includeinc('head') ?>
</head>
<body>
<? print $_lib['message']->get() ?>
<? print $authentication_challenge_message ?>
<? $target_page = $_POST['request_type'] == 'feedback' ? 'altinnsalary.show4' : 'altinnsalary.list'?>
<form name="altinnsalary_search" action="<? print $_lib['sess']->dispatch ?>t=<? print $target_page ?>" method="post">
  <input type="hidden" name="request_receivers_reference" value='<?print $_POST['request_receivers_reference']; ?>'>
  <? print $_lib['form3']->text(array('field'=>'user_pin_code', 'width'=>'10' , 'value'=>'')) ?>
    <?
    if($_POST['request_type'] == 'feedback'){
        print $_lib['form3']->submit(array('name'=>'action_soap4', 'value'=>'Get Feedback'));
    }elseif($_POST['request_type'] == 'archive'){
        print $_lib['form3']->submit(array('name'=>'action_soap5', 'value'=>'Archive Report'));
    }
    ?>
</form>

</body>
</html>

<?
require_once "record.inc";
print $_lib['sess']->doctype
?>

<head>
  <title>Empatix - Altinn lønnslipper</title>
  <? includeinc('head') ?>
</head>
<body>
<? print $_lib['message']->get() ?>
<? print $authentication_challenge_message ?>
<? $target_page = $_POST['request_type'] == 'feedback' ? 'altinnsalary.show4' : 'altinnsalary.list'?>
<form name="altinnsalary_search" action="<? print $_lib['sess']->dispatch ?>t=<? print $target_page ?>" method="post">
  <input type="hidden" name="request_receivers_reference" value='<?print $_POST['request_receivers_reference']; ?>'>
  <? print $_lib['form3']->text(array('name'=>'user_pin_code', 'width'=>'10' , 'value'=>'')) ?>
    <?
    if($_POST['request_type'] == 'feedback'){
        print $_lib['form3']->submit(array('name'=>'action_soap4', 'value'=>'Get Feedback'));
    }elseif($_POST['request_type'] == 'archive'){
        print $_lib['form3']->submit(array('name'=>'action_soap5', 'value'=>'Archive Report'));
    }
    ?>
</form>

</body>
</html>

Fix pin input name on authentication challenge page


<?php

namespace Tighten\TLint\Formatters;

use PhpParser\Node;
use PhpParser\Lexer;
use PhpParser\Parser;
use PhpParser\NodeTraverser;
use PhpParser\Node\Expr\New_;
use PhpParser\Node\Stmt\Class_;
use PhpParser\Node\Stmt\Return_;
use Tighten\TLint\BaseFormatter;
use PhpParser\PrettyPrinter\Standard;
use PhpParser\NodeVisitor\CloningVisitor;
use Tighten\TLint\Linters\Concerns\LintsMigrations;

class UseAnonymousMigrations extends BaseFormatter
{
    use LintsMigrations;

    public const description = 'Prefer anonymous class migrations.';

    public function format(Parser $parser, Lexer $lexer)
    {
        $traverser = new NodeTraverser;
        $traverser->addVisitor(new CloningVisitor);

        $originalStatements = $parser->parse($this->code);
        $tokens = $lexer->getTokens();

        $statements = array_map(function (Node $node) {
            if (
                $node instanceof Class_
                    && $node->extends->toString() === 'Migration'
                    && $node->name
            ) {
                return new Return_(new New_($node));
            }

            return $node;
        }, $traverser->traverse($originalStatements));

        return (new Standard)->printFormatPreserving($statements, $originalStatements, $tokens);
    }
}

<?php

namespace Tighten\TLint\Formatters;

use PhpParser\Node;
use PhpParser\Lexer;
use PhpParser\Parser;
use PhpParser\NodeTraverser;
use PhpParser\Node\Expr\New_;
use PhpParser\Node\Stmt\Class_;
use PhpParser\Node\Stmt\Return_;
use Tighten\TLint\BaseFormatter;
use PhpParser\PrettyPrinter\Standard;
use PhpParser\NodeVisitor\CloningVisitor;
use Tighten\TLint\Linters\Concerns\LintsMigrations;

class UseAnonymousMigrations extends BaseFormatter
{
    use LintsMigrations;

    public const description = 'Prefer anonymous class migrations.';

    public function format(Parser $parser, Lexer $lexer)
    {
        $traverser = new NodeTraverser;
        $traverser->addVisitor(new CloningVisitor);

        $className = null;
        array_map(function (Node $node) use (&$className) {
            if (
                $node instanceof Class_
                    && $node->extends->toString() === 'Migration'
                    && $node->name
            ) {
                $className = $node->name->toString();
            }
        }, $traverser->traverse($parser->parse($this->code)));

        if ($className) {
            $this->code = str_replace("class {$className}", 'return new class', $this->code);
            $this->code = $this->str_lreplace('}', '};', $this->code);
        }

        return $this->code;
    }

    public function str_lreplace($search, $replace, $subject)
    {
        $pos = strrpos($subject, $search);

        if ($pos !== false) {
            $subject = substr_replace($subject, $replace, $pos, strlen($search));
        }

        return $subject;
    }
}

Change to simple string manipulation

Change to simple string manipulation


<?php
/**
 * This file is part of the BEAR.Package package
 *
 * @license http://opensource.org/licenses/bsd-license.php BSD
 */
namespace BEAR\Package\Provide\TemplateEngine\Twig\Extension;

use Aura\Html\HelperLocatorFactory;

class AuraForm_Twig_Extension extends \Twig_Extension
{
    private static $helper;

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

    public function getFunctions()
    {
        return [
            new \Twig_SimpleFunction('form', [$this, 'createForm']),
        ];
    }

    public function createForm($hint)
    {
        if (! static::$helper) {
            $factory = new HelperLocatorFactory();
            static::$helper = $factory->newInstance();
        }

        $formElementHtml = static::$helper->input($hint);
        return $formElementHtml;
    }
}

<?php
/**
 * This file is part of the BEAR.Package package
 *
 * @license http://opensource.org/licenses/bsd-license.php BSD
 */
namespace BEAR\Package\Provide\TemplateEngine\Twig\Extension;

use Aura\Html\HelperLocatorFactory;

class AuraForm_Twig_Extension extends \Twig_Extension
{
    private static $helper;

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

    public function getFunctions()
    {
        return [
            new \Twig_SimpleFunction(
                'form',
                [$this, 'createForm'],
                ['is_safe' => ['html']]
            ),
        ];
    }

    public function createForm($hint)
    {
        if (! static::$helper) {
            $factory = new HelperLocatorFactory();
            static::$helper = $factory->newInstance();
        }

        $formElementHtml = static::$helper->input($hint);
        return $formElementHtml;
    }
}

Add is_safe option to Twig "form" function for AuraForm


<?php

final class ManiphestPeopleMenuEventListener extends PhutilEventListener {

  public function register() {
    $this->listen(PhabricatorEventType::TYPE_UI_DIDRENDERACTIONS);
  }

  public function handleEvent(PhutilEvent $event) {
    switch ($event->getType()) {
      case PhabricatorEventType::TYPE_UI_DIDRENDERACTIONS:
        $this->handleActionsEvent($event);
      break;
    }
  }

  private function handleActionsEvent($event) {
    $actions = $event->getValue('actions');

    $action = id(new PhabricatorActionView())
      ->setIcon('maniphest-dark')
      ->setIconSheet(PHUIIconView::SPRITE_APPS)
      ->setName(pht('View Tasks'));

    $object = $event->getValue('object');
    if ($object instanceof PhabricatorUser) {
      $href = '/maniphest/view/action/?users='.$object->getPHID();
      $actions[] = $action->setHref($href);
    } else if ($object instanceof PhabricatorProject) {
      $href = '/maniphest/view/all/?projects='.$object->getPHID();
      $actions[] = $action->setHref($href);
    }

    $event->setValue('actions', $actions);
  }

}

<?php

final class ManiphestPeopleMenuEventListener extends PhutilEventListener {

  public function register() {
    $this->listen(PhabricatorEventType::TYPE_UI_DIDRENDERACTIONS);
  }

  public function handleEvent(PhutilEvent $event) {
    switch ($event->getType()) {
      case PhabricatorEventType::TYPE_UI_DIDRENDERACTIONS:
        $this->handleActionsEvent($event);
      break;
    }
  }

  private function handleActionsEvent($event) {
    $actions = $event->getValue('actions');

    $action = id(new PhabricatorActionView())
      ->setIcon('maniphest-dark')
      ->setIconSheet(PHUIIconView::SPRITE_APPS)
      ->setName(pht('View Tasks'));

    $object = $event->getValue('object');
    if ($object instanceof PhabricatorUser) {
      $href = '/maniphest/view/action/?users='.$object->getPHID();
      $actions[] = $action->setHref($href);
    } else if ($object instanceof PhabricatorProject) {
      $href = '/maniphest/view/all/?projects='.$object->getPHID();
      $actions[] = $action->setHref($href);

      $actions[] = id(new PhabricatorActionView())
        ->setName(pht("Add Task"))
        ->setIcon('create')
        ->setHref('/maniphest/task/create/?projects=' . $object->getPHID());
    }

    $event->setValue('actions', $actions);
  }

}

Create 'Add Task' link on project/view page

Reviewed by: epriestley

See: https://github.com/facebook/phabricator/pull/368


<?php

/*
 * This file is part of the PredisServiceProvider package.
 *
 * (c) Daniele Alessandri <suppakilla@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

require_once __DIR__.'/../vendor/.composer/autoload.php';
require_once __DIR__.'/../lib/Predis/Silex/PredisServiceProvider.php';

<?php

/*
 * This file is part of the PredisServiceProvider package.
 *
 * (c) Daniele Alessandri <suppakilla@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

require_once __DIR__.'/../vendor/.composer/autoload.php';
require_once __DIR__.'/../vendor/pimple/pimple/lib/Pimple.php';
require_once __DIR__.'/../lib/Predis/Silex/PredisServiceProvider.php';

Fix Pimple not loading when running the test suite.

This is a temporary fix since Pimple does not use Composer autoloading yet.

We are not going to push a new patch release since it does not affect the
actual service provider.


<?php # -*- coding: utf-8 -*-
/**
 * Created by PhpStorm.
 * User: Arbeit
 * Date: 15.08.2014
 * Time: 11:29
 */

class Biont_SubPlugins_PluginsView
{

    private $installed_plugins = array();

    private $active_plugins = array();

    private $prefix = '';

    public function __construct($installed_plugins, $active_plugins, $prefix)
    {

        $this->installed_plugins = $installed_plugins;
        $this->active_plugins = $active_plugins;
        $this->prefix = $prefix;
    }

    public function show()
    {

        ?>

<?php echo esc_html(get_admin_page_title()); ?>

            <form id="sub_plugins" method="get">
                <input type="hidden" name="page" value="<?php echo $_REQUEST['page'] ?>"/>
                <?php
                $table = new Biont_SubPlugins_PluginListTable($this->installed_plugins, $this->prefix);
                $table->prepare_items();
                $table->display();
                ?>
            </form>

    <?php
    }
}

<?php # -*- coding: utf-8 -*-
/**
 * Created by PhpStorm.
 * User: Arbeit
 * Date: 15.08.2014
 * Time: 11:29
 */
class Biont_SubPlugins_PluginsView {

	/**
	 * @var array
	 */
	private $installed_plugins = array();

	/**
	 * @var array
	 */
	private $active_plugins = array();

	/**
	 * @var string
	 */
	private $prefix = '';

	/**
	 * Setup class variables
	 *
	 * @param $installed_plugins
	 * @param $active_plugins
	 * @param $prefix
	 */
	public function __construct( $installed_plugins, $active_plugins, $prefix ) {

		$this->installed_plugins = $installed_plugins;
		$this->active_plugins    = $active_plugins;
		$this->prefix            = $prefix;
	}

	/**
	 * Display the PluginListTable that manages the subplugins
	 */
	public function show() {

		?>

<?php echo esc_html( get_admin_page_title() ); ?>

			<?php do_action( 'biont_before_subplugin_list' ) ?>
			<form id="sub_plugins" method="get">
				<input type="hidden" name="page" value="<?php echo $_REQUEST[ 'page' ] ?>" />
				<?php
				do_action( 'biont_subplugin_form_fields' );
				$table = new Biont_SubPlugins_PluginListTable( $this->installed_plugins, $this->prefix );
				$table->prepare_items();
				$table->display();
				?>
			</form>
			<?php do_action( 'biont_after_subplugin_list' ) ?>

	<?php
	}
}

Add a bunch of actions to the sub-plugin list


<?php

namespace GrumPHP\Parser\Php\Visitor;

use PhpParser\Node;

class DeclareStrictTypesVisitor extends AbstractVisitor
{
    /**
     * @var bool
     */
    private $hasStrictType = false;

    /**
     * @param Node $node
     *
     * @return void
     */
    public function leaveNode(Node $node)
    {
        if (!$node instanceof Node\Stmt\Declare_) {
            return;
        }

        foreach ($node->declares as $id => $declare) {
            if ($declare->key !== 'strict_types') {
                continue;
            }

            $this->hasStrictType = $declare->value->value === 1;
        }
    }

    /**
     * @param array $nodes
     *
     * @return void
     */
    public function afterTraverse(array $nodes)
    {
        if (!$this->hasStrictType) {
            $this->addError('No "declare(strict_types = 1)" found in file!');
        }
    }
}

<?php

namespace GrumPHP\Parser\Php\Visitor;

use PhpParser\Node;

class DeclareStrictTypesVisitor extends AbstractVisitor
{
    /**
     * @var bool
     */
    private $hasStrictType = false;

    /**
     * @param Node $node
     *
     * @return void
     */
    public function leaveNode(Node $node)
    {
        if (!$node instanceof Node\Stmt\Declare_) {
            return;
        }

        foreach ($node->declares as $id => $declare) {
            // In PhpParser 3 and lower the key used in a `declare()` statement
            // is represented as a string value. Starting with PhpParser 4 this
            // key is represented by a 'PhpParser\Node\Identifier' object. To
            // support backwards compatibility with older versions the object
            // can be cast to a string to get the original string value.
            if ((string) $declare->key !== 'strict_types') {
                continue;
            }

            $this->hasStrictType = $declare->value->value === 1;
        }
    }

    /**
     * @param array $nodes
     *
     * @return void
     */
    public function afterTraverse(array $nodes)
    {
        if (!$this->hasStrictType) {
            $this->addError('No "declare(strict_types = 1)" found in file!');
        }
    }
}

Make detection of strict types compatible with PhpParser 4.


<?php
use PhpBrew\Testing\CommandTestCase;

/**
 * @large
 * @group command
 */
class PathCommandTest extends CommandTestCase
{
    public function argumentsProvider() {

        return array(
            array("build",   "#\.phpbrew/build/.+#"),
            array("ext-src", "#\.phpbrew/build/.+/ext$#"),
            array("include", "#\.phpbrew/php/.+/include$#"),
            array("etc",     "#\.phpbrew/php/.+/etc$#"),
            array("dist",    "#\.phpbrew/distfiles$#"),
            array("root",    "#\.phpbrew$#"),
            array("home",    "#\.phpbrew$#"),
        );
    }

    public function testUseLatestPHP() {
        $this->runCommand("phpbrew use latest");
    }

    /**
     * @outputBuffering enabled
     * @dataProvider argumentsProvider
     * @depends testInstallOnePHP
     */
    public function testPathCommand($arg, $pattern) {
        ob_start();
        $this->runCommandWithStdout("phpbrew path $arg");
        $path = ob_get_clean();
        $this->assertRegExp($pattern, $path);
    }
}

<?php
use PhpBrew\Testing\CommandTestCase;

/**
 * @large
 * @group command
 */
class PathCommandTest extends CommandTestCase
{
    public function argumentsProvider() {

        return array(
            array("build",   "#\.phpbrew/build/.+#"),
            array("ext-src", "#\.phpbrew/build/.+/ext$#"),
            array("include", "#\.phpbrew/php/.+/include$#"),
            array("etc",     "#\.phpbrew/php/.+/etc$#"),
            array("dist",    "#\.phpbrew/distfiles$#"),
            array("root",    "#\.phpbrew$#"),
            array("home",    "#\.phpbrew$#"),
        );
    }

    public function testUseLatestPHP() {
        $this->runCommand("phpbrew use latest");
    }

    /**
     * @outputBuffering enabled
     * @dataProvider argumentsProvider
     * @depends testUseLatestPHP
     */
    public function testPathCommand($arg, $pattern) {
        ob_start();
        $this->runCommandWithStdout("phpbrew path $arg");
        $path = ob_get_clean();
        $this->assertRegExp($pattern, $path);
    }
}

Fix test: use latest php

Fix test: use latest php


<?php
namespace App\Helper;

use App\Options\SuitwalkOptions;
use Interop\Container\ContainerInterface;

class SuitwalkOptionsHelperFactory
{
    public function __invoke(ContainerInterface $container)
    {
        return new SuitwalkOptionsHelper(
            $container->getServiceLocator()->get(SuitwalkOptions::class)
        );
    }
}

<?php
namespace App\Helper;

use App\Options\SuitwalkOptions;
use Interop\Container\ContainerInterface;

class SuitwalkOptionsHelperFactory
{
    public function __invoke(ContainerInterface $container)
    {
        return new SuitwalkOptionsHelper(
            $container->get(SuitwalkOptions::class)
        );
    }
}

Make use of service manager v3

Make use of service manager v3


<?php
/**
 * Created by PhpStorm.
 * User: daedeloth
 * Date: 25/12/14
 * Time: 15:55
 */

namespace CatLab\OAuth2\Mappers;

use Neuron\DB\Query;

class AccessTokenMapper {

	/**
	 * @param $token
	 * @return null|int
	 */
	public function getUserIdFromAccessToken ($token)
	{
		$data = Query::select (
			'oauth2_access_tokens',
			array (
				'user_id'
			),
			array (
				'access_token' => $token
			)
		)->execute ();

		if ($data)
		{
			return intval ($data[0]['user_id']);
		}
		return null;
	}

}

<?php
/**
 * Created by PhpStorm.
 * User: daedeloth
 * Date: 25/12/14
 * Time: 15:55
 */

namespace CatLab\OAuth2\Mappers;

use CatLab\Accounts\Models\User;
use Neuron\DB\Query;

class AccessTokenMapper {

	/**
	 * @param $token
	 * @return null|int
	 */
	public function getUserIdFromAccessToken ($token)
	{
		$data = Query::select (
			'oauth2_access_tokens',
			array (
				'user_id'
			),
			array (
				'access_token' => $token
			)
		)->execute ();

		if ($data)
		{
			return intval ($data[0]['user_id']);
		}
		return null;
	}

    /**
     * @param User $user
     */
	public function deleteFromUser(User $user)
    {
        Query::delete('oauth2_access_tokens', [ 'user_id' => $user->getId() ])->execute();
    }

}

Add method to remove all access tokens from a user.


<?php

namespace App\Api\Middleware;

use Closure;
use App\Api\Controllers\ApiController;
use Tymon\JWTAuth\Exceptions\JWTException;

class VerifyJWTToken extends ApiController
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string|null  $guard
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null)
    {
        try {
            \JWTAuth::parseToken()->authenticate();
        } catch (Tymon\JWTAuth\Exceptions\TokenExpiredException $e) {
            $errors[] = $this->buildErrorObject(
                'Token expired',
                $e->getMessage(),
                $request->path(),
                500
            );
        } catch (Tymon\JWTAuth\Exceptions\TokenInvalidException $e) {
            $errors[] = $this->buildErrorObject(
                'Token invalid',
                $e->getMessage(),
                $request->path(),
                500
            );
        } catch (Tymon\JWTAuth\Exceptions\JWTException $e) {
            $errors[] = $this->buildErrorObject(
                'Token unknown or not found',
                $e->getMessage(),
                $request->path(),
                500
            );
        }

        if (!empty($errors)) {
            return $this->apiErrorResponse($errors);
        }

        return $next($request);
    }
}

<?php

namespace App\Api\Middleware;

use Closure;
use App\Api\Controllers\ApiController;
use Tymon\JWTAuth\Exceptions\JWTException;

class VerifyJWTToken extends ApiController
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string|null  $guard
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null)
    {
        try {
            \JWTAuth::parseToken()->authenticate();
        } catch (JWTException $e) {
            $errors[] = $this->buildErrorObject(
                'Authorization error',
                $e->getMessage(),
                $request->path(),
                500
            );
        }

        if (!empty($errors)) {
            return $this->apiErrorResponse($errors);
        }

        return $next($request);
    }
}

Fix JWT auth middleware not catching JWTException's