<?php

namespace eHOSP\Http\Middleware;

use Closure;
use Auth;

class RoleMiddleware
{
    /**
     * Redirect to home if user has no permission, due to their user_type
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string   $roles
     * @return mixed
     */
    public function handle($request, Closure $next, ...$roles)
    {
        if (!in_array(Auth::user()->user_type, $roles)) {
            return redirect('home');
        }

        return $next($request);
    }
}

<?php

namespace eHOSP\Http\Middleware;

use Closure;
use Auth;

class RoleMiddleware
{
    /**
     * Redirect to home if user has no permission, due to their user_type
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string   $roles
     * @return mixed
     */
    public function handle($request, Closure $next, ...$roles)
    {
        if (!in_array(Auth::user()->user_type, $roles)) {
            // Send 404 error for security purposes
            abort(404);
            // return redirect('home');
        }

        return $next($request);
    }
}

Send 404 error for security purposes

Send 404 error for security purposes


<?php

/* Libre.fm -- a free network service for sharing your music listening habits

   Copyright (C) 2009 Libre.fm Project

   This program is free software: you can redistribute it and/or modify
   it under the terms of the GNU Affero General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU Affero General Public License for more details.

   You should have received a copy of the GNU Affero General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/

require_once('database.php');

function check_web_auth($username, $token, $timestamp, $api_key, $sk) {
	// Validates authentication using a web services token
	global $mdb2;

}

function check_standard_auth($username, $token, $timestamp) {
	// Validates authentication using a standard authentication token
	global $mdb2;

	$result = $mdb2->query("SELECT password FROM Users WHERE username=" . $mdb2->quote($username, 'text'));
	if (PEAR::isError($result) || !$result->numRows()) {
		// TODO: Log failures somewhere
		return false;
	}

	$pass = $result->fetchOne(0);
	$check_token = md5($pass . $timestamp);

	return $check_token == $token;
}

?>

<?php

/* Libre.fm -- a free network service for sharing your music listening habits

   Copyright (C) 2009 Libre.fm Project

   This program is free software: you can redistribute it and/or modify
   it under the terms of the GNU Affero General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU Affero General Public License for more details.

   You should have received a copy of the GNU Affero General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/

require_once('database.php');

function check_web_auth($username, $token, $timestamp, $api_key, $sk) {
	// Validates authentication using a web services token
	global $mdb2;

}

function check_standard_auth($username, $token, $timestamp) {
	// Validates authentication using a standard authentication token
	global $mdb2;

	$result = $mdb2->query("SELECT password FROM Users WHERE username ILIKE " . $mdb2->quote($username, 'text'));
	if (PEAR::isError($result) || !$result->numRows()) {
		// TODO: Log failures somewhere
		return false;
	}

	$pass = $result->fetchOne(0);
	$check_token = md5($pass . $timestamp);

	return $check_token == $token;
}

?>

Make committing with case-insensitive username possible


<?php

/**
 * Copyright 2022 SURFnet B.V.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace Surfnet\ServiceProviderDashboard\Application\Service;

use Surfnet\ServiceProviderDashboard\Application\ViewObject\Attribute;

interface AttributeServiceInterface
{
    /**
     * @return Attribute[]
     */
    public function getAttributeTypeAttributes(): array;
}

<?php

/**
 * Copyright 2022 SURFnet B.V.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace Surfnet\ServiceProviderDashboard\Application\Service;

use Surfnet\ServiceProviderDashboard\Application\Service\ValueObject\EntityMergeAttribute;
use Surfnet\ServiceProviderDashboard\Application\ViewObject\Attribute;

interface AttributeServiceInterface
{
    /**
     * @return Attribute[]
     */
    public function getAttributeTypeAttributes(): array;

    /**
     * @return EntityMergeAttribute[]
     */
    public function getEntityMergeAttributes(): array;

    public function getUrns(): array;
}

Add remaining AttributeService methods to the interface


<?php

use Illuminate\Database\Seeder;

class AuthorizationRoleSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $authorization = DB::table('authorizations');

        // admin
        foreach ($authorization->get() as $row) {
            DB::table('authorization_roles')->insert([
                'role_id' => 1,
                'authorization_id' => $row->id,
                'created_at' => sql_date()
            ]);
        }

        // employee
        foreach ($authorization->get() as $row) {
            DB::table('authorization_roles')->insert([
                'role_id' => 2,
                'authorization_id' => $row->id,
                'created_at' => sql_date()
            ]);
        }
    }
}

<?php

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;

class AuthorizationRoleSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $authorization = DB::table('authorizations');
        $roles = ['admin', 'employee'];

        foreach ($roles as $role) {
            $find_role = \App\Models\Role::where('slug', $role)->first();

            if ($find_role) {
                foreach ($authorization->get() as $row) {
                    DB::table('authorization_roles')->insert([
                        'role_id' => $find_role->id,
                        'authorization_id' => $row->id,
                        'created_at' => sql_date()
                    ]);
                }
            }
        }
    }
}

Update on role seeder for auth

Update on role seeder for auth


<?php

use Mimic\Functional as F;

/**
 * Unit Test for collectionNumberOperation Mimic library function.
 *
 * @since 0.1.0
 */
class CollectionNumberOperationFuncTest extends PHPUnit_Framework_TestCase {
	public function dataProvider() {
		return array(
			array(1, 0, 1, true),
			array(1.25, 0, 1.25, true),
			array('1', 0, '1', true),
			array('1.25', 0, '1.25', true),
			array('something', 1, 1, false),
		);
	}

	/**
	 * @dataProvider dataProvider
	 */
	public function testCallbackIsCalledAndPassesResult($element, $current, $expected, $willBeCalled) {
		$called = false;
		$callback = function($element, $current) use (&$called) {
			$called = true;
			return $element;
		};
		$operation = F\collectionNumberOperation($callback);
		$actual = $operation($element, $current);
		$this->assertEquals($willBeCalled, $called);
		$this->assertEquals($expected, $actual);
	}
}

<?php

use Mimic\Functional as F;

/**
 * Unit Test for collectionNumberOperation Mimic library function.
 *
 * @since 0.1.0
 *
 * @todo Need to use QuickTest library.
 */
class CollectionNumberOperationFuncTest extends PHPUnit_Framework_TestCase {
	public function dataProvider() {
		return array(
			array(1, 0, 1, true),
			array(1.25, 0, 1.25, true),
			array('1', 0, '1', true),
			array('1.25', 0, '1.25', true),
			array('something', 1, 1, false),
		);
	}

	/**
	 * @dataProvider dataProvider
	 */
	public function testCallbackIsCalledAndPassesResult($element, $current, $expected, $willBeCalled) {
		$called = false;
		$callback = function($element, $current) use (&$called) {
			$called = true;
			return $element;
		};
		$operation = F\collectionNumberOperation($callback);
		$actual = $operation($element, $current);
		$this->assertEquals($willBeCalled, $called);
		$this->assertEquals($expected, $actual);
	}
}

Add comment to switch to quicktest library.


<?php // $Id$

/////////////////////////////////////////////////////////////////////////////////
///  Code fragment to define the version of glossary
///  This fragment is called by moodle_needs_upgrading() and /admin/index.php
/////////////////////////////////////////////////////////////////////////////////

$module->version  = 2004091700;  // YYYYMMDD   = current module version
                                 //         X  = point release version 1,2,3 etc
                                 //          Y = increments between point releases
$module->requires = 2004091700;  // Requires this Moodle version
$module->cron     = 0;           // Period for cron to check this module (secs)

$release = "1.5 development";   // User-friendly version number

?>

<?php // $Id$

/////////////////////////////////////////////////////////////////////////////////
///  Code fragment to define the version of glossary
///  This fragment is called by moodle_needs_upgrading() and /admin/index.php
/////////////////////////////////////////////////////////////////////////////////

$module->version  = 2004091700;
$module->requires = 2004091700;  // Requires this Moodle version
$module->cron     = 0;           // Period for cron to check this module (secs)

$release = "1.5 development";   // User-friendly version number

?>

Undo las changes. Point releases are only for STABLE branches.


<?php
namespace Task;
use Mage\Task\AbstractTask;

class CreateBuildProperties extends AbstractTask {

  public function getName() {
    return 'Creating build.properties file...';
  }

  public function run() {

    $commandForBranch = "git status | grep -o \"origin/.*'\"";
    $output = $this->runCommandLocal($commandForBranch);
    $branch = str_replace("'", "", $output);

    $date = new \DateTime();

    $commandForCommit = 'git rev-parse HEAD';
    $output = $this->runCommandLocal($commandForCommit);
    $commit = $output;

    $fileContent = "branch=$branch\n" . "commit=$commit\n" . "date=" . $date->format("d/m/Y H:i") ."\n";

    file_put_contents(getcwd().'/build.properties', $fileContent);

    return $result;
  }
}

<?php
namespace Task;
use Mage\Task\AbstractTask;

class CreateBuildProperties extends AbstractTask {

  public function getName() {
    return 'Creating build.properties file...';
  }

  public function run() {

    $commandForBranch = "git status | grep -o \"origin/.*'\"";
    $output = "";
    $this->runCommandLocal($commandForBranch, $output);
    $branch = str_replace("'", "", $output);

    $date = new \DateTime();

    $commandForCommit = "git rev-parse HEAD";
    $result = $this->runCommandLocal($commandForCommit, $output);
    $commit = $output;

    $fileContent = "branch=$branch\n" . "commit=$commit\n" . "date=" . $date->format("d/m/Y H:i") ."\n";

    file_put_contents(getcwd().'/build.properties', $fileContent);

    return $result;
  }
}

Fix task to create build.properties

Fix task to create build.properties


<?php
/**
 * Allows editing of site banner data "globally".
 */
class SiteBannerSiteConfigExtension extends DataExtension
{

    public function updateCMSFields(FieldList $fields)
    {
        $fields->findOrMakeTab(
            'Root.SiteBanner',
            _t('SiteBanner.TabTitle', 'Site Banners')
        );

        $gridConfig = GridFieldConfig_RecordEditor::create();
        $grid = GridField::create('SiteBanners', null, SiteBanner::get())
            ->setConfig($gridConfig);

        if (class_exists('GridFieldSortableRows')) {
            $grid->getConfig()->addComponent(new GridFieldSortableRows('Sort'));
        }

        if (class_exists('Heyday\VersionedDataObjects\VersionedDataObjectDetailsForm')) {
            $gridConfig->removeComponentsByType('GridFieldDetailForm');
            $gridConfig->addComponent(new Heyday\VersionedDataObjects\VersionedDataObjectDetailsForm());
        }

        $fields->addFieldToTab(
            'Root.SiteBanner',
            $grid
        );
    }

    /**
     * Get all displayable site banners
     *
     * @return DataList
     */
    public function getSiteBanners()
    {
        return SiteBanner::get()->filterByCallback(function ($banner) {
            return $banner->isActive();
        });
    }
}

<?php
/**
 * Allows editing of site banner data "globally".
 */
class SiteBannerSiteConfigExtension extends DataExtension
{

    public function updateCMSFields(FieldList $fields)
    {
        $fields->findOrMakeTab(
            'Root.SiteBanner',
            _t('SiteBanner.TabTitle', 'Site Banners')
        );

        $gridConfig = GridFieldConfig_RecordEditor::create();
        $grid = GridField::create('SiteBanners', null, SiteBanner::get())
            ->setConfig($gridConfig);

        $gridConfig->removeComponentsByType('GridFieldPaginator');
        $gridConfig->removeComponentsByType('GridFieldPageCount');

        if (class_exists('GridFieldSortableRows')) {
            $grid->getConfig()->addComponent(new GridFieldSortableRows('Sort'));
        }

        if (class_exists('Heyday\VersionedDataObjects\VersionedDataObjectDetailsForm')) {
            $gridConfig->removeComponentsByType('GridFieldDetailForm');
            $gridConfig->addComponent(new Heyday\VersionedDataObjects\VersionedDataObjectDetailsForm());
        }

        $fields->addFieldToTab(
            'Root.SiteBanner',
            $grid
        );
    }

    /**
     * Get all displayable site banners
     *
     * @return DataList
     */
    public function getSiteBanners()
    {
        return SiteBanner::get()->filterByCallback(function ($banner) {
            return $banner->isActive();
        });
    }
}

Remove pagination, its overkill here

Remove pagination, its overkill here


<?php

/**
 *    Copyright 2016 ppy Pty. Ltd.
 *
 *    This file is part of osu!web. osu!web is distributed in the hopes of
 *    attracting more community contributions to the core ecosystem of osu!
 *
 *    osu!web is free software: you can redistribute it and/or modify
 *    it under the terms of the Affero GNU General Public License version 3
 *    as published by the Free Software Foundation.
 *
 *    osu!web is distributed WITHOUT ANY WARRANTY; without even the implied
 *    warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 *    See the GNU Affero General Public License for more details.
 *
 *    You should have received a copy of the GNU Affero General Public License
 *    along with osu!web.  If not, see <http://www.gnu.org/licenses/>.
 */

return [
    'authorizations' => [
        'update' => [
            'null_user' => 'Moet ingelogd zijn om te bewerken.',
            'system_generated' => 'Systeemgegenereerde posts kunnen niet bewerkt worden.',
            'wrong_user' => 'Moet de eigenaar zijn om te bewerken.',
        ],
    ],

    'system' => [
        'resolved' => [
            'true' => 'Gemarkeerd als opgelost door :user',
            'false' => 'Heropend door :user',
        ],
    ],
];

<?php

/**
 *    Copyright 2016 ppy Pty. Ltd.
 *
 *    This file is part of osu!web. osu!web is distributed in the hopes of
 *    attracting more community contributions to the core ecosystem of osu!
 *
 *    osu!web is free software: you can redistribute it and/or modify
 *    it under the terms of the Affero GNU General Public License version 3
 *    as published by the Free Software Foundation.
 *
 *    osu!web is distributed WITHOUT ANY WARRANTY; without even the implied
 *    warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 *    See the GNU Affero General Public License for more details.
 *
 *    You should have received a copy of the GNU Affero General Public License
 *    along with osu!web.  If not, see <http://www.gnu.org/licenses/>.
 */

return [
    'authorizations' => [
        'update' => [
            'null_user' => 'Moet ingelogd zijn om te bewerken.',
            'system_generated' => 'Systeemgegenereerde posts kunnen niet worden bewerkt.',
            'wrong_user' => 'Je moet de eigenaar zijn om te kunnen bewerken.',
        ],
    ],

    'system' => [
        'resolved' => [
            'true' => 'Gemarkeerd als opgelost door :user',
            'false' => 'Heropend door :user',
        ],
    ],
];

Fix Dutch translation of beatmap_discussion.php


<?php

class rfc_2047 {

  static function encoding_encode($str, $encoding = '7bit'){
        if($encoding == "quoted-printable") return quoted_printable_encode($str);
        elseif($encoding == "base64") return rtrim(chunk_split(base64_encode($str), 72),CRLF);
        else return $str; //8bit LOL
    }

  static function header_encode($str){
    if(preg_match("#[^\x20-\x7E]#", $str))
        $str = "=?UTF-8?Q?" . quoted_printable_encode($str)."?=";

    return $str;
  }

}

<?php

class rfc_2047 {

  static function encoding_encode($str, $encoding = '7bit'){
        if($encoding == "quoted-printable") return quoted_printable_encode($str);
        elseif($encoding == "base64") return rtrim(chunk_split(base64_encode($str), 72),CRLF);
        else return $str; //8bit LOL
    }

  static function header_encode($str){
    if(preg_match("#[^\x20-\x7E]#", $str))
        $str = "=?UTF-8?Q?" . php_legacy::quoted_printable_encode_filter($str,1024)."?=";

    return $str;
  }

}

Use php legacy quote printable encode (use word wrap)

git-svn-id: 4cd2d1688610a87757c9f4de95975a674329c79f@1735 b8ca103b-dd03-488c-9448-c80b36131af2


<?php

namespace geotime\Test;

use geotime\Database;
use geotime\Geotime;
use geotime\models\Map;
use PHPUnit_Framework_TestCase;

class MapTest extends \PHPUnit_Framework_TestCase {

    static function setUpBeforeClass() {
        Map::$log->info(__CLASS__." tests started");
    }

    static function tearDownAfterClass() {
        Map::$log->info(__CLASS__." tests ended");
    }

    protected function setUp() {
        Database::connect(Database::$testDbName);
    }

    protected function tearDown() {
        Geotime::clean();
    }

    public function testGenerateMap() {
        $date1Str = '2011-01-02';
        $date2Str = '2013-07-15';
        $imageFileName = 'testImage.svg';

        $map = Map::generateAndSaveReferences($imageFileName, $date1Str, $date2Str);
        $this->assertNotNull($map);
        $this->assertEquals($imageFileName, $map->getFileName());

        $territories = $map->getTerritories();
        $this->assertInstanceOf('MongoDate', $territories[0]->getPeriod()->getStart());
        $this->assertInstanceOf('MongoDate', $territories[0]->getPeriod()->getEnd());
    }
}

<?php

namespace geotime\Test;

use geotime\Database;
use geotime\Geotime;
use geotime\models\Map;
use PHPUnit_Framework_TestCase;

class MapTest extends \PHPUnit_Framework_TestCase {

    static function setUpBeforeClass() {
        Map::$log->info(__CLASS__." tests started");
    }

    static function tearDownAfterClass() {
        Map::$log->info(__CLASS__." tests ended");
    }

    protected function setUp() {
        Database::connect(Database::$testDbName);
    }

    protected function tearDown() {
        Geotime::clean();
    }

    public function testGenerateMap() {
        $date1Str = '2011-01-02';
        $date2Str = '2013-07-15';
        $imageFileName = 'testImage.svg';

        $map = Map::generateAndSaveReferences($imageFileName, $date1Str, $date2Str);
        $this->assertNotNull($map);
        $this->assertEquals($imageFileName, $map->getFileName());

        $territories = $map->getTerritories();
        $this->assertInstanceOf('MongoDate', $territories[0]->getPeriod()->getStart());
        $this->assertInstanceOf('MongoDate', $territories[0]->getPeriod()->getEnd());
    }

    public function testDeleteReferences() {
        $date1Str = '2011-01-02';
        $date2Str = '2013-07-15';
        $imageFileName = 'testImage.svg';

        $map = Map::generateAndSaveReferences($imageFileName, $date1Str, $date2Str);
        $map->save();
        $map->deleteReferences();

        /** @var Map $map */
        $map = Map::one(array());
        $this->assertEquals(0, count($map->getTerritories()));

    }
}

Add a test to delete the references of a map


<?php

class HashPathExtensionTest extends PHPUnit_Framework_TestCase
{

    public function testHashFile()
    {

        $hashPath = new HashPathExtension();

        $this->assertEquals(
            '2f7d9c3e0cfd47e8fcab0c12447b2bf0',
            $hashPath->HashFile(
                __DIR__ . '/test.txt',
                false
            )
        );

        $this->assertEquals(
            '',
            $hashPath->HashFile(
                'fakefile',
                false
            )
        );

    }

    public function testHashPath()
    {

        $hashPath = new HashPathExtension();

        $this->assertEquals(
            '/tests/test.v2f7d9c3e0cfd47e8fcab0c12447b2bf0.txt',
            $hashPath->HashPath(
                '/tests/test.txt',
                false
            )
        );

        $hashPath->setFormat('%s/%s.v.%s.%s');

        $this->assertEquals(
            '/tests/test.v.2f7d9c3e0cfd47e8fcab0c12447b2bf0.txt',
            $hashPath->HashPath(
                '/tests/test.txt',
                false
            )
        );

    }

}

<?php

class HashPathExtensionTest extends PHPUnit_Framework_TestCase
{

    public function testHashFile()
    {

        $hashPath = new HashPathExtension();

        $this->assertEquals(
            'L32cPgz9Rj8qwwSRHsr8A',
            $hashPath->HashFile(
                __DIR__ . '/test.txt',
                false
            )
        );

        $this->assertEquals(
            '',
            $hashPath->HashFile(
                'fakefile',
                false
            )
        );

    }

    public function testHashPath()
    {

        $hashPath = new HashPathExtension();

        $this->assertEquals(
            '/tests/test.vL32cPgz9Rj8qwwSRHsr8A.txt',
            $hashPath->HashPath(
                '/tests/test.txt',
                false
            )
        );

        $hashPath->setFormat('%s/%s.v.%s.%s');

        $this->assertEquals(
            '/tests/test.v.L32cPgz9Rj8qwwSRHsr8A.txt',
            $hashPath->HashPath(
                '/tests/test.txt',
                false
            )
        );

    }

}

Update unit tests to work with compact hash format added in d192cc4


<?php

namespace Moip\Tests\Resource;

use Moip\Tests\MoipTestCase;

/**
* class CustomerTest
*/
class CustomerTest extends MoipTestCase
{
	/**
	 * Test if const \Moip\Resource\Customer::PATH is valid.
	 */
	public function testShouldReceiveConstPathIsValid()
	{
		$path = 'customers';
		$const_path = constant('\Moip\Resource\Customer::PATH');

		$this->assertEquals($path, $const_path);
	}

	/**
	 * Test if const \Moip\Resource\Customer::ADDRESS_BILLING is valid.
	 */
	public function testShouldReceiveConstAddressBillingIsValid()
	{
		$address_billing = 'BILLING';
		$const_address_billing = constant('\Moip\Resource\Customer::ADDRESS_BILLING');

		$this->assertEquals($address_billing, $const_address_billing);
	}

	/**
	 * Test if const \Moip\Resource\Customer::ADDRESS_SHIPPING is valid.
	 */
	public function testShouldReceiveConstAddressShippingIsValid()
	{
		$address_shipping = 'SHIPPING';
		$const_address_shipping = constant('\Moip\Resource\Customer::ADDRESS_SHIPPING');

		$this->assertEquals($address_shipping, $const_address_shipping);
	}
}

<?php

namespace Moip\Tests\Resource;

use Moip\Tests\MoipTestCase;

/**
* class CustomerTest
*/
class CustomerTest extends MoipTestCase
{
	/**
	 * Test if const \Moip\Resource\Customer::PATH is valid.
	 */
	public function testShouldReceiveConstPathIsValid()
	{
		$path = 'customers';
		$const_path = constant('\Moip\Resource\Customer::PATH');

		$this->assertEquals($path, $const_path);
	}

	/**
	 * Test if const \Moip\Resource\Customer::ADDRESS_BILLING is valid.
	 */
	public function testShouldReceiveConstAddressBillingIsValid()
	{
		$address_billing = 'BILLING';
		$const_address_billing = constant('\Moip\Resource\Customer::ADDRESS_BILLING');

		$this->assertEquals($address_billing, $const_address_billing);
	}

	/**
	 * Test if const \Moip\Resource\Customer::ADDRESS_SHIPPING is valid.
	 */
	public function testShouldReceiveConstAddressShippingIsValid()
	{
		$address_shipping = 'SHIPPING';
		$const_address_shipping = constant('\Moip\Resource\Customer::ADDRESS_SHIPPING');

		$this->assertEquals($address_shipping, $const_address_shipping);
	}

	/**
	 * Test if const \Moip\Resource\Customer::ADDRESS_COUNTRY is valid.
	 */
	public function testShouldReceiveConstCountryIsValid()
	{
		$address_country = 'BRA';
		$const_address_country = constant('\Moip\Resource\Customer::ADDRESS_COUNTRY');

		$this->assertEquals($address_country, $const_address_country);
	}
}


<?php

namespace DevelMe;

use Illuminate\Support\ServiceProvider;

class SchemaServiceProvider extends ServiceProvider
{
    /**
     * Schema Wireframe Commands
     *
     * @type Array
     */
    private $commands = [
        'ControllerMake',
        'ModelMake',
        'SchemaAppMake',
        'ViewMake'
    ];

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        $this->registerCommands();
    }

    /**
     * Register all of the schema-wireframe commands.
     *
     * @return void
     */
    private function registerCommands()
    {
        $commands = $this->commands;

        foreach ($commands as $command) {
            $this->registerCommand($command);
        }

        $this->commands(
            'command.schema.app',
            'command.schema.controller',
            'command.schema.model',
            'command.schema.view'
        );
    }

    /**
     * Register ControllerMake Command
     *
     * @author Verron Knowles <Verron.Knowles@develme.com>
     * @return void
     */
    private function registerCommand($name)
    {
        $bind_name = strtolower($name);
        $this->app->singleton("command.schema.$bind_name", function ($app) use ($name) {
            return $app->make('DevelMe\Console\\'.$name.'Command');
        });
    }

}

<?php

namespace DevelMe;

use Illuminate\Support\ServiceProvider;

class SchemaServiceProvider extends ServiceProvider
{
    /**
     * Schema Wireframe Commands
     *
     * @type Array
     */
    private $commands = [
        'ControllerMake',
        'ModelMake',
        'SchemaAppMake',
        'ViewMake'
    ];

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        $this->registerCommands();
    }

    /**
     * Register all of the schema-wireframe commands.
     *
     * @return void
     */
    private function registerCommands()
    {
        $commands = $this->commands;
        $bind_names = [];

        foreach ($commands as $command) {
            $this->registerCommand($command);

            $bind_name = strtolower($command);
            $bind_names[] = "command.schema.$bind_name";
        }

        call_user_func_array([$this, 'commands'], $bind_names);
    }

    /**
     * Register ControllerMake Command
     *
     * @author Verron Knowles <Verron.Knowles@develme.com>
     * @return void
     */
    private function registerCommand($name)
    {
        $bind_name = strtolower($name);
        $this->app->singleton("command.schema.$bind_name", function ($app) use ($name) {
            return $app->make('DevelMe\Console\\'.$name.'Command');
        });
    }

}

Fix issues with schema service provider.


<?php

namespace LaraParse\Auth;

use Illuminate\Contracts\Auth\Registrar as RegistrarContract;
use Illuminate\Contracts\Validation\Factory as ValidationFactory;
use Illuminate\Support\MessageBag;
use LaraParse\Subclasses\User;
use Parse\ParseException;

class Registrar implements RegistrarContract
{
    /**
     * @var \Illuminate\Contracts\Validation\Factory
     */
    private $validator;

    /**
     * @param \Illuminate\Contracts\Validation\Factory $validator
     */
    public function __construct(ValidationFactory $validator)
    {
        $this->validator = $validator;
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array $data
     *
     * @return \Illuminate\Contracts\Validation\Validator
     */
    public function validator(array $data)
    {
        $messages = [
            'parse_user_unique' => 'Testing message.',
        ];

        $rules = [
            'email'    => ['required', 'email', 'max:255', 'parse_user_unique'],
            'password' => ['required', 'confirmed', 'min:6'],
        ];

        return $this->validator->make($data, $rules, $messages);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array $data
     *
     * @return User
     */
    public function create(array $data)
    {
        $user           = new User;
        $user->username = $data['email'];
        $user->password = $data['password'];
        $user->signUp();

        return $user;
    }
}

<?php

namespace LaraParse\Auth;

use Illuminate\Contracts\Auth\Registrar as RegistrarContract;
use Illuminate\Contracts\Validation\Factory as ValidationFactory;
use LaraParse\Subclasses\User;
use Parse\ParseObject;

class Registrar implements RegistrarContract
{
    /**
     * @var \Illuminate\Contracts\Validation\Factory
     */
    private $validator;

    /**
     * @param \Illuminate\Contracts\Validation\Factory $validator
     */
    public function __construct(ValidationFactory $validator)
    {
        $this->validator = $validator;
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array $data
     *
     * @return \Illuminate\Contracts\Validation\Validator
     */
    public function validator(array $data)
    {
        $messages = [
            'parse_user_unique' => 'Testing message.',
        ];

        $rules = [
            'email'    => ['required', 'email', 'max:255', 'parse_user_unique'],
            'password' => ['required', 'confirmed', 'min:6'],
        ];

        return $this->validator->make($data, $rules, $messages);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array $data
     *
     * @return User
     */
    public function create(array $data)
    {
        $userSubclass   = ParseObject::getRegisteredSubclass('_User');
        $user           = new $userSubclass;
        $user->username = $data['email'];
        $user->password = $data['password'];
        $user->signUp();

        return $user;
    }
}

Update registrar to dynamically fetch registered `_User` subclass


<?php
/**
 * Hooks
 *
 * @author Gerry Demaret <gerry@tigron.be>
 * @author Christophe Gosiau <christophe@tigron.be>
 */

class Hook_Admin {
	/**
	 * Bootstrap the application
	 *
	 * @access private
	 */
	public static function bootstrap(\Skeleton\Core\Web\Module $module) {
		// Bootsprap the application
		// Example: check if we need to log in, if we do and we aren't, redirect
		/*
		if ($module->is_login_required()) {
			if (!isset($_SESSION['user'])) {
				\Skeleton\Core\Web\Session::destroy();
				\Skeleton\Core\Web\Session::redirect('/login');
			}

			User::set($_SESSION['user']);
		}
		*/
	}

	/**
	 * Teardown of the application
	 *
	 * @access private
	 */
	public static function teardown(\Skeleton\Core\Web\Module $module) {
		// Do your cleanup jobs here
	}
}

<?php
/**
 * Hooks
 *
 * @author Gerry Demaret <gerry@tigron.be>
 * @author Christophe Gosiau <christophe@tigron.be>
 */

class Hook_Admin {
	/**
	 * Bootstrap the application
	 *
	 * @access private
	 */
	public static function bootstrap(\Skeleton\Core\Web\Module $module) {
		// Bootsprap the application
		// Example: check if we need to log in, if we do and we aren't, redirect
		/*
		if ($module->is_login_required()) {
			if (!isset($_SESSION['user'])) {
				\Skeleton\Core\Web\Session::destroy();
				\Skeleton\Core\Web\Session::redirect('/login');
			}

			User::set($_SESSION['user']);
		}

		// Assign the sticky session object to our template
		$template = \Skeleton\Core\Web\Template::get();
		$sticky_session = new \Skeleton\Core\Web\Session\Sticky();

		$template->add_environment('sticky_session', $sticky_session);

		// This is entirely optional, the use cases for having access to the
		// sticky session object in the module is are rather limited.
		$module->sticky_session = $sticky_session;

		// Clear the new session so we can start using it again
		\Skeleton\Core\Web\Session::clear_sticky();
		*/
	}

	/**
	 * Teardown of the application
	 *
	 * @access private
	 */
	public static function teardown(\Skeleton\Core\Web\Module $module) {
		// Do your cleanup jobs here
	}
}

Add sample hook using sticky session variables


<?php

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

namespace Pyz\Zed\ZedNavigation;

use Spryker\Zed\ZedNavigation\ZedNavigationConfig as SprykerZedNavigationConfig;

class ZedNavigationConfig extends SprykerZedNavigationConfig
{
    /**
     * @return array
     */
    public function getNavigationSchemaPathPattern()
    {
        $paths = parent::getNavigationSchemaPathPattern();
        $paths = $this->addSprykerFilePath($paths);

        return $paths;
    }

    /**
     * @project Only needed in Project, not in demoshop
     *
     * @param array $paths
     *
     * @return array
     */
    private function addSprykerFilePath($paths)
    {
        $paths[] = APPLICATION_VENDOR_DIR . '/spryker/spryker/Bundles/*/src/*/Zed/*/Communication';

        return $paths;
    }
}

<?php

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

namespace Pyz\Zed\ZedNavigation;

use Spryker\Zed\ZedNavigation\ZedNavigationConfig as SprykerZedNavigationConfig;

class ZedNavigationConfig extends SprykerZedNavigationConfig
{
    /**
     * @project Only needed in Project, not in demoshop
     *
     * @return array
     */
    public function getNavigationSchemaPathPattern()
    {
        $paths = parent::getNavigationSchemaPathPattern();
        $paths = $this->addSprykerFilePath($paths);

        return $paths;
    }

    /**
     * @project Only needed in Project, not in demoshop
     *
     * @param array $paths
     *
     * @return array
     */
    private function addSprykerFilePath($paths)
    {
        $paths[] = APPLICATION_VENDOR_DIR . '/spryker/spryker/Bundles/*/src/*/Zed/*/Communication';

        return $paths;
    }
}

Fix merge issue to demoshop.

Fix merge issue to demoshop.


@card(['heading' => !$hideTitle && $post_title != "" ? $post_title : ''])
    <div class="c-card__body">
        {!! apply_filters('the_content', apply_filters('Modularity/Display/SanitizeContent', $post_content)) !!}
    </div>
@endcard

@card()

        @if (!$hideTitle && !empty($post_title))

                @typography([
                    "element" => "h2",
                    "variant" => "h2",
                    "classList" => ['c-card__heading']
                ])
                    {{ $post_title }}
                @endtypography

        @endif

        {!! apply_filters('the_content', apply_filters('Modularity/Display/SanitizeContent', $post_content)) !!}

@endcard

Add titles to text cards

Add titles to text cards


<?php
/*
 * Example 6 - How to get the currently activated payment methods.
 */
try
{
    /*
     * Initialize the Mollie API library with your API key.
     *
     * See: https://www.mollie.com/dashboard/settings/profiles
     */
    require "initialize.php";
    /*
     * Get all the activated methods for this API key.
     */
    $methods = $mollie->methods->all();
    foreach ($methods as $method)
    {
        echo '
';
        echo 'image->size1x) . '" srcset="' . htmlspecialchars($method->image->size2x) .' 2x"> ';
        echo htmlspecialchars($method->description) . ' (' .  htmlspecialchars($method->id) . ')';
        echo '
';
    }
}
catch (Mollie_API_Exception $e)
{
    echo "API call failed: " . htmlspecialchars($e->getMessage());
}

<?php
/*
 * Example 6 - How to get the currently activated payment methods.
 */

use Mollie\Api\Exceptions\ApiException;

try
{
    /*
     * Initialize the Mollie API library with your API key.
     *
     * See: https://www.mollie.com/dashboard/settings/profiles
     */
    require "initialize.php";
    /*
     * Get all the activated methods for this API key.
     */
    $methods = $mollie->methods->all();
    foreach ($methods as $method)
    {
        echo '
';
        echo 'image->size1x) . '" srcset="' . htmlspecialchars($method->image->size2x) .' 2x"> ';
        echo htmlspecialchars($method->description) . ' (' .  htmlspecialchars($method->id) . ')';
        echo '
';
    }
}
catch (ApiException $e)
{
    echo "API call failed: " . htmlspecialchars($e->getMessage());
}

Use v2 api exception in example

Use v2 api exception in example


<?php

namespace Deamon\LoggerExtraBundle\Services;

class DeamonLoggerExtraContext
{
    public function __construct(
        private string $applicationName,
        private ?string $locale = null)
    {}

    public function getLocale(): ?string
    {
        return $this->locale;
    }

    public function getApplicationName(): string
    {
        return $this->applicationName;
    }
}

<?php

namespace Deamon\LoggerExtraBundle\Services;

class DeamonLoggerExtraContext
{
    public function __construct(
        private ?string $applicationName,
        private ?string $locale = null)
    {}

    public function getLocale(): ?string
    {
        return $this->locale;
    }

    public function getApplicationName(): ?string
    {
        return $this->applicationName;
    }
}

[Bug] Fix applicationName must be nullable in type inting


<?php

$config = array();

$config['db_dsnw'] = 'sqlite:////data/webmail/roundcube.db';
$config['default_host'] = 'localhost';
$config['smtp_server'] = 'localhost';
$config['smtp_port'] = 25;
$config['des_key'] = 'rcmail-!24ByteDESkey*Str';

// List of active plugins (in plugins/ directory)
$config['plugins'] = array(
    'archive',
    'zipdownload',
);

// skin name: folder from skins/
$config['skin'] = 'larry';

<?php

$config = array();

// Generals
$config['db_dsnw'] = 'sqlite:////data/webmail/roundcube.db';
$config['des_key'] = 'rcmail-!24ByteDESkey*Str';
$config['identities_level'] = 3;
$config['reply_all_mode'] = 1;

// Mail servers
$config['default_host'] = 'localhost';
$config['default_port'] = 143;
$config['smtp_server'] = 'localhost';
$config['smtp_port'] = 25;

// List of active plugins (in plugins/ directory)
$config['plugins'] = array(
    'archive',
    'zipdownload',
    'managesieve',
    'markasjunk'
);

// skin name: folder from skins/
$config['skin'] = 'larry';

Enable some sieve, spam and quota related plugins for roundcube


<?php

namespace Gitiki\Controller;

use Gitiki\Exception\InvalidSizeException,
    Gitiki\Gitiki,
    Gitiki\Image;

use Symfony\Component\HttpFoundation\Request;

class ImageController
{
    private $gitiki;

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

    public function imageAction(Request $request, $path, $_format)
    {
        $image = new Image($this->gitiki['wiki_dir'], $path.'.'.$_format);
        if (false === $image->isFile() || false === $image->isReadable()) {
            $this->gitiki->abort(404, sprintf('The image "%s" was not found.', $image->getRelativePath()));
        }

        if ($request->query->has('details')) {
            return $this->gitiki['twig']->render('image.html.twig', [
                'page' => $image,
            ]);
        }

        if (null !== $size = $request->query->get('size')) {
            try {
                return $this->gitiki->sendFile($this->gitiki['image']->resize($image, $size));
            } catch (InvalidSizeException $e) {
            }
        }

        return $this->gitiki->sendFile($image);
    }
}

<?php

namespace Gitiki\Controller;

use Gitiki\Exception\InvalidSizeException,
    Gitiki\Gitiki,
    Gitiki\Image;

use Symfony\Component\HttpFoundation\Request;

class ImageController
{
    private $gitiki;

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

    public function imageAction(Request $request, $path, $_format)
    {
        $image = new Image($this->gitiki['wiki_dir'], $path.'.'.$_format);
        if (false === $image->isFile() || false === $image->isReadable()) {
            $this->gitiki->abort(404, sprintf('The image "%s" was not found.', $image->getRelativePath()));
        }

        if ($request->query->has('details')) {
            return $this->gitiki['twig']->render('image.html.twig', [
                'page' => $image,
            ]);
        }

        $response = $this->gitiki->sendFile($image)->setMaxAge(0);

        if (!$response->isNotModified($request) && null !== $size = $request->query->get('size')) {
            try {
                $response->setFile($this->gitiki['image']->resize($image, $size), null, false, false);
            } catch (InvalidSizeException $e) {
            }
        }

        return $response;
    }
}

Check if request have cache header before resize an image


<?php

namespace OParl\Spec\Commands;

use App\Jobs\ResourcesUpdateJob;
use Illuminate\Console\Command;
use Illuminate\Foundation\Bus\DispatchesJobs;

class UpdateResourcesCommand extends Command
{
    use DispatchesJobs;

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'oparl:update:resources';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Update the resources';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->dispatch(new ResourcesUpdateJob());

        return 0;
    }
}

<?php

namespace OParl\Spec\Commands;

use App\Jobs\ResourcesUpdateJob;
use Illuminate\Console\Command;
use Illuminate\Foundation\Bus\DispatchesJobs;

class UpdateResourcesCommand extends Command
{
    use DispatchesJobs;

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'oparl:update:resources';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Update the resources';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->info('Updating validator');

        $this->dispatch(new ResourcesUpdateJob());

        return 0;
    }
}

Add informative output to resources update


<?php

namespace Tests\Browser;

use Laravel\Dusk\Browser;
use Tests\DuskTestCase;

class ExampleTest extends DuskTestCase
{
    /**
     * A basic browser test example.
     *
     * @return void
     */
    public function testBasicExample()
    {
        $this->browse(function (Browser $browser) {
            $browser->visit('/')
                    ->assertSee('New to Voten?');
        });
    }
}

<?php

namespace Tests\Browser;

use Illuminate\Foundation\Testing\DatabaseMigrations;
use Laravel\Dusk\Browser;
use Tests\DuskTestCase;

class ExampleTest extends DuskTestCase
{
    use DatabaseMigrations;

    /**
     * A basic browser test example.
     *
     * @return void
     */
    public function testBasicExample()
    {
        $this->browse(function (Browser $browser) {
            $browser->visit('/')
                    ->assertSee('New to Voten?');
        });
    }
}

Use migrations so that the test doesn't fail


<?php

namespace Gen;

class Blog
{
    protected $util;

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

    public function getIndex($dir, $skip = []) {

        $out = ['blogs' => []];

        foreach ($this->util->scan($dir, 'twig') as $entry) {
            if (!in_array($entry['file'], $skip)) {
                if (preg_match('#content(.*+)#', $entry['path'], $results)) {
                    $path = $results[1];
                    $file = $this->util->replaceExtension($entry['file'], 'html');
                    $title = ucfirst(str_replace('-', ' ', $this->util->replaceExtension($file, '')));

                    $out['blogs'][] = [
                        'title' => $title,
                        'path' => $path . '/' . $file
                    ];
                }
            }
        }
        return $out;
    }
}

<?php

namespace Gen;

class Blog
{
    protected $util;

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

    public function getIndex($dir, $skip = []) {

        $out = ['blogs' => []];

        foreach ($this->util->scan($dir, 'twig') as $entry) {
            if (!in_array($entry['file'], $skip)) {
                if (preg_match('#content(.*+)#', $entry['path'], $results)) {

                    $meta = [];
                    $metaFile = $this->util->replaceExtension($entry['file'], 'meta.php');
                    if (file_exists($entry['path'] . '/' . $metaFile)) {
                        $meta = (array) include $entry['path'] . '/' . $metaFile;
                    }

                    $partUrl = $results[1];
                    $file = $this->util->replaceExtension($entry['file'], 'html');
                    $title = ucfirst(str_replace('-', ' ', $this->util->replaceExtension($file, '')));

                    $out['blogs'][] = [
                        'title' => $title,
                        'path' => $path . '/' . $file
                    ];
                }
            }
        }
        return $out;
    }
}

Add the ability for individual blog entries to read a *.meta.php file.


<?php

namespace ArchiveAppBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;

class DefaultController extends Controller
{
    /**
     * @Route("/")
     */
    public function indexAction()
    {
        return $this->render('ArchiveAppBundle:Default:index.html.twig');
    }
}

<?php

namespace ArchiveAppBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;

class DefaultController extends Controller
{
    /**
     * @Route("/", name="home")
     */
    public function indexAction()
    {
        return $this->render('home.html.twig');
    }
}

Change to the default Application Controller


<?php
if (!empty($postresult)) {
	include 'includes/form-xmlresult.inc.php';

	echo formResult2Xml($postresult, $formmessages, $tplHelper);
}

if (empty($postresult)) {
	if (isset($formmessages)) {
		include "includes/form-messages.inc.php";
	} # if
}

<?php
    require "includes/form-messages.inc.php";

    showResults($result);

Update template to use the new DTO object instead of relying on the old system


<?php

namespace Tests;

use Laravel\Dusk\TestCase as BaseTestCase;
use Facebook\WebDriver\Chrome\ChromeOptions;
use Facebook\WebDriver\Remote\RemoteWebDriver;
use Facebook\WebDriver\Remote\DesiredCapabilities;
use Illuminate\Foundation\Testing\RefreshDatabase;

abstract class DuskTestCase extends BaseTestCase
{
    use CreatesApplication, RefreshDatabase, WithMocks, WithAuthentication;

    /**
     * The Faker generator, for creating test data.
     *
     * @var \Faker\Generator
     */
    protected $faker;

    /**
     * Setup the test environment.
     *
     * @return void
     */
    public function setUp()
    {
        parent::setUp();

        $this->configureMocks();
    }

    /**
     * Prepare for Dusk test execution.
     *
     * @beforeClass
     * @return void
     */
    public static function prepare()
    {
        static::startChromeDriver();
    }

    /**
     * Create the RemoteWebDriver instance.
     *
     * @return \Facebook\WebDriver\Remote\RemoteWebDriver
     */
    protected function driver()
    {
        $options = (new ChromeOptions)->addArguments([
            '--disable-gpu',
            '--headless',
            'no-sandbox',
        ]);

        return RemoteWebDriver::create(
            'http://localhost:9515', DesiredCapabilities::chrome()->setCapability(
                ChromeOptions::CAPABILITY, $options
            )
        );
    }
}

<?php

namespace Tests;

use Rogue\Models\User;
use Laravel\Dusk\TestCase as BaseTestCase;
use Facebook\WebDriver\Chrome\ChromeOptions;
use Facebook\WebDriver\Remote\RemoteWebDriver;
use Facebook\WebDriver\Remote\DesiredCapabilities;

abstract class DuskTestCase extends BaseTestCase
{
    use CreatesApplication, WithMocks, WithAuthentication;

    /**
     * The Faker generator, for creating test data.
     *
     * @var \Faker\Generator
     */
    protected $faker;

    /**
     * Get the default user for Dusk's login() helper.
     *
     * @return User
     */
    protected function user()
    {
        return factory(User::class, 'admin')->create();
    }

    /**
     * Setup the test environment.
     *
     * @return void
     */
    public function setUp()
    {
        parent::setUp();

        $this->configureMocks();
    }

    /**
     * Prepare for Dusk test execution.
     *
     * @beforeClass
     * @return void
     */
    public static function prepare()
    {
        static::startChromeDriver();
    }

    /**
     * Create the RemoteWebDriver instance.
     *
     * @return \Facebook\WebDriver\Remote\RemoteWebDriver
     */
    protected function driver()
    {
        $options = (new ChromeOptions)->addArguments([
            '--disable-gpu',
            '--headless',
            'no-sandbox',
        ]);

        return RemoteWebDriver::create(
            'http://localhost:9515', DesiredCapabilities::chrome()->setCapability(
                ChromeOptions::CAPABILITY, $options
            )
        );
    }
}

Disable RefreshDatabase & set default user.

The RefreshDatabase trait doesn't seem to work with Dusk, probably because the transaction isn't committed when request is made?


<?php
$home = drush_server_home();
// Solve the key file to use
$path = explode('/', dirname(__FILE__));
array_pop($path);
array_pop($path);
$path[] = '.vagrant';
$path = implode('/', $path);
$key = shell_exec('find ' . $path . ' -iname private_key');
if (!$key) {
  $key = $home . '/.vagrant.d/insecure_private_key';
}
$key = rtrim($key);

$aliases['vagrant'] = array(
  'parent' => '@parent',
  'site' => 'ansibleref',
  'env' => 'vagrant',
  'root' => '/vagrant/drupal/current',
  'remote-host' => 'local.ansibleref.com',
  'remote-user' => 'vagrant',
  'ssh-options' => '-i ' . $key,
);

<?php
$home = drush_server_home();
// Solve the key file to use
$path = explode('/', dirname(__FILE__));
array_pop($path);
array_pop($path);
$path[] = '.vagrant';
$path = implode('/', $path);
$key = shell_exec('find ' . $path . ' -iname private_key');
if (!$key) {
  $key = $home . '/.vagrant.d/insecure_private_key';
}
$key = rtrim($key);

$aliases['local'] = array(
  'parent' => '@parent',
  'site' => 'ansibleref',
  'env' => 'vagrant',
  'root' => '/vagrant/drupal/current',
  'remote-host' => 'local.ansibleref.com',
  'remote-user' => 'vagrant',
  'ssh-options' => '-i ' . $key,
);

Use local as alias name.

Use local as alias name.


<?php
/*
Template Name: Full Width - About Us
*/
get_header(); ?>

    <?php get_template_part( 'template-parts/part-main-navigation' ); ?>

Unique Layouts, Customize wireframes & User
					Interface Kit

				<button type="button" class="button">Take a Tour</button>

	<?php get_template_part('template-parts/part-quick-view'); ?>

<?php get_footer();

<?php
/*
Template Name: Full Width - About Us
*/
get_header(); ?>

    <?php get_template_part( 'template-parts/part-main-navigation' ); ?>

Unique Layouts, Customize wireframes & User
					Interface Kit

				<button type="button" class="button">Take a Tour</button>

	<?php get_template_part( 'template-parts/part-quick-view' ); ?>
	<?php get_template_part( 'template-parts/part-our-team' ); ?>
	<?php get_template_part( 'template-parts/part-our-services' ); ?>
	<?php get_template_part( 'template-parts/part-subfooter' ); ?>

<?php get_footer();

Add parts to the page template

Add parts to the page template


<?php

namespace Liuggio\Fastest\Process;

/**
 *  Number of processors seen by the OS and used for process scheduling.
 */
class ProcessorCounter
{
    const PROC_DEFAULT_NUMBER = 4;
    const PROC_CPUINFO = '/proc/cpuinfo';

    private static $count = null;

    private $procCPUInfo;

    public function __construct($procCPUInfo = self::PROC_CPUINFO)
    {
        $this->procCPUInfo = $procCPUInfo;
    }

    public function execute()
    {
        if (null !== self::$count) {
            return self::$count;
        }
        self::$count = $this->readFromProcCPUInfo();

        return self::$count;
    }

    private function readFromProcCPUInfo()
    {
        if (PHP_OS === 'Darwin') {
            $processors = system('/usr/sbin/sysctl -n hw.physicalcpu');

            if ($processors !== false && $processors) {
                return $processors;
            }
        } elseif (PHP_OS === 'Linux') {
            $file = $this->procCPUInfo;
            if (is_file($file) && is_readable($file)) {
                try {
                    $contents = trim(file_get_contents($file));
                    return substr_count($contents, 'processor');
                } catch (\Exception $e) {
                }
            }
        }

        return self::PROC_DEFAULT_NUMBER;
    }
}

<?php

namespace Liuggio\Fastest\Process;

use Symfony\Component\Process\Process;

/**
 *  Number of processors seen by the OS and used for process scheduling.
 */
class ProcessorCounter
{
    const PROC_DEFAULT_NUMBER = 4;
    const PROC_CPUINFO = '/proc/cpuinfo';

    private static $count = null;

    private $procCPUInfo;

    public function __construct($procCPUInfo = self::PROC_CPUINFO)
    {
        $this->procCPUInfo = $procCPUInfo;
    }

    public function execute()
    {
        if (null !== self::$count) {
            return self::$count;
        }
        self::$count = $this->readFromProcCPUInfo();

        return self::$count;
    }

    private function readFromProcCPUInfo()
    {
        if (PHP_OS === 'Darwin') {
            $processors = system('/usr/sbin/sysctl -n hw.physicalcpu');

            if ($processors !== false && $processors) {
                return $processors;
            }
        } elseif (PHP_OS === 'Linux') {
            $file = $this->procCPUInfo;
            if (is_file($file) && is_readable($file)) {
                try {
                    $contents = trim(file_get_contents($file));
                    return substr_count($contents, 'processor');
                } catch (\Exception $e) {
                }
            }
        } elseif ('\\' === DIRECTORY_SEPARATOR) {
            $process = new Process('for /F "tokens=2 delims==" %C in (\'wmic cpu get NumberOfLogicalProcessors /value ^| findstr NumberOfLogicalProcessors\') do @echo %C');
            $process->run();

            if ($process->isSuccessful() && ($numProc = intval($process->getOutput())) > 0) {
                return $numProc;
            }
        }

        return self::PROC_DEFAULT_NUMBER;
    }
}

Add the Windows compatibility for the processor counter


<?php
/**
 * oskr-portal
 * Created: 11.05.17 12:44
 * @copyright Copyright (c) 2017 OSKR NIAEP
 */

namespace frontend\controllers;

use frontend\models\audioconference\AudioConferenceService;
use yii\web\Controller;
use yii\filters\VerbFilter;

/**
 * Class AudioConferenceController
 *
 * @author Shubnikov Alexey <a.shubnikov@niaep.ru>
 *
 */
class AudioConferenceController extends Controller
{
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'index' => ['get'],
                    'create' => ['post'],
                    'delete' => ['post', 'delete']
                ]
            ]
        ];
    }

    public function actionIndex()
    {
        return $this->render('index', ['conference' => (new AudioConferenceService())->getConferenceByUserId(\Yii::$app->user->getId())]);
    }

    public function actionCreate()
    {
        return $this->render('index', ['conference' => (new AudioConferenceService())->createConferenceForUser(\Yii::$app->user->getId())]);
    }

    public function actionDelete()
    {
        (new AudioConferenceService())->deleteConferenceForUser(\Yii::$app->user->getId());
        return $this->render('index', ['conference' => null]);
    }
}

<?php
/**
 * oskr-portal
 * Created: 11.05.17 12:44
 * @copyright Copyright (c) 2017 OSKR NIAEP
 */

namespace frontend\controllers;

use frontend\models\audioconference\AudioConferenceService;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\filters\VerbFilter;

/**
 * Class AudioConferenceController
 *
 * @author Shubnikov Alexey <a.shubnikov@niaep.ru>
 *
 */
class AudioConferenceController extends Controller
{
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::class,
                'rules' => [
                    [
                        'allow' => true,
                        'actions' => ['index', 'create', 'delete'],
                        'roles' => ['@'],
                    ],

                ]
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'index' => ['get'],
                    'create' => ['post'],
                    'delete' => ['post', 'delete']
                ]
            ]
        ];
    }

    public function actionIndex()
    {
        return $this->render('index', ['conference' => (new AudioConferenceService())->getConferenceByUserId(\Yii::$app->user->getId())]);
    }

    public function actionCreate()
    {
        return $this->render('index', ['conference' => (new AudioConferenceService())->createConferenceForUser(\Yii::$app->user->getId())]);
    }

    public function actionDelete()
    {
        (new AudioConferenceService())->deleteConferenceForUser(\Yii::$app->user->getId());
        return $this->render('index', ['conference' => null]);
    }
}

Add Access Rules in AudioConference controller


#!/usr/bin/env php
<?php
chdir(__DIR__);

$returnStatus = null;
passthru('composer install --dev', $returnStatus);
if ($returnStatus !== 0) {
    exit(1);
}

passthru(
    './vendor/bin/phpcs --standard=PSR2 src tests *.php',
    $returnStatus
);
if ($returnStatus !== 0) {
    exit(1);
}

passthru('./vendor/bin/phpunit', $returnStatus);
if ($returnStatus !== 0) {
    exit(1);
}

$xml = new SimpleXMLElement(file_get_contents('clover.xml'));
foreach ($xml->xpath('//file/metrics') as $metric) {
    if ((int)$metric['elements'] !== (int)$metric['coveredelements']) {
        fputs(STDERR, "Code coverage was NOT 100%\n");
        exit(1);
    }
}

echo "Code coverage was 100%\n";

#!/usr/bin/env php
<?php
chdir(__DIR__);

$returnStatus = null;
passthru('composer install', $returnStatus);
if ($returnStatus !== 0) {
    exit(1);
}

passthru(
    './vendor/bin/phpcs --standard=PSR2 src tests *.php',
    $returnStatus
);
if ($returnStatus !== 0) {
    exit(1);
}

passthru('./vendor/bin/phpunit', $returnStatus);
if ($returnStatus !== 0) {
    exit(1);
}

$xml = new SimpleXMLElement(file_get_contents('clover.xml'));
foreach ($xml->xpath('//file/metrics') as $metric) {
    if ((int)$metric['elements'] !== (int)$metric['coveredelements']) {
        fputs(STDERR, "Code coverage was NOT 100%\n");
        exit(1);
    }
}

echo "Code coverage was 100%\n";

Remove depecated --dev composer argument


<?php
require_once('PHPWebDriver/WebDriver.php');
require_once('SystemWebDriverSession.php');

class SystemWebDriver extends PHPWebDriver_WebDriver {
    function __construct($executor = null) {
        if (! is_null($executor)) {
            parent::__construct($executor);
        } else {
            parent::__construct();
        }
    }

    public function session($browser = 'firefox',
                            $additional_capabilities = array(),
                            $curl_opts = array(),
                            $browser_profile = null) {
        $capabilities = new PHPWebDriver_WebDriverDesiredCapabilities();
        $desired_capabilities = array_merge($capabilities->$browser, $additional_capabilities);
        if ($browser == 'firefox' && $browser_profile) {
            $desired_capabilities['firefox_profile'] = $browser_profile->encoded();
        }

        $curl_opts = $curl_opts + array(CURLOPT_FOLLOWLOCATION => true);

        $results = $this->curl(
            'POST',
            '/session',
            array('desiredCapabilities' => $desired_capabilities),
                $curl_opts);

        return new SystemWebDriverSession($results['info']['url']);
    }
}

<?php
require_once('PHPWebDriver/WebDriver.php');
require_once('SystemWebDriverSession.php');

/**
 * SystemWebDriver This class is a duplication of WebDriver class in order to return a custom session object, which extends a few methods based on WebDriverSession class
 *
 * @uses PHPWebDriver_WebDriver
 * @package tests
 * @version //autogen//
 * @copyright Copyright (c) 2013 All rights reserved.
 * @author
 * @license PHP Version 3.0 {@link http://www.php.net/license/3_0.txt}
 */
class SystemWebDriver extends PHPWebDriver_WebDriver {
    function __construct($executor = null) {
        if (! is_null($executor)) {
            parent::__construct($executor);
        } else {
            parent::__construct();
        }
    }

    public function session($browser = 'firefox',
                            $additional_capabilities = array(),
                            $curl_opts = array(),
                            $browser_profile = null) {
        $capabilities = new PHPWebDriver_WebDriverDesiredCapabilities();
        $desired_capabilities = array_merge($capabilities->$browser, $additional_capabilities);
        if ($browser == 'firefox' && $browser_profile) {
            $desired_capabilities['firefox_profile'] = $browser_profile->encoded();
        }

        $curl_opts = $curl_opts + array(CURLOPT_FOLLOWLOCATION => true);

        $results = $this->curl(
            'POST',
            '/session',
            array('desiredCapabilities' => $desired_capabilities),
                $curl_opts);

        return new SystemWebDriverSession($results['info']['url'].$results['sessionId']);
    }
}

Update to compatible with PHPWebDriver 1.12.0


<?php

require_once "autoloader.php";
require_once "/lib/xsrf.php";
require_once("/etc/apache2/teamcuriosity-mysql/encrypted-config.php");

use Edu\Cnm\TeamCuriosity;

/**
 * api for the NewsArticle class
 *
 * @author Anthony Williams <awilliams144@cnm.edu>
 **/

//verify the session, start if not active
if(session_status() !== PHP_SESSION_ACTIVE) {
	session_start();
}
//prepare an empty reply
$reply = new stdClass();
$reply->status = 200;
$reply->data = null;
try {
	//grab the mySQL connection
	$pdo = connectToEncryptedMySQL("/etc/apache2/teamcuriosity-mysql/newsArticle.ini");
	//determine which HTTP method was used
	$method = array_key_exists("HTTP_X_HTTP_METHOD", $_SERVER) ? $_SERVER["HTTP_X_HTTP_METHOD"] : $_SERVER["REQUEST_METHOD"];
	//sanitize input
	$id = filter_input(INPUT_GET, "id", FILTER_VALIDATE_INT);
	//make sure the id is valid for methods that require it
	if(($method === "DELETE" || $method === "PUT") && (empty($id) === true || $id < 0)) {
		throw(new InvalidArgumentException("id cannot be empty or negative", 405));
	}
// handle GET request - if id is present, that NewsArticle is returned, otherwise all NewsArticles are returned
	if($method === "GET") {
		//set XSRF cookie
		setXsrfCookie();

Handle Get request if id is present

Handle Get request if id is present


@can(App\Policies\UserPolicy::ADMIN, App\User::class)
    username()) }}">
        gravatarUrl($avatarSize ?? 150) }}">

@else
    username()) }}">
        gravatarUrl($avatarSize ?? 150) }}">

@endcan

{{ $user->name() }}

@if ($bio = $user->bio())

        {{ $bio }}

@endif

@if ($user->isAdmin())

Admin

@elseif ($user->isModerator())

Moderator

@endif

    @if ($user->githubUsername())
        githubUsername() }}" class="text-green-darker text-3xl block">

    @endif

Remove hover state from label

Remove hover state from label


#!/usr/bin/env php
<?php
chdir(__DIR__);

$returnStatus = null;
passthru('composer install --dev', $returnStatus);
if ($returnStatus !== 0) {
    exit(1);
}

require 'vendor/autoload.php';

passthru('./vendor/bin/phpcs --standard=PSR1 -n src tests *.php', $returnStatus);
if ($returnStatus !== 0) {
    exit(1);
}

$phpunitConfiguration = PHPUnit_Util_Configuration::getInstance(__DIR__ . '/phpunit.xml');
$phpunitArguments = array('coverageHtml' => 'coverage', 'configuration' => $phpunitConfiguration);
$testRunner = new PHPUnit_TextUI_TestRunner();
$result = $testRunner->doRun($phpunitConfiguration->getTestSuiteConfiguration(), $phpunitArguments);
if (!$result->wasSuccessful()) {
    exit(1);
}

$coverageFactory = new PHP_CodeCoverage_Report_Factory();
$coverageReport = $coverageFactory->create($result->getCodeCoverage());
if ($coverageReport->getNumExecutedLines() !== $coverageReport->getNumExecutableLines()) {
    file_put_contents('php://stderr', "Code coverage was NOT 100%\n");
    exit(1);
}

echo "Code coverage was 100%\n";

#!/usr/bin/env php
<?php
chdir(__DIR__);

$returnStatus = null;
passthru('composer install --dev', $returnStatus);
if ($returnStatus !== 0) {
    exit(1);
}

require 'vendor/autoload.php';

passthru('./vendor/bin/phpcs --standard=PSR1 -n src tests *.php', $returnStatus);
if ($returnStatus !== 0) {
    exit(1);
}

$phpunitConfiguration = PHPUnit_Util_Configuration::getInstance(__DIR__ . '/phpunit.xml');
$phpunitArguments = array('coverageHtml' => __DIR__ . '/coverage', 'configuration' => $phpunitConfiguration);
$testRunner = new PHPUnit_TextUI_TestRunner();
$result = $testRunner->doRun($phpunitConfiguration->getTestSuiteConfiguration(), $phpunitArguments);
if (!$result->wasSuccessful()) {
    exit(1);
}

$coverageFactory = new PHP_CodeCoverage_Report_Factory();
$coverageReport = $coverageFactory->create($result->getCodeCoverage());
if ($coverageReport->getNumExecutedLines() !== $coverageReport->getNumExecutableLines()) {
    file_put_contents('php://stderr', "Code coverage was NOT 100%\n");
    exit(1);
}

echo "Code coverage was 100%\n";

Use full path to code coverage.

Use full path to code coverage.


<?php

namespace Gerencianet\Exception;

use Exception;

class GerencianetException extends Exception
{
    private $error;
    private $errorDescription;

    public function __construct($exception)
    {
        $error = $exception;

        if ($exception instanceof \GuzzleHttp\Psr7\Stream) {
            $error = $this->parseStream($exception);
        }

        $message = isset($error['error_description']['message']) ? $error['error_description']['message'] : $error['error_description'];

        if (isset($error['error_description']['property'])) {
            $message .= ': '.$error['error_description']['property'];
        }

        $this->error = $error['error'];
        $this->errorDescription = $error['error_description'];

        parent::__construct($message, $error['code']);
    }

    private function parseStream($stream)
    {
        $error = '';
        while (!$stream->eof()) {
            $error .= $stream->read(1024);
        }

        return json_decode($error, true);
    }

    public function __toString()
    {
        return 'Error '.$this->code.': '.$this->message."\n";
    }

    public function __get($property)
    {
        if (property_exists($this, $property)) {
            return $this->$property;
        }
    }
}

<?php

namespace Gerencianet\Exception;

use Exception;

class GerencianetException extends Exception
{
    private $error;
    private $errorDescription;

    public function __construct($exception)
    {
        $error = $exception;

        if ($exception instanceof \GuzzleHttp\Stream\Stream) {
            $error = $this->parseStream($exception);
        }

        $message = isset($error['error_description']['message']) ? $error['error_description']['message'] : $error['error_description'];

        if (isset($error['error_description']['property'])) {
            $message .= ': '.$error['error_description']['property'];
        }

        $this->error = $error['error'];
        $this->errorDescription = $error['error_description'];

        parent::__construct($message, $error['code']);
    }

    private function parseStream($stream)
    {
        $error = '';
        while (!$stream->eof()) {
            $error .= $stream->read(1024);
        }

        return json_decode($error, true);
    }

    public function __toString()
    {
        return 'Error '.$this->code.': '.$this->message."\n";
    }

    public function __get($property)
    {
        if (property_exists($this, $property)) {
            return $this->$property;
        }
    }
}

Fix Stream instance of Guzzle

Fix Stream instance of Guzzle


<?php

namespace Robo\TaskCollection;

use Robo\Result;
use Robo\Contract\TaskInterface;

/**
 * Creates a task group consisting of a task, all of the before tasks,
 * and all of the after tasks.
 *
 * This class is internal to Collection; it should not be used directly.
 */
class TaskBeforeAfterGroup
{
    protected $task;
    protected $before = [];
    protected $after = [];

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

    public function before($before, $name)
    {
        if ($name) {
            $this->before[$name] = $before;
        }
        else {
            $this->before[] = $before;
        }
    }

    public function after($after, $name)
    {
        if ($name) {
            $this->after[$name] = $after;
        }
        else {
            $this->after[] = $after;
        }
    }

    public function getBefore()
    {
        return $this->before;
    }

    public function getAfter()
    {
        return $this->after;
    }

    public function getTask()
    {
        return $this->task;
    }

    public function getTaskList()
    {
        return array_merge($this->before, [$this->task], $this->after);
    }
}

Format 'else' to satisfy Nitpick CI.

Format 'else' to satisfy Nitpick CI.


<?php
$time_start = microtime(true);
ini_set ('include_path', '.' . PATH_SEPARATOR . 'lib/pear/php');	// Add PEAR's folder. XXX This is needed before the includes just for their paths to be correct

require_once 'include/config.php';
if (aftertime_init() === false) {
	TemplateLog::render('templates/apperror.php');
} else {
	require_once 'include/log.php';
	require_once 'include/app.php';

	$app = appFactory::getApp($_REQUEST);
	if ($app) {
		if ($app->run() !== 'redirect') {
			$app->render_template();
		}
	} else {
		require_once 'include/template_log.php';
		TemplateLog::render('templates/apperror.php');
	}

	log_entry ('=== Page generation time was ' . (microtime(true) - $time_start) . ' ===');
}
?>

<?php
$time_start = microtime(true);
ini_set ('include_path', '.' . PATH_SEPARATOR . 'lib/pear/php');	// Add PEAR's folder. XXX This is needed before the includes just for their paths to be correct

require_once 'include/config.php';
require_once 'include/log.php';
if (aftertime_init() === false) {
	TemplateLog::render('templates/apperror.php');
} else {
	require_once 'include/app.php';

	$app = appFactory::getApp($_REQUEST);
	if ($app) {
		if ($app->run() !== 'redirect') {
			$app->render_template();
		}
	} else {
		require_once 'include/template_log.php';
		TemplateLog::render('templates/apperror.php');
	}

	log_entry ('=== Page generation time was ' . (microtime(true) - $time_start) . ' ===');
}
?>

Fix PHP error reporting not showing in the logs

The Log class must be defined prior to the initialization of the
aftertime framework. Move the require statement just before that.


<!DOCTYPE HTML>

	<title>Graph generator thingy</title>

Graph generator

<form method="post" action="gen.php">

Type: <input type="radio" name="type" value="graph" id="type_g"> undirected or <input type="radio" name="type"
value="digraph" id="type_d" checked="checked">
directed graph

Definition (contents of a dot graph {} container):

<textarea name="def" rows="20" cols="50"></textarea>

<input type="checkbox" name="private" value="1" id="priv"> private (non-guessable URL)

<input type="submit">
</form>

<!DOCTYPE HTML>

	<title>Graph generator thingy</title>

Graph generator

Here you can generate your own graphs. Generated graphs will be stored
indefinitely and the generated image URLs will not change. Once generated, a
graph cannot be changed, but you can generate a new one.

<form method="post" action="gen.php">

Type: <input type="radio" name="type" value="graph" id="type_g"> undirected or <input type="radio" name="type"
value="digraph" id="type_d" checked="checked">
directed graph

Definition (without the surrounding [di]graph {} thing): (syntax, example)

<textarea name="def" rows="20" cols="50"><?php if ($_GET['example']):
?>Sleep -> Work [label="zombie"]
Work -> TV [label="zombie"]
TV -> Sleep [label="zombie"]
<?php endif; ?></textarea>

<input type="checkbox" name="private" value="1" id="priv"> private (non-guessable URL)

<input type="submit">
</form>

Add reference to syntax and provide example graph

To make the pastebin form slightly more user-friendly, link to the
Wikipedia article describing the DOT syntax, and make an example graph
definition available. Also very briefly explain what the pastebin page
is all about and what the rules are.


<?php

require 'vendor/autoload.php';

$router = new AltoRouter();

/*
 * Map our routes
 */

$router->map( 'GET', '/', function()
{
    require __DIR__ . '/home.php';
});

$router->map( 'GET', '/business/[a:id]', function($id)
{
    require __DIR__ . '/business.php';
}, 'business-details' );

$router->map( 'GET', '/search/[a:query]', function($query)
{
    require __DIR__ . '/search.php';
}, 'search' );

$router->map( 'GET', '/api/business/[a:id]', function($id)
{
    require __DIR__ . '/api/business.php';
}, 'api-business-details' );

$router->map( 'GET', '/search/[a:query]', function($query)
{
    require __DIR__ . '/api/search.php';
}, 'api-search' );

$router->map( 'GET', '/recent', function()
{
    require __DIR__ . '/api/recent.php';
});

$match = $router->match();

if ( is_array($match) && is_callable( $match['target'] ) )
{
	call_user_func_array( $match['target'], $match['params'] );
}

/*
 * 404
 */
else
{
	header($_SERVER["SERVER_PROTOCOL"] . ' 404 Not Found');
}

<?php

require 'vendor/autoload.php';

$router = new AltoRouter();

/*
 * Map our routes
 */

$router->map( 'GET', '/', function()
{
    require __DIR__ . '/home.php';
});

$router->map( 'GET', '/business/[a:id]', function($id)
{
    require __DIR__ . '/business.php';
}, 'business-details' );

$router->map( 'GET', '/search/[a:query]', function($query)
{
    require __DIR__ . '/search.php';
}, 'search' );

$router->map( 'GET', '/api/business/[a:id]', function($id)
{
    require __DIR__ . '/api/business.php';
}, 'api-business-details' );

$router->map( 'GET', '/api/search/[a:query]', function($query)
{
    require __DIR__ . '/api/search.php';
}, 'api-search' );

$router->map( 'GET', '/api/recent', function()
{
    require __DIR__ . '/api/recent.php';
});

$match = $router->match();

if ( is_array($match) && is_callable( $match['target'] ) )
{
	call_user_func_array( $match['target'], $match['params'] );
}

/*
 * 404
 */
else
{
	header($_SERVER["SERVER_PROTOCOL"] . ' 404 Not Found');
}

Fix routes for API calls

Fix routes for API calls


<?php
namespace AppBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\Validator\Constraints\File;

class UserProfilType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('aboutme', TextareaType::class, array(
                'attr'          => array( 'class' => 'materialize-textarea'),
                'required'      => false
            ))
            ->add('imagepath', FileType::class, array(
                'label'         => false,
                'mapped'        => false,
                'data_class'    => null,
                'required'      => false,
                'attr'          => array('class' => 'upload'),
                'constraints' => [
                    new File([
                        'maxSize' => '5M',
                        'mimeTypes' => [
                            'image/jpeg',
                            'image/gif',
                            'image/png'
                        ],
                        'mimeTypesMessage'  => 'avatar_format',
                        'maxSizeMessage'    => 'avatar_size',
                    ])
                ]
            ))
        ;
    }

    public function setDefaultOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'error_bubbling' => true
        ));
    }

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

Fix (profil): Text files should end with a newline character


<?php

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

namespace AppBundle\Repository;

use Doctrine\ORM\EntityRepository;
use AppBundle\Entity\Post;

/**
 * This custom Doctrine repository contains some methods which are useful when
 * querying for blog post information.
 * See http://symfony.com/doc/current/book/doctrine.html#custom-repository-classes
 *
 * @author Ryan Weaver <weaverryan@gmail.com>
 * @author Javier Eguiluz <javier.eguiluz@gmail.com>
 */
class PostRepository extends EntityRepository
{
    public function findLatest($limit = Post::NUM_ITEMS)
    {
        return $this
            ->createQueryBuilder('p')
            ->select('p')
            ->where('p.publishedAt <= :now')->setParameter('now', new \DateTime())
            ->orderBy('p.publishedAt', 'DESC')
            ->setMaxResults($limit)
            ->getQuery()
            ->getResult()
        ;
    }
}

<?php

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

namespace AppBundle\Repository;

use Doctrine\ORM\EntityRepository;
use AppBundle\Entity\Post;

/**
 * This custom Doctrine repository contains some methods which are useful when
 * querying for blog post information.
 * See http://symfony.com/doc/current/book/doctrine.html#custom-repository-classes
 *
 * @author Ryan Weaver <weaverryan@gmail.com>
 * @author Javier Eguiluz <javier.eguiluz@gmail.com>
 */
class PostRepository extends EntityRepository
{
    public function findLatest($limit = Post::NUM_ITEMS)
    {
        return $this->getEntityManager()
            ->createQuery('
                SELECT p
                FROM AppBundle:Post p
                WHERE p.publishedAt <= :now
                ORDER BY p.publishedAt DESC
            ')
            ->setParameter('now', new \DateTime())
            ->setMaxResults($limit)
            ->getResult()
        ;
    }
}

Replace query builder with DQL

Replace query builder with DQL


<?php

namespace Awesomite\Chariot;

class HttpMethods
{
    const METHOD_ANY = '*';
    const METHOD_HEAD = 'HEAD';
    const METHOD_GET = 'GET';
    const METHOD_POST = 'POST';
    const METHOD_PUT = 'PUT';
    const METHOD_DELETE = 'DELETE';
    const METHOD_PATCH = 'PATCH';
    const METHOD_CONNECT = 'CONNECT';
    const METHOD_OPTIONS = 'OPTIONS';
    const METHOD_TRACE = 'TRACE';
    const METHOD_PURGE = 'PURGE';

    const ALL_METHODS
        = [
            self::METHOD_ANY,
            self::METHOD_HEAD,
            self::METHOD_GET,
            self::METHOD_POST,
            self::METHOD_PUT,
            self::METHOD_DELETE,
            self::METHOD_PATCH,
            self::METHOD_CONNECT,
            self::METHOD_OPTIONS,
            self::METHOD_TRACE,
            self::METHOD_PURGE,
        ];
}

<?php

namespace Awesomite\Chariot;

class HttpMethods
{
    const METHOD_ANY = '*';
    const METHOD_HEAD = 'HEAD';
    const METHOD_GET = 'GET';
    const METHOD_POST = 'POST';
    const METHOD_PUT = 'PUT';
    const METHOD_DELETE = 'DELETE';
    const METHOD_PATCH = 'PATCH';
    const METHOD_CONNECT = 'CONNECT';
    const METHOD_OPTIONS = 'OPTIONS';
    const METHOD_TRACE = 'TRACE';

    const ALL_METHODS
        = [
            self::METHOD_ANY,
            self::METHOD_HEAD,
            self::METHOD_GET,
            self::METHOD_POST,
            self::METHOD_PUT,
            self::METHOD_DELETE,
            self::METHOD_PATCH,
            self::METHOD_CONNECT,
            self::METHOD_OPTIONS,
            self::METHOD_TRACE,
        ];
}

PURGE is not defined in HTTP RFCs

PURGE is not defined in HTTP RFCs


<?php

use Phinx\Db\Adapter\MysqlAdapter;
use Phinx\Migration\AbstractMigration;

class Corporations extends AbstractMigration
{
    /**
     * Change Method.
     *
     * Write your reversible migrations using this method.
     *
     * More information on writing migrations is available here:
     * http://docs.phinx.org/en/latest/migrations.html#the-abstractmigration-class
     */
    public function change()
    {
        $corporations = $this->table('corporations', array("engine" => "TokuDB"));
        $corporations
         ->addColumn("corporationID", "integer", array("limit" => 16))
         ->addColumn("allianceID", "integer", array("limit" => 16))
         ->addColumn("corporationName", "string", array("limit" => 128))
         ->addColumn("ceoID", "integer", array("limit" => 16))
         ->addColumn("corpTicker", "string", array("limit" => 6))
         ->addColumn("memberCount", "integer", array("limit" => 5))
         ->addColumn('information', 'text', array("limit" => MysqlAdapter::TEXT_MEDIUM))
         ->addColumn('dateAdded', 'datetime', array('default' => 'CURRENT_TIMESTAMP'))
         ->addColumn('lastUpdated', 'datetime', array('default' => '0000-00-00 00:00:00'))
         ->addIndex(array("corporationID", "corporationName"), array("unique" => true))
         ->addIndex(array("allianceID"))
         ->addIndex(array("corporationName"))
         ->addIndex(array("lastUpdated"))
         ->save();
    }
}

<?php

use Phinx\Db\Adapter\MysqlAdapter;
use Phinx\Migration\AbstractMigration;

class Corporations extends AbstractMigration
{
    /**
     * Change Method.
     *
     * Write your reversible migrations using this method.
     *
     * More information on writing migrations is available here:
     * http://docs.phinx.org/en/latest/migrations.html#the-abstractmigration-class
     */
    public function change()
    {
        $corporations = $this->table('corporations', array("engine" => "TokuDB"));
        $corporations
         ->addColumn("corporationID", "integer", array("limit" => 16))
         ->addColumn("allianceID", "integer", array("limit" => 16))
         ->addColumn("corporationName", "string", array("limit" => 128))
         ->addColumn("ceoID", "integer", array("limit" => 16))
         ->addColumn("corpTicker", "string", array("limit" => 6))
         ->addColumn("memberCount", "integer", array("limit" => 5))
         ->addColumn('information', 'text', array("limit" => MysqlAdapter::TEXT_MEDIUM))
         ->addColumn('dateAdded', 'datetime', array('default' => 'CURRENT_TIMESTAMP'))
         ->addColumn('lastUpdated', 'datetime', array('default' => '0000-00-00 00:00:00'))
         ->addIndex(array("corporationID"))
         ->addIndex(array("allianceID"))
         ->addIndex(array("corporationName"))
         ->addIndex(array("lastUpdated"))
         ->save();
    }
}

Fix the corporation migration to not have any unique indexes


<?php namespace Orchestra\Routing;

use Illuminate\Http\Request;

class RoutingServiceProvider extends \Illuminate\Routing\RoutingServiceProvider
{
    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->registerRequestOnConsole();

        parent::register();
    }

    /**
     * Register the requst on console interface.
     *
     * @return void
     */
    protected function registerRequestOnConsole()
    {
        $app = $this->app;

        if ($app->runningInConsole()) {
            $url = $app['config']->get('app.url', 'http://localhost');

            $app->instance('request', Request::create($url, 'GET', [], [], [], $_SERVER));
        }
    }

    /**
     * Register the router instance.
     *
     * @return void
     */
    protected function registerRouter()
    {
        $this->app['router'] = $this->app->share(function ($app) {
            return new Router($app['events'], $app);
        });
    }
}

<?php namespace Orchestra\Routing;

use Illuminate\Http\Request;

class RoutingServiceProvider extends \Illuminate\Routing\RoutingServiceProvider
{
    /**
     * Register the router instance.
     *
     * @return void
     */
    protected function registerRouter()
    {
        $this->app['router'] = $this->app->share(function ($app) {
            return new Router($app['events'], $app);
        });
    }
}

Revert registering request for console.

Revert registering request for console.

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


<?php

namespace ZfcBase\EventManager;

use Zend\EventManager\EventCollection,
    Zend\EventManager\EventManager;

abstract class EventProvider
{
    /**
     * @var EventCollection
     */
    protected $events;

    /**
     * Set the event manager instance used by this context
     *
     * @param  EventCollection $events
     * @return mixed
     */
    public function setEventManager(EventCollection $events)
    {
        $this->events = $events;
        return $this;
    }

    /**
     * Retrieve the event manager
     *
     * Lazy-loads an EventManager instance if none registered.
     *
     * @return EventCollection
     */
    public function events()
    {
        if (!$this->events instanceof EventCollection) {
            $identifiers = array(__CLASS__, get_class($this));
            if (isset($this->eventIdentifier)) {
                if ((is_string($this->eventIdentifier))
                    || (is_array($this->eventIdentifier))
                    || ($this->eventIdentifier instanceof Traversable)
                ) {
                    $identifiers = array_unique(array_merge($identifiers, (array) $this->eventIdentifier));
                } elseif (is_object($this->eventIdentifier)) {
                    $identifiers[] = $this->eventIdentifier;
                }
                // silently ignore invalid eventIdentifier types
            }
            $this->setEventManager(new EventManager($identifiers));
        }
        return $this->events;
    }
}

<?php

namespace ZfcBase\EventManager;

use Zend\EventManager\EventCollection,
    Zend\EventManager\EventManager;

abstract class EventProvider
{
    /**
     * @var EventCollection
     */
    protected $events;

    /**
     * Set the event manager instance used by this context
     *
     * @param  EventCollection $events
     * @return mixed
     */
    public function setEventManager(EventCollection $events)
    {
        $identifiers = array(__CLASS__, get_class($this));
        if (isset($this->eventIdentifier)) {
            if ((is_string($this->eventIdentifier))
                || (is_array($this->eventIdentifier))
                || ($this->eventIdentifier instanceof Traversable)
            ) {
                $identifiers = array_unique(array_merge($identifiers, (array) $this->eventIdentifier));
            } elseif (is_object($this->eventIdentifier)) {
                $identifiers[] = $this->eventIdentifier;
            }
            // silently ignore invalid eventIdentifier types
        }
        $events->setIdentifiers($identifiers);
        $this->events = $events;
        return $this;
    }

    /**
     * Retrieve the event manager
     *
     * Lazy-loads an EventManager instance if none registered.
     *
     * @return EventCollection
     */
    public function events()
    {
        if (!$this->events instanceof EventCollection) {
            $this->setEventManager(new EventManager());
        }
        return $this->events;
    }
}

Move identifier setter to setEventManager


<?php

/**
 * This file is part of the Krystal Framework
 *
 * Copyright (c) No Global State Lab
 *
 * For the full copyright and license information, please view
 * the license file that was distributed with this source code.
 */

namespace Krystal\Db\Sql\Connector;

use PDO;

final class MySQL implements ConnectorInterface
{
    /**
     * {@inheritDoc}
     */
    public function getArgs(array $config)
    {
        $dsn = 'mysql:host='.$config['host'];

        if (isset($config['dbname'])) {
            $dsn .= ';dbname='.$config['dbname'];
        }

        $dsn .= ';charset=utf8';

        return array($dsn, $config['username'], $config['password'], array(
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_EMULATE_PREPARES => true,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            // Disable STRICT mode
            PDO::MYSQL_ATTR_INIT_COMMAND => 'SET sql_mode="IGNORE_SPACE,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION"'
        ));
    }
}

<?php

/**
 * This file is part of the Krystal Framework
 *
 * Copyright (c) No Global State Lab
 *
 * For the full copyright and license information, please view
 * the license file that was distributed with this source code.
 */

namespace Krystal\Db\Sql\Connector;

use PDO;

final class MySQL implements ConnectorInterface
{
    /**
     * {@inheritDoc}
     */
    public function getArgs(array $config)
    {
        $dsn = 'mysql:host='.$config['host'];

        if (isset($config['dbname'])) {
            $dsn .= ';dbname='.$config['dbname'];
        }

        $dsn .= ';charset=utf8';

        return array($dsn, $config['username'], $config['password'], array(
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_EMULATE_PREPARES => true,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            // Disable STRICT mode
            PDO::MYSQL_ATTR_INIT_COMMAND => 'SET sql_mode="IGNORE_SPACE,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION", NAMES utf8'
        ));
    }
}

Define charset at start as well

Define charset at start as well


<?php
/* @var $this yii\web\View */
/* @var $item frontend\models\Item */

$preview = $item->originalPreview($item->preview, '250x150');
?>

        <a href="<?= $item->preview ?>" data-toggle="lightbox" data-gallery="global-gallery" data-parent=".img-row" data-footer="<?= $item->description ?>">
            <img alt="product description" src="<?= $preview ?>" data-src="<?= $item->preview ?>" class="img-responsive">

<?php
/* @var $this yii\web\View */
/* @var $item frontend\models\Item */

$preview = $item->originalPreview($item->preview, '250x150');
?>

        <a href="<?= $preview ?>" data-toggle="lightbox" data-gallery="global-gallery" data-parent=".img-row" data-footer="">
            <img alt="product description" src="<?= $preview ?>" data-src="<?= $preview ?>" class="img-responsive">

Fix image gallery on the item view page.


<?php
namespace Tpg\ExtjsBundle\DependencyInjection;

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

class SerializerParserPass implements CompilerPassInterface {

    /**
     * You can modify the container here before it is dumped to PHP code.
     *
     * @param ContainerBuilder $container
     *
     * @api
     */
    public function process(ContainerBuilder $container)
    {
        if (
            $container->getDefinition("nelmio_api_doc.parser.jms_metadata_parser") !== null &&
            (
                $container->getAlias("fos_rest.serializer") == "tpg_extjs.orm_serializer" ||
                $container->getAlias("fos_rest.serializer") == "tpg_extjs.odm_serializer" ||
                $container->getAlias("fos_rest.serializer") == "tpg_extjs.serializer"
            )
        ) {
            $container
                ->getDefinition("nelmio_api_doc.parser.jms_metadata_parser")
                ->replaceArgument(1, new Reference("tpg_extjs.naming_strategy"));
        }
    }
}

<?php
namespace Tpg\ExtjsBundle\DependencyInjection;

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

class SerializerParserPass implements CompilerPassInterface {

    /**
     * You can modify the container here before it is dumped to PHP code.
     *
     * @param ContainerBuilder $container
     *
     * @api
     */
    public function process(ContainerBuilder $container)
    {
        if (
            $container->hasDefinition("nelmio_api_doc.parser.jms_metadata_parser") &&
            (
                $container->getAlias("fos_rest.serializer") == "tpg_extjs.orm_serializer" ||
                $container->getAlias("fos_rest.serializer") == "tpg_extjs.odm_serializer" ||
                $container->getAlias("fos_rest.serializer") == "tpg_extjs.serializer"
            )
        ) {
            $container
                ->getDefinition("nelmio_api_doc.parser.jms_metadata_parser")
                ->replaceArgument(1, new Reference("tpg_extjs.naming_strategy"));
        }
    }
}

Fix failed Continue Integration. use hasDefinition to check existence of jms_metadata_parser


<?php
namespace Math\LinearAlgebra;
class DiagonalMatrixTest extends \PHPUnit_Framework_TestCase
{
    public function setUp()
    {
        $this->A = [
            [1, 0, 0],
            [0, 2, 0],
            [0, 0, 3],
        ];
        $this->D = [1,2,3];
        $this->matrix = new DiagonalMatrix($this->D);
    }

    public function testGetMatrix()
    {
        $this->assertEquals($this->A, $this->matrix->getMatrix());
    }
}

<?php
namespace Math\LinearAlgebra;

class DiagonalMatrixTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider dataProviderMulti
     */
    public function testConstructor(array $A, array $R)
    {
        $D = new DiagonalMatrix($A);
        $R = new Matrix($R);

        $this->assertInstanceOf('Math\LinearAlgebra\DiagonalMatrix', $D);
        $this->assertInstanceOf('Math\LinearAlgebra\Matrix', $D);

        $m = $D->getM();
        for ($i = 0; $i < $m; $i++) {
            $this->assertEquals($R[$i], $D[$i]);
        }
        $m = $R->getM();
        for ($i = 0; $i < $m; $i++) {
            $this->assertEquals($R[$i], $D[$i]);
        }
    }

    /**
     * @dataProvider dataProviderMulti
     */
    public function testGetMatrix(array $A, array $R)
    {
        $D = new DiagonalMatrix($A);

        $this->assertEquals($R, $D->getMatrix());
    }

    public function dataProviderMulti()
    {
        return [
            [
                [1, 2, 3],
                [
                    [1, 0, 0],
                    [0, 2, 0],
                    [0, 0, 3],
                ],
            ],
            [
                [1],
                [
                    [1]
                ]
            ],
        ];
    }
}

Add additional unit tests for DiagonalMatrix.


<?php

    // change username column length for w command
    putenv("PROCPS_USERLEN=20");
    exec('w -h | awk \'{print ""$1","$3","$4","$5}\'',$users);
    $result = array();
    foreach ($users as $user)
    {
        $result[] = explode(",", $user);
    }
	header('Content-Type: application/json; charset=UTF-8');
    echo json_encode($result);

<?php

    // change username column length for w command
    putenv("PROCPS_USERLEN=20");
    exec('w -h | awk \'{print $1","$3","$4","$5}\'',$users);
    $result = array();
    foreach ($users as $user)
    {
        $result[] = explode(",", $user);
    }
	header('Content-Type: application/json; charset=UTF-8');
    echo json_encode($result);

Remove the first set of quotation

Remove the first set of quotation