<?php

namespace App\Tests\Util;

use App\Entity\Camp;
use App\Entity\CampCollaboration;
use App\Entity\DayResponsible;
use App\Entity\User;
use App\Util\CamelPascalNamingStrategy;
use PHPUnit\Framework\TestCase;

/**
 * @internal
 */
class CamelPascalNamingStrategyTest extends TestCase {
    /**
     * @dataProvider getTableNameExamples
     */
    public function testClassToTableName($className, $output) {
        // given
        $strategy = new CamelPascalNamingStrategy();

        // when
        $result = $strategy->classToTableName($className);

        // then
        $this->assertEquals($output, $result);
    }

    public function getTableNameExamples() {
        return [
            ['', ''],
            [User::class, 'user'],
            [CampCollaboration::class, 'camp_collaboration'],
            ['CampCollaboration', 'camp_collaboration'],
        ];
    }

    /**
     * @dataProvider getPropertyExamples
     */
    public function testPropertyToColumnName($input, $output) {
        // given
        $strategy = new CamelPascalNamingStrategy();

        // when
        $result = $strategy->propertyToColumnName($input);

        // then
        $this->assertEquals($output, $result);
    }

    public function getPropertyExamples() {
        return [
            ['', ''],
            ['camp', 'camp'],
            ['campCollaboration', 'campCollaboration'],
        ];
    }

    /**
     * @dataProvider getEmbeddedFieldExamples
     */
    public function testEmbeddedFieldToColumnName($propertyName, $embeddedColumnName, $output) {
        // given
        $strategy = new CamelPascalNamingStrategy();

        // when
        $result = $strategy->embeddedFieldToColumnName($propertyName, $embeddedColumnName);

        // then
        $this->assertEquals($output, $result);
    }

    public function getEmbeddedFieldExamples() {
        return [
            ['', '', ''],
            ['address', 'street', 'addressStreet'],
        ];
    }

    /**
     * @dataProvider getJoinColumnExamples
     */
    public function testJoinColumnName($propertyName, $output) {
        // given
        $strategy = new CamelPascalNamingStrategy();

        // when
        $result = $strategy->joinColumnName($propertyName);

        // then
        $this->assertEquals($output, $result);
    }

    public function getJoinColumnExamples() {
        return [
            ['', 'Id'],
            ['camp', 'campId'],
            ['campCollaboration', 'campCollaborationId'],
        ];
    }

    /**
     * @dataProvider getJoinKeyColumnExamples
     */
    public function testJoinKeyColumnName($entityName, $referencedColumnName, $output) {
        // given
        $strategy = new CamelPascalNamingStrategy();

        // when
        $result = $strategy->joinKeyColumnName($entityName, $referencedColumnName);

        // then
        $this->assertEquals($output, $result);
    }

    public function getJoinKeyColumnExamples() {
        return [
            ['', null, 'Id'],
            ['', 'email', 'Email'],
            [Camp::class, null, 'campId'],
            [CampCollaboration::class, null, 'campCollaborationId'],
            [User::class, 'name', 'userName'],
            [DayResponsible::class, 'name', 'dayResponsibleName'],
        ];
    }
}

Add basic unit tests for CamelPascalNamingStrategy


<?php

/**
 *    Copyright 2015-2017 ppy Pty. Ltd.
 *
 *    This file is part of osu!web. osu!web is distributed with the hope 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/>.
 */

namespace App\Transformers\API\Chat;

use App\Models\Chat\Channel;
use League\Fractal;

class ChannelTransformer extends Fractal\TransformerAbstract
{
    public function transform(Channel $channel)
    {
        return [
            'channel_id' => $channel->channel_id,
            'name' => $channel->name,
            'description' => $channel->description,
            'type' => $channel->type,
        ];
    }
}

<?php

/**
 *    Copyright 2015-2017 ppy Pty. Ltd.
 *
 *    This file is part of osu!web. osu!web is distributed with the hope 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/>.
 */

namespace App\Transformers\API\Chat;

use App\Models\Chat\Channel;
use League\Fractal;

class ChannelTransformer extends Fractal\TransformerAbstract
{
    public function transform(Channel $channel)
    {
        return [
            'channel_id' => $channel->channel_id,
            'name' => $channel->name,
            'description' => $channel->description,
            'type' => strtolower($channel->type),
        ];
    }
}

Return channel types as lowercase

Return channel types as lowercase


<?php

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

class AddIndexToRefreshTokens extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('refresh_tokens', function (Blueprint $collection) {
            $collection->unique('token');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('refresh_tokens', function (Blueprint $collection) {
            $collection->dropUnique('token');
        });
    }
}

Add a unique index to refresh tokens.

Add a unique index to refresh tokens.


<?php
/**
 * @file
 */

namespace CultuurNet\UDB3\EventExport\Command;

use CultuurNet\Deserializer\JSONDeserializer;
use CultuurNet\Deserializer\MissingValueException;
use CultuurNet\UDB3\EventExport\EventExportQuery;
use CultuurNet\UDB3\EventExport\HTML\Brand;
use CultuurNet\UDB3\EventExport\HTML\Footer;
use CultuurNet\UDB3\EventExport\HTML\Publisher;
use CultuurNet\UDB3\EventExport\HTML\Subtitle;
use CultuurNet\UDB3\EventExport\HTML\Title;
use ValueObjects\String\String;
use ValueObjects\Web\EmailAddress;

class ExportEventsAsPDFJSONDeserializer extends JSONDeserializer
{
    /**
     * @param String $data
     * @return ExportEventsAsPDF
     */
    public function deserialize(String $data)
    {
        $json = parent::deserialize($data);

        if (!isset($json->query)) {
            throw new MissingValueException('query is missing');
        }

        $query = new EventExportQuery($json->query);

        if (!isset($json->customizations)) {
            throw new MissingValueException('customizations is missing');
        }

        if (!is_object($json->customizations)) {
            throw new \InvalidArgumentException(
                'customizations should be an object'
            );
        }

        $customizations = $json->customizations;

        if (!isset($customizations->brand)) {
            throw new MissingValueException('brand is missing');
        }

        $brand = new Brand($customizations->brand);

        if (!isset($customizations->title)) {
            throw new MissingValueException('title is missing');
        }

        $title = new Title($customizations->title);

        $command = new ExportEventsAsPDF(
            $query,
            $brand,
            $title
        );

        if (isset($json->email)) {
            $emailAddress = new EmailAddress($json->email);
            $command = $command->withEmailNotificationTo($emailAddress);
        }

        if (isset($json->selection)) {
            $command = $command->withSelection($json->selection);
        }

        if (isset($customizations->subtitle)) {
            $command = $command->withSubtitle(
                new Subtitle($customizations->subtitle)
            );
        }

        if (isset($customizations->footer)) {
            $command = $command->withFooter(
                new Footer($customizations->footer)
            );
        }

        if (isset($customizations->publisher)) {
            $command = $command->withPublisher(
                new Publisher($customizations->publisher)
            );
        }

        return $command;
    }
}

III-217: Add JSON deserializer for ExportEventsAsPDF


<?php

namespace Ice\ExternalUserBundle\Form\Type;

use FOS\UserBundle\Form\Type\RegistrationFormType as BaseType;

use Symfony\Component\Form\FormBuilderInterface,
    Symfony\Component\OptionsResolver\OptionsResolverInterface;

class RegistrationFormType extends BaseType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
//        parent::buildForm($builder, $options);

        $builder
            ->add('plainPassword', 'password', array(
                'description' => 'Plain text password. Encoded before new user is persisted.',
            ))
            ->add('email', 'email', array(
                'description' => 'Email address. Must be unique.',
            ))
            ->add('title', 'text', array(
                'description' => 'Salutation.',
            ))
            ->add('firstNames', 'text', array(
                'description' => 'First name(s).',
            ))
            ->add('lastName', 'text', array(
                'description' => 'Last name.',
            ))
            ->add('dob', 'date', array(
                'widget' => 'single_text',
                'description' => 'Date of birth.',
                'required' => false,
            ))
        ;
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Ice\ExternalUserBundle\Entity\User',
            'csrf_protection' => false,
            'validation_groups' => array('rest_register'),
        ));
    }

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

<?php

namespace Ice\ExternalUserBundle\Form\Type;

use FOS\UserBundle\Form\Type\RegistrationFormType as BaseType;

use Symfony\Component\Form\FormBuilderInterface,
    Symfony\Component\OptionsResolver\OptionsResolverInterface;

class RegistrationFormType extends BaseType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
//        parent::buildForm($builder, $options);

        $builder
            ->add('plainPassword', 'password', array(
                'description' => 'Plain text password. Encoded before new user is persisted.',
            ))
            ->add('email', 'email', array(
                'description' => 'Email address. Must be unique.',
            ))
            ->add('title', 'text', array(
                'description' => 'Salutation.',
            ))
            ->add('firstNames', 'text', array(
                'description' => 'First name(s).',
            ))
            ->add('lastName', 'text', array(
                'description' => 'Last name.',
            ))
            ->add('dob', 'date', array(
                'widget' => 'single_text',
                'description' => 'Date of birth.',
                'required' => false,
            ))
        ;
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Ice\ExternalUserBundle\Entity\User',
            'csrf_protection' => false,
            'validation_groups' => array('rest_register'),
        ));
    }

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

Remove Registration form name so the name does not form part of the register JSON request body.


<?php namespace Illuminate\Auth\Middleware;

use Closure;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Contracts\Routing\Middleware;

class AuthenticatedWithBasicAuth implements Middleware {

	/**
	 * The Guard implementation.
	 *
	 * @var Guard
	 */
	protected $auth;

	/**
	 * Create a new filter instance.
	 *
	 * @param  Guard  $auth
	 * @return void
	 */
	public function __construct(Guard $auth)
	{
		$this->auth = $auth;
	}

	/**
	 * Handle an incoming request.
	 *
	 * @param  \Illuminate\Http\Request  $request
	 * @param  \Closure  $next
	 * @return mixed
	 */
	public function handle($request, Closure $next)
	{
		return $this->auth->basic() ?: $next($request);
	}

}

Add basic auth middleware to core. Uncommon to change.


<?php // @codeCoverageIgnoreStart
namespace Doctrine\DBAL\Schema;

use Vanio\DoctrineGenericTypes\Patches\ComposerUtility;

$cacheDirectory = defined('VANIO_DOCTRINE_GENERIC_TYPES_CACHE_DIRECTORY')
    ? VANIO_DOCTRINE_GENERIC_TYPES_CACHE_DIRECTORY
    : sys_get_temp_dir();
$originalFile = ComposerUtility::findClassFileUsingPsr0(PostgreSqlSchemaManager::class);
$patchedFile = sprintf(
    '%s/%s_%s_%s.php',
    $cacheDirectory,
    basename(__FILE__, '.php'),
    md5(__DIR__),
    filemtime($originalFile)
);

if (!is_readable($patchedFile)) {
    $code = preg_replace(
        '~function\s+_getPortableSequenceDefinition\s*\(.*\)\s*{~',
        '
            function _getPortableSequenceDefinition($sequence)
            {
                if ($sequence["schemaname"] != "public") {
                    $sequenceName = "$sequence[schemaname].$sequence[relname]";
                } else {
                    $sequenceName = $sequence["relname"];
                }

                $version = (float) $this->_conn->getWrappedConnection()->getServerVersion();
                $data = $this->_conn->fetchAll(sprintf(
                    $version >= 10
                        ? "SELECT min_value, increment_by FROM pg_sequences WHERE schemaname = \'public\' AND sequencename = %s"
                        : "SELECT min_value, increment_by FROM %s",
                    $version >= 10
                        ? $this->_conn->quote($sequenceName)
                        : $this->_platform->quoteIdentifier($sequenceName)
                ));

                return new Sequence($sequenceName, $data[0]["increment_by"], $data[0]["min_value"]);
        ',
        file_get_contents($originalFile)
    );
    @mkdir($cacheDirectory, 0777, true);

    if (!@file_put_contents($patchedFile, $code)) {
        eval('?>' . $code);

        return;
    }
}

require $patchedFile;

Support for migrations in Postgres 10

Support for migrations in Postgres 10


<?php

use Phinx\Migration\AbstractMigration;

class StandardizeCreatedUpdatedFields extends AbstractMigration
{
    public function change()
    {
        $userTable = $this->table('user');
        $userTable->removeColumn('last_updated')
                  ->addTimestamps()
                  ->update();

        $previousPasswordTable = $this->table('previous_password');
        $previousPasswordTable->removeColumn('created')
                  ->addTimestamps()
                  ->update();
    }
}

Standardize the created, updated db fields.


<?php

namespace UCP\AbsenceBundle\Command;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class verifyStatutCommand extends ContainerAwareCommand
{
    protected function configure()
    {
        $this
            ->setName('ucp:statut:absence:check')
            ->setDescription('Verifie si l\'appel a été effectué et envoie par mail les absents a la secrétaire.')
            ->addArgument('mailTo', InputArgument::REQUIRED, 'Destinataire du mail')
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        //Récupere la date actuel
        $currentDate = date();
        //Récupere tous les cours qui on lieu en ce moment
        $em = $this->_container->get('doctrine.orm.entity_manager');
        $repo = $em->getRepository('UCPAbsenceBundle:Lesson');
        $lessons = $repo->findAll()
        //Si date actuel > date debut + 30 min alors on envoi un mail de rappel toute les 5 min sauf s'il y a deja des absent de selectionné
        //Si date actuel > date benut + 60min alors on envoi un mail avec la liste des absents.
    }
}

?>

Create command check statut lessons

Create command check statut lessons


<?php namespace Larapress\Tests\Controllers;

use Config;
use Larapress\Tests\TestCase;

class ControlPanelControllerTest extends TestCase
{
    private $backend_route;

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

        $this->backend_route = Config::get('larapress.urls.backend');
    }

    /*
    |--------------------------------------------------------------------------
    | ControlPanelController@getDashboard Tests
    |--------------------------------------------------------------------------
    |
    | Here is where you can test the ControlPanelController@getDashboard method
    |
    */

    public function test_can_browse_the_dashboard()
    {
        $this->call('GET', $this->backend_route . '/cp/dashboard');

        $this->assertResponseOk();
    }

}

Add tests for the control panel controller


<?php
defined("_VALID_ACCESS") || die('Direct access forbidden');

$sql = 'UPDATE utils_attachment_field SET tooltip=%d WHERE field=%s';
DB::Execute($sql, array(1, 'Title'));
DB::Execute($sql, array(1, 'Permission'));
DB::Execute($sql, array(1, 'Attached to'));
DB::Execute($sql, array(1, 'Crypted'));
DB::Execute($sql, array(1, 'Sticky'));

DB::Execute($sql, array(0, 'Note'));
DB::Execute($sql, array(0, 'Edited on'));

Set tooltip columns for notes.

Set tooltip columns for notes.


<?php

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

class AddScoreToPostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('posts', function (Blueprint $table) {
            $table->integer('score');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('posts', function (Blueprint $table) {
            $table->dropColumn('score');
        });
    }
}

Add migration for score in posts

Add migration for score in posts


<?php

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

class CreateFailedJobsTable extends Migration {
    public function up() {
        Schema::create('failed_jobs', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->text('connection');
            $table->text('queue');
            $table->longText('payload');
            $table->longText('exception');
            $table->timestamp('failed_at')->useCurrent();
        });
    }

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

Create migration for generating failed_jobs table


<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;

class FixWineDetailsColumns extends Migration
{
    public function up()
    {
        $sql = <<<'SQL'
CREATE  OR REPLACE VIEW `wine_details` AS
SELECT 1 as x, w.*, ass.id as association_id, ws.`order` AS winesort_order, ws.name AS winesort_name, wq.id AS quality_id, wq.label AS quality_label, uapp.username AS applicant_username, uass.username AS association_username, harm_mean(tn1.id) AS rating1, harm_mean(tn2.id) AS rating2
FROM wine w
JOIN applicant app
	ON app.id = w.applicant_id
JOIN association ass
	ON ass.id = app.association_id
JOIN winesort ws
	ON ws.id = w.winesort_id
LEFT OUTER JOIN winequality wq
	ON wq.id = w.winequality_id
LEFT OUTER JOIN wuser uapp
	ON uapp.username = app.wuser_username
LEFT OUTER JOIN wuser uass
	ON uass.username = ass.wuser_username
LEFT OUTER JOIN tastingnumber AS tn1
	ON w.id = tn1.wine_id
AND tn1.tastingstage_id = 1
LEFT OUTER JOIN tastingnumber AS tn2
ON w.id = tn2.wine_id
AND tn2.tastingstage_id IN (2, NULL);
SQL;
        DB::unprepared($sql);
    }

    public function down()
    {
        $sql = <<<'SQL'
CREATE  OR REPLACE VIEW `wine_details` AS
SELECT 1 as x, w.*, ws.`order` AS winesort_order, ws.name AS winesort_name, wq.id AS quality_id, wq.label AS quality_label, uapp.username AS applicant_username, uass.username AS association_username, harm_mean(tn1.id) AS rating1, harm_mean(tn2.id) AS rating2
FROM wine w
JOIN applicant app
	ON app.id = w.applicant_id
JOIN association ass
	ON ass.id = app.association_id
JOIN winesort ws
	ON ws.id = w.winesort_id
LEFT OUTER JOIN winequality wq
	ON wq.id = w.winequality_id
LEFT OUTER JOIN wuser uapp
	ON uapp.username = app.wuser_username
LEFT OUTER JOIN wuser uass
	ON uass.username = ass.wuser_username
LEFT OUTER JOIN tastingnumber AS tn1
	ON w.id = tn1.wine_id
AND tn1.tastingstage_id = 1
LEFT OUTER JOIN tastingnumber AS tn2
ON w.id = tn2.wine_id
AND tn2.tastingstage_id IN (2, NULL);
SQL;

        DB::unprepared($sql);
    }
}

Add missing columns in wine details view

Signed-off-by: Christoph Wurst <7abde52c298496fa169fb750f91f213a282142af@winzerhof-wurst.at>


<?php
/**
 * contentinum - accessibility websites
 *
 * LICENSE
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * @category contentinum
 * @package Controller Plugin
 * @author Michael Jochum, michael.jochum@jochum-mediaservices.de
 * @copyright Copyright (c) 2009-2013 jochum-mediaservices, Katja Jochum (http://www.jochum-mediaservices.de)
 * @license http://www.opensource.org/licenses/bsd-license
 * @since contentinum version 5.0
 * @link      https://github.com/Mikel1961/contentinum-components
 * @version   1.0.0
 */
namespace Contentinum\Controller\Plugin;

use Zend\Mvc\Controller\Plugin\AbstractPlugin;

/**
 * Access review
 * @author Michael Jochum, michael.jochum@jochum-mediaservices.de
 */
class IsAllowed extends AbstractPlugin
{

	public function __invoke($acl,$role,$action)
	{
		return 1;

	}
}

Prepare controller plugin user access validation per acl list

Change-Id: Id33ddab923b0c22cb6d970d9a17648002f151bf8


<?php namespace Lecturize\Taxonomies\Traits;

use Exception;
use Illuminate\Http\RedirectResponse;
use Lecturize\Taxonomies\Models\Taxonomy;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

/**
 * Class PresentsCategories
 * @package Lecturize\Taxonomies\Traits
 */
trait PresentsCategories
{
    /**
     * Check taxonomy hierarchy.
     *
     * @param  string|null    $slug
     * @param  Taxonomy|null  $current
     * @param  Taxonomy|null  $parent
     * @param  string|null    $route
     * @return null|RedirectResponse
     * @throws Exception
     * @throws NotFoundHttpException
     */
    protected function checkTaxonomyHierarchy(?string $slug, ?Taxonomy $current, ?Taxonomy $parent = null, string $route = ''): ?RedirectResponse
    {
        // if there is no slug given, do nothing
        if (empty($slug))
            return null;

        // no taxonomy has been found for the given slug
        // let's redirect to parent if given or abort
        if (! $current)
            if ($parent) {
                return redirect()->route($route, $parent->getRouteParameters());
            } else {
                throw new NotFoundHttpException();
            }

        // a taxonomy has been found, see if it matches the given parent
        // redirect to calculated destination
        if ($current->parent_id !== ($parent ? $parent->id : null))
            return redirect()->route($route, $current->getRouteParameters());

        return null;
    }
}

Add a trait for controllers to check the given taxonomy hierarchy


<?php

declare(strict_types=1);

function is_shuffle(string $string1, string $string2, string $string3) : bool {
    if ($string1 . $string2 . $string3 === '') {
        return false;
    }

    $string1Length = strlen($string1);
    if ($string1Length + strlen($string2) !== strlen($string3)) {
        return false;
    }

    $pattern = [];
    $replace = '';
    for ($i=0; $i<$string1Length; $i++) {
        $pattern[] = '(?:(?:' . preg_quote($string1[$i], '/') .')([^\\1]*))';
        $replace .= '$' . ($i + 1);
    }

    return preg_replace('/' . implode('', $pattern) . '/', $replace, $string3) === $string2;
}

assert(is_shuffle('abc', 'def', 'dabecf') === true);
assert(is_shuffle('bac', 'def', 'dabecf') === false);
assert(is_shuffle('otto', 'anna', '') === false);
assert(is_shuffle('otto', 'anna', 'oatntnoa') === true);

Add regex based php solution for "combine-two-strings" problem


<?php

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

class AddPastebinToBasesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('bases', function (Blueprint $table) {
            $table->string('pastebin')->nullable();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('bases', function (Blueprint $table) {
            //
        });
    }
}

Create migration for pastebin url

Create migration for pastebin url


<?php

namespace Zimbra\Mail\Tests\Struct;

use Zimbra\Mail\Tests\ZimbraMailTestCase;
use Zimbra\Mail\Struct\AddedComment;

/**
 * Testcase class for AddedComment.
 */
class AddedCommentTest extends ZimbraMailTestCase
{
    public function testAddedComment()
    {
        $parentId = $this->faker->word;
        $text = $this->faker->word;

        $comment = new AddedComment($parentId, $text);
        $this->assertSame($parentId, $comment->getParentId());
        $this->assertSame($text, $comment->getText());

        $comment->setParentId($parentId)
                ->setText($text);
        $this->assertSame($parentId, $comment->getParentId());
        $this->assertSame($text, $comment->getText());

        $xml = '<?xml version="1.0"?>' . "\n"
            .'<comment parentId="' . $parentId . '" text="' . $text . '" />';
        $this->assertXmlStringEqualsXmlString($xml, (string) $comment);

        $array = array(
            'comment' => array(
                'parentId' => $parentId,
                'text' => $text,
            ),
        );
        $this->assertEquals($array, $comment->toArray());
    }
}

Add Test case for AddedComment.

Add Test case for AddedComment.


<?php

namespace Oro\Bundle\OrganizationBundle\Form\Transformer;

use Doctrine\Common\Collections\Collection;
use Oro\Bundle\OrganizationBundle\Entity\BusinessUnit;
use Oro\Bundle\OrganizationBundle\Entity\Manager\BusinessUnitManager;
use Symfony\Component\Form\DataTransformerInterface;

class BusinessUnitTreeTransformer implements DataTransformerInterface
{
    /** @var BusinessUnitManager */
    protected $manager;

    /** @var BusinessUnit */
    protected $entity;

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

    /**
     * {@inheritdoc}
     */
    public function reverseTransform($value)
    {
        if (null === $value) {
            return null;
        } elseif (is_array($value)) {
            return $this->manager->getBusinessUnitRepo()->findBy(['id' => $value]);
        }

        return $this->manager->getBusinessUnitRepo()->find($value);
    }

    /**
     * {@inheritdoc}
     */
    public function transform($value)
    {
        if (null === $value) {
            return null;
        }

        if (is_array($value) || (is_object($value) && ($value instanceof Collection))) {
            $result = [];
            foreach ($value as $object) {
                $result[] = $object->getId();
            }
        } elseif (is_object($value)) {
            $result = $value->getId();
        } else {
            $result = $value;
        }

        return $result;
    }
}

<?php

namespace Oro\Bundle\OrganizationBundle\Form\Transformer;

use Doctrine\Common\Collections\Collection;
use Oro\Bundle\OrganizationBundle\Entity\BusinessUnit;
use Oro\Bundle\OrganizationBundle\Entity\Manager\BusinessUnitManager;
use Symfony\Component\Form\DataTransformerInterface;

class BusinessUnitTreeTransformer implements DataTransformerInterface
{
    /** @var BusinessUnitManager */
    protected $manager;

    /** @var BusinessUnit */
    protected $entity;

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

    /**
     * {@inheritdoc}
     */
    public function reverseTransform($value)
    {
        if (null == $value) {
            return 0;
        } elseif (is_array($value)) {
            foreach($value as &$val) {
                if ($val === "") {
                    $val =0;
                }
            }

            return $this->manager->getBusinessUnitRepo()->findBy(['id' => $value]);
        }

        return $this->manager->getBusinessUnitRepo()->find($value);
    }

    /**
     * {@inheritdoc}
     */
    public function transform($value)
    {
        if (null == $value) {
            return 0;
        }

        if (is_array($value) || (is_object($value) && ($value instanceof Collection))) {
            $result = [];
            foreach ($value as $object) {
                $result[] = $object->getId();
            }
        } elseif (is_object($value)) {
            $result = $value->getId();
        } else {
            $result = $value;
        }

        return $result;
    }
}

BAP-10985: Update the rules displaying autocomplete result for business unit owner field


<?php
    /*********************************************************************************
     * Zurmo is a customer relationship management program developed by
     * Zurmo, Inc. Copyright (C) 2012 Zurmo Inc.
     *
     * Zurmo is free software; you can redistribute it and/or modify it under
     * the terms of the GNU General Public License version 3 as published by the
     * Free Software Foundation with the addition of the following permission added
     * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
     * IN WHICH THE COPYRIGHT IS OWNED BY ZURMO, ZURMO DISCLAIMS THE WARRANTY
     * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
     *
     * Zurmo 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 General Public License for more
     * details.
     *
     * You should have received a copy of the GNU General Public License along with
     * this program; if not, see http://www.gnu.org/licenses or write to the Free
     * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
     * 02110-1301 USA.
     *
     * You can contact Zurmo, Inc. with a mailing address at 113 McHenry Road Suite 207,
     * Buffalo Grove, IL 60089, USA. or at email address contact@zurmo.com.
     ********************************************************************************/

    class ZurmoActiveFormTest extends ZurmoBaseTest
    {
        public static function setUpBeforeClass()
        {
            parent::setUpBeforeClass();
            SecurityTestHelper::createSuperAdmin();
            SecurityTestHelper::createUsers();
        }

        public function setUp()
        {
            parent::setUp();
            Yii::app()->user->userModel = User::getByUsername('super');
        }

        public function testMakeErrorsDataAndResolveForOwnedModelAttributes()
        {
            $user = UserTestHelper::createBasicUser('TestUser');

            $account                                = new Account();
            $account->owner                         = $user;
            $account->name                          = '';
            $account->officePhone                   = '1234567890';
            $account->primaryEmail->emailAddress    = 'testaccountzurmocom';
            $this->assertFalse($account->save());
            $errorData = ZurmoActiveForm::makeErrorsDataAndResolveForOwnedModelAttributes($account);
            $this->assertEquals('Name cannot be blank.', $errorData['Account_name'][0]);
            $this->assertEquals('Email Address is not a valid email address.', $errorData['Account_primaryEmail_emailAddress'][0]);
            $account->name                          = 'Test Account';
            $account->primaryEmail->emailAddress    = 'testaccount@zurmo.com';
            $this->assertTrue($account->save());
        }
    }
?>

Test for method makeErrorsDataAndResolveForOwnedModelAttributes, complete coverage


<?php
/**
 * Created by PhpStorm.
 * User: sonja
 * Date: 01.02.18
 * Time: 15:05
 */

namespace AppBundle\Validator\Constraints;

class IsValidFennecUser
{

}

Add new class for custom constraint

Add new class for custom constraint


<?php

use Phinx\Migration\AbstractMigration;

class FixTxnLineForeignKeys extends AbstractMigration
{
    public function change()
    {
      $table= $this->table('txn_line', [ 'signed' => false ]);
      $table
        ->renameColumn('txn', 'txn_id')
        ->renameColumn('item', 'item_id')
        ->save();
    }
}

Add _id to txn_line.txn and txn_line.item


<?php declare(strict_types=1);

namespace hollodotme\Readis\Application\ReadModel\KeyDataBuilders;

use hollodotme\Readis\Application\Interfaces\ProvidesKeyInfo;
use hollodotme\Readis\Application\ReadModel\Constants\KeyType;
use hollodotme\Readis\Application\ReadModel\DTO\KeyData;
use hollodotme\Readis\Application\ReadModel\Interfaces\BuildsKeyData;
use hollodotme\Readis\Application\ReadModel\Interfaces\PrettifiesString;
use hollodotme\Readis\Application\ReadModel\Interfaces\ProvidesKeyData;
use hollodotme\Readis\Application\ReadModel\Interfaces\ProvidesKeyName;
use hollodotme\Readis\Infrastructure\Redis\Exceptions\ConnectionFailedException;
use hollodotme\Readis\Infrastructure\Redis\ServerManager;

final class HashKeyDataBuilder implements BuildsKeyData
{
	private const FIELD_SEPARATOR = "\n\n---\n\n";

	/** @var ServerManager */
	private $manager;

	/** @var PrettifiesString */
	private $prettifier;

	public function __construct( ServerManager $manager, PrettifiesString $prettifier )
	{
		$this->manager    = $manager;
		$this->prettifier = $prettifier;
	}

	public function canBuildKeyData( ProvidesKeyInfo $keyInfo, ProvidesKeyName $keyName ) : bool
	{
		return !$keyName->hasSubKey() && (KeyType::HASH === $keyInfo->getType());
	}

	/**
	 * @param ProvidesKeyInfo $keyInfo
	 * @param ProvidesKeyName $keyName
	 *
	 * @throws ConnectionFailedException
	 * @return ProvidesKeyData
	 */
	public function buildKeyData( ProvidesKeyInfo $keyInfo, ProvidesKeyName $keyName ) : ProvidesKeyData
	{
		$rawFields  = [];
		$hashValues = $this->manager->getAllHashValues( $keyName->getKeyName() );

		foreach ( $hashValues as $hashKey => $hashValue )
		{
			$rawFields[] = $this->getFieldOutput( $hashKey, $hashValue );
		}

		$prettyFields = [];
		foreach ( $hashValues as $hashKey => $hashValue )
		{
			$prettyHashValue = $this->prettifier->prettify( $hashValue );
			$prettyFields[]  = $this->getFieldOutput( $hashKey, $prettyHashValue );
		}

		$rawKeyData = implode( self::FIELD_SEPARATOR, $rawFields );
		$keyData    = implode( self::FIELD_SEPARATOR, $prettyFields );

		return new KeyData( $keyData, $rawKeyData );
	}

	private function getFieldOutput( string $hashKey, string $hashValue ) : string
	{
		return sprintf(
			"Hash key %s:\n%s\n%s",
			$hashKey,
			str_repeat( '=', 10 + strlen( (string)$hashKey ) ),
			$hashValue
		);
	}
}

Add hash key data builder

Add hash key data builder


<?php

/**
 * This file is part of CSBill package.
 *
 * (c) 2013-2014 Pierre du Plessis <info@customscripts.co.za>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace CSBill\ClientBundle\Tests\Twig\Extension;

use CSBill\ClientBundle\Twig\Extension\ContactTypesExtension;

class ContactTypesExtensionTest extends \PHPUnit_FrameWork_TestCase
{
    public function testGetGlobals()
    {
        $array = array(
            1,
            3,
            5,
            7,
            9
        );

        $extension = new ContactTypesExtension($array);

        $this->assertSame(
            array(
                'contact_types' => $array
            ),
            $extension->getGlobals()
        );
    }

    public function testGetName()
    {
        $extension = new ContactTypesExtension(array());

        $this->assertSame('client_contact_types_extension', $extension->getName());
    }
}

Add unit test for twig extension

Add unit test for twig extension


<?php

declare(strict_types=1);

namespace Overblog\GraphQLBundle\Tests\EventListener;

use GraphQL\Error\Error;
use Overblog\GraphQLBundle\Error\InvalidArgumentError;
use Overblog\GraphQLBundle\Error\InvalidArgumentsError;
use Overblog\GraphQLBundle\Event\ErrorFormattingEvent;
use Overblog\GraphQLBundle\EventListener\ValidationErrorsListener;
use PHPUnit\Framework\TestCase;
use Psr\Log\LoggerInterface;
use Symfony\Component\Validator\ConstraintViolation;
use Symfony\Component\Validator\ConstraintViolationList;

class ValidationErrorsListenerTest extends TestCase
{
    /** @var ErrorLoggerListener */
    private $listener;

    /** @var LoggerInterface|\PHPUnit_Framework_MockObject_MockObject */
    private $logger;

    public function setUp(): void
    {
        $this->logger = $this->getMockBuilder(LoggerInterface::class)->getMock();
        $this->listener = new ValidationErrorsListener($this->logger);
    }

    public function testOnErrorFormatting(): void
    {
        $invalidArguments = new InvalidArgumentsError([new InvalidArgumentError('invalid', new ConstraintViolationList([new ConstraintViolation('message', 'error_template', [], '', 'prop1', 'invalid')]))]);
        $formattedError = [];
        $event = new ErrorFormattingEvent(Error::createLocatedError($invalidArguments), $formattedError);
        $this->listener->onErrorFormatting($event);

        $this->assertEquals($event->getFormattedError()->getArrayCopy(), ['state' => ['invalid' => [0 => ['path' => 'prop1', 'message' => 'message', 'code' => null]]]]);
    }
}

Add validation error listener test

Add validation error listener test


<?php

namespace Hitmeister\Component\Api\Endpoints\Traits;

/**
 * Class RequestPatch
 *
 * @category PHP-SDK
 * @package  Hitmeister\Component\Api\Endpoints\Traits
 * @author   Alex Litvinenko <alex.litvinenko@hitmeister.de>
 * @license  https://opensource.org/licenses/MIT MIT
 * @link     https://www.hitmeister.de/api/v1/
 */
trait RequestPut
{
	/**
	 * @return string
	 */
	public function getMethod()
	{
		return 'PUT';
	}
}

Add trait for PUT request

Add trait for PUT request


<?php
namespace Concrete\Core\Updater\Migrations\Migrations;

use Concrete\Core\Updater\Migrations\AbstractMigration;
use Concrete\Core\Updater\Migrations\RepeatableMigrationInterface;

class Version20190826000000 extends AbstractMigration implements RepeatableMigrationInterface
{
    public function upgradeDatabase()
    {
        /* Refresh youtube block */
        $this->refreshBlockType('youtube');
    }
}

Add migration version file for youtube block


<?php
/*
 * Reset a password
 *
 * arg0 = email
 * arg1 = new password
 */
class AuthkeyShell extends AppShell {

	public $uses = array('User', 'Log');

	public function main() {
		if (!isset($this->args[0]) || empty($this->args[0])) echo 'MISP authkey reset command line tool.' . PHP_EOL . 'To assign a new authkey for a user:' . PHP_EOL . APP . 'Console/cake Authkey [email]' . PHP_EOL;
		else {
			// get the users that need their password hashed
			$user = $this->User->find('first', array('conditions' => array('email' => $this->args[0]), 'recursive' => -1, 'contain' => 'Organisation'));
			if (empty($user)) {
				echo 'User not found. Make sure you use the correct syntax: /var/www/MISP/app/Console/cake Authkey [email]' . PHP_EOL;
				exit;
			}
			$this->User->id = $user['User']['id'];
			$newkey = $this->User->generateAuthKey();
			if ($this->User->saveField('authkey', $newkey)) {
				$this->Log->create();
				$this->Log->save(array(
					'org' => $user['Organisation']['name'],
					'model' => 'User',
					'model_id' => $user['User']['id'],
					'email' => 'SYSTEM',
					'action' => 'reset_auth_key',
					'title' => 'Authentication key for user ' . $user['User']['id'] . ' (' . $user['User']['email'] . ')',
					'change' => 'authkey(' . $user['User']['authkey'] . ') => (' . $newkey . ')'
				));
				echo $newkey . PHP_EOL;
			} else {
				echo 'Could not update account for User.id = ', $user['User']['id'], PHP_EOL;
				echo json_encode($this->User->validationErrors) . PHP_EOL;
				$this->out(print_r($this->User->invalidFields(), true));
			}
		}
		exit;
	}
}

new: Add console command to reset user's authkey

/var/www/MISP/app/Console/cake Authkey [email@of.user]

- sets a new random authkey and returns it in the output


<?php
/**
 * @package Core
 * @subpackage externalWidgets
 */
class servefileAction extends sfAction
{
	/**
	 * Will forward to the regular swf player according to the widget_id
	 */
	public function execute()
	{
		requestUtils::handleConditionalGet();

		$file_sync_id = $this->getRequestParameter( "id" );
		$hash = $this->getRequestParameter( "hash" );
		$file_name = $this->getRequestParameter( "fileName" );
		if ($file_name) {
			$file_name = base64_decode($file_name);
		}

		$file_sync = FileSyncPeer::retrieveByPk ( $file_sync_id );
		if ( ! $file_sync )
		{
			$error = "DC[$current_dc_id]: Cannot find FileSync with id [$file_sync_id]";
			KalturaLog::err($error);
			throw new Exception ($error);
		}

		KalturaMonitorClient::initApiMonitor(false, 'extwidget.serveFile', $file_sync->getPartnerId());

		kDataCenterMgr::serveFileToRemoteDataCenter ( $file_sync , $hash, $file_name );
		die();
	}
}

<?php
/**
 * @package Core
 * @subpackage externalWidgets
 */
class servefileAction extends sfAction
{
	/**
	 * Will forward to the regular swf player according to the widget_id
	 */
	public function execute()
	{
		requestUtils::handleConditionalGet();

		$file_sync_id = $this->getRequestParameter( "id" );
		$hash = $this->getRequestParameter( "hash" );
		$file_name = $this->getRequestParameter( "fileName" );
		if ($file_name) {
			$file_name = base64_decode($file_name);
		}

		$file_sync = FileSyncPeer::retrieveByPk ( $file_sync_id );
		if ( ! $file_sync )
		{
			$current_dc_id = kDataCenterMgr::getCurrentDcId();
			$error = "DC[$current_dc_id]: Cannot find FileSync with id [$file_sync_id]";
			KalturaLog::err($error);
			throw new Exception ($error);
		}

		KalturaMonitorClient::initApiMonitor(false, 'extwidget.serveFile', $file_sync->getPartnerId());

		kDataCenterMgr::serveFileToRemoteDataCenter ( $file_sync , $hash, $file_name );
		die();
	}
}

Fix PHP Notice Undefined variable "current_dc_id"


<?php

namespace Oro\Bundle\LocaleBundle\Migrations\Schema\Data\ORM;

use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\ORM\EntityManager;

use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Intl\Intl;

use Oro\Bundle\LocaleBundle\Entity\Localization;

class LoadLocalizationData extends AbstractFixture implements ContainerAwareInterface
{
    /**
     * @var ContainerInterface
     */
    protected $container;

    /**
     * {@inheritDoc}
     */
    public function setContainer(ContainerInterface $container = null)
    {
        $this->container = $container;
    }

    /**
     * @param ObjectManager $manager
     */
    public function load(ObjectManager $manager)
    {
        $localeSettings = $this->container->get('oro_locale.settings');
        $localeCode = $localeSettings->getLocale();
        $title = Intl::getLocaleBundle()->getLocaleName($localeSettings->getLanguage(), $localeCode);

        $localization = new Localization();
        $localization->setName($title)
            ->setDefaultTitle($title)
            ->setLanguageCode($localeCode)
            ->setFormattingCode($localeCode);

        $manager->persist($localization);
        /** @var EntityManager $manager */
        $manager->flush($localization);

        $this->addReference('default_localization', $localization);
    }
}

BAP-10639: Update fixture for default locales
- Added default data


<?php
declare(strict_types=1);

namespace PerFi\Domain;

use PerFi\Domain\Account\CommandHandler\CreateAccount as CreateAccountHandler;
use PerFi\Domain\Account\Command\CreateAccount as CreateAccountCommand;
use PerFi\Domain\Equity\CommandHandler\StartOpeningBalance as StartOpeningBalanceHandler;
use PerFi\Domain\Equity\Command\StartOpeningBalance as StartOpeningBalanceCommand;
use PerFi\Domain\Transaction\CommandHandler\ExecuteTransaction as ExecuteTransactionHandler;
use PerFi\Domain\Transaction\Command\ExecuteTransaction as ExecuteTransactionCommand;
use SimpleBus\Message\Bus\Middleware\FinishesHandlingMessageBeforeHandlingNext;
use SimpleBus\Message\Bus\Middleware\MessageBusSupportingMiddleware;
use SimpleBus\Message\CallableResolver\CallableMap;
use SimpleBus\Message\CallableResolver\ServiceLocatorAwareCallableResolver;
use SimpleBus\Message\Handler\DelegatesToMessageHandlerMiddleware;
use SimpleBus\Message\Name\ClassBasedNameResolver;
use SimpleBus\Message\Subscriber\Resolver\NameBasedMessageSubscriberResolver;

class CommandBusFactory
{
    /**
     * Configure and get a command bus that is ready to handle commands
     *
     * For now the command handlers and the service locator are
     * hard-coded in here, but they should come from a container-interop
     * a la Zend ServiceManager.
     *
     * @return MessageBusSupportingMiddleware
     */
    public static function getCommandBus() : MessageBusSupportingMiddleware
    {
        $commandHandlersByCommandName = [
            ExecuteTransactionCommand::class => ExecuteTransactionHandler::class,
            CreateAccountCommand::class => CreateAccountHandler::class,
            StartOpeningBalanceCommand::class => StartOpeningBalanceHandler::class,
        ];

        $serviceLocator = function ($serviceId) {
            return new $serviceId();
        };

        $commandHandlerMap = new CallableMap(
            $commandHandlersByCommandName,
            new ServiceLocatorAwareCallableResolver($serviceLocator)
        );
        $commandNameResolver = new ClassBasedNameResolver();
        $commandHandlerResolver = new NameBasedMessageSubscriberResolver(
            $commandNameResolver,
            $commandHandlerMap
        );

        $commandBus = new MessageBusSupportingMiddleware();
        $commandBus->appendMiddleware(new FinishesHandlingMessageBeforeHandlingNext());
        $commandBus->appendMiddleware(
            new DelegatesToMessageHandlerMiddleware(
                $commandHandlerResolver
            )
        );

        return $commandBus;
    }
}

Create a command bus factory

Create a command bus factory

This one is not that useful in behat tests,
so I'm going to leave it unused for now.


<?php

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

class AlterRelationshipRevisionTrigger extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		DB::unprepared('DROP TRIGGER `on_relationships_revisions_insert`');
		DB::unprepared('
			CREATE TRIGGER `on_relationships_revisions_insert`
			AFTER INSERT ON `relationship_revisions`
			FOR EACH ROW
			BEGIN

				UPDATE `relationships`
					SET latest_revision_id = NEW.id
					, latest_revision_state = NEW.state
					, updated_at = NOW()
				WHERE id = NEW.relationship_id;

				INSERT INTO `activity` (activity_id, activity_model, created_by, created_at, updated_at)
				VALUES (NEW.id, "RelationshipRevision", NEW.created_by, NOW(), NOW());
			END
		');
	}

	/**
	 * Reverse the migrations.
	 *
	 * @return void
	 */
	public function down()
	{
		DB::unprepared('DROP TRIGGER `on_relationships_revisions_insert`');
		DB::unprepared('
			CREATE TRIGGER `on_relationships_revisions_insert`
			AFTER INSERT ON `relationship_revisions`
			FOR EACH ROW
			BEGIN

				UPDATE `relationships`
					SET latest_revision_id = NEW.id
					, latest_revision_state = NEW.state
				WHERE id = NEW.relationship_id;

				INSERT INTO `activity` (activity_id, activity_model, created_by, created_at, updated_at)
				VALUES (NEW.id, "RelationshipRevision", NEW.created_by, NOW(), NOW());
			END
		');
	}

}

Update trigger on relationship_revisions so it updates updated_at on relationships


<?php

namespace Ivory\GoogleMapBundle\Tests\Templating\Helper;

use Ivory\GoogleMapBundle\Templating\Helper\Overlays\MarkerImageHelper;
use Ivory\GoogleMapBundle\Templating\Helper\Base\PointHelper;
use Ivory\GoogleMapBundle\Templating\Helper\Base\SizeHelper;
use Ivory\GoogleMapBundle\Model\Overlays\MarkerImage;
use Ivory\GoogleMapBundle\Model\Base\Point;
use Ivory\GoogleMapBundle\Model\Base\Size;

/**
 * Marker image helper test
 *
 * @author GeLo <geloen.eric@gmail.com>
 */
class MarkerImageHelperTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var Ivory\GoogleMapBundle\Templating\Helper\Overlays\MarkerImageHelper
     */
    protected static $markerImageHelper = null;

    /**
     * @override
     */
    protected function setUp()
    {
        self::$markerImageHelper = new MarkerImageHelper(new PointHelper(), new SizeHelper());
    }

    /**
     * Checks the render method
     */
    public function testRender()
    {
        $markerImageTest = new MarkerImage();
        $markerImageTest->setUrl('url');
        $markerImageTest->setSize(new Size(1, 2));
        $markerImageTest->setOrigin(new point(3, 4));
        $markerImageTest->setAnchor(new Point(5, 6));
        $markerImageTest->setScaledSize(new Size(7, 8));

        $this->assertEquals(self::$markerImageHelper->render($markerImageTest),
            'var '.$markerImageTest->getJavascriptVariable().' = new google.maps.MarkerImage("url");'.PHP_EOL.
            $markerImageTest->getJavascriptVariable().'.size = new google.maps.Size(1, 2);'.PHP_EOL.
            $markerImageTest->getJavascriptVariable().'.origin = new google.maps.Point(3, 4);'.PHP_EOL.
            $markerImageTest->getJavascriptVariable().'.anchor = new google.maps.Point(5, 6);'.PHP_EOL.
            $markerImageTest->getJavascriptVariable().'.scaledSize = new google.maps.Size(7, 8);'.PHP_EOL
        );
    }
}

Add marker image helper tests

Add marker image helper tests


<?php

/* GNU FM -- a free network service for sharing your music listening habits

   Copyright (C) 2009 Free Software Foundation, Inc

   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');
require_once('templating.php');
require_once('data/sanitize.php');
require_once('data/Server.php');

$smarty->display('popular-page.tpl');
?>

Make popular artist tag cloud available to non-logged in users as a separate page from the welcome page


<?php

namespace StrictPhpTest\TypeChecker\TypeChecker;

use phpDocumentor\Reflection\Type;
use phpDocumentor\Reflection\Types\Array_;
use phpDocumentor\Reflection\Types\Boolean;
use phpDocumentor\Reflection\Types\Integer;
use phpDocumentor\Reflection\Types\Mixed;
use phpDocumentor\Reflection\Types\Null_;
use phpDocumentor\Reflection\Types\Object_;
use phpDocumentor\Reflection\Types\String_;
use StrictPhp\TypeChecker\TypeChecker\NullTypeChecker;

/**
 * Tests for {@see \StrictPhp\TypeChecker\TypeChecker\NullTypeChecker}
 *
 * @author Marco Pivetta <ocramius@gmail.com>
 * @license MIT
 *
 * @group Coverage
 *
 * @covers \StrictPhp\TypeChecker\TypeChecker\NullTypeChecker
 */
class NullTypeCheckerTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var NullTypeChecker
     */
    private $nullCheck;

    /**
     * {@inheritDoc}
     */
    public function setUp()
    {
        $this->nullCheck = new NullTypeChecker();
    }

    public function testRejectsNotNullType()
    {
        $this->setExpectedException(\InvalidArgumentException::class);

        $this->nullCheck->validate(null, new Integer());
    }

    /**
     * @dataProvider mixedDataTypes
     *
     * @param Type    $type
     * @param boolean $expected
     */
    public function testTypeCanBeApplied(Type $type, $expected)
    {
        $this->assertSame($expected, $this->nullCheck->canApplyToType($type));
    }

    /**
     * @covers        \StrictPhp\TypeChecker\TypeChecker\IntegerTypeChecker::validate
     *
     * @dataProvider  mixedDataTypesToValidate
     *
     * @param string  $value
     * @param boolean $expected
     */
    public function testIfDataTypeIsValid($value, $expected)
    {
        $this->assertSame($expected, $this->nullCheck->validate($value, new Null_()));
    }

    public function testSimulateFailureRaisesExceptionWhenNotPassAString()
    {
        $this->setExpectedException(\ErrorException::class);

        $this->nullCheck->simulateFailure([], new Null_());
    }

    public function testSimulateFailureDoesNothingWhenPassAString()
    {
        $this->nullCheck->simulateFailure(null, new Null_());
    }

    /**
     * @return mixed[][] - mixed type
     *                   - boolean expected
     *
     */
    public function mixedDataTypesToValidate()
    {
        return [
            [123,             false],
            [0x12,            false],
            [new \StdClass,   false],
            ['Marco Pivetta', false],
            [[],              false],
            [true,            false],
            [null,            true],
        ];
    }

    /**
     * @return mixed[][] - string with type of data
     *                   - expected output
     */
    public function mixedDataTypes()
    {
        return [
            [new Null_(),   true],
            [new Integer(), false],
            [new Object_(), false],
            [new String_(), false],
            [new Array_(),  false],
            [new Boolean(), false],
            [new Mixed(),   false],
        ];
    }
}

Test coverage for the `NullTypeChecker`

Test coverage for the `NullTypeChecker`


<?php

	/*
	 * Inquire all server connection channel statuses for queuemanager PIGEON.
	 * MQWeb runs on localhost and is listening on port 8081.
	 */
	$url = "http://localhost:8081/api/chstatus/inquire/PIGEON?ChannelType=Server-connection";
	$curl = curl_init();
	curl_setopt($curl, CURLOPT_URL, $url);
	curl_setopt($curl, CURLOPT_HEADER, false);
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
	$response = curl_exec($curl);
	$data = json_decode($response, true);
	print_r($data);

Add chstatus example for PHP

Add chstatus example for PHP


<?php

namespace App\Validation\EntityRules;

use App\Entities\User;
use Somnambulist\EntityValidation\AbstractEntityRules;

class UserRules extends AbstractEntityRules
{
    /**
     * Return an array of rules for validating Users
     *
     * @param object $entity
     * @return array
     */
    protected function buildRules($entity)
    {
        return [
            'name'     => 'required|min:1',
            'email'    => 'required|email|unique:'. User::class .',email,' . ($entity->getId() ?: 'null'),
            'username' => 'required|alphanum|unique:' . User::class . ',username,' . ($entity->getId() ?: 'null'),
        ];
    }

    /**
     * Define the entity that this validator supports
     *
     * @param object $entity
     * @return bool
     */
    public function supports($entity)
    {
        return $entity instanceof User;
    }
}

Create a validator class for the User entity


<?php

PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT');

class PHPUnit_Extensions_Database_DataSet_ArrayDataSet
extends PHPUnit_Extensions_Database_DataSet_AbstractDataSet {

	private $tables;

	public function __construct(
		array $data,
		array $tables=array()
	) {
		$this->tables = $tables;
		foreach ($data as $table_name => $row) {
			$table = new PHPUnit_Extensions_Database_DataSet_DefaultTable(
				new PHPUnit_Extensions_Database_DataSet_DefaultTableMetaData(
				    $table_name,
				    $this->getColumns($rows);
			    )
			);
			foreach ($rows as $row) {
				$table->addRow($row);
			}
			$this->tables[$table_name] = $table;
		}
	}

	private function getColumns($rows) {
		$columns = array();
		foreach ($rows as $row) {
			$columns = array_merge($columns, array_keys($row));
		}
		return array_values(array_unique($columns));
	}

	protected function createIterator($reverse=false) {
		return new PHPUnit_Extensions_Database_DataSet_DefaultTableIterator(
			$this->tables,
			$reverse
		);
	}

	public function getTable($table_name) {
        if (!array_key_exists($table_name, $this->tables)) {
        	throw new InvalidArgumentException(
        		sprintf(
        			'%s is not a table in the current database.',
        			$table_name
        		)
        	);
        }
        return $this->tables[$table_name];
	}
}

Add an array dataset. Seems silly to copy from documentation all the time.


@if ($message = Session::get('success'))

  <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
  Success: {{ $message }}

{{ Session::forget('success') }}
@endif

@if ($message = Session::get('error'))

  <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
  Error: {{ $message }}

{{ Session::forget('error') }}
@endif

@if ($message = Session::get('warning'))

  <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
  Warning: {{ $message }}

{{ Session::forget('warning') }}
@endif

@if ($message = Session::get('info'))

  <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
  FYI: {{ $message }}

{{ Session::forget('info') }}
@endif

@if ($message = Session::get('success'))

  <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
  Success: {{ $message['text'] }}

{{ Session::forget('success') }}
@endif

@if ($message = Session::get('error'))

  <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
  Error: {{ $message['text'] }}

{{ Session::forget('error') }}
@endif

@if ($message = Session::get('warning'))

  <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
  Warning: {{ $message['text'] }}

{{ Session::forget('warning') }}
@endif

@if ($message = Session::get('info'))

  <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
  FYI: {{ $message['text'] }}

{{ Session::forget('info') }}
@endif

Refactor where notifications look for messages.


<?php

/*
 * This file is part of the php-ga-measurement-protocol package.
 *
 * (c) Kristian Zondervan <kristian.zondervan@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Krizon\Google\Analytics\MeasurementProtocol;

use Guzzle\Common\Collection;
use Guzzle\Http\Message\Request;
use Guzzle\Service\Client;
use Guzzle\Service\Description\ServiceDescription;

class MeasurementProtocolClient extends Client
{
    public static function factory($config = array())
    {
        $default = array(
            'ssl' => false,
            'tid' => null
        );
        $required = array('ssl');

        $config = Collection::fromConfig($config, $default, $required);

        $baseUrl = ($config->get('ssl') === true) ? 'https://ssl.google-analytics.com' : 'http://www.google-analytics.com';

        $client = new self($baseUrl, $config);

        $description = ServiceDescription::factory(__DIR__ . '/Resources/service.php');
        $client->setDescription($description);

        if (true === isset($config['tid'])) {
            $client->setDefaultOption('query/tid', $config['tid']);
        }

        return $client;
    }
}

<?php

/*
 * This file is part of the php-ga-measurement-protocol package.
 *
 * (c) Kristian Zondervan <kristian.zondervan@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Krizon\Google\Analytics\MeasurementProtocol;

use Guzzle\Common\Collection;
use Guzzle\Http\Message\Request;
use Guzzle\Service\Client;
use Guzzle\Service\Description\ServiceDescription;

class MeasurementProtocolClient extends Client
{
    public static function factory($config = array())
    {
        $default = array(
            'ssl' => false,
            'tid' => null
        );
        $required = array('ssl');

        $config = Collection::fromConfig($config, $default, $required);

        $baseUrl = ($config->get('ssl') === true) ? 'https://ssl.google-analytics.com' : 'http://www.google-analytics.com';

        $client = new self($baseUrl, $config);

        $description = ServiceDescription::factory(__DIR__ . '/Resources/service.php');
        $client->setDescription($description);

        if (true === isset($config['tid'])) {
            $client->getEventDispatcher()->addListener('command.before_prepare', function (\Guzzle\Common\Event $e) use($config) {
                if (false === $e['command']->hasKey('tid')) {
                    $e['command']->set('tid', $config['tid']);
                }
            });
        }

        return $client;
    }
}

Fix tid as default config option and also as required parameter


<?php

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

class CreateJobsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('jobs', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('queue');
            $table->longText('payload');
            $table->unsignedTinyInteger('attempts');
            $table->unsignedInteger('reserved_at')->nullable();
            $table->unsignedInteger('available_at');
            $table->unsignedInteger('created_at');

            $table->index(['queue', 'reserved_at']);
        });
    }

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

Add DB migration for database queueing

Add DB migration for database queueing


<?php

namespace Magium\Magento2\Actions\Checkout;

use Magium\Magento\Actions\Checkout\RegisterNewCustomerCheckout as M1Checkout;
use Magium\Magento\Actions\Checkout\Steps\NewCustomerPassword;
use Magium\Magento\Actions\Checkout\Steps\PaymentMethod;
use Magium\Magento\Actions\Checkout\Steps\PlaceOrder;
use Magium\Magento\Actions\Checkout\Steps\SelectRegisterNewCustomerCheckout;
use Magium\Magento\Actions\Checkout\Steps\ShippingAddress;
use Magium\Magento\Actions\Checkout\Steps\ShippingMethod;
use Magium\Magento\Extractors\Checkout\CartSummary;
use Magium\Magento\Extractors\Checkout\OrderId;
use Magium\Magento\Navigators\Checkout\CheckoutStart;
use Magium\Magento2\Actions\Checkout\Steps\CustomerBillingAddress;
use Magium\Magento2\Themes\Magento2\ThemeConfiguration;

class RegisterNewCustomerCheckout extends M1Checkout
{

    public function __construct(
        CheckoutStart             $navigator,
        ThemeConfiguration    $theme,
        SelectRegisterNewCustomerCheckout           $registerNewCustomerCheckout,
        CustomerBillingAddress  $billingAddress,
        ShippingAddress         $shippingAddress,
        ShippingMethod          $shippingMethod,
        PaymentMethod           $paymentMethod,
        CartSummary             $cartSummary,
        PlaceOrder              $placeOrder,
        OrderId                 $orderIdExtractor,
        NewCustomerPassword     $newCustomerPassword
    )
    {
        $this->addStep($navigator);
        $this->addStep($registerNewCustomerCheckout);
        $this->addStep($newCustomerPassword);
        $this->addStep($billingAddress);
        $this->addStep($shippingAddress);
        $this->addStep($shippingMethod);
        $this->addStep($paymentMethod);
        $this->addStep($cartSummary);
        $this->addStep($placeOrder);
        $this->addStep($orderIdExtractor);

    }

}

Work on the register new customer method.


<?php

namespace Laravel\Passport\Http\Middleware;

use Illuminate\Auth\AuthenticationException;

class CheckScopes
{
    /**
     * Handle the incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  array  $scopes
     * @return \Illuminate\Http\Response
     */
    public function handle($request, $next, ...$scopes)
    {
        if (! $request->user() || ! $request->user()->token()) {
            throw new AuthenticationException;
        }

        foreach ($scopes as $scope) {
            if (! $request->user()->tokenCan($scope)) {
                throw new AuthenticationException;
            }
        }

        return $next($request);
    }
}

<?php

namespace Laravel\Passport\Http\Middleware;

use Illuminate\Auth\AuthenticationException;
use Illuminate\Auth\Access\AuthorizationException;

class CheckScopes
{
    /**
     * Handle the incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  array  $scopes
     * @return \Illuminate\Http\Response
     */
    public function handle($request, $next, ...$scopes)
    {
        if (! $request->user() || ! $request->user()->token()) {
            throw new AuthenticationException;
        }

        foreach ($scopes as $scope) {
            if (! $request->user()->tokenCan($scope)) {
                throw new AuthorizationException;
            }
        }

        return $next($request);
    }
}

Throw AuthorizationException if user doesn't have scope

Should this not throw AuthorizationException when the user doesn't have the required scopes as the user is authenticated but doesn't have the scope to access the route?


<?php namespace GenericCollections\Tests;

use GenericCollections\Collection;
use GenericCollections\Interfaces\CollectionInterface;
use GenericCollections\Set;

/**
 * Set is a Collection's extended class.
 * It only overrides the constructor to deny duplicates
 *
 * This test does not check other than the constructor, the
 * option for Unique Values is tested in CollectionUniqueValuesTest
 */
class SetTest extends \PHPUnit_Framework_TestCase
{

    public function testConstructor()
    {
        $set = new Set('int');
        $this->assertInstanceOf(CollectionInterface::class, $set);
        $this->assertInstanceOf(Collection::class, $set);
        $this->assertSame(true, $set->optionUniqueValues());
        $this->assertSame(false, $set->optionAllowNullMembers());
        $this->assertSame(true, $set->optionComparisonIsIdentical());
    }

    public function testConstructorWithNotUniqueValuesOption()
    {
        $set = new Set('int', [], 0);
        $this->assertSame(true, $set->optionUniqueValues());
    }
}

Set test as an extended class of collection


<?php

namespace ZendTest\Code\TestAsset;

class NullDefaultHintsClass
{
    public function arrayParameter(array $foo = null)
    {
    }

    public function callableParameter(callable $foo = null)
    {
    }

    public function intParameter(int $foo = null)
    {
    }

    public function floatParameter(float $foo = null)
    {
    }

    public function stringParameter(string $foo = null)
    {
    }

    public function boolParameter(bool $foo = null)
    {
    }

    public function selfParameter(self $foo = null)
    {
    }

    public function nullDefaultHintsClassParameter(NullDefaultHintsClass $foo = null)
    {
    }
}

Test asset: class with default-null return parameter


<?php

use YMLParser\YMLParser;

class YMLParser_YMLParser extends PHPUnit_Framework_TestCase
{

    public function testErrorOnFileDoesntExists()
    {

        $fakefile = dirname(__DIR__) . '/fixtures/non_existing_file.xml';
        $yml = new YMLParser(new \YMLParser\Driver\XMLReader);
        $result = $yml->open($fakefile);

        $this->assertFalse($result, "File shouldn/t be found");
        $this->assertTrue($yml->hasError());
        $this->assertEquals(YMLParser::ERROR_FILE_DOESNT_EXIST, $yml->getErrorCode());
    }

    public function testErrorOnBrokenFile()
    {
    }

    public function testValidXML()
    {
        $valid_xml_file = dirname(__DIR__) . '/fixtures/valid_xml.xml';
        $yml = new YMLParser(new \YMLParser\Driver\XMLReader);
        $result = $yml->open($valid_xml_file);

        $this->assertTrue($result);
    }
}

Test for missing file Test for existing file


<?php

use yii\db\Schema;
use yii\db\Migration;

class m150803_095959_alter_table_poll_add_locked_column extends Migration
{
    public function up()
    {
        $this->addColumn('poll', 'locked', Schema::TYPE_INTEGER .' AFTER organizer_id');
    }

    public function down()
    {
        $this->dropColumn('poll', 'locked');
        return true;
    }

    /*
    // Use safeUp/safeDown to run migration code within a transaction
    public function safeUp()
    {
    }

    public function safeDown()
    {
    }
    */
}

Create migration for poll locked column

Create migration for poll locked column


<?php

// Source : https://www.drupal.org/node/1545298

// Queue node for reindexing by apachesolr.
// Happens on next cron or next manual (re)indexing.
// @see admin/config/search/apachesolr
$id = 123;
$type = 'node';
$bundle = 'node_type';
$indexer_table = apachesolr_get_indexer_table($type);
db_merge($indexer_table)
  ->key(array(
    'entity_type' => $type,
    'entity_id' => $id,
  ))
  ->insertFields(array(
    'entity_type' => $type,
    'entity_id' => $id,
    'bundle' => $bundle,
    'status' => 1,
  ))
  ->fields(array(
    'changed' => REQUEST_TIME,
  ))
  ->execute();

Add D7 apachesolr manual reindex single node snippet.


<?php

namespace League\Plates\Template;

class FunctionsTest extends \PHPUnit_Framework_TestCase
{
    private $functions;

    public function setUp()
    {
        $this->functions = new Functions();
    }

    public function testCanCreateInstance()
    {
        $this->assertInstanceOf('League\Plates\Template\Functions', $this->functions);
    }

    public function testAddAndGetFunction()
    {
        $this->assertInstanceOf('League\Plates\Template\Functions', $this->functions->add('upper', 'strtoupper'));
        $this->assertEquals($this->functions->get('upper')->getCallback(), 'strtoupper');
    }

    public function testAddFunctionConflict()
    {
        $this->setExpectedException('LogicException', 'The template function name "upper" is already registered.');
        $this->functions->add('upper', 'strtoupper');
        $this->functions->add('upper', 'strtoupper');
    }

    public function testGetNonExistentFunction()
    {
        $this->setExpectedException('LogicException', 'The template function "foo" was not found.');
        $this->functions->get('foo');
    }

    public function testRemoveFunction()
    {
        $this->functions->add('upper', 'strtoupper');
        $this->assertEquals($this->functions->exists('upper'), true);
        $this->functions->remove('upper');
        $this->assertEquals($this->functions->exists('upper'), false);
    }

    public function testRemoveNonExistentFunction()
    {
        $this->setExpectedException('LogicException', 'The template function "foo" was not found.');
        $this->functions->remove('foo');
    }

    public function testFunctionExists()
    {
        $this->assertEquals($this->functions->exists('upper'), false);
        $this->functions->add('upper', 'strtoupper');
        $this->assertEquals($this->functions->exists('upper'), true);
    }
}

Add tests for Function class.

Add tests for Function class.


Add thera table row to git

Add thera table row to git


<?php
namespace Onion\Framework\Router\Strategy;

use function Onion\Framework\merge;

class TreeStrategy
{
    private $routes;

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

    public function resolve(string $method, string $path)
    {
        $parts = explode('/', trim($path, '/'));

        $params = [];
        $match = $this->match($this->routes, $parts, $params);

        if ($match === null) {
            throw new \RuntimeException('No match found');
        }
        $params = array_filter($params, function ($key) {
            return !is_integer($key);
        }, ARRAY_FILTER_USE_KEY);

        if (isset($match['methods']) && !in_array($method, $match['methods'])) {
            throw new \BadMethodCallException("Method {$method} not allowed");
        }

        return [$match, $params];
    }

    private function match(array $routes, array $parts, &$params = []): ?array
    {
        $part = array_shift($parts);

        if ($part === null) {
            return $routes;
        }

        foreach ($routes as $segment => $remaining) {
            if (preg_match("/^{$segment}$/i", $part, $matches) > 0) {
                $params = merge($params ?? [], $matches);
                return $this->match($remaining, $parts, $params);
            }
        }

        return null;
    }
}

Introduce concept of resolution strategies


@extends('template')

@section('content')

TMLP Stats

Welcome to the Home of TMLP Stats! We're still building an awesome new stats site, but it's not quite ready yet. Check back soon!

@endsection

@extends('template')

@section('content')

TMLP Stats

Welcome to the Home of TMLP Stats! Click Login/Register in the top right to login and get started.

@endsection

Update landing page text to guide people to login


<?php
class Vpc_Columns_TestComponent extends Vpc_Columns_Component
{
    public static function getSettings()
    {
        $ret = parent::getSettings();
        $ret['generators']['columns']['model'] = 'Vpc_Columns_TestColumnsModel';
        $ret['generators']['columns']['component'] = 'Vpc_Columns_TestComponent_Column';
        $ret['ownModel'] = 'Vpc_Columns_TestModel';
        return $ret;
    }

}

<?php
class Vpc_Columns_TestComponent extends Vpc_Columns_Component
{
    public static function getSettings()
    {
        $ret = parent::getSettings();
        $ret['generators']['child']['model'] = 'Vpc_Columns_TestColumnsModel';
        $ret['generators']['child']['component'] = 'Vpc_Columns_TestComponent_Column';
        $ret['ownModel'] = 'Vpc_Columns_TestModel';
        return $ret;
    }

}

Fix test, generator wurde umbenannt

Fix test, generator wurde umbenannt

ist noch von der list umstellung


<?php

namespace Tienvx\Bundle\MbtBundle\Message;

class QueuedLoopMessage
{
    protected $bugId;
    protected $length;
    protected $pair;

    public function __construct(int $bugId, int $length, array $pair)
    {
        $this->bugId = $bugId;
        $this->length = $length;
        $this->pair = $pair;
    }

    public function getBugId(): int
    {
        return $this->bugId;
    }

    public function getLength(): int
    {
        return $this->length;
    }

    public function getPair(): array
    {
        return $this->pair;
    }

    public function __toString()
    {
        return json_encode([
            'bugId' => $this->bugId,
            'length' => $this->length,
            'pair' => $this->pair,
        ]);
    }

    public static function fromString(string $message)
    {
        $decoded = json_decode($message, true);
        return new static($decoded['bugId'], $decoded['length'], $decoded['pair']);
    }
}

<?php

namespace Tienvx\Bundle\MbtBundle\Message;

class QueuedLoopMessage
{
    protected $id;
    protected $length;
    protected $pair;

    public function __construct(int $id, int $length, array $pair)
    {
        $this->id     = $id;
        $this->length = $length;
        $this->pair   = $pair;
    }

    public function getId(): int
    {
        return $this->id;
    }

    public function getLength(): int
    {
        return $this->length;
    }

    public function getPair(): array
    {
        return $this->pair;
    }

    public function __toString()
    {
        return json_encode([
            'id' => $this->id,
            'length' => $this->length,
            'pair' => $this->pair,
        ]);
    }

    public static function fromString(string $message)
    {
        $decoded = json_decode($message, true);
        return new static($decoded['id'], $decoded['length'], $decoded['pair']);
    }
}

Fix typo: identifier should be 'id' not 'bugId'


<?php
namespace Josegonzalez\Upload\Path;

use Cake\Utility\Hash;
use LogicException;

class DefaultPathProcessor
{
    public function __invoke($table, $entity, $field, $settings)
    {
        $defaultPath = 'webroot{DS}files{DS}{model}{DS}{field}{DS}';
        $path = Hash::get($settings, 'path', $defaultPath);
        $replacements = [
            '{primaryKey}' => $entity->get($table->primaryKey()),
            '{model}' => $table->alias(),
            '{field}' => $field,
            '{time}' => time(),
            '{microtime}' => microtime(),
            '{DS}' => DIRECTORY_SEPARATOR,
        ];
        return str_replace(
            array_keys($replacements),
            array_values($replacements),
            $path
        );
    }
}

<?php
namespace Josegonzalez\Upload\Path;

use Cake\Utility\Hash;
use LogicException;

class DefaultPathProcessor
{
    public function __invoke($table, $entity, $field, $settings)
    {
        $defaultPath = 'webroot{DS}files{DS}{model}{DS}{field}{DS}';
        $path = Hash::get($settings, 'path', $defaultPath);
        if (strpos($path, '{primaryKey}') !== false) {
            if ($entity->isNew()) {
                throw new LogicException('{primaryKey} substitution not allowed for new entities');
            }
            if (is_array($table->primaryKey())) {
                throw new LogicException('{primaryKey} substitution not valid for composite primary keys');
            }
        }

        $replacements = [
            '{primaryKey}' => $entity->get($table->primaryKey()),
            '{model}' => $table->alias(),
            '{field}' => $field,
            '{time}' => time(),
            '{microtime}' => microtime(),
            '{DS}' => DIRECTORY_SEPARATOR,
        ];
        return str_replace(
            array_keys($replacements),
            array_values($replacements),
            $path
        );
    }
}

Handle case where primaryKey isn't a valid subsitution


<?php

namespace Studio\Parts\Composer;

use League\Flysystem\Filesystem;
use Studio\Parts\AbstractPart;

class Part extends AbstractPart
{

    public function setupPackage($composer, Filesystem $target)
    {
        // Ask for package name
        $composer->name = $this->input->ask(
            'Please name this package',
            '/[[:alnum:]]+\/[[:alnum:]]+/'
        );

        // Ask for the root namespace
        $namespace = $this->input->ask(
            'Please provide a default namespace (PSR-4)',
            '/([[:alnum:]]+\\\\?)+/',
            $this->makeDefaultNamespace($composer->name)
        );

        // Normalize and store the namespace
        $namespace = rtrim($namespace, '\\');
        @$composer->autoload->{'psr-4'}->{$namespace} = 'src/';

        // Create an example file
        $this->copyTo(
            __DIR__ . '/stubs/src/Example.php',
            $target,
            'src/Example.php',
            function ($content) use ($namespace) {
                return preg_replace('/namespace[^;]+;/', "namespace $namespace;", $content);
            }
        );
    }

    protected function makeDefaultNamespace($package)
    {
        list($vendor, $name) = explode('/', $package);

        return ucfirst($vendor) . '\\' . ucfirst($name);
    }

}

<?php

namespace Studio\Parts\Composer;

use League\Flysystem\Filesystem;
use Studio\Parts\AbstractPart;

class Part extends AbstractPart
{

    public function setupPackage($composer, Filesystem $target)
    {
        // Ask for package name
        $composer->name = $this->input->ask(
            'Please name this package',
            '/[[:alnum:]]+\/[[:alnum:]]+/'
        );

        // Ask for the root namespace
        $namespace = $this->input->ask(
            'Please provide a default namespace (PSR-4)',
            '/([[:alnum:]]+\\\\?)+/',
            $this->makeDefaultNamespace($composer->name)
        );

        // Normalize and store the namespace
        $namespace = rtrim($namespace, '\\');
        @$composer->autoload->{'psr-4'}->{"$namespace\\"} = 'src/';

        // Create an example file
        $this->copyTo(
            __DIR__ . '/stubs/src/Example.php',
            $target,
            'src/Example.php',
            function ($content) use ($namespace) {
                return preg_replace('/namespace[^;]+;/', "namespace $namespace;", $content);
            }
        );
    }

    protected function makeDefaultNamespace($package)
    {
        list($vendor, $name) = explode('/', $package);

        return ucfirst($vendor) . '\\' . ucfirst($name);
    }

}

Fix namespace in autoload list.

Fix namespace in autoload list.


<?php

namespace Tga\OpenGraphBundle\Tests\Renderer;

use Symfony\Component\Routing\Router;
use Tga\OpenGraphBundle\Registry\Registry;
use Tga\OpenGraphBundle\Renderer\OpenGraphMapRenderer;
use Tga\OpenGraphBundle\Tests\Mock\Map;

class OpenGraphMapRendererTest extends \PHPUnit_Framework_TestCase
{
    public function testConstruct()
    {
        $router = new Router();

        $registry = new Registry($router);
        $registry->register(new Map());

        $renderer = new OpenGraphMapRenderer($registry);

        $this->assertEquals($renderer->getRegistry(), $registry);
        $this->assertEquals($renderer->getRegistry()->getRouter(), $registry->getRouter());

        return $renderer;

    }

    /**
     * @depends testConstruct
     */
    public function testRenderValid(OpenGraphMapRenderer $renderer)
    {
        $entity = new \stdClass();
        $entity->name = 'TestName';

        $this->assertEquals("\t<meta property=\"og:title\" content=\"TestName\" />\r\n", $renderer->render($entity));
    }

    /**
     * @expectedException \Tga\OpenGraphBundle\Renderer\Exception\EntityNotSupported
     */
    public function testRenderInvalid()
    {
        $router = new Router();
        $registry = new Registry($router);
        $renderer = new OpenGraphMapRenderer($registry);

        $entity = new \stdClass();
        $entity->name = 'TestName';

        $renderer->render($entity);
    }
}

<?php

namespace Tga\OpenGraphBundle\Tests\Renderer;

use Symfony\Component\Routing\Router;
use Tga\OpenGraphBundle\Registry\Registry;
use Tga\OpenGraphBundle\Renderer\OpenGraphMapRenderer;
use Tga\OpenGraphBundle\Tests\Mock\Map;

class OpenGraphMapRendererTest extends \PHPUnit_Framework_TestCase
{
    public function testConstruct()
    {
        $router = new Router();

        $registry = new Registry($router);
        $registry->register(new Map());

        $renderer = new OpenGraphMapRenderer($registry);

        $this->assertEquals($renderer->getRegistry(), $registry);
        $this->assertEquals($renderer->getRegistry()->getRouter(), $registry->getRouter());

        return $renderer;

    }

    /**
     * @depends testConstruct
     */
    public function testRenderValid(OpenGraphMapRenderer $renderer)
    {
        $entity = new \stdClass();
        $entity->name = 'TestName';

        $this->assertTrue(strpos($renderer->render($entity), '<meta property="og:title" content="TestName" />') !== false);
    }

    /**
     * @expectedException \Tga\OpenGraphBundle\Renderer\Exception\EntityNotSupported
     */
    public function testRenderInvalid()
    {
        $router = new Router();
        $registry = new Registry($router);
        $renderer = new OpenGraphMapRenderer($registry);

        $entity = new \stdClass();
        $entity->name = 'TestName';

        $renderer->render($entity);
    }
}

Update renderer test for Unix lines

Update renderer test for Unix lines


<?php

declare(strict_types=1);

namespace Rinvex\Support\Traits;

use DateTimeZone;
use Illuminate\Support\Arr;

trait HasTimezones
{
    /**
     * Return a timestamp as DateTime object.
     *
     * @param  mixed  $value
     * @return \Illuminate\Support\Carbon
     */
    protected function asDateTime($value)
    {
        $datetime = parent::asDateTime($value);

        $setAttributeCalled = Arr::first(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 30), function ($trace) {
            return $trace['function'] === 'setAttribute';
        });

        // When setting attributes, skip custom timezone setting,
        // and use default application settings for consistent storage!
        if (! $setAttributeCalled && app()->bound('request.user') && $timezone = optional(app('request.user'))->timezone) {
            $datetime->setTimezone(new DateTimeZone($timezone));
        }

        return $datetime;
    }
}

<?php

declare(strict_types=1);

namespace Rinvex\Support\Traits;

use DateTimeZone;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Date;

trait HasTimezones
{
    /**
     * Return a timestamp as DateTime object.
     *
     * @param  mixed  $value
     *
     * @return \Illuminate\Support\Carbon
     */
    protected function asDateTime($value)
    {
        $datetime = parent::asDateTime($value);
        $timezone = app()->bound('request.user') ? optional(app('request.user'))->timezone : null;

        if (! $timezone || $timezone === config('app.timezone')) {
            return $datetime;
        }

        $thisIsUpdateRequest = Arr::first(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 30), function ($trace) {
            return $trace['function'] === 'setAttribute';
        });

        if ($thisIsUpdateRequest) {
            // When updating attributes, we need to reset user timezone to system timezone before saving!
            return Date::parse($datetime->toDateTimeString(), $timezone)->setTimezone(config('app.timezone'));
        }

        return $datetime->setTimezone(new DateTimeZone($timezone));
    }
}

Refactor timezone implementation to fix read/write date attributes


<?php

/*

Plugin Name: Castlegate IT WP Breadcrumb
Plugin URI: http://github.com/castlegateit/cgit-wp-breadcrumb
Description: Simple breadcrumb navigation for WordPress.
Version: 3.1
Author: Castlegate IT
Author URI: http://www.castlegateit.co.uk/
License: MIT

*/

if (!defined('ABSPATH')) {
    wp_die('Access denied');
}

require_once __DIR__ . '/classes/autoload.php';
require_once __DIR__ . '/functions.php';

do_action('cgit_breadcrumb_loaded');

<?php

/*

Plugin Name: Castlegate IT WP Breadcrumb
Plugin URI: http://github.com/castlegateit/cgit-wp-breadcrumb
Description: Simple breadcrumb navigation for WordPress.
Version: 3.1
Author: Castlegate IT
Author URI: http://www.castlegateit.co.uk/
License: AGPL

*/

if (!defined('ABSPATH')) {
    wp_die('Access denied');
}

require_once __DIR__ . '/classes/autoload.php';
require_once __DIR__ . '/functions.php';

do_action('cgit_breadcrumb_loaded');

Switch license from MIT to AGPL in plugin file


<?php

namespace Illuminate\Database;

use Throwable;
use Illuminate\Support\Str;

trait DetectsLostConnections
{
    /**
     * Determine if the given exception was caused by a lost connection.
     *
     * @param  \Throwable  $e
     * @return bool
     */
    protected function causedByLostConnection(Throwable $e)
    {
        $message = $e->getMessage();

        return Str::contains($message, [
            'server has gone away',
            'no connection to the server',
            'Lost connection',
            'is dead or not enabled',
            'Error while sending',
            'decryption failed or bad record mac',
            'server closed the connection unexpectedly',
            'SSL connection has been closed unexpectedly',
            'Error writing data to the connection',
            'Resource deadlock avoided',
            'Transaction() on null',
            'child connection forced to terminate due to client_idle_limit',
            'query_wait_timeout',
            'reset by peer',
            'Physical connection is not usable',
            'TCP Provider: Error code 0x68',
            'php_network_getaddresses: getaddrinfo failed: Name or service not known',
            'ORA-03114',
            'Packets out of order. Expected',
            'Adaptive Server connection failed',
        ]);
    }
}

<?php

namespace Illuminate\Database;

use Throwable;
use Illuminate\Support\Str;

trait DetectsLostConnections
{
    /**
     * Determine if the given exception was caused by a lost connection.
     *
     * @param  \Throwable  $e
     * @return bool
     */
    protected function causedByLostConnection(Throwable $e)
    {
        $message = $e->getMessage();

        return Str::contains($message, [
            'server has gone away',
            'no connection to the server',
            'Lost connection',
            'is dead or not enabled',
            'Error while sending',
            'decryption failed or bad record mac',
            'server closed the connection unexpectedly',
            'SSL connection has been closed unexpectedly',
            'Error writing data to the connection',
            'Resource deadlock avoided',
            'Transaction() on null',
            'child connection forced to terminate due to client_idle_limit',
            'query_wait_timeout',
            'reset by peer',
            'Physical connection is not usable',
            'TCP Provider: Error code 0x68',
            'php_network_getaddresses: getaddrinfo failed: Name or service not known',
            'ORA-03114',
            'Packets out of order. Expected',
            'Adaptive Server connection failed',
            'Communication link failure',
        ]);
    }
}

Add Azure SQL Server "connection lost" message


<?php

declare(strict_types=1);

namespace JMS\Serializer\Exclusion;

use JMS\Serializer\Context;
use JMS\Serializer\Metadata\ClassMetadata;
use JMS\Serializer\Metadata\PropertyMetadata;

/**
 * @author Adrien Brault <adrien.brault@gmail.com>
 */
final class DepthExclusionStrategy implements ExclusionStrategyInterface
{
    public function shouldSkipClass(ClassMetadata $metadata, Context $context): bool
    {
        return $this->isTooDeep($context);
    }

    public function shouldSkipProperty(PropertyMetadata $property, Context $context): bool
    {
        return $this->isTooDeep($context);
    }

    private function isTooDeep(Context $context): bool
    {
        $depth = $context->getDepth();
        $metadataStack = $context->getMetadataStack();

        $nthProperty = 0;
        // iterate from the first added items to the lasts
        for ($i = $metadataStack->count() - 1; $i > 0; $i--) {
            $metadata = $metadataStack[$i];
            if ($metadata instanceof PropertyMetadata) {
                $nthProperty++;
                $relativeDepth = $depth - $nthProperty;

                if (null !== $metadata->maxDepth && $relativeDepth > $metadata->maxDepth) {
                    return true;
                }
            }
        }

        return false;
    }
}

<?php

declare(strict_types=1);

namespace JMS\Serializer\Exclusion;

use JMS\Serializer\Context;
use JMS\Serializer\Metadata\ClassMetadata;
use JMS\Serializer\Metadata\PropertyMetadata;

/**
 * @author Adrien Brault <adrien.brault@gmail.com>
 */
final class DepthExclusionStrategy implements ExclusionStrategyInterface
{
    public function shouldSkipClass(ClassMetadata $metadata, Context $context): bool
    {
        return $this->isTooDeep($context);
    }

    public function shouldSkipProperty(PropertyMetadata $property, Context $context): bool
    {
        return $this->isTooDeep($context);
    }

    private function isTooDeep(Context $context): bool
    {
        $relativeDepth = 0;

        foreach ($context->getMetadataStack() as $metadata) {
            if (!$metadata instanceof PropertyMetadata) {
                continue;
            }

            $relativeDepth++;

            if (null !== $metadata->maxDepth && $relativeDepth > $metadata->maxDepth) {
                return true;
            }
        }

        return false;
    }
}

Improve performance of max depth exclusions


<?php
require_once __DIR__ . '/login.php';
require_once __DIR__ . '/../lib/utils.php';

class LoginDoubleChecker extends RawDataContainer {
  static protected function requiredFieldSchema(): array {
    return [
      'login' => 'LoginInfo',
      'db-query-set' => 'DatabaseQuerySet',
    ];
  }

  public function verify(): void {
    if (!$this->checkAll()) throw SecurityException::permission();
  }

  public function checkAll(): bool {
    return $this->checkLogin() && $this->checkPermission();
  }

  public function checkLogin(): bool {
    [
      'cookie' => $cookie,
      'session' => $session,
      'login' => $login,
      'db-query-set' => $dbQuerySet,
    ] = $this->getData();

    return Login::checkLogin(
      $login->assign([
        'cookie' => $cookie,
        'session' => $session,
        'db-query-set' => $dbQuerySet,
      ])->getData()
    )->isLoggedIn();
  }

  public function checkPermission(): bool {
    return $this->get('login')->isAdmin();
  }
}

class SecurityException extends Exception {
  static public function permission(): self {
    return new static('Permission Denied');
  }
}
?>

<?php
require_once __DIR__ . '/login.php';
require_once __DIR__ . '/../lib/utils.php';

class LoginDoubleChecker extends RawDataContainer {
  static protected function requiredFieldSchema(): array {
    return [
      'login' => 'LoginInfo',
      'db-query-set' => 'DatabaseQuerySet',
    ];
  }

  public function verify(): void {
    if (!$this->checkAll()) throw SecurityException::permission();
  }

  public function checkAll(): bool {
    return $this->checkLogin() && $this->checkPermission();
  }

  public function checkLogin(): bool {
    [
      'cookie' => $cookie,
      'session' => $session,
      'login' => $login,
      'db-query-set' => $dbQuerySet,
    ] = $this->getData();

    return Login::checkLogin(
      $login->assign([
        'cookie' => $cookie,
        'session' => $session,
        'db-query-set' => $dbQuerySet,
      ])->getData()
    )->isLoggedIn();
  }

  public function checkPermission(): bool {
    return $this->get('login')->isAdmin();
  }

  public function username(): string {
    return $this->get('login')->username();
  }

  public function password(): string {
    return $this->get('login')->password();
  }
}

class SecurityException extends Exception {
  static public function permission(): self {
    return new static('Permission Denied');
  }
}
?>

Create username and password method

Create username and password method


<?php

namespace Styde\Html;

use Illuminate\Support\Facades\{Auth, Gate};

trait HandlesAccess
{
    public $included = true;

    public function includeIf(bool $value = true)
    {
        $this->included = $value;

        return $this;
    }

    public function ifAuth()
    {
        return $this->includeIf(Auth::check());
    }

    public function ifGuest()
    {
        return $this->includeIf(Auth::guest());
    }

    public function ifCan($ability, $arguments = [])
    {
        return $this->includeIf(Gate::allows($ability, $arguments));
    }

    public function ifCannot($ability, $arguments = [])
    {
        return $this->includeIf(Gate::denies($ability, $arguments));
    }

    public function ifIs($role)
    {
        $user = Auth::user();

        return $this->includeIf($user && $user->isA($role));
    }
}

<?php

namespace Styde\Html;

use Illuminate\Support\Facades\{Auth, Gate};

trait HandlesAccess
{
    public $included = true;

    public function includeIf(bool $value = true)
    {
        $this->included = $value;

        if (! $this->included && isset($this->rules)) {
            $this->disableRules();
        }

        return $this;
    }

    public function ifAuth()
    {
        return $this->includeIf(Auth::check());
    }

    public function ifGuest()
    {
        return $this->includeIf(Auth::guest());
    }

    public function ifCan($ability, $arguments = [])
    {
        if ($this->rules && ! Gate::allows($ability, $arguments)) {
            $this->rules = [];
        }

        return $this->includeIf(Gate::allows($ability, $arguments));
    }

    public function ifCannot($ability, $arguments = [])
    {
        return $this->includeIf(Gate::denies($ability, $arguments));
    }

    public function ifIs($role)
    {
        $user = Auth::user();

        return $this->includeIf($user && $user->isA($role));
    }
}

Remove all rules if not included

Remove all rules if not included