<@php

namespace {namespace};

use CodeIgniter\Model;

class {class} extends Model
{
	protected $table      = '{table}';
	protected $primaryKey = 'id';

	protected $insertID = 0;
	protected $DBGroup  = '{dbgroup}';

	protected $returnType     = '{return}';
	protected $useSoftDeletes = false;
	protected $allowedFields  = [];

	// Dates
	protected $useTimestamps = false;
	protected $dateFormat    = 'datetime';
	protected $createdField  = 'created_at';
	protected $updatedField  = 'updated_at';
	protected $deletedField  = 'deleted_at';
	protected $protectFields = true;

	// Validation
	protected $validationRules      = [];
	protected $validationMessages   = [];
	protected $skipValidation       = false;
	protected $cleanValidationRules = true;

	// Callbacks
	protected $allowCallbacks = true;
	protected $beforeInsert   = [];
	protected $afterInsert    = [];
	protected $beforeUpdate   = [];
	protected $afterUpdate    = [];
	protected $beforeFind     = [];
	protected $afterFind      = [];
	protected $beforeDelete   = [];
	protected $afterDelete    = [];
}

<@php

namespace {namespace};

use CodeIgniter\Model;

class {class} extends Model
{
	protected $table      = '{table}';
	protected $primaryKey = 'id';
	protected $useAutoIncrement = true;

	protected $insertID = 0;
	protected $DBGroup  = '{dbgroup}';

	protected $returnType     = '{return}';
	protected $useSoftDeletes = false;
	protected $allowedFields  = [];

	// Dates
	protected $useTimestamps = false;
	protected $dateFormat    = 'datetime';
	protected $createdField  = 'created_at';
	protected $updatedField  = 'updated_at';
	protected $deletedField  = 'deleted_at';
	protected $protectFields = true;

	// Validation
	protected $validationRules      = [];
	protected $validationMessages   = [];
	protected $skipValidation       = false;
	protected $cleanValidationRules = true;

	// Callbacks
	protected $allowCallbacks = true;
	protected $beforeInsert   = [];
	protected $afterInsert    = [];
	protected $beforeUpdate   = [];
	protected $afterUpdate    = [];
	protected $beforeFind     = [];
	protected $afterFind      = [];
	protected $beforeDelete   = [];
	protected $afterDelete    = [];
}

Add $useAutoIncrement property to model template


<?php

namespace fennecweb\ajax\listing;

use \fennecweb\WebService as WebService;

class TraitsTest extends \PHPUnit_Framework_TestCase
{

    public function testExecute()
    {
        //Test for error returned by user is not logged in
        list($service) = WebService::factory('listing/Traits');
        $results = ($service->execute(array('dbversion' => DEFAULT_DBVERSION, 'search' => '', 'limit' => '')));

        $expected = array(
            array(
                "name" => "PlantHabit",
                "trait_type_id" => 1,
                "frequency" => 48916
            )
        );
        $this->assertArraySubset($expected, $results);
    }
}

<?php

namespace fennecweb\ajax\listing;

use \fennecweb\WebService as WebService;

class TraitsTest extends \PHPUnit_Framework_TestCase
{

    public function testExecute()
    {
        //Test for error returned by user is not logged in
        list($service) = WebService::factory('listing/Traits');
        $results = ($service->execute(array('dbversion' => DEFAULT_DBVERSION, 'search' => '')));
        $expected = array(
            array(
                "name" => "PlantHabit",
                "trait_type_id" => 1,
                "frequency" => 48916
            )
        );
        $this->assertArraySubset($expected, $results);
    }
}

Fix test for Traits listing

Fix test for Traits listing


<?php

namespace BenTools\ETL\Tests\Iterator;

use BenTools\ETL\Iterator\CsvFileIterator;
use BenTools\ETL\Tests\TestSuite;
use PHPUnit\Framework\TestCase;

class CsvFileIteratorTest extends TestCase
{

    public function testIterator()
    {
        $file     = new \SplFileObject(TestSuite::getDataFile('dictators.csv'));
        $iterator = new CsvFileIterator($file);
        $this->assertEquals([
            [
                'country',
                'name',
            ],
            [
                'USA',
                'Donald Trump',
            ],
            [
                'Russia',
                'Vladimir Poutine',
            ],
        ], array_values(iterator_to_array($iterator)));
    }
}

<?php

namespace BenTools\ETL\Tests\Iterator;

use BenTools\ETL\Iterator\CsvFileIterator;
use BenTools\ETL\Tests\TestSuite;
use PHPUnit\Framework\TestCase;

class CsvFileIteratorTest extends TestCase
{

    public function testIterator()
    {
        $file     = new \SplFileObject(TestSuite::getDataFile('dictators.csv'));
        $iterator = new CsvFileIterator($file);
        $this->assertCount(3, $iterator);
        $this->assertEquals([
            [
                'country',
                'name',
            ],
            [
                'USA',
                'Donald Trump',
            ],
            [
                'Russia',
                'Vladimir Poutine',
            ],
        ], array_values(iterator_to_array($iterator)));

    }
}

Fix count() method that might not return a relevant result


<?php get_header(); ?>

<a href="<?php bloginfo('url'); ?>" title="<?php bloginfo('name'); ?>"><?php bloginfo('name'); ?>

<?php bloginfo('description'); ?>

			Download brewtah

	<?php dynamic_sidebar( 'homepage-widgets' ); ?>

<?php get_footer(); ?>

<?php get_header(); ?>

<a href="<?php bloginfo('url'); ?>" title="<?php bloginfo('name'); ?>"><?php bloginfo('name'); ?>

<?php bloginfo('description'); ?>

	<?php dynamic_sidebar( 'homepage-widgets' ); ?>

<?php get_footer(); ?>

Remove “download” button from homepage.

Remove “download” button from homepage.


<?php

$args = [];
$taxonomy = get_post_meta(get_the_ID(), 'praha_taxonomy', true);

if ($taxonomy) {
	$catName = strtolower(get_cat_name($taxonomy));
	$args['relatedTitle'] = 'Články k tématu ' . $catName . ':';

	$args['relatedQuery'] = new WP_Query([
		'cat' => $taxonomy,
		'posts_per_page' => 3,
	]);

	if ($args['relatedQuery']->max_num_pages > 1) {
		$args['relatedButton'] = [
			'label' => 'Všechny články k tématu ' . $catName,
			'link' => get_category_link($taxonomy),
		];
	}
}

view('singular', $args);

<?php

$args = [];
$taxonomy = get_post_meta(get_the_ID(), 'praha_taxonomy', true);

if ($taxonomy) {

	$relatedQuery = new WP_Query([
		'cat' => $taxonomy,
		'posts_per_page' => 3,
	]);

	if ($relatedQuery->post_count) {
		$args['relatedQuery'] = $relatedQuery;

		$catName = strtolower(get_cat_name($taxonomy));

		$args['relatedTitle'] = 'Články k tématu ' . $catName . ':';

		if ($args['relatedQuery']->max_num_pages > 1) {
			$args['relatedButton'] = [
				'label' => 'Všechny články k tématu ' . $catName,
				'link' => get_category_link($taxonomy),
			];
		}
	}
}

view('singular', $args);

Fix related posts show condition

Fix related posts show condition


<?php
class Kwf_Util_RobotsTxt
{
    public static function output()
    {
        $baseUrl = Kwf_Setup::getBaseUrl();
        $contents = "User-agent: *\n".
            "Disallow: $baseUrl/admin/\n".
            "Disallow: $baseUrl/kwf/util/kwc/render\n"; //used to load eg. lightbox content async, we don't want getting that indexed

        $contents .= "Sitemap: http".(isset($_SERVER['HTTPS']) ? 's' : '')."://"
                        .$_SERVER['HTTP_HOST'].$baseUrl."/sitemap.xml\n";

        Kwf_Media_Output::output(array(
            'contents' => $contents,
            'mimeType' => 'text/plain'
        ));
    }
}

<?php
class Kwf_Util_RobotsTxt
{
    public static function output()
    {
        $baseUrl = Kwf_Setup::getBaseUrl();
        $contents = "User-agent: *\n".
            "Disallow: $baseUrl/admin/\n";

        $contents .= "Sitemap: http".(isset($_SERVER['HTTPS']) ? 's' : '')."://"
                        .$_SERVER['HTTP_HOST'].$baseUrl."/sitemap.xml\n";

        Kwf_Media_Output::output(array(
            'contents' => $contents,
            'mimeType' => 'text/plain'
        ));
    }
}

Remove Disallow /kwf/util/kwc/render from robots.txt

GoogleBot executes JavaScript and complains about this resource being blocked


<?php

namespace AppBundle\API\Mapping;

use AppBundle\API\Webservice;
use AppBundle\User\FennecUser;
use Symfony\Component\HttpFoundation\ParameterBag;

class ByDbxrefId extends Webservice
{
    private $db;

    /**
     * @inheritdoc
     */
    public function execute(ParameterBag $query, FennecUser $user = null)
    {
        $this->db = $this->getManagerFromQuery($query)->getConnection();
        if(!$query->has('ids') || !is_array($query->get('ids')) || count($query->get('ids')) === 0){
            return array();
        }
        $ids = $query->get('ids');
        $result = array_fill_keys($ids, null);
        $placeholders = implode(',', array_fill(0, count($ids), '?'));
        $query_get_mapping = <<<EOF
SELECT fennec_id, identifier AS ncbi_taxid
    FROM fennec_dbxref
        WHERE db_id=(SELECT db_id FROM db WHERE name='ncbi_taxonomy')
        AND identifier IN ({$placeholders})
EOF;
        $stm_get_mapping = $this->db->prepare($query_get_mapping);
        $stm_get_mapping->execute($ids);

        while($row = $stm_get_mapping->fetch(\PDO::FETCH_ASSOC)){
            $result[$row['ncbi_taxid']] = $row['fennec_id'];
        }

        return $result;
    }
}

<?php

namespace AppBundle\API\Mapping;

use AppBundle\API\Webservice;
use AppBundle\User\FennecUser;
use Symfony\Component\HttpFoundation\ParameterBag;

class ByDbxrefId extends Webservice
{
    private $db;

    /**
     * @inheritdoc
     */
    public function execute(ParameterBag $query, FennecUser $user = null)
    {
        $this->db = $this->getManagerFromQuery($query)->getConnection();
        if(!$query->has('ids') || !is_array($query->get('ids')) || count($query->get('ids')) === 0 || !$query->has('db')){
            return array();
        }
        $ids = $query->get('ids');
        $result = array_fill_keys($ids, null);
        $placeholders = implode(',', array_fill(0, count($ids), '?'));
        $query_get_mapping = <<<EOF
SELECT fennec_id, identifier AS ncbi_taxid
    FROM fennec_dbxref
        WHERE db_id=(SELECT db_id FROM db WHERE name=?)
        AND identifier IN ({$placeholders})
EOF;
        $stm_get_mapping = $this->db->prepare($query_get_mapping);
        $stm_get_mapping->execute(array_merge([$query->get('db')], $ids));

        while($row = $stm_get_mapping->fetch(\PDO::FETCH_ASSOC)){
            $result[$row['ncbi_taxid']] = $row['fennec_id'];
        }

        return $result;
    }
}

Extend dbxref mapping service to work with arbitrary dbs


<?php

namespace FOS\HttpCacheBundle\HttpCache\Invalidation;

/**
 * An HTTP cache that supports invalidation by purging, that is, removing one
 * URL from the cache
 *
 */
interface PurgeInterface
{
    /**
     * Purge a URL
     *
     * @param string $url
     *
     * @return $this
     */
    public function purge($url);
}

<?php

namespace FOS\HttpCacheBundle\HttpCache\Invalidation;

/**
 * An HTTP cache that supports invalidation by purging, that is, removing one
 * URL from the cache
 *
 */
interface PurgeInterface
{
    /**
     * Purge a URL
     *
     * Purging a URL will remove the cache for the URL, including the query
     * string, with all its Vary variants.
     *
     * @param string $url
     *
     * @return $this
     */
    public function purge($url);
}

Add note on query string and variants

Add note on query string and variants


<?php

namespace Caffeinated\Repository\Listeners;

use Caffeinated\Repository\Contracts\Repository;

class RepositoryEventListener
{
    /**
     * Register the listeners for the subscriber.
     *
     * @param Illuminate\Events\Dispatcher $events
     */
    public function subscribe($events)
    {
        $events->listen('*.entity.created', __CLASS__.'@entityCreated');
        $events->listen('*.entity.updated', __CLASS__.'@entityUpdated');
        $events->listen('*.entity.deleted', __CLASS__.'@entityDeleted');
    }

    /**
     * Listen for the *.entity.created event.
     *
     * @param Repository $repository
     * @param mixed      $entity
     *
     * @return void
     */
    public function entityCreated(Repository $repository, $entity)
    {
        $repository->flushCache();
    }

    /**
     * Listen for the *.entity.updated event.
     *
     * @param Repository $repository
     * @param mixed      $entity
     *
     * @return void
     */
    public function entityUpdated(Repository $repository, $entity)
    {
        $repository->flushCache();
    }

    /**
     * Listen for the *.entity.deleted event.
     *
     * @param Repository $repository
     * @param mixed      $entity
     *
     * @return void
     */
    public function entityDeleted(Repository $repository, $entity)
    {
        $repository->flushCache();
    }
}

<?php

namespace Caffeinated\Repository\Listeners;

use Caffeinated\Repository\Contracts\Repository;

class RepositoryEventListener
{
    /**
     * Register the listeners for the subscriber.
     *
     * @param Illuminate\Events\Dispatcher $events
     */
    public function subscribe($events)
    {
        $events->listen('*.entity.created', __CLASS__.'@entityCreated');
        $events->listen('*.entity.updated', __CLASS__.'@entityUpdated');
        $events->listen('*.entity.deleted', __CLASS__.'@entityDeleted');
    }

    /**
     * Listen for the *.entity.created event.
     *
     * @param Repository $repository
     * @param mixed      $entity
     *
     * @return void
     */
    public function entityCreated($event, $data)
    {
        $repository = $data[0];

        $repository->flushCache();
    }

    /**
     * Listen for the *.entity.updated event.
     *
     * @param Repository $repository
     * @param mixed      $entity
     *
     * @return void
     */
    public function entityUpdated($event, $data)
    {
        $repository = $data[0];

        $repository->flushCache();
    }

    /**
     * Listen for the *.entity.deleted event.
     *
     * @param Repository $repository
     * @param mixed      $entity
     *
     * @return void
     */
    public function entityDeleted($event, $data)
    {
        $repository = $data[0];

        $repository->flushCache();
    }
}

Patch event listener for 5.4 support

Patch event listener for 5.4 support


Add ignition to exculded uris

Add ignition to exculded uris


<?php
	/*
	 * Site constants
	 *
	 * To change constants define them in config.inc.php
	 */

	/* SYSTEM */
	if(!defined('STANDARD_URL'))					define('STANDARD_URL','http://felixonline.co.uk/'); // standard site url
	if(!defined('ADMIN_URL'))					 	define('ADMIN_URL','http://felixonline.co.uk/engine/'); // url of engine page
	if(!defined('PRODUCTION_FLAG'))					define('PRODUCTION_FLAG', true); // if set to true css and js will be minified etc..
	if(!defined('AUTHENTICATION_SERVER'))			define('AUTHENTICATION_SERVER','dougal.union.ic.ac.uk'); // authentication server
	if(!defined('AUTHENTICATION_PATH'))				define('AUTHENTICATION_PATH','https://dougal.union.ic.ac.uk/media/felix/'); // authentication path

<?php
	/*
	 * Site constants
	 *
	 * To change constants define them in config.inc.php
	 */

	/* SYSTEM */
	if(!defined('STANDARD_URL'))					define('STANDARD_URL','http://felixonline.co.uk/'); // standard site url
	if(!defined('ADMIN_URL'))					 	define('ADMIN_URL','http://felixonline.co.uk/engine/'); // url of engine page
	if(!defined('PRODUCTION_FLAG'))					define('PRODUCTION_FLAG', true); // if set to true css and js will be minified etc.
	if(!defined('LOCAL'))							define('LOCAL', false); // if true then site is hosted locally - don't use pam_auth etc.
	if(!defined('AUTHENTICATION_SERVER'))			define('AUTHENTICATION_SERVER','dougal.union.ic.ac.uk'); // authentication server
	if(!defined('AUTHENTICATION_PATH'))				define('AUTHENTICATION_PATH','https://dougal.union.ic.ac.uk/media/felix/'); // authentication path

Define local as false if not set

Define local as false if not set


<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>
        @yield('title')
    </title>
    <link rel="stylesheet" href="{{ asset('css/app.css') }}" charset="utf-8">
    @yield('stylesheet')
</head>
<body>
@yield('content')
</body>
</html>

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>
        @yield('title')
    </title>
    <link rel="stylesheet" href="{{ \App\ElixirResource::asset('css/app.css') }}" charset="utf-8">
    @yield('stylesheet')
</head>
<body>
@yield('content')
</body>
</html>

Use our wrapper class to include the app.css


<?php

/**
 * Copyright 2016 Bitban Technologies, S.L.
 * Todos los derechos reservados.
 */

namespace Bitban\PhpCodeQualityTools;

class PhpCodeQualityTools
{
    const APP_NAME = 'Bitban Technologies PHP Code Quality Tools';
    const APP_VERSION = '0.9.3';
}

<?php

/**
 * Copyright 2016 Bitban Technologies, S.L.
 * Todos los derechos reservados.
 */

namespace Bitban\PhpCodeQualityTools;

class PhpCodeQualityTools
{
    const APP_NAME = 'Bitban Technologies PHP Code Quality Tools';
    const APP_VERSION = '0.9.4';
}

Update tool version to 0.9.4

Update tool version to 0.9.4


<?php
/***************************************************************************
 * @author           Pierre-Henry Soria <ph7software@gmail.com>
 * @category         PH7 Template Engine
 * @package          PH7 / Framework / Layout / Tpl / Engine / PH7Tpl / Syntax
 * @copyright        (c) 2018, Pierre-Henry Soria. All Rights Reserved.
 * @license          CC-BY License - http://creativecommons.org/licenses/by/3.0/
 ***************************************************************************/

namespace PH7\Framework\Layout\Tpl\Engine\PH7Tpl\Syntax;

defined('PH7') or exit('Restricted access');

interface Parsable
{
    public function autoIncludeStatements();

    public function includeStatements();

    public function phpOpeningTag();

    public function phpClosingTag();

    public function phpOpeningTagWithEchoFunction();

    public function ifStatement();

    public function elseifStatement();

    public function elseStatement();

    public function forLoopStatement();

    public function whileLoopStatement();

    public function eachLoopStatement();

    public function closingBlockStructures();

    public function variable();

    public function designModelFunction();

    public function escapeFunction();

    public function langFunctions();

    public function literalFunction();

    public function clearComment();
}

<?php
/***************************************************************************
 * @author           Pierre-Henry Soria <ph7software@gmail.com>
 * @category         PH7 Template Engine
 * @package          PH7 / Framework / Layout / Tpl / Engine / PH7Tpl / Syntax
 * @copyright        (c) 2018, Pierre-Henry Soria. All Rights Reserved.
 * @license          CC-BY License - http://creativecommons.org/licenses/by/3.0/
 ***************************************************************************/

namespace PH7\Framework\Layout\Tpl\Engine\PH7Tpl\Syntax;

interface Parsable
{
    public function autoIncludeStatements();

    public function includeStatements();

    public function phpOpeningTag();

    public function phpClosingTag();

    public function phpOpeningTagWithEchoFunction();

    public function ifStatement();

    public function elseifStatement();

    public function elseStatement();

    public function forLoopStatement();

    public function whileLoopStatement();

    public function eachLoopStatement();

    public function closingBlockStructures();

    public function variable();

    public function designModelFunction();

    public function escapeFunction();

    public function langFunctions();

    public function literalFunction();

    public function clearComment();
}

Remove useless "defined or exit" code

[pH7Tpl:Parsable] Remove useless "defined or exit" code


<?php

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

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

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

<?php

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

class CreatePollsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('polls', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned();
            $table->string('title');
            $table->text('desc');
            $table->timestamp('start')->nullable();
            $table->timestamp('end')->nullable();
            $table->string('status')->default('active');
            $table->string('type')->default('once');
            $table->timestamps();
            $table->softDeletes();
        });
    }

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

Add columns to polls table

Add columns to polls table


<?php

use Aedart\Overload\Interfaces\PropertyOverloadable;
use Aedart\Testing\TestCases\Unit\UnitTestCase;
use \Mockery as m;

/**
 * MockPropertyOverloadableTest
 *
 * @group integration
 * @group interfaces
 * @group property-overloadable-interface
 *
 * @author Alin Eugen Deac <aedart@gmail.com>
 */
class MockPropertyOverloadableTest extends UnitTestCase
{
    /**
     * @test
     */
    public function canMockPropertyOverloadableInterface()
    {
        $mock = m::mock(PropertyOverloadable::class);

        $this->assertNotNull($mock);
    }

}

<?php

use Aedart\Overload\Interfaces\PropertyOverloadable;
use Aedart\Testing\TestCases\Unit\UnitTestCase;
use \Mockery as m;

/**
 * MockPropertyOverloadableTest
 *
 * @group integration
 * @group interfaces
 * @group property-overloadable-interface
 *
 * @author Alin Eugen Deac <aedart@gmail.com>
 */
class MockPropertyOverloadableTest extends UnitTestCase
{
    /**
     * @test
     */
    public function canMockPropertyOverloadableInterfaceViaPhpUnit()
    {
        $this->createMock(PropertyOverloadable::class);

        $this->assertNotNull($mock);
    }

    /**
     * @test
     */
    public function canMockPropertyOverloadableInterfaceViaMockery()
    {
        $mock = m::mock(PropertyOverloadable::class);

        $this->assertNotNull($mock);
    }

}

Add another mock of interface test

Add another mock of interface test

This time via PHPUnit, which doesn't seem to have issues.


<?php

namespace SimpleSAML\Test\Auth;

use SimpleSAML\Auth\SourceFactory;
use SimpleSAML\Test\Utils\ClearStateTestCase;

/**
 * Tests for SimpleSAML_Auth_Source
 */
class SourceTest extends ClearStateTestCase
{
    public function testParseAuthSource()
    {
        $class = new \ReflectionClass('SimpleSAML_Auth_Source');
        $method = $class->getMethod('parseAuthSource');
        $method->setAccessible(true);

        // test direct instantiation of the auth source object
        $authSource = $method->invokeArgs(null, ['test', ['SimpleSAML\Test\Auth\TestAuthSource']]);
        $this->assertInstanceOf('SimpleSAML\Test\Auth\TestAuthSource', $authSource);

        // test instantiation via an auth source factory
        $authSource = $method->invokeArgs(null, ['test', ['SimpleSAML\Test\Auth\TestAuthSourceFactory']]);
        $this->assertInstanceOf('SimpleSAML\Test\Auth\TestAuthSource', $authSource);
    }
}

class TestAuthSource extends \SimpleSAML_Auth_Source
{
    public function authenticate(array &$state)
    {
    }
}

class TestAuthSourceFactory implements SourceFactory
{
    public function create(array $info, array $config)
    {
        return new TestAuthSource($info, $config);
    }
}

<?php

namespace SimpleSAML\Test\Auth;

use SimpleSAML\Auth\SourceFactory;
use SimpleSAML\Test\Utils\ClearStateTestCase;

/**
 * Tests for SimpleSAML_Auth_Source
 */
class SourceTest extends ClearStateTestCase
{
    public function testParseAuthSource()
    {
        $class = new \ReflectionClass('SimpleSAML_Auth_Source');
        $method = $class->getMethod('parseAuthSource');
        $method->setAccessible(true);

        // test direct instantiation of the auth source object
        $authSource = $method->invokeArgs(null, ['test', ['SimpleSAML\Test\Auth\TestAuthSource']]);
        $this->assertInstanceOf('SimpleSAML\Test\Auth\TestAuthSource', $authSource);

        // test instantiation via an auth source factory
        $authSource = $method->invokeArgs(null, ['test', ['SimpleSAML\Test\Auth\TestAuthSourceFactory']]);
        $this->assertInstanceOf('SimpleSAML\Test\Auth\TestAuthSource', $authSource);
    }
}

class TestAuthSource extends \SimpleSAML_Auth_Source
{
    public function authenticate(&$state)
    {
    }
}

class TestAuthSourceFactory implements SourceFactory
{
    public function create(array $info, array $config)
    {
        return new TestAuthSource($info, $config);
    }
}

Revert "Make signature of test auth source match that of class it extends"

This reverts commit a4dcf65abfa0cba1feed8ffba80be943b14fa67c.


<?php

return [
    /*
     * Set trusted proxy IP addresses.
     *
     * Both IPv4 and IPv6 addresses are
     * supported, along with CIDR notation.
     *
     * The "*" character is syntactic sugar
     * within TrustedProxy to trust any proxy
     * that connects directly to your server,
     * a requirement when you cannot know the address
     * of your proxy (e.g. if using Rackspace balancers).
     *
     * The "**" character is syntactic sugar within
     * TrustedProxy to trust not just any proxy that
     * connects directly to your server, but also
     * proxies that connect to those proxies, and all
     * the way back until you reach the original source
     * IP. It will mean that $request->getClientIp()
     * always gets the originating client IP, no matter
     * how many proxies that client's request has
     * subsequently passed through.
     */
    'proxies' => in_array(env('TRUSTED_PROXIES', []), ['*', '**']) ?
        env('TRUSTED_PROXIES') : explode(',', env('TRUSTED_PROXIES', null)),

    /*
     * Or, to trust all proxies that connect
     * directly to your server, uncomment this:
     */
    // 'proxies' => '*',

    /*
     * Or, to trust ALL proxies, including those that
     * are in a chain of forwarding, uncomment this:
     */
    // 'proxies' => '**',

    /*
     * Default Header Names
     *
     * Change these if the proxy does
     * not send the default header names.
     *
     * Note that headers such as X-Forwarded-For
     * are transformed to HTTP_X_FORWARDED_FOR format.
     *
     * The following are Symfony defaults, found in
     * \Symfony\Component\HttpFoundation\Request::$trustedHeaders
     */
    'headers' => \Illuminate\Http\Request::HEADER_X_FORWARDED_ALL,
];

<?php

return [
    /*
     * Set trusted proxy IP addresses.
     *
     * Both IPv4 and IPv6 addresses are
     * supported, along with CIDR notation.
     *
     * The "*" character is syntactic sugar
     * within TrustedProxy to trust any proxy
     * that connects directly to your server,
     * a requirement when you cannot know the address
     * of your proxy (e.g. if using Rackspace balancers).
     *
     * The "**" character is syntactic sugar within
     * TrustedProxy to trust not just any proxy that
     * connects directly to your server, but also
     * proxies that connect to those proxies, and all
     * the way back until you reach the original source
     * IP. It will mean that $request->getClientIp()
     * always gets the originating client IP, no matter
     * how many proxies that client's request has
     * subsequently passed through.
     */
    'proxies' => in_array(env('TRUSTED_PROXIES', []), ['*', '**']) ?
        env('TRUSTED_PROXIES') : explode(',', env('TRUSTED_PROXIES') ?? ''),
];

Fix bad config for PHP 8.1

Fix bad config for PHP 8.1


<?php

namespace Endroid\Tests\Sudoku;

use Endroid\Sudoku\Puzzle;

class PuzzleTest extends \PHPUnit_Framework_TestCase
{
    public function testSolveEasy()
    {
        // An easy puzzle
        $values = '
            003020600
            900305001
            001806400
            008102900
            700000008
            006708200
            002609500
            800203009
            005010300';

        // Create the object
        $sudoku = new Puzzle($values);
        $sudoku->solve();

        // Check if the puzzle is solved
        $this->assertTrue($sudoku->isSolved());
    }

    public function testSolveHard()
    {
        // A difficult puzzle
        $values = '
            800000000
            003600000
            070090200
            050007000
            000045700
            000100030
            001000068
            008500010
            090000400';

        // Create the object
        $sudoku = new Puzzle($values);
        $sudoku->solve();

        // Check if the puzzle is solved
        $this->assertTrue($sudoku->isSolved());
    }
}

<?php

namespace Endroid\Tests\Sudoku;

use Endroid\Sudoku\Puzzle;

class PuzzleTest extends \PHPUnit_Framework_TestCase
{
    public function testSolveEasy()
    {
        // An easy puzzle
        $values = '
            003020600
            900305001
            001806400
            008102900
            700000008
            006708200
            002609500
            800203009
            005010300';

        // Create the object
        $sudoku = new Puzzle($values);
        $sudoku = $sudoku->solve();

        // Check if the puzzle is solved
        $this->assertTrue($sudoku->isSolved());
    }

    public function testSolveHard()
    {
        // A difficult puzzle
        $values = '
            800000000
            003600000
            070090200
            050007000
            000045700
            000100030
            001000068
            008500010
            090000400';

        // Create the object
        $sudoku = new Puzzle($values);
        $sudoku = $sudoku->solve();

        // Check if the puzzle is solved
        $this->assertTrue($sudoku->isSolved());
    }
}

Use right result for determining success


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

session_start();

// Instantiate the app
$settings = require __DIR__ . '/../app/settings.php';
$app = new \Slim\App($settings);

// Set up dependencies
require __DIR__ . '/../app/dependencies.php';

// Register middleware
// e.g: $app->add(new \Slim\Csrf\Guard);

// Register routes
require __DIR__ . '/../app/routes.php';

// Run!
$app->run();

<?php

if (PHP_SAPI == 'cli-server') {
    // To help the built-in PHP dev server, check if the request was actually for
    // something which should probably be served as a static file
    $file = __DIR__ . $_SERVER['REQUEST_URI'];
    if (is_file($file)) {
        return false;
    }
}

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

session_start();

// Instantiate the app
$settings = require __DIR__ . '/../app/settings.php';
$app = new \Slim\App($settings);

// Set up dependencies
require __DIR__ . '/../app/dependencies.php';

// Register middleware
// e.g: $app->add(new \Slim\Csrf\Guard);

// Register routes
require __DIR__ . '/../app/routes.php';

// Run!
$app->run();

Add support for PHP's built-in server

Add support for PHP's built-in server


<?php
class Kwc_Box_TitleEditable_Events extends Kwc_Abstract_Events
{
    protected function _onOwnRowUpdate(Kwf_Component_Data $c, Kwf_Component_Event_Row_Abstract $event)
    {
        parent::_onOwnRowUpdate($c, $event);
        if (Kwc_Abstract::getFlag($c->parent->componentClass, 'subroot')) {
            $this->fireEvent(new Kwf_Component_Event_Component_RecursiveContentChanged(
                $this->_class, $c
            ));
        }
    }
}

<?php
class Kwc_Box_TitleEditable_Events extends Kwc_Abstract_Events
{
    protected function _onOwnRowUpdate(Kwf_Component_Data $c, Kwf_Component_Event_Row_Abstract $event)
    {
        parent::_onOwnRowUpdate($c, $event);
        if (Kwc_Abstract::getFlag($c->parent->componentClass, 'subroot') || $c->parent instanceof Kwf_Component_Data_Root) {
            $this->fireEvent(new Kwf_Component_Event_Component_RecursiveContentChanged(
                $this->_class, $c
            ));
        }
    }
}

Delete cache also when title is changed in root


<?php

namespace JWX\Util;

/**
 * Class offering Base64 encoding and decoding.
 */
class Base64
{
	/**
	 * Encode a string using base64url variant.
	 *
	 * @param string $data
	 * @return string
	 */
	public static function urlEncode($data) {
		return strtr(rtrim(base64_encode($data), "="), "+/", "-_");
	}

	/**
	 * Decode a string using base64url variant.
	 *
	 * @param string $data
	 * @throws \UnexpectedValueException
	 * @return string
	 */
	public static function urlDecode($data) {
		$data = strtr($data, "-_", "+/");
		switch (strlen($data) % 4) {
		case 0:
			break;
		case 2:
			$data .= "==";
			break;
		case 3:
			$data .= "=";
			break;
		default:
			throw new \UnexpectedValueException("Malformed base64url encoding.");
		}
		$data = base64_decode($data, true);
		if ($data === false) {
			throw new \UnexpectedValueException("Malformed base64 encoding.");
		}
		return $data;
	}
}

<?php

namespace JWX\Util;

/**
 * Class offering Base64 encoding and decoding.
 */
class Base64
{
	/**
	 * Encode a string using base64url variant.
	 *
	 * @link https://en.wikipedia.org/wiki/Base64#URL_applications
	 * @param string $data
	 * @return string
	 */
	public static function urlEncode($data) {
		return strtr(rtrim(base64_encode($data), "="), "+/", "-_");
	}

	/**
	 * Decode a string using base64url variant.
	 *
	 * @link https://en.wikipedia.org/wiki/Base64#URL_applications
	 * @param string $data
	 * @throws \UnexpectedValueException
	 * @return string
	 */
	public static function urlDecode($data) {
		$data = strtr($data, "-_", "+/");
		switch (strlen($data) % 4) {
		case 0:
			break;
		case 2:
			$data .= "==";
			break;
		case 3:
			$data .= "=";
			break;
		default:
			throw new \UnexpectedValueException("Malformed base64url encoding.");
		}
		$data = base64_decode($data, true);
		if ($data === false) {
			throw new \UnexpectedValueException("Malformed base64 encoding.");
		}
		return $data;
	}

	/**
	 * Check whether string is validly base64url encoded.
	 *
	 * @link https://en.wikipedia.org/wiki/Base64#URL_applications
	 * @param string $data
	 * @return bool
	 */
	public static function isValidURLEncoding($data) {
		return preg_match('#[A-Za-z0-9\-_]*#', $data) == 1;
	}
}

Add base64url encoding validation method


<?php
/**
 * Created by PhpStorm.
 * User: Vladimir
 * Date: 9/18/2015
 * Time: 12:38 AM
 */

namespace akavov\countries\widgets;
use dosamigos\selectize\SelectizeTextInput;
use akavov\countries\assets\CountriesAsset;
use yii\web\JsExpression;

class CountriesSelectizeTextInput extends SelectizeTextInput
{

    /**
     * @var array
     */
    public $customRender;
    /**
     * @inheritdoc
     */
    public function run(){
        $view = $this->getView();
        CountriesAsset::register($view);
        parent::run();
    }

    /**
     * @inheritdoc
     */
    public function registerClientScript()
    {

        if ($this->customRender !== null && !empty($this->customRender)) {

            foreach($this->customRender as $template => $templateValue){
                $this->clientOptions['render'][$template] = new JsExpression("function(item, escape_html){return $templateValue;}");
            }

        }

       parent::registerClientScript();
    }

}

<?php
/**
 * Created by PhpStorm.
 * User: Vladimir
 * Date: 9/18/2015
 * Time: 12:38 AM
 */

namespace akavov\countries\widgets;
use dosamigos\selectize\SelectizeTextInput;
use akavov\countries\assets\CountriesAsset;
use yii\web\JsExpression;

class CountriesSelectizeTextInput extends SelectizeTextInput
{

    /**
     * @var array
     */
    public $customRender;
    /**
     * @var array
     */
    private $patterns = array('/{/', '/}/');
    /**
     * @var array
     */
    private $replacement = array('\'+', '+\'');
    /**
     * @inheritdoc
     */
    public function run(){
        $view = $this->getView();
        CountriesAsset::register($view);
        parent::run();
    }

    /**
     * @inheritdoc
     */
    public function registerClientScript()
    {

        if ($this->customRender !== null && !empty($this->customRender)) {

            foreach($this->customRender as $template => $templateValue){
                $templateValue = preg_replace($this->patterns, $this->replacement, $templateValue);
                $this->clientOptions['render'][$template] = new JsExpression("function(item, escape_html){return '$templateValue';}");
            }

        }

       parent::registerClientScript();
    }

}

Add easy way to provide a customRender template


<?php

/**
 * This file is part of the PHP Telegram Bot example-bot package.
 * https://github.com/php-telegram-bot/example-bot/
 *
 * (c) PHP Telegram Bot Team
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

/**
 * Generic message command
 *
 * Gets executed when any type of message is sent.
 */

namespace Longman\TelegramBot\Commands\SystemCommands;

use Longman\TelegramBot\Commands\SystemCommand;
use Longman\TelegramBot\Entities\ServerResponse;
use Longman\TelegramBot\Request;

class GenericmessageCommand extends SystemCommand
{
    /**
     * @var string
     */
    protected $name = 'genericmessage';

    /**
     * @var string
     */
    protected $description = 'Handle generic message';

    /**
     * @var string
     */
    protected $version = '0.1.0';

    /**
     * Main command execution
     *
     * @return ServerResponse
     */
    public function execute(): ServerResponse
    {
        $message = $this->getMessage();
        $user_id = $message->getFrom()->getId();

        // Handle successful payment
        if ($payment = $message->getSuccessfulPayment()) {
            return PaymentCommand::handleSuccessfulPayment($payment, $user_id);
        }

        return Request::emptyResponse();
    }
}

<?php

/**
 * This file is part of the PHP Telegram Bot example-bot package.
 * https://github.com/php-telegram-bot/example-bot/
 *
 * (c) PHP Telegram Bot Team
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

/**
 * Generic message command
 *
 * Gets executed when any type of message is sent.
 */

namespace Longman\TelegramBot\Commands\SystemCommands;

use Longman\TelegramBot\Commands\SystemCommand;
use Longman\TelegramBot\Commands\UserCommands\PaymentCommand;
use Longman\TelegramBot\Entities\ServerResponse;
use Longman\TelegramBot\Request;

class GenericmessageCommand extends SystemCommand
{
    /**
     * @var string
     */
    protected $name = 'genericmessage';

    /**
     * @var string
     */
    protected $description = 'Handle generic message';

    /**
     * @var string
     */
    protected $version = '0.1.0';

    /**
     * Main command execution
     *
     * @return ServerResponse
     */
    public function execute(): ServerResponse
    {
        $message = $this->getMessage();
        $user_id = $message->getFrom()->getId();

        // Handle successful payment
        if ($payment = $message->getSuccessfulPayment()) {
            return PaymentCommand::handleSuccessfulPayment($payment, $user_id);
        }

        return Request::emptyResponse();
    }
}

Fix namespace for PaymentCommand class

Fix namespace for PaymentCommand class


<?php

namespace OuterEdge\Layout\Controller\Adminhtml\Elements;

use Magento\Backend\App\Action;

class Delete extends \Magento\Backend\App\Action
{

    /**
     * @param Action\Context $context
     */
    public function __construct(Action\Context $context)
    {
        parent::__construct($context);
    }

    /**
     * Delete action
     *
     * @return \Magento\Framework\Controller\ResultInterface
     */
    public function execute()
    {
        $id = $this->getRequest()->getParam('id_element');

        /** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */
        $resultRedirect = $this->resultRedirectFactory->create();
        if ($id) {
            try {

                $model = $this->_objectManager->create('OuterEdge\Layout\Model\Elements');
                $model->load($id);
                $model->delete();

                $this->messageManager->addSuccess(__('You deleted the element.'));
                return $resultRedirect->setPath('*/*/');
            } catch (\Exception $e) {
                $this->messageManager->addError($e->getMessage());
                return $resultRedirect->setPath('*/*/edit', ['id_element' => $id]);
            }
        }
        $this->messageManager->addError(__('We can\'t find a element to delete.'));
        return $resultRedirect->setPath('*/*/');
    }
}

<?php

namespace OuterEdge\Layout\Controller\Adminhtml\Elements;

use Magento\Backend\App\Action;

class Delete extends \Magento\Backend\App\Action
{

    /**
     * @param Action\Context $context
     */
    public function __construct(Action\Context $context)
    {
        parent::__construct($context);
    }

    /**
     * Delete action
     *
     * @return \Magento\Framework\Controller\ResultInterface
     */
    public function execute()
    {
        $id = $this->getRequest()->getParam('id_element');

        /** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */
        $resultRedirect = $this->resultRedirectFactory->create();
        if ($id) {
            try {

                $model = $this->_objectManager->create('OuterEdge\Layout\Model\Elements');
                $model->load($id);
                $model->delete();

                $this->messageManager->addSuccess(__('You deleted the element.'));
                return $resultRedirect->setPath('layout/groups/edit', ['id_group' => $model->getFkGroup()]);
            } catch (\Exception $e) {
                $this->messageManager->addError($e->getMessage());
                return $resultRedirect->setPath('*/*/edit', ['id_element' => $id]);
            }
        }
        $this->messageManager->addError(__('We can\'t find a element to delete.'));
        return $resultRedirect->setPath('*/*/');
    }
}

Fix redirect after delete element

Fix redirect after delete element


<?php

class Cache
{

    private function createCacheKey($key, $isUserValue, $userId = null) {

        $CC_CONFIG = Config::getConfig();
        $a = $CC_CONFIG["apiKey"][0];

        if ($isUserValue) {
                $cacheKey = "{$key}{$userId}{$a}";
        }
        else {
                $cacheKey = "{$key}{$a}";
        }

        return $cacheKey;
    }

    public function store($key, $value, $isUserValue, $userId = null) {

        $cacheKey = self::createCacheKey($key, $userId);
        //XXX: Disabling APC on SaaS because it turns out we have multiple webservers
        //     running, which means we have to use a distributed data cache like memcached.
        //return apc_store($cacheKey, $value);
        return false;
    }

    public function fetch($key, $isUserValue, $userId = null) {

        $cacheKey = self::createCacheKey($key, $isUserValue, $userId);
        //XXX: Disabling APC on SaaS because it turns out we have multiple webservers
        //     running, which means we have to use a distributed data cache like memcached.
        //return apc_fetch($cacheKey);
        return false;
    }

	public static function clear()
	{
	    apc_clear_cache('user');
	    apc_clear_cache();
	}
}

<?php

class Cache
{

    private function createCacheKey($key, $isUserValue, $userId = null) {

        $CC_CONFIG = Config::getConfig();
        $a = $CC_CONFIG["apiKey"][0];

        if ($isUserValue) {
                $cacheKey = "{$key}{$userId}{$a}";
        }
        else {
                $cacheKey = "{$key}{$a}";
        }

        return $cacheKey;
    }

    public function store($key, $value, $isUserValue, $userId = null) {

        $cacheKey = self::createCacheKey($key, $userId);
        //XXX: Disabling APC on SaaS because it turns out we have multiple webservers
        //     running, which means we have to use a distributed data cache like memcached.
        //return apc_store($cacheKey, $value);
        return false;
    }

    public function fetch($key, $isUserValue, $userId = null) {

        $cacheKey = self::createCacheKey($key, $isUserValue, $userId);
        //XXX: Disabling APC on SaaS because it turns out we have multiple webservers
        //     running, which means we have to use a distributed data cache like memcached.
        //return apc_fetch($cacheKey);
        return false;
    }

	public static function clear()
	{
	   // Disabled on SaaS
	   // apc_clear_cache('user');
	   // apc_clear_cache();
	}
}

Disable APC cache clearing on SaaS

Disable APC cache clearing on SaaS


{{ formatKey(key) }}

{{ formatValue(key, value) }}<button class="icon-info"></button>

Add loading spinner to the podcast details pane

Shown while waiting for the contents for the pane.


<?php

declare(strict_types=1);

namespace Sylius\Migrations;

use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;

/**
 * Auto-generated Migration: Please modify to your needs!
 */
final class Version20200309172908 extends AbstractMigration
{
    public function getDescription() : string
    {
        return '';
    }

    public function up(Schema $schema) : void
    {
        // this up() migration is auto-generated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');

        $this->addSql('ALTER TABLE sylius_product_variant ADD enabled TINYINT(1) NOT NULL');
    }

    public function down(Schema $schema) : void
    {
        // this down() migration is auto-generated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');

        $this->addSql('ALTER TABLE sylius_product_variant DROP enabled');
    }
}

<?php

declare(strict_types=1);

namespace Sylius\Migrations;

use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;

/**
 * Auto-generated Migration: Please modify to your needs!
 */
final class Version20200309172908 extends AbstractMigration
{
    public function getDescription() : string
    {
        return '';
    }

    public function up(Schema $schema) : void
    {
        // this up() migration is auto-generated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');

        $this->addSql('ALTER TABLE sylius_product_variant ADD enabled TINYINT(1) DEFAULT 1 NOT NULL');
    }

    public function down(Schema $schema) : void
    {
        // this down() migration is auto-generated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');

        $this->addSql('ALTER TABLE sylius_product_variant DROP enabled');
    }
}

Add default value to variant enabled column migration


<?php

namespace App\Console;

use App\Console\Commands\BackupRun;
use App\Console\Commands\ResetApiKeyCount;
use App\Console\Commands\UserCreate;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        UserCreate::class,
        ResetApiKeyCount::class,
        BackupRun::class,
    ];

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        // $schedule->command('inspire')
        //          ->hourly();
        $schedule->command('api-key:reset')->dailyAt('00:00');
    }

    /**
     * Register the Closure based commands for the application.
     *
     * @return void
     */
    protected function commands()
    {
        require base_path('routes/console.php');
    }
}

<?php

namespace App\Console;

use App\Console\Commands\BackupRun;
use App\Console\Commands\ResetApiKeyCount;
use App\Console\Commands\UserCreate;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        UserCreate::class,
        ResetApiKeyCount::class,
        BackupRun::class,
    ];

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        $schedule->command('api-key:reset')->dailyAt('00:00')->timezone('America/Los_Angeles');
    }

    /**
     * Register the Closure based commands for the application.
     *
     * @return void
     */
    protected function commands()
    {
        require base_path('routes/console.php');
    }
}

Add timezone on api reset

Add timezone on api reset


<?php

namespace App\Console;

use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        Commands\SecurityCheck::class,
        Commands\ParseCachedWebMentions::class,
        Commands\ReDownloadWebMentions::class,
        Commands\GenerateToken::class,
        Commands\UpdatePlacesURLs::class,
    ];

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        // $schedule->command('inspire')
        //          ->hourly();
    }

    /**
     * Register the Closure based commands for the application.
     *
     * @return void
     */
    protected function commands()
    {
        require base_path('routes/console.php');
    }
}

<?php

namespace App\Console;

use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        Commands\SecurityCheck::class,
        Commands\ParseCachedWebMentions::class,
        Commands\ReDownloadWebMentions::class,
        Commands\GenerateToken::class,
        //Commands\UpdatePlacesURLs::class,
    ];

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        // $schedule->command('inspire')
        //          ->hourly();
    }

    /**
     * Register the Closure based commands for the application.
     *
     * @return void
     */
    protected function commands()
    {
        require base_path('routes/console.php');
    }
}

Test if new conosle command is causing travis issues


<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
        <meta http-equiv="x-ua-compatible" content="ie=edge">
        <link rel="stylesheet" href="{{ mix('css/main.css', 'assets/build') }}">
    </head>
    <body>
        @yield('body')
    </body>
</html>

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
        <meta http-equiv="x-ua-compatible" content="ie=edge">
        <link rel="stylesheet" href="{{ mix('css/main.css', 'assets/build') }}">
    </head>
    <body>
        @yield('body')
        <script type="text/javascript" src="{{ mix('js/main.js', 'assets/build') }}"></script>
    </body>
</html>

Add script to master layout

Add script to master layout


<?php
namespace Sandhje\Spanner\Adapter;

/**
 *
 * @author Sandhje
 *
 */
class BaseAdapter
{
    protected function mergeConfig($baseConfig, $environmentConfig)
    {
        if(is_array($baseConfig) && is_array($environmentConfig)) {
            return array_replace_recursive($baseConfig, $environmentConfig);
        } else if(is_array($environmentConfig)) {
            return $environmentConfig;
        } else if(is_array($baseConfig)) {
            return $baseConfig;
        } else {
            return false;
        }
    }
}

?>

<?php
namespace Sandhje\Spanner\Adapter;

/**
 *
 * @author Sandhje
 *
 */
class BaseAdapter
{

    protected function mergeConfig()
    {
        $result = array();

        $arg_list = func_get_args();
        for ($i = 0; $i < func_num_args(); $i++) {
            if(is_array($arg_list[$i])) {
                $result = array_replace_recursive($result, $arg_list[$i]);
            }
        }

        return $result;
    }
}

?>

Allow merging of multiple arrays

Allow merging of multiple arrays


<?php

namespace RandomState\LaravelApi\Http\Routing;

use Illuminate\Contracts\Routing\Registrar;
use Illuminate\Contracts\Support\Responsable;
use ArrayObject;
use Illuminate\Support\Facades\App;
use JsonSerializable;
use Illuminate\Http\Response;
use Illuminate\Http\JsonResponse;
use Illuminate\Contracts\Support\Jsonable;
use Illuminate\Contracts\Support\Arrayable;
use Psr\Http\Message\ResponseInterface as PsrResponseInterface;
use RandomState\LaravelApi\Http\Response\ResponseFactory;
use Symfony\Bridge\PsrHttpMessage\Factory\HttpFoundationFactory;
use Symfony\Component\HttpFoundation\Response as SymfonyResponse;

class Router extends \Illuminate\Routing\Router implements Registrar {

	/**
	 * @var \Illuminate\Routing\Router
	 */
	protected $router;

	public static function prepareResponse($request, $response)
	{
		if($response instanceof Responsable)
		{
			$response = $response->toResponse($request);
		}

		if($response instanceof PsrResponseInterface)
		{
			$response = (new HttpFoundationFactory)->createResponse($response);
		}
		elseif( ! $response instanceof SymfonyResponse)
		{
			$response = App::make(ResponseFactory::class)->build($response);
			$response = new Response($response);
		}
		elseif( ! $response instanceof SymfonyResponse &&
		          ($response instanceof Arrayable ||
		           $response instanceof Jsonable ||
		           $response instanceof ArrayObject ||
		           $response instanceof JsonSerializable ||
		           is_array($response)))
		{
			$response = new JsonResponse($response);
		}

		if($response->getStatusCode() === Response::HTTP_NOT_MODIFIED)
		{
			$response->setNotModified();
		}

		return $response->prepare($request);
	}
}

<?php

namespace RandomState\LaravelApi\Http\Routing;

use Illuminate\Contracts\Routing\Registrar;
use RandomState\LaravelApi\Http\Response\ResponseFactory;

class Router extends \Illuminate\Routing\Router implements Registrar {

	/**
	 * @var \Illuminate\Routing\Router
	 */
	protected $router;

	public static function prepareResponse($request, $response)
	{
		$response = app(ResponseFactory::class)->build($response);

		return parent::prepareResponse($request,$response);
	}
}

Clean up router to defer to base router as much as possible.


<?php

declare(strict_types=1);

use PhpCsFixer\Fixer\ClassNotation\FinalInternalClassFixer;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;

return static function (ContainerConfigurator $containerConfigurator): void {
    $containerConfigurator->import(__DIR__ . '/config.php');

    $services = $containerConfigurator->services();

    $services->defaults()
        ->public()
        ->autowire()
        ->autoconfigure();

    $services->set(FinalInternalClassFixer::class);

    $services->load('Symplify\CodingStandard\Fixer\\', __DIR__ . '/../src/Fixer')
        ->exclude([__DIR__ . '/../src/Fixer/Annotation']);
};

<?php

declare(strict_types=1);

use PhpCsFixer\Fixer\ClassNotation\FinalInternalClassFixer;
use PhpCsFixer\Fixer\Phpdoc\GeneralPhpdocAnnotationRemoveFixer;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;

return static function (ContainerConfigurator $containerConfigurator): void {
    $containerConfigurator->import(__DIR__ . '/config.php');

    $services = $containerConfigurator->services();

    $services->defaults()
        ->public()
        ->autowire()
        ->autoconfigure();

    $services->set(FinalInternalClassFixer::class);

    $services->load('Symplify\CodingStandard\Fixer\\', __DIR__ . '/../src/Fixer')
        ->exclude([__DIR__ . '/../src/Fixer/Annotation']);

    $services->set(GeneralPhpdocAnnotationRemoveFixer::class)
        ->call('configure', [[
            'annotations' => ['throws', 'author', 'package', 'group', 'covers'],
        ]]);
};

Add general doc removal for thorws

[ECS] Add general doc removal for thorws


<?php
/**
 * Gallery - A project for 'WPF - Moderne Webanwendungen' at
 * Cologne University of Applied Sciences.
 *
 * @author    Dominik Schilling <dominik.schilling@smail.fh-koeln.de>
 * @author    Laura Hermann
 * @author    Dario Vizzaccaro
 * @link      https://github.com/ocean90/wpfmw-gallery
 * @license   MIT
 */

// Set application paths (has trailing slash)
define( 'APP_PATH', dirname( dirname( __FILE__ ) ) . '/' );
define( 'APP_INCLUDES_PATH', APP_PATH . 'includes/' );
define( 'APP_VIEWS_PATH', APP_INCLUDES_PATH . 'views/' );

// Load some files
require APP_INCLUDES_PATH . 'autoloader.php';
require APP_INCLUDES_PATH . 'functions.php';

check_php_mysql_version();

// Init the application
global $app;
$app = new Application();

// Load config file
require APP_PATH . 'config.php';

// Init the database
$app->init_database();

// Parse the request
global $request;
$request = new Request();

// Check if application is installed
maybe_install();

<?php
/**
 * Gallery - A project for 'WPF - Moderne Webanwendungen' at
 * Cologne University of Applied Sciences.
 *
 * @author    Dominik Schilling <dominik.schilling@smail.fh-koeln.de>
 * @author    Laura Hermann
 * @author    Dario Vizzaccaro
 * @link      https://github.com/ocean90/wpfmw-gallery
 * @license   MIT
 */

// Set application paths (has trailing slash)
define( 'APP_PATH', dirname( dirname( __FILE__ ) ) . '/' );
define( 'APP_INCLUDES_PATH', APP_PATH . 'includes/' );
define( 'APP_VIEWS_PATH', APP_INCLUDES_PATH . 'views/' );

// Load some files
require APP_INCLUDES_PATH . 'autoloader.php';
require APP_INCLUDES_PATH . 'functions.php';

check_php_mysql_version();

// Init the application
global $app;
$app = new Application();

// Load config file
if ( is_file( APP_PATH . 'config.php' ) )
	require APP_PATH . 'config.php';
else
	die( 'Config Error: Please copy config-sample.php, change the settings and name it config.php!' );

// Init the database
$app->init_database();

// Parse the request
global $request;
$request = new Request();

// Check if application is installed
maybe_install();

Add notice if config.php is missing

Add notice if config.php is missing


<?php namespace Digbang\Security\Roles;

use Doctrine\Common\Collections\ArrayCollection;

trait RoleableTrait
{
	/**
	 * @type ArrayCollection
	 */
	protected $roles;

	/**
	 * {@inheritdoc}
	 */
	public function getRoles()
	{
		return $this->roles;
	}

	/**
	 * {@inheritdoc}
	 */
	public function inRole($role)
	{
		return $this->roles->exists(function($key, Role $myRole) use ($role){
			return $myRole->is($role);
		});
	}

	/**
	 * {@inheritdoc}
	 */
	public function addRole(Role $role)
	{
		$this->roles->add($role);
	}

	/**
	 * {@inheritdoc}
	 */
	public function removeRole(Role $role)
	{
		$this->roles->removeElement($role);
	}
}

<?php namespace Digbang\Security\Roles;

use Doctrine\Common\Collections\ArrayCollection;

trait RoleableTrait
{
	/**
	 * @type ArrayCollection
	 */
	protected $roles;

	/**
	 * {@inheritdoc}
	 */
	public function getRoles()
	{
		return $this->roles;
	}

	/**
	 * {@inheritdoc}
	 */
	public function inRole($role)
	{
		return $this->roles->exists(function($key, Role $myRole) use ($role){
			return $myRole->is($role);
		});
	}

	/**
	 * {@inheritdoc}
	 */
	public function addRole(Role $role)
	{
		if (! $this->inRole($role))
		{
			$this->roles->add($role);
		}
	}

	/**
	 * {@inheritdoc}
	 */
	public function removeRole(Role $role)
	{
		$this->roles->removeElement($role);
	}
}

Check if a Roleable already has the role before assigning it


<?php

use \photon\config\Container as Conf;

class SessionTest extends \photon\test\TestCase
{
    protected $conf;

    public function setup()
    {
        parent::setup();
        Conf::set('session_storage', '\photon\session\storage\MongoDB');
    }

    public function testEmptySession()
    {
        $req = \photon\test\HTTP::baseRequest();
        $mid = new \photon\session\Middleware();
        $this->assertEquals(false, $mid->process_request($req));

        $res = new \photon\http\Response('Hello!');
        $mid->process_response($req, $res);
    }

    public function testFilledSession()
    {

    }
}

<?php

use \photon\config\Container as Conf;

class SessionTest extends \photon\test\TestCase
{
    protected $conf;

    public function setup()
    {
        parent::setup();
        Conf::set('session_storage', '\photon\session\storage\MongoDB');
    }

    public function testEmptySession()
    {
        $req = \photon\test\HTTP::baseRequest();
        $mid = new \photon\session\Middleware();
        $this->assertEquals(false, $mid->process_request($req));

        $res = new \photon\http\Response('Hello!');
        $mid->process_response($req, $res);
        $this->assertEquals(false, isset($res->COOKIE['sid']));
        $this->assertEquals(false, isset($res->headers['Vary']));
    }

    public function testFilledSession()
    {
        // Receive a request, and store a counter in the answer
        $req = \photon\test\HTTP::baseRequest();
        $mid = new \photon\session\Middleware();
        $this->assertEquals(false, $mid->process_request($req));

        $req->session['cpt'] = 1234;
        $res = new \photon\http\Response('Hello!');
        $mid->process_response($req, $res);
        $this->assertEquals(true, isset($res->COOKIE['sid']));

        // Save the signed cookie
        $headers = $res->getHeaders();
        $rc = preg_match('/Set-Cookie: sid=([\w\.]+);/', $headers, $sid);
        $this->assertEquals($rc, 1);
        $sid = $sid[1];

        unset($req);
        unset($res);
        unset($mid);

        // Reload the session
        $req = \photon\test\HTTP::baseRequest('GET', '/', '', '', array(), array('cookie' => 'sid=' . $sid));
        $mid = new \photon\session\Middleware();
        $this->assertEquals(false, $mid->process_request($req));
        $cpt = $req->session['cpt'];
        $this->assertEquals(1234, $cpt);
    }
}

Add unit test which use the mongodb session backend


<?php

define('UNIT_TESTING', true);
define('HEYSTACK_BASE_PATH', dirname(__DIR__));
define('BASE_PATH', HEYSTACK_BASE_PATH);

if (!file_exists(BASE_PATH . '/vendor/autoload.php')) {
    echo 'You must first install the vendors using composer.' . PHP_EOL;
    exit(1);
}

$loader = require BASE_PATH . '/vendor/autoload.php';

use Symfony\Component\ClassLoader\ClassMapGenerator;

$loader->addClassMap(ClassMapGenerator::createMap(BASE_PATH . '/framework'));
$loader->add('Heystack\Core\Test', __DIR__);

Remove need for tests autoloading

Remove need for tests autoloading


<?php
namespace Concrete\Core\Routing;

use Concrete\Core\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Controller\ArgumentResolver;

class ClosureRouteAction implements RouteActionInterface
{

    protected $callback;

    /**
     * ClosureRouteAction constructor.
     * @param $callback
     */
    public function __construct($callback)
    {
        $this->callback = $callback;
    }

    public function __sleep()
    {
        unset($this->callback);
    }

    public function execute(Request $request, Route $route, $parameters)
    {
        $resolver = new ArgumentResolver();
        $arguments = $resolver->getArguments($request, $this->callback);
        $response = call_user_func_array($this->callback, $arguments);

        if (is_string($response)) {
            $r = new Response();
            $r->setContent($response);
            return $r;
        } else {
            return $response;
        }

    }
}

<?php

namespace Concrete\Core\Routing;

use Concrete\Core\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Controller\ArgumentResolver;

class ClosureRouteAction implements RouteActionInterface
{
    protected $callback;

    /**
     * ClosureRouteAction constructor.
     *
     * @param $callback
     */
    public function __construct($callback)
    {
        $this->callback = $callback;
    }

    public function __sleep()
    {
        unset($this->callback);
    }

    public function execute(Request $request, Route $route, $parameters)
    {
        $resolver = new ArgumentResolver();
        $arguments = $resolver->getArguments($request, $this->callback);
        ob_start();
        $response = call_user_func_array($this->callback, $arguments);
        $echoedResponse = ob_get_contents();
        ob_end_clean();

        if ($response instanceof Response) {
            return $response;
        }
        $r = new Response();
        if (is_string($response)) {
            $r->setContent($response);
        } else {
            $r->setContent($echoedResponse);
        }

        return $r;
    }
}

Make it so routes can echo their output

Make it so routes can echo their output


<?php
namespace RDM\Generics;

class TypedArrayObject extends \ArrayObject
{
    private $type;

    /**
     * {@inheritDoc}
     *
     * @param string $type The type of elements the array can contain.
     *                     Can be any of the primitive types or a class name.
     */
    public function __construct($type, $array = array())
    {
        $this->type = $type;
    }

    private function isValid($value)
    {
        switch ($this->type) {
            case 'bool':
                return is_bool($value);
            case 'int':
                return is_int($value);
            case 'float':
                return is_float($value);
            case 'string':
                return is_string($value);
            case 'array':
                return is_array($value);
            case 'resource':
                return is_resource($value);
            case 'callable':
                return is_callable($value);
            default:
                return is_a($value, $this->type);
        }
    }

    /**
     * {@inheritDoc}
     *
     * @throws \InvalidArgumentException If the given value was not of the specified type
     */
    public function offsetSet($offset, $value)
    {
        if ($this->isValid($value)) {
            parent::offsetSet($offset, $value);
        } else {
            throw new \InvalidArgumentException('The given value was not of type ' . $this->type);
        }
    }
}

<?php
namespace RDM\Generics;

class TypedArrayObject extends \ArrayObject
{
    private $type;

    /**
     * {@inheritDoc}
     *
     * @param string $type The type of elements the array can contain.
     *                     Can be any of the primitive types or a class name.
     */
    public function __construct($type, $array = array())
    {
        $this->type = $type;
    }

    private function isValid($value)
    {
        switch ($this->type) {
            case 'bool':
                return is_bool($value);
            case 'int':
                return is_int($value);
            case 'float':
                return is_float($value);
            case 'string':
                return is_string($value);
            case 'array':
                return is_array($value);
            case 'resource':
                return is_resource($value);
            case 'callable':
                return is_callable($value);
            default:
                return is_a($value, $this->type);
        }
    }

    /**
     * {@inheritDoc}
     *
     * @throws \InvalidArgumentException If the given value was not of the specified type
     */
    public function offsetSet($offset, $value)
    {
        if ($this->isValid($value)) {
            parent::offsetSet($offset, $value);
        } else {
            throw new \InvalidArgumentException('The given value was not of type ' . $this->type);
        }
    }

    /**
     * {@inheritDoc}
     */
    public function exchangeArray($input)
    {
        foreach ($input as $item) {
            if (!$this->isValid($value)) {
                throw new \InvalidArgumentException('The given value was not of type ' . $this->type);
            }
        }

        parent::exchangeArray($input);
    }
}

Add type check when exchanging an array

Add type check when exchanging an array


<?php

namespace wcatron\CommonDBFramework;

abstract class DBObject {

    /**
     * @var DB Class name for default DB class used.
     */
    protected static $dbClass = DB::class;
    /**
     * @return string
     */
    public function getID() {

    }
    /**
     * @return DB
     */
    public static function getDBInstance() {
        $class = static::$dbClass;
        return $class::getInstance();
    }

    /**
     * @param $class string Class that inherits DB.
     */
    public static function setDBInstance($class) {
        static::$dbClass = $class;
    }
}

?>

<?php

namespace wcatron\CommonDBFramework;

abstract class DBObject {

    /**
     * @var DB Class name for default DB class used.
     */
    protected static $dbClass = DB::class;
    /**
     * @return string
     */
    public function getID() {

    }

    /**
     * @param $id string
     * @return static
     */
    public function getByID($id) {

    }
    /**
     * @return DB
     */
    public static function getDBInstance() {
        $class = static::$dbClass;
        return $class::getInstance();
    }

    /**
     * @param $class string Class that inherits DB.
     */
    public static function setDBInstance($class) {
        static::$dbClass = $class;
    }
}

?>

Add getID to DBobject force support for LinkedObject.


<?php namespace Codesleeve\Fixture\Facades;

use Illuminate\Support\Facades\Facade;

class ClassName extends Facade
{
	/**
     * Get the registered name of the component.
     *
     * @return string
     */
    protected static function getFacadeAccessor() { return 'fixture'; }
}

<?php namespace Codesleeve\Fixture\Facades;

use Illuminate\Support\Facades\Facade;

class Fixture extends Facade
{
	/**
     * Get the registered name of the component.
     *
     * @return string
     */
    protected static function getFacadeAccessor() { return 'fixture'; }
}

Add name to fixture facade.

Add name to fixture facade.

Changed the classname of the fixture facade so that it's now correctly
named 'Fixture'.


<?php

/*
 * Test bootstrapper. This leaves out all stuff registering services and
 * related to request dispatching.
 */

// Define our install type
if (!defined('INSTALL_TYPE')) {
    if (file_exists(__DIR__ . '/../../../../../vendor/bolt/bolt/')) {
        define('INSTALL_TYPE', 'composer');
    } else {
        define('INSTALL_TYPE', 'git');
    }
}

// Install base location
if (!defined('TEST_ROOT')) {
    define('TEST_ROOT', realpath(__DIR__ . '/../../'));
}

// PHPUnit's base location
if (!defined('PHPUNIT_ROOT')) {
    define('PHPUNIT_ROOT', realpath(TEST_ROOT . '/tests/phpunit/unit'));
}

// PHPUnit's temporary web root
if (!defined('PHPUNIT_WEBROOT')) {
    define('PHPUNIT_WEBROOT', PHPUNIT_ROOT . '/../web-root');
}

if (!defined('BOLT_AUTOLOAD')) {
    if (INSTALL_TYPE === 'composer') {
        define('BOLT_AUTOLOAD', TEST_ROOT . '/../../autoload.php');
    } else {
        define('BOLT_AUTOLOAD', TEST_ROOT . '/vendor/autoload.php');
    }

    // Load the autoloader
    require_once BOLT_AUTOLOAD;
}

// Path to Nut
if (!defined('NUT_PATH')) {
    define('NUT_PATH', realpath(__DIR__ . '/nutty'));
}

// Load the upload bootstrap
require_once 'unit/bootstraps/upload-bootstrap.php';

<?php

/*
 * Test bootstrapper. This leaves out all stuff registering services and
 * related to request dispatching.
 */

// Define our install type
if (!defined('INSTALL_TYPE')) {
    if (file_exists(__DIR__ . '/../../../../../vendor/bolt/bolt/')) {
        define('INSTALL_TYPE', 'composer');
    } else {
        define('INSTALL_TYPE', 'git');
    }
}

// Install base location
if (!defined('TEST_ROOT')) {
    define('TEST_ROOT', realpath(__DIR__ . '/../../'));
}

// PHPUnit's base location
if (!defined('PHPUNIT_ROOT')) {
    define('PHPUNIT_ROOT', realpath(TEST_ROOT . '/tests/phpunit/unit'));
}

// PHPUnit's temporary web root… It doesn't exist yet, so we can't realpath()
if (!defined('PHPUNIT_WEBROOT')) {
    define('PHPUNIT_WEBROOT', dirname(PHPUNIT_ROOT) . '/web-root');
}

if (!defined('BOLT_AUTOLOAD')) {
    if (INSTALL_TYPE === 'composer') {
        define('BOLT_AUTOLOAD', TEST_ROOT . '/../../autoload.php');
    } else {
        define('BOLT_AUTOLOAD', TEST_ROOT . '/vendor/autoload.php');
    }

    // Load the autoloader
    require_once BOLT_AUTOLOAD;
}

// Path to Nut
if (!defined('NUT_PATH')) {
    define('NUT_PATH', realpath(__DIR__ . '/nutty'));
}

// Load the upload bootstrap
require_once 'unit/bootstraps/upload-bootstrap.php';

[Tests] Set a real path for PHPUNIT_WEBROOT as we can't realpath() yet


<?php
/**
 * PHP version 5.6
 *
 * This source file is subject to the license that is bundled with this package in the file LICENSE.
 */
namespace specs\Ewallet\Accounts;

use Assert\InvalidArgumentException;
use Ewallet\Accounts\MemberId;
use PhpSpec\ObjectBehavior;

class MemberIdSpec extends ObjectBehavior
{
    function it_should_be_created_from_a_string()
    {
        $this->beConstructedThrough('with', ['abcd']);
        $this->value()->shouldBe('abcd');
    }

    function it_should_be_created_randomly_using_any_non_empty_value()
    {
        $this->beConstructedThrough('any', []);
        $this->value()->shouldNotBe('');
    }

    function it_should_not_be_created_from_an_empty_string()
    {
        $this->beConstructedThrough('with', ['']);
        $this
            ->shouldThrow(InvalidArgumentException::class)
            ->duringInstantiation()
        ;
    }

    function it_should_know_when_it_is_equal_to_another_id()
    {
        $this->beConstructedThrough('with', ['abcd']);
        $this->equals(MemberId::with('abcd'))->shouldBe(true);
    }

    function it_should_be_casted_to_string()
    {
        $this->beConstructedThrough('with', ['abcd']);
        $this->__toString()->shouldBe('abcd');
    }
}

<?php
/**
 * PHP version 5.6
 *
 * This source file is subject to the license that is bundled with this package in the file LICENSE.
 */
namespace specs\Ewallet\Accounts;

use Assert\InvalidArgumentException;
use Ewallet\Accounts\MemberId;
use PhpSpec\ObjectBehavior;

class MemberIdSpec extends ObjectBehavior
{
    function it_should_be_created_from_a_string()
    {
        $this->beConstructedThrough('with', ['abcd']);
        $this->value()->shouldBe('abcd');
    }

    function it_should_not_be_created_from_an_empty_string()
    {
        $this->beConstructedThrough('with', ['']);
        $this
            ->shouldThrow(InvalidArgumentException::class)
            ->duringInstantiation()
        ;
    }

    function it_should_know_when_it_is_equal_to_another_id()
    {
        $this->beConstructedThrough('with', ['abcd']);
        $this->equals(MemberId::with('abcd'))->shouldBe(true);
    }

    function it_should_be_casted_to_string()
    {
        $this->beConstructedThrough('with', ['abcd']);
        $this->__toString()->shouldBe('abcd');
    }
}

Remove spec for method MemberId::any, method was removed.


<?php
declare (strict_types = 1);

namespace GrottoPress\Jentil\Utilities\ThemeMods;

use GrottoPress\Jentil\Jentil;

class Colophon extends AbstractThemeMod
{
    /**
     * @var ThemeMods
     */
    private $themeMods;

    public function __construct(ThemeMods $theme_mods)
    {
        $this->themeMods = $theme_mods;

        $this->id = \apply_filters('jentil_colophon_mod_id', 'colophon');
        $this->default = $this->default();
    }

    public function get(): string
    {
        return $this->themeMods->utilities->shortTags->replace(parent::get());
    }

    private function default(): string
    {
        return \apply_filters(
            'jentil_colophon_mod_default',
            \sprintf(
                \esc_html__(
                    '© %1$s %2$s. Built with %3$s on %4$s',
                    'jentil'
                ),
                '{{this_year}}',
                '
                    {{site_name}}
                ',
                ''.
                    Jentil::NAME.
                '',
                'WordPress.'
            )
        );
    }
}

<?php
declare (strict_types = 1);

namespace GrottoPress\Jentil\Utilities\ThemeMods;

use GrottoPress\Jentil\Jentil;

class Colophon extends AbstractThemeMod
{
    /**
     * @var ThemeMods
     */
    private $themeMods;

    public function __construct(ThemeMods $theme_mods)
    {
        $this->themeMods = $theme_mods;

        $this->id = \apply_filters('jentil_colophon_mod_id', 'colophon');
        $this->default = $this->default();
    }

    public function get(): string
    {
        return $this->themeMods->utilities->shortTags->replace(parent::get());
    }

    private function default(): string
    {
        return \apply_filters(
            'jentil_colophon_mod_default',
            \sprintf(
                \esc_html__(
                    '© %1$s %2$s. Built with %3$s on %4$s',
                    'jentil'
                ),
                '{{this_year}}',
                ''.
                    '{{site_name}}'.
                '',
                ''.
                    Jentil::NAME.
                '',
                'WordPress.'
            )
        );
    }
}

Remove whitespace before and after link text


<?php namespace Avetmiss;

use Avetmiss\Row;

class File
{

	protected $rows = array();
	protected $time;

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

	/**
	 *	Add a row to the file
	 */
	public function addRow(Row $row)
	{
		if(!$row->isValid())
		{
			throw new \Exception('Cant add invalid row');
		}

		$this->rows[] = $row;
	}

	/**
	 *	Exports the rows to a file
	 */
	public function export($name)
	{
		$file = fopen($name, 'w');

		foreach($this->rows as $row)
		{
			fwrite($file, $row ."\n");
		}

		fclose($file);
	}

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

<?php namespace Avetmiss;

use Avetmiss\Row;

class File
{

	protected $rows = array();
	protected $time;

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

	/**
	 *	Add a row to the file
	 */
	public function addRow(Row $row)
	{
		if(!$row->isValid())
		{
			throw new \Exception('Cant add invalid row');
		}

		$this->rows[] = $row;
	}

	/**
	 *	Exports the rows to a file
	 */
	public function export($name)
	{
		$file = fopen($name, 'w');

		foreach($this->rows as $row)
		{
			fwrite($file, $row ."\r\n");
		}

		fclose($file);
	}

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

Change the new line in file to match results from Avetmiss


<?php namespace App\Filters;

use App\Data\User;

class DiscussionFilters extends Filters
{
	protected $filters = ['by'];

	protected function by($username)
	{
		$user = User::where('name', $username)->firstOrFail();

		return $this->builder->where('user_id', $user->id);
	}
}

<?php namespace App\Filters;

use App\Data\User;

class DiscussionFilters extends Filters
{
	protected $filters = ['by', 'popular'];

	protected function by($username)
	{
		$user = User::where('name', $username)->firstOrFail();

		return $this->builder->where('user_id', $user->id);
	}

	protected function popular()
	{
		// Clear out any existing ordering that we have
		$this->builder->getQuery()->orders = [];

		$this->builder->orderBy('replies_count', 'desc');
	}
}

Add a filter for popular discussions

Add a filter for popular discussions


<?php

	require __DIR__.'/../includes/init.php';

	use App\RegExp;
	use App\HTTP;
	use App\Users;
	use App\CoreUtils;

	$permRedirectPattern = new RegExp('^\s*(.*?)\.php(\?.*)?$','i');
	if (preg_match($permRedirectPattern, $_SERVER['REQUEST_URI']))
		HTTP::redirect(preg_replace($permRedirectPattern, '$1$2', $_SERVER['REQUEST_URI']));
	$decoded_uri = urldecode(CoreUtils::trim($_SERVER['REQUEST_URI']));
	if (!preg_match($REWRITE_REGEX,strtok($decoded_uri,'?'),$matches)){
		Users::authenticate();
		CoreUtils::notFound();
	}

	$do = empty($matches[1]) ? 'index' : $matches[1];
	$data = $matches[2] ?? '';

	require INCPATH.'routes.php';
	/** @var $match array */
	$match = $router->match($decoded_uri);
	if (!isset($match['target']))
		CoreUtils::notFound();
	(\App\RouteHelper::processHandler($match['target']))($match['params']);

<?php

	require __DIR__.'/../includes/init.php';

	use App\RegExp;
	use App\HTTP;
	use App\Users;
	use App\CoreUtils;

	$permRedirectPattern = new RegExp('^\s*(.*?)\.php(\?.*)?$','i');
	if (preg_match($permRedirectPattern, $_SERVER['REQUEST_URI']))
		HTTP::redirect(preg_replace($permRedirectPattern, '$1$2', $_SERVER['REQUEST_URI']));
	$decoded_uri = CoreUtils::trim(urldecode($_SERVER['REQUEST_URI']));
	if (!preg_match($REWRITE_REGEX,strtok($decoded_uri,'?'),$matches)){
		Users::authenticate();
		CoreUtils::notFound();
	}

	$do = empty($matches[1]) ? 'index' : $matches[1];
	$data = $matches[2] ?? '';

	require INCPATH.'routes.php';
	/** @var $match array */
	$match = $router->match($decoded_uri);
	if (!isset($match['target']))
		CoreUtils::notFound();
	(\App\RouteHelper::processHandler($match['target']))($match['params']);

Fix whitespace at the end of the URL breaking routing


<?php

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

class CreateBudgetsTable extends Migration {
    public function up() {
        Schema::create('budgets', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('month');
            $table->integer('year');
            $table->float('amount');
        });
    }

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

<?php

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

class CreateBudgetsTable extends Migration {
    public function up() {
        Schema::create('budgets', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned();
            $table->integer('month');
            $table->integer('year');
            $table->float('amount');
        });
    }

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

Add user_id field to budgets migration

Add user_id field to budgets migration


@extends('layouts.offcanvas')

@section('sidebar')
@endsection

@section('main')

@lang("ui.about")

  {{ link_to_action('FriendsController@getGoals', trans('ui.goals.title_index'), $d->id) }}
  {{ link_to_action('FriendsController@getEndorsements', trans('ui.endorsements.title_index'), $d->id) }}

    @include('field', array('name' => 'avatar'))

    @include('field', array('name' => 'full_name'))
    @include('field', array('name' => 'email'))
    @include('field', array('name' => 'birth_date'))
    {{link_to_route('users.edit', trans('forms.edit'), $d->id, array('class' => 'button small right'))}}

  {{ link_to('tribe', trans('ui.back'), array('class' => 'left')) }}

@endsection

@extends('layouts.offcanvas')

@section('sidebar')
@endsection

@section('main')

@lang("ui.about")

  {{ link_to_action('FriendsController@getGoals', trans('ui.goals.title_index'), $d->id, array('class' => 'button small')) }}
  {{ link_to_action('FriendsController@getEndorsements', trans('ui.endorsements.title_index'), $d->id, array('class' => 'button small')) }}

    @include('field', array('name' => 'avatar'))

    @include('field', array('name' => 'full_name'))
    @include('field', array('name' => 'email'))
    @include('field', array('name' => 'birth_date'))
    {{link_to_route('users.edit', trans('forms.edit'), $d->id, array('class' => 'button small right'))}}

  {{ link_to('tribe', trans('ui.back'), array('class' => 'left')) }}

@endsection

Make buttons of person links

Make buttons of person links


<?php namespace App\Providers;

use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;

class EventServiceProvider extends ServiceProvider {

	/**
	 * The event handler mappings for the application.
	 *
	 * @var array
	 */
	protected $listen = [
		'event.name' => [
			'EventListener',
		],
	];

	/**
	 * Register any other events for your application.
	 *
	 * @return void
	 */
	public function boot()
	{
		//
	}

}

<?php namespace App\Providers;

use Illuminate\Contracts\Events\Dispatcher as DispatcherContract;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;

class EventServiceProvider extends ServiceProvider {

	/**
	 * The event handler mappings for the application.
	 *
	 * @var array
	 */
	protected $listen = [
		'event.name' => [
			'EventListener',
		],
	];

	/**
	 * Register any other events for your application.
	 *
	 * @param  \Illuminate\Contracts\Events\Dispatcher  $events
	 * @return void
	 */
	public function boot(DispatcherContract $events)
	{
		//
	}

}

Fix app event service provider contract

Fix app event service provider contract


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

$id= (int)$_REQUEST['txn'];
if (!$id)
  die_jsonp("no transaction specified.");

if ($txn['paid']) {
  die_jsonp("This order is already paid!");
}

$q= "UPDATE txn_line SET allocated = ordered WHERE txn = $id";
$r= $db->query($q)
  or die_jsonp($db->error);
$lines= $r->num_rows;

$q= "UPDATE txn SET filled = NOW() WHERE id = $id";
$r= $db->query($q)
  or die_jsonp($db->error);

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

generate_jsonp(array("success" => "Allocated all lines.",
                     "txn" => $txn,
                     "lines" => $r->num_rows));

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

$id= (int)$_REQUEST['txn'];
if (!$id)
  die_jsonp("no transaction specified.");

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

if ($txn['paid']) {
  die_jsonp("This order is already paid!");
}

$q= "UPDATE txn_line SET allocated = ordered WHERE txn = $id";
$r= $db->query($q)
  or die_jsonp($db->error);
$lines= $r->num_rows;

$q= "UPDATE txn SET filled = NOW() WHERE id = $id";
$r= $db->query($q)
  or die_jsonp($db->error);

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

generate_jsonp(array("success" => "Allocated all lines.",
                     "txn" => $txn,
                     "lines" => $r->num_rows));

Add missing call to txn_load()

Add missing call to txn_load()


<?php

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

namespace App\Http\Middleware;

use App\Libraries\OsuAuthorize;
use Carbon\Carbon;
use Closure;

class LegacyInterOpAuth
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $timestamp = $request->query('timestamp');
        $diff = Carbon::createFromTimestamp($timestamp)->diffInSeconds();
        $signature = $request->header('X-LIO-Signature');
        // don't use $request->fullUrl() because it returns normalised url.
        $fullUrl = $request->getSchemeAndHttpHost().$request->getRequestUri();
        $expected = hash_hmac('sha1', $fullUrl, config('osu.legacy.shared_interop_secret'));

        if (!present($signature) || !present($timestamp) || $diff > 300 || !hash_equals($expected, $signature)) {
            abort(403);
        }

        request()->attributes->set(OsuAuthorize::REQUEST_IS_INTEROP_KEY, true);

        return $next($request);
    }
}

<?php

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

namespace App\Http\Middleware;

use App\Libraries\OsuAuthorize;
use Carbon\Carbon;
use Closure;

class LegacyInterOpAuth
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $timestamp = $request->query('timestamp');
        $diff = Carbon::createFromTimestamp($timestamp)->diffInSeconds();
        $signature = $request->header('X-LIO-Signature');
        // don't use $request->fullUrl() because it returns normalised url.
        $fullUrl = $request->getSchemeAndHttpHost().$request->getRequestUri();
        $expected = hash_hmac('sha1', $fullUrl, config('osu.legacy.shared_interop_secret'));

        if (!present($signature) || !present($timestamp) || $diff > 300 || !hash_equals($expected, $signature)) {
            $reason = match (true) {
                !present($signature) => 'missing_signature',
                !present($timestamp) => 'missing_timestamp',
                $diff > 300 => 'expired_signature',
                !hash_equals($expected, $signature) => 'invalid_signature',
            };

            abort(403, "{$reason} ({$fullUrl})");
        }

        request()->attributes->set(OsuAuthorize::REQUEST_IS_INTEROP_KEY, true);

        return $next($request);
    }
}

Add more detailed interop auth error message


<?php namespace Coreplex\Crumbs\Renderers;

use Coreplex\Crumbs\Contracts\Renderer as Contract;
use Coreplex\Crumbs\Contracts\Container;

class Basic implements Contract {

    /**
     * Render the breadcrumbs from the container
     *
     * @return string
     */
    public function render(Container $container)
    {
        $rendered = '';

        if ($container->count() > 0) {
            $rendered .= '
';

            foreach ($container->getCrumbs() as $crumb) {
                $rendered .= '
';

                if ( ! $crumb->isCurrent() && $crumb->hasUrl()) {
                    $rendered .= 'getUrl() . '">';
                }

                $rendered .= $crumb->hasLabel() ? $crumb->getLabel() : $crumb->getUrl();

                if ( ! $crumb->isCurrent() && $crumb->hasUrl()) {
                    $rendered .= '';
                }

                $rendered .= '
';
            }

            $rendered .= '
';
        }

        return $rendered;
    }

}

<?php namespace Coreplex\Crumbs\Renderers;

use Coreplex\Crumbs\Contracts\Renderer as Contract;
use Coreplex\Crumbs\Contracts\Container;

class Basic implements Contract {

    /**
     * Render the breadcrumbs from the container
     *
     * @return string
     */
    public function render(Container $container)
    {
        $rendered = '';

        if ($container->count() > 0) {
            $rendered .= '
';

            foreach ($container->getCrumbs() as $crumb) {
                $rendered .= $crumb->isCurrent() ? '
' : '
';

                if ( ! $crumb->isCurrent() && $crumb->hasUrl()) {
                    $rendered .= 'getUrl() . '">';
                }

                $rendered .= $crumb->hasLabel() ? $crumb->getLabel() : $crumb->getUrl();

                if ( ! $crumb->isCurrent() && $crumb->hasUrl()) {
                    $rendered .= '';
                }

                $rendered .= '
';
            }

            $rendered .= '
';
        }

        return $rendered;
    }

}

Add active class to current breadcrumb

Add active class to current breadcrumb


<?
function smarty_block_set($params, $content, &$smarty) {
  if (!empty($params["var"])) {
    $mode = any($params["mode"], "set");

    $realsmarty = ($smarty instanceof Smarty_Internal_Template ? $smarty->parent : $smarty);

    if ($mode == "set")
      $realsmarty->varreplace[$params["var"]] = $content;
    else if ($mode == "append")
      $realsmarty->varreplace[$params["var"]] .= $content;
  }
}

<?
function smarty_block_set($params, $content, &$smarty) {
  if (!empty($params["var"])) {
    $mode = any($params["mode"], "set");

    $realsmarty = ($smarty instanceof Smarty_Internal_Template || $smarty instanceof TemplateManager ? $smarty->parent : $smarty);

    if ($mode == "set")
      $realsmarty->varreplace[$params["var"]] = $content;
    else if ($mode == "append")
      $realsmarty->varreplace[$params["var"]] .= $content;
  }
}

Fix for problems with some smarty installs


<?php
class Kwc_Editable_ComponentsModel extends Kwf_Model_Data_Abstract
{
    public function __construct(array $config = array())
    {
        $data = array();
        $components = Kwf_Component_Data_Root::getInstance()
            ->getComponentsByClass(array('Kwc_Editable_Component', 'Kwc_Editable_Trl_Component'));
        $user = Kwf_Registry::get('userModel')->getAuthedUser();
        foreach ($components as $c) {
            if (Kwf_Registry::get('acl')->getComponentAcl()->isAllowed($user, $c)) {
                $data[] = array(
                    'id' => $c->dbId,
                    'name' => $c->getComponent()->getNameForEdit(),
                    'content_component_class' => $c->getChildComponent('-content')->componentClass,
                );
            }
        }
        $this->_data = $data;
        parent::__construct($config);
    }
}

<?php
class Kwc_Editable_ComponentsModel extends Kwf_Model_Data_Abstract
{
    public function __construct(array $config = array())
    {
        $data = array();
        $components = Kwf_Component_Data_Root::getInstance()
            ->getComponentsByClass(array('Kwc_Editable_Component', 'Kwc_Editable_Trl_Component'), array('ignoreVisible' => true));
        $user = Kwf_Registry::get('userModel')->getAuthedUser();
        foreach ($components as $c) {
            if (Kwf_Registry::get('acl')->getComponentAcl()->isAllowed($user, $c)) {
                $data[] = array(
                    'id' => $c->dbId,
                    'name' => $c->getComponent()->getNameForEdit(),
                    'content_component_class' => $c->getChildComponent('-content')->componentClass,
                );
            }
        }
        $this->_data = $data;
        parent::__construct($config);
    }
}

Fix problem edit_component not shown in list if invisible

It's done like with mail_editable.


<?php namespace app\controllers;

use Yii;
use yii\web\Controller;

class SiteController extends Controller
{
    public function actionIndex() {
        $this->render('index');
    }
}

<?php namespace app\controllers;

use Yii;
use yii\web\Controller;

class SiteController extends Controller
{
    public function actionIndex() {
        return $this->render('index');
    }
}

Add return statement to site/index action


<?php

namespace Codeception\Event;

use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\EventDispatcher\Debug\TraceableEventDispatcherInterface;

trait DispatcherWrapper
{
    /**
     * Compatibility wrapper for dispatcher change between Symfony 4 and 5
     * @param EventDispatcher $dispatcher
     * @param string $eventType
     * @param Event $eventObject
     */
    protected function dispatch(EventDispatcher $dispatcher, $eventType, Event $eventObject)
    {
        //TraceableEventDispatcherInterface was introduced in symfony/event-dispatcher 2.5 and removed in 5.0
        if (!interface_exists(TraceableEventDispatcherInterface::class)) {
            //Symfony 5
            $dispatcher->dispatch($eventObject, $eventType);
        } else {
            //Symfony 2,3 or 4
            $dispatcher->dispatch($eventType, $eventObject);
        }
    }
}

<?php

namespace Codeception\Event;

use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface as ContractsEventDispatcherInterface;

trait DispatcherWrapper
{
    /**
     * Compatibility wrapper for dispatcher change between Symfony 4 and 5
     * @param EventDispatcher $dispatcher
     * @param string $eventType
     * @param Event $eventObject
     */
    protected function dispatch(EventDispatcher $dispatcher, $eventType, Event $eventObject)
    {
        // The `EventDispatcherInterface` of `Symfony\Contracts` is only implemented in Symfony 4.3 or higher
        if ($dispatcher instanceof ContractsEventDispatcherInterface) {
            //Symfony 4.3 or higher
            $dispatcher->dispatch($eventObject, $eventType);
        } else {
            //Symfony 4.2 or lower
            $dispatcher->dispatch($eventType, $eventObject);
        }
    }
}

Improve compatibility logic for the EventDispatcher


<?php

namespace App\Models\Access\Role\Traits\Relationship;

/**
 * Class RoleRelationship
 * @package App\Models\Access\Role\Traits\Relationship
 */
trait RoleRelationship
{
    /**
     * @return mixed
     */
    public function users()
    {
        return $this->belongsToMany(config('auth.model'), config('access.assigned_roles_table'), 'role_id', 'user_id');
    }

    /**
     * @return mixed
     */
    public function permissions()
    {
        return $this->belongsToMany(config('access.permission'), config('access.permission_role_table'), 'role_id', 'permission_id')
            ->orderBy('display_name', 'asc');
    }
}

<?php

namespace App\Models\Access\Role\Traits\Relationship;

/**
 * Class RoleRelationship
 * @package App\Models\Access\Role\Traits\Relationship
 */
trait RoleRelationship
{
    /**
     * @return mixed
     */
    public function users()
    {
        return $this->belongsToMany(config('auth.providers.users.model'), config('access.assigned_roles_table'), 'role_id', 'user_id');
    }

    /**
     * @return mixed
     */
    public function permissions()
    {
        return $this->belongsToMany(config('access.permission'), config('access.permission_role_table'), 'role_id', 'permission_id')
            ->orderBy('display_name', 'asc');
    }
}

Change auth.model to auth.providers.users.model in users function