<?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');
require_once('data/TagCloud.php');
require_once('artist-menu.php');

if($logged_in == false) {
	$smarty->assign('pageheading', 'Log in required');
	$smarty->assign('details', 'You need to log in to tag artists.');
	$smarty->display('error.tpl');
	die();
}

try {
	$artist = new Artist(urldecode($_GET['artist']));
} catch (exception $e) {
        $smarty->assign('pageheading', 'Artist not found.');
        $smarty->assign('details', 'The artist '.($_GET['artist']).' was not found in the database.');
	$smarty->display('error.tpl');
	die();
}

if ($_POST['tag']) {
	$artist->addTags($_POST['tags'], $this_user->uniqueid);
}

$smarty->assign('name', $artist->name);
$smarty->assign('pagetitle', $artist->name);

try {
	$tagCloud = TagCloud::generateTagCloud('tags', 'tag', 10, $artist->name, "artist");
	$smarty->assign('tagcloud', $tagCloud);
} catch (exception $ex) {
	$tagCloud = array();
}

$smarty->assign('mytags', $this_user->getTagsForArtist($artist->name));

$submenu = artist_menu($artist, 'Tag');
$smarty->assign('submenu', $submenu);

$smarty->assign('headerfile', 'artist-header.tpl');
$smarty->display("artist-tag.tpl");
?>

Add artist tagging page (missed from last commit)


<?php

class Bubble extends Eloquent {

    protected $guarded = ['id'];

    public function strip() {
        return $this->belongTo('Strip');
    }

    public function user() {
        return $this->belongTo('User');
    }

    public function language() {
        return $this->belongTo('Language', 'lang_id');
    }

    public function parent() {
        return $this->belongTo('Bubble', 'parent_id');
    }

    public function original() {
        return $this->belongTo('Bubble', 'original_id');
    }

}

Create bubble model with external links.


<?php
/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2016 Bruno P. Kinoshita, Peter Florijn
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to
 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
 * the Software, and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

namespace Repositories;

use \TestCase;
use \Mockery;
use \Hash;
use Nestor\Entities\ProjectStatuses;
use Nestor\Repositories\ProjectStatusesRepository;
use Illuminate\Foundation\Testing\DatabaseTransactions;

class ProjectRepositoryTest extends TestCase
{

    use DatabaseTransactions;

    public function testRepositoryModelClass() {
        $projectsRepository = $this->app->make('Nestor\Repositories\ProjectsRepository');
        $this->assertEquals(Projects::class, $projectsRepository->model());
    }

    public function testCreateExecutionType() {
        $payload = [
            'name' => 'Some random Test',
            'description' => 'A good food is hard to find'
        ];

        $projectStatusesRepository = $this->mock(Nestor\Repositories\ProjectStatusesRepository::class);
        $projectStatusesRepository
            ->shouldReceive('create')
            ->with(Mockery::any())
            ->once()
            ->andReturn(factory(ProjectStatuses::class)->make($payload));
        $executionType = $projectStatusesRepository->create($payload);

        $this->assertEquals($payload['name'], $executionType['name']);
        $this->assertEquals($payload['description'], $executionType['description']);
        $this->assertTrue($executionType['id'] > 0);
    }

}

Fix copy and paste mistake

Fix copy and paste mistake


<?php

use yii\db\Migration;

/**
 * Handles adding PriceCorrection to table `sizes`.
 */
class m160615_155827_add_PriceCorrection_to_Sizes extends Migration
{
    /**
     * @inheritdoc
     */
    public function up()
    {
        $this->addColumn('Sizes', 'PriceCorrection',$this->decimal(8,2)->notNull()->defaultValue(0));
    }

    /**
     * @inheritdoc
     */
    public function down()
    {
        $this->dropColumn('Sizes', 'PriceCorrection');
    }
}

Migrate table Sizes - added column PriceCorrection


<?php
namespace AB\Bundle\Command;

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

use AB\Bundle\Entity\University;

class DBPopulateCommand extends ContainerAwareCommand
{
    protected function configure()
    {
        $this
            ->setName('ab:dbpopulate')
            ->setDescription('Populate the database')
            ->addArgument('unilist', InputArgument::REQUIRED, 'Path to a newline-separated list of universities')
            ;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $em = $this->getContainer()->get('doctrine')->getEntityManager();

        $list = $input->getArgument('unilist');
        $lines = file($list, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

        if($lines == false) {
            $text = 'There was an error reading the university list.';
        } else {
            foreach($lines as $line) {
                $u = explode("|", $line);

                $uni = new University();
                $uni->setName($u[0]);
                $uni->setCountry($u[1]);

                $em->persist($uni);
            }

            $em->flush();
            $text = 'Loaded university names.';
        }

        $output->writeln($text);
    }
}

?>

Implement app/console command to populate database

Currently only universities, will add-on anything else if required


<?php

	class User extends Model
	{
		var $_table_name = 'users';
		var $_key_field = 'user_id';
		var $_insert_timestamp_field = 'create_date';
		var $_update_timestamp_field = 'update_date';

		static function find($criteria, $sort = false, $limitStart = false, $limitEnd = false) {
			return parent::find('User', 'users', $criteria, $sort, $limitStart, $limitEnd);
		}
		static function findByUserId($userId) {
			return self::find(array('user_id' => $userId));
		}
	}

Add sample User model class to illustrate find() functionality.


<?php

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

class CreateFailedJobsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    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();
        });
    }

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

Add migration for failed jobs table

Add migration for failed jobs table


<?php
# -- BEGIN LICENSE BLOCK ----------------------------------
# This file is part of Apercite, a plugin for Dotclear.
#
# Copyright (c) 2009 Francis Besset
# francis.besset@free.fr
#
# Licensed under the GPL version 2.0 license.
# A copy of this license is available in LICENSE file or at
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
# -- END LICENSE BLOCK ------------------------------------

if (!defined('DC_RC_PATH')) { return; }

$this->registerModule(
	/* Name */				"Apercite",
	/* Description*/		"Apercite is a module to include a thumbnail of your links in your post.",
	/* Author */			"Francis Besset",
	/* Version */			'1.1.2',
	/* Permissions */		'admin'
);
?>

Move files plugin to trunk folder

Move files plugin to trunk folder


<?php

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

class NullablesOnForumCovers extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('forum_forum_covers', function ($table) {
            $table->datetime('created_at')->nullable()->default(null)->change();
            $table->datetime('updated_at')->nullable()->default(null)->change();
            $table->string('hash')->nullable()->change();
            $table->string('ext')->nullable()->change();
        });

        Schema::table('forum_topic_covers', function ($table) {
            $table->datetime('created_at')->nullable()->default(null)->change();
            $table->datetime('updated_at')->nullable()->default(null)->change();
            $table->string('hash')->nullable()->change();
            $table->string('ext')->nullable()->change();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('forum_forum_covers', function ($table) {
            $table->datetime('created_at')->nullable(false)->change();
            $table->datetime('updated_at')->nullable(false)->change();
            $table->string('hash')->nullable(false)->change();
            $table->string('ext')->nullable(false)->change();
        });

        Schema::table('forum_topic_covers', function ($table) {
            $table->datetime('created_at')->nullable(false)->change();
            $table->datetime('updated_at')->nullable(false)->change();
            $table->string('hash')->nullable(false)->change();
            $table->string('ext')->nullable(false)->change();
        });
    }
}

Fix topic and forum covers

Fix topic and forum covers

Nullables where they should be.


<?php

namespace Tooly\Tests\Factory;

use org\bovigo\vfs\vfsStream;
use Tooly\Factory\ToolFactory;
use Tooly\Model\Tool;

/**
 * @package Tooly\Tests\Factory
 */
class ToolFactoryTest extends \PHPUnit_Framework_TestCase
{
    public function testCanCreateATool()
    {
        vfsStream::setup();

        $tool = ToolFactory::createTool('test', 'vfs://root', [
            'url' => 'my-url',
            'sign-url' => 'my-sign-url',
            'force-replace' => true
        ]);

        $this->assertInstanceOf(Tool::class, $tool);
        $this->assertEquals('my-url', $tool->getUrl());
        $this->assertEquals('my-sign-url', $tool->getSignUrl());
        $this->assertTrue($tool->forceReplace());
        $this->assertTrue($tool->isOnlyDev());
    }

    public function testCanCreateMultipleTools()
    {
        vfsStream::setup();

        $data = [
            'tool-1' => [
                'url' => 'my-tool-1-url',
            ],
            'tool-2' => [
                'url' => 'my-tool-2-url',
            ]
        ];

        $tools = ToolFactory::createTools('vfs://root', $data);
        $this->assertCount(2, $tools);
    }
}

Add tests for factory and model

Add tests for factory and model


<?php

date_default_timezone_set('UTC');
include 'init.php';

class ModelColor extends \atk4\data\Model
{

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

        $this->addField('name', [
            'type' => 'string',
            'ui'   => [
                'table' => [
                    'Tooltip',
                    [
                        'tooltip_field' => 'note',
                        'icon' => 'info circle blue'
                    ]
                ]
            ]
        ]);

        $this->addField('value_not_always_present', [
            'type' => 'string',
            'ui'   => [
                'table' => [
                    'NoValue',
                    [
                        'no_value' => ' no value '
                    ]
                ]
            ]
        ]);

        $this->addField('key_value', [
            'type' => 'string',
            'values' => [
                1 => '1st val',
                '2nd val',
                '3rd val',
                '4th val',
            ],
            'ui'   => [
                'table' => [
                    'KeyValue'
                ]
            ]
        ]);

        $this->addField('key_value_string', [
            'type' => 'string',
            'values' => [
                'one' => '1st val',
                'two' => '2nd val',
                'three' => '3rd val',
                'four' => '4th val',
            ],
            'ui'   => [
                'table' => [
                    'KeyValue'
                ]
            ]
        ]);

        $this->addField('interests', [
            'type' => 'string',
            'ui'   => [
              'table' => [
                  'Labels'
              ]
            ]
        ]);

        $this->addField('rating', [
            'type' => 'float',
            'ui'   => [
                'table' => [
                    'ColorRating',
                    [
                        'min'    => 1,
                        'max'    => 3,
                        'steps'  => 3,
                        'colors' => [
                            '#FF0000',
                            '#FFFF00',
                            '#00FF00'
                        ]
                    ]
                ]
            ]
        ]);

        $this->addField('note',['system' => true]);
    }
}

$key_value_string = [
    1 => 'one',
    'two',
    'three',
    'four'
];

$m                             = new ModelColor(new \atk4\data\Persistence\Static_([]));
foreach(range(1,50) as $id)
{
    $key_value = rand(1,4);

    $m->insert([
        'id' => $id,
        'name' => 'name ' . $id,
        'key_value' => $key_value,
        'key_value_string' => $key_value_string[$key_value],
        'value_not_always_present' => rand(0,100) > 50 ? 'have value' : '',
        'interests' => '1st label, 2nd label',
        'rating' => rand(100,300) / 100,
        'note' => 'lorem ipsum lorem dorem lorem'
    ]);
}

$table = $app->add(['Table']);
$table->setModel($m);

Add Demo for new columns

Add Demo for new columns


<?php

class Stripe_ObjectTest extends Stripe_TestCase
{
  public function testArrayAccessorsSemantics()
  {
    $s = new Stripe_Object();
    $s['foo'] = 'a';
    $this->assertSame($s['foo'], 'a');
    $this->assertTrue(isset($s['foo']));
    unset($s['foo']);
    $this->assertFalse(isset($s['foo']));
  }

  public function testNormalAccessorsSemantics()
  {
    $s = new Stripe_Object();
    $s->foo = 'a';
    $this->assertSame($s->foo, 'a');
    $this->assertTrue(isset($s->foo));
    unset($s->foo);
    $this->assertFalse(isset($s->foo));
  }

  public function testArrayAccessorsMatchNormalAccessors()
  {
    $s = new Stripe_Object();
    $s->foo = 'a';
    $this->assertSame($s['foo'], 'a');

    $s['bar'] = 'b';
    $this->assertSame($s->bar, 'b');
  }

  public function testKeys()
  {
    $s = new Stripe_Object();
    $s->foo = 'a';
    $this->assertSame($s->keys(), array('foo'));
  }
}

Add PHPUnit test for Stripe_Object

Add PHPUnit test for Stripe_Object


<?php

use Fhaculty\Graph\Algorithm\Bipartit as AlgorithmBipartit;
use Fhaculty\Graph\Graph;

class BipartitTest extends TestCase
{
    public function testGraphEmpty()
    {
        $graph = new Graph();

        $alg = new AlgorithmBipartit($graph);

        $this->assertTrue($alg->isBipartit());
        $this->assertEquals(array(), $alg->getColors());
        $this->assertEquals(array(0 => array(), 1 => array()), $alg->getColorVertices());
    }

    public function testGraphPairIsBipartit()
    {
        // 1 -> 2
        $graph = new Graph();
        $v1 = $graph->createVertex(1);
        $v2 = $graph->createVertex(2);
        $v1->createEdgeTo($v2);

        $alg = new AlgorithmBipartit($graph);

        $this->assertTrue($alg->isBipartit());
        $this->assertEquals(array(1 => 0, 2 => 1), $alg->getColors());
        $this->assertEquals(array(0 => array(1 => $v1), 1 => array(2 => $v2)), $alg->getColorVertices());

        return $alg;
    }

    /**
     *
     * @param AlgorithmBipartit $alg
     * @depends testGraphPairIsBipartit
     */
    public function testGraphPairBipartitGroups(AlgorithmBipartit $alg)
    {
        // graph does not have any groups assigned, so its groups are not bipartit
        $this->assertFalse($alg->isBipartitGroups());

        // create a cloned graph with groups assigned according to bipartition
        $graph = $alg->createGraphGroups();

        $this->assertInstanceOf('Fhaculty\Graph\Graph', $graph);

        $alg2 = new AlgorithmBipartit($graph);
        $this->assertTrue($alg2->isBipartitGroups());
    }

    public function testGraphTriangleCycleIsNotBipartit()
    {
        // 1 -> 2 --> 3 --> 1
        $graph = new Graph();
        $v1 = $graph->createVertex(1);
        $v2 = $graph->createVertex(2);
        $v3 = $graph->createVertex(3);
        $v1->createEdgeTo($v2);
        $v2->createEdgeTo($v3);
        $v3->createEdgeTo($v1);

        $alg = new AlgorithmBipartit($graph);

        $this->assertFalse($alg->isBipartit());

        return $alg;
    }

    /**
     *
     * @param AlgorithmBipartit $alg
     * @expectedException UnexpectedValueException
     * @depends testGraphTriangleCycleIsNotBipartit
     */
    public function testGraphTriangleCycleColorsInvalid(AlgorithmBipartit $alg)
    {
        $alg->getColors();
    }

    /**
     *
     * @param AlgorithmBipartit $alg
     * @expectedException UnexpectedValueException
     * @depends testGraphTriangleCycleIsNotBipartit
     */
    public function testGraphTriangleCycleColorVerticesInvalid(AlgorithmBipartit $alg)
    {
        $alg->getColorVertices();
    }
}

Add tests with 100% coverage for Algorithm\Bipartit


<?php

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

class TicketsFixPaymentgroup extends Migration {

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('tickets', function(Blueprint $table) {
            $table->dropForeign('tickets_valid_paymentgroup_id_foreign');
            $table->dropForeign('tickets_revoked_paymentgroup_id_foreign');
            $table->foreign('valid_paymentgroup_id')->references('id')->on('paymentgroups');
            $table->foreign('revoked_paymentgroup_id')->references('id')->on('paymentgroups');

        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('tickets', function(Blueprint $table)
        {
            $table->dropForeign('tickets_valid_paymentgroup_id_foreign');
            $table->dropForeign('tickets_revoked_paymentgroup_id_foreign');
            $table->foreign('valid_paymentgroup_id')->references('id')->on('eventgroups');
            $table->foreign('revoked_paymentgroup_id')->references('id')->on('eventgroups');
        });
    }

}

Fix foreign keys in tickets table

Fix foreign keys in tickets table


<?php

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

namespace Predis\Command;

use PHPUnit_Framework_TestCase as StandardTestCase;

/**
 * @group commands
 * @group realm-string
 */
class StringSetPreserveTest extends CommandTestCase
{
    /**
     * {@inheritdoc}
     */
    protected function getExpectedCommand()
    {
        return 'Predis\Command\StringSetPreserve';
    }

    /**
     * {@inheritdoc}
     */
    protected function getExpectedId()
    {
        return 'SETNX';
    }

    /**
     * @group disconnected
     */
    public function testFilterArguments()
    {
        $arguments = array('foo', 'bar');
        $expected = array('foo', 'bar');

        $command = $this->getCommand();
        $command->setArguments($arguments);

        $this->assertSame($expected, $command->getArguments());
    }

    /**
     * @group disconnected
     */
    public function testParseResponse()
    {
        $this->assertTrue($this->getCommand()->parseResponse(1));
    }

    /**
     * @group connected
     */
    public function testSetStringValue()
    {
        $redis = $this->getClient();

        $this->assertTrue($redis->setnx('foo', 'bar'));
        $this->assertFalse($redis->setnx('foo', 'barbar'));
        $this->assertEquals('bar', $redis->get('foo'));
    }
}

Add missing tests for SETNX.

[tests] Add missing tests for SETNX.

For some obscure reason Predis/Command/StringSetPreserve had no tests.


<?php

namespace CftfBundle\Form\Type;

use CftfBundle\Entity\LsAssociation;
use CftfBundle\Entity\LsDoc;
use Doctrine\ORM\EntityRepository;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class LsAssociationTreeType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $choiceList = [];
        foreach (LsAssociation::typeChoiceList() as $choice) {
            $choiceList[$choice] = $choice;
        }

        if (!$options['ajax']) {
            $builder
                ->add('uri')
                ->add('originNodeUri')
            ;
        }

        $builder
            ->add('type', ChoiceType::class, [
                'choices' => $choiceList,
                'label' => 'Relationship Type',
            ])
        ;
    }

    /**
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => LsAssociation::class,
            'ajax' => false,
            //'csrf_protection' => false,
        ));
    }
}

Add form type to create association via dragging from one tree to another in tree view


<?php

namespace Becklyn\RadBundle\Entity\Extension;

use Doctrine\ORM\Mapping as ORM;

/**
 *
 */
trait EntityId
{
    /**
     * @var int
     * @ORM\Id()
     * @ORM\GeneratedValue(strategy="AUTO")
     * @ORM\Column(name="id", type="integer")
     */
    private $id;

    /**
     * @return int
     */
    public function getId ()
    {
        return $this->id;
    }
}

Add default id entity property trait

Add default id entity property trait

Add a new trait for ids


<?php //var_dump($rooms); ?>

								#
								Room No.
								Purpose
								Reservation Date
								Time Start
								Time End
								Date Filed
								Reserved by

							<?php $counter = 1; ?>
							<?php foreach($rooms as $row): ?>

									<?php echo $counter ?>
									<?php echo $row->room_no ?>
									<?php echo $row->purpose ?>
									<?php echo $row->date_reserved ?>
									<?php echo $row->time_start ?>
									<?php echo $row->time_end ?>
									<?php echo $row->date_filed ?>
									<?php echo $row->fullname ?>

										<button class="btn btn-flat btn-success">Approve </button>

										<button class="btn btn-flat btn-danger">Deny </button>

								<?php $counter++; ?>
							<?php endforeach; ?>

Add view for pending request

Add view for pending request


<?php
    $title = "Visit Count";
    $file = "/tmp/ip-lab_2b_count";

    $count = 1;

    if (!file_exists($file))
    {
        $handle = fopen($file, "w");
        fwrite($handle, $count);
        fclose($handle);
    }
    else
    {
        $handle = fopen($file, "r");
        fscanf($handle, "%d", $count);
        fclose($handle);

        $handle = fopen($file, "w");
        $count = $count + 1;
        fputs($handle, $count);
        fclose($handle);
    }
?>

<!DOCTYPE html>

    <title><?php echo $title?></title>

        <?php
            if ($count == 1) { echo "
You are our first visitor.
"; }
            else { echo "
You are visitor number $count.
"; }
        ?>

Add PHP script to display number of visits to a page.


<?php

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

class AddDatetimeIndexesToTables extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('devices', function (Blueprint $table) {
           $table->index('created_at');
        });
        Schema::table('samples', function (Blueprint $table) {
            $table->index('created_at');
        });
        Schema::table('app_processes', function (Blueprint $table) {
            $table->index('created_at');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('devices', function (Blueprint $table) {
            $table->dropIndex('created_at');
        });
        Schema::table('samples', function (Blueprint $table) {
            $table->dropIndex('created_at');
        });
        Schema::table('app_processes', function (Blueprint $table) {
            $table->dropIndex('created_at');
        });
    }
}

Add migration to add indexes to devices, samples and processes tables


<?php

namespace Bolt\Composer\Action;

use Composer\Installer;

class UpdatePackage
{
    /**
     * @param $io       Composer\IO\BufferIO
     * @param $composer Composer\Composer
     * @param $options  array
     */
    public function __construct($io, $composer, $options)
    {
        $this->options = $options;
        $this->io = $io;
        $this->composer = $composer;
    }

    /**
     * Update packages
     *
     * @param  $packages array Indexed array of package names to remove
     * @return integer 0 on success or a positive error code on failure
     */
    public function execute(array $packages = array())
    {
        $install = Installer::create($this->io, $this->composer);
        $config = $this->composer->getConfig();
        $optimize = $config->get('optimize-autoloader');

        $preferSource = true; // Forces installation from package sources when possible, including VCS information.
        $preferDist = false;

        switch ($config->get('preferred-install')) {
            case 'source':
                $preferSource = true;
                break;
            case 'dist':
                $preferDist = true;
                break;
            case 'auto':
            default:
                break;
        }

        $install
            ->setDryRun($this->options['dryrun'])
            ->setVerbose($this->options['verbose'])
            ->setPreferSource($preferSource)
            ->setPreferDist($preferDist)
            ->setDevMode(!$this->options['nodev'])
            ->setDumpAutoloader(!$this->options['noautoloader'])
            ->setRunScripts(!$this->options['noscripts'])
            ->setOptimizeAutoloader($optimize)
            ->setUpdate(true)
            ->setUpdateWhitelist($packages)
            ->setWhitelistDependencies($this->options['withdependencies'])
            ->setIgnorePlatformRequirements($this->options['ignoreplatformreqs'])
            ->setPreferStable($this->options['preferstable'])
            ->setPreferLowest($this->options['preferlowest'])
            ->disablePlugins();
        ;

        return $install->run();
    }
}

Add Composer class to update package(s)

Add Composer class to update package(s)


<?php

namespace RoyallTheFourth\QuickList\Tests;

use PHPUnit\Framework\TestCase;
use RoyallTheFourth\QuickList\Delivery;

class DeliveryTest extends TestCase
{
    public function testUnsubLink()
    {
        $message = Delivery\appendUnsubLink('hello', 'asdf', 'example.com');
        static::assertContains('hello', $message);
        static::assertContains('asdf', $message);
        static::assertContains('example.com', $message);
    }
}

Add basic tests for Delivery

Add basic tests for Delivery


<?php
/**
 * This file is part of the PHPLucidFrame library.
 * The script executes the command `php lucidframe secret:generate`
 *
 * @package     LC
 * @since       PHPLucidFrame v 1.11.0
 * @copyright   Copyright (c), PHPLucidFrame.
 * @author      Sithu K. <cithukyaw@gmail.com>
 * @link        http://phplucidframe.sithukyaw.com
 * @license     http://www.opensource.org/licenses/mit-license.php MIT License
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.txt
 */

_consoleCommand('secret:generate')
    ->setDescription('Generate secret')
    ->addOption('method', 'm', 'The hashing algorithm method (e.g. "md5", "sha256", etc..)', 'md5')
    ->addOption('data', 'd', 'Secret text to be hashed.')
    ->setDefinition(function(\LC\Core\Console\Command $cmd) {
        $data = $cmd->getOption('data');
        if (!$data) {
            $data = time();
        }

        $secret = hash($cmd->getOption('method'), $data) . "\n";
        $file = INC . '.secret';
        file_put_contents($file, $secret);
    })
    ->register();

Add a core command `php lucidframe secret:generate [--options]` to generate a secret key


<?php
	/**
	AGORA - an interactive and web-based argument mapping tool that stimulates reasoning,
			reflection, critique, deliberation, and creativity in individual argument construction
			and in collaborative or adversarial settings.
    Copyright (C) 2011 Georgia Institute of Technology

    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 'errorcodes.php';
	header("Content-type: text/xml");
	$outputstr = "<?xml version='1.0' ?>\n<map version='$version'></map>";
	$output = new SimpleXMLElement($outputstr);
	$query = "example query";
	$iquery = "example insert";
	$uquery = "example update";
	noTime($output);
	metaError($output);
	badDBLink($output);
	databaseNotFound($output);
	rolledBack($output);
	dataNotFound($output, $query);
	insertFailed($output, $iquery);
	updateFailed($output, $uquery);
	deleteFailed($output, $query);
	mailSendFailed($output);
	incorrectLogin($output);
	poorXML($output);
	modifyOther($output);
	accessDeleted($output);
	nonexistent($output, $query);
	repeatEmail($output);
	repeatUsername($output);
	cannotDeleteFromNonexistent($output);
	print($output->asXML());
?>

Revert "Error testing file is no longer needed"

This reverts commit 8928ee23d58ec5ac2993e8a8ea5ac66866706482.


<?php

namespace Oro\Bundle\ApiBundle\Processor\DeleteList;

use Oro\Component\ChainProcessor\ContextInterface;
use Oro\Component\ChainProcessor\ProcessorInterface;

/**
 * Unset the "X-Include-Delete-Count" response header
 *  in case if it was requested by "X-Include: deleteCount" request header and an error occurred in deletion process.
 */
class UnsetDeleteCountHeader implements ProcessorInterface
{
    /**
     * {@inheritdoc}
     */
    public function process(ContextInterface $context)
    {
        /** @var DeleteListContext $context */

        if (!$context->getResponseHeaders()->has(SetDeleteCountHeader::HEADER_NAME)) {
            // delete count header was not set
            return;
        }

        if ($context->hasResult()) {
            $context->getResponseHeaders()->remove(SetDeleteCountHeader::HEADER_NAME);
        }
    }
}

<?php

namespace Oro\Bundle\ApiBundle\Processor\DeleteList;

use Oro\Component\ChainProcessor\ContextInterface;
use Oro\Component\ChainProcessor\ProcessorInterface;

/**
 * Unset the "X-Include-Delete-Count" response header
 *  in case if it was requested by "X-Include: deleteCount" request header but an error occurred in deletion process.
 */
class UnsetDeleteCountHeader implements ProcessorInterface
{
    /**
     * {@inheritdoc}
     */
    public function process(ContextInterface $context)
    {
        /** @var DeleteListContext $context */

        if (!$context->getResponseHeaders()->has(SetDeleteCountHeader::HEADER_NAME)) {
            // delete count header was not set
            return;
        }

        if ($context->hasResult()) {
            $context->getResponseHeaders()->remove(SetDeleteCountHeader::HEADER_NAME);
        }
    }
}

BAP-9985: Add processor that will set total deleted items count into response header
-- comment fix


<?php

class BasicsTest extends \PHPUnit_Framework_TestCase
{
    public function testIdentity()
    {
      $x = 42;
      $this->assertTrue(
        $x === Basics::id($x),
        'Identity is a no-op'
      );
    }

    public function testCurrying() {
      $f = function ($x, $y) {
        return $x + $y;
      };
      $g = Basics::curry2($f);
      $h = $g(21);

      $this->assertEquals(
        $h(21),
        $f(21, 21),
        'Basics::curry2'
      );

      $f2 = function ($x, $y, $z) {
        return $x + $y + $z;
      };
      $g2 = Basics::curry3($f2);
      $h2 = $g2(21);
      $i2 = $h2(21);

      $this->assertEquals(
        $i2(21),
        $f2(21, 21, 21),
        'Basics::curry3'
      );
    }
}

Add tests for Basics. Incomplete.

Add tests for Basics. Incomplete.


<?php

/*
 * Unit test for LuminousUtils module (class)
 */

include dirname(__FILE__) . '/helper.inc';

function test_balance() {
  // balanced delimiters:
  // most character when used as a dynamic delimiter (perl, ruby) will map to
  // themselves as the end delimiter. But brackets pair up.

  $balanced = array(
    '{' => '}',
    '[' => ']',
    '(' => ')',
    '<' => '>');

  for($i=32; $i<=126; $i++) {
    $chr = chr($i);
    $expected = isset($balanced[$chr])? $balanced[$chr] : $chr;
    if (($out = LuminousUtils::balance_delimiter($chr)) !== $expected) {
      echo "balance_delimiter($chr) = $out (expected $expected)\n";
      assert(0);
    }
  }
}

function _test_escape_token($token) {
  $escaped = LuminousUtils::escape_token($token);
  // name should be unchanged
  assert($token[0] === $escaped[0]);
  $expected =  $token[2]?
                 $token[1] // already escaped, should be unchanged
                 // else ...
                 : LuminousUtils::escape_string($token[1]);
  assert($escaped[1] === $expected);
  assert($escaped[2]);
}

function test_escape_token() {
  $tokens = array(
    // unescaped should escape to HTML entities
    array('NAME', '<>&', false),
    array('NAME', 'no html entities here', false),
    // should be double escaped as the token is not yet escaped
    array('NAME', '<>&', false),

    // should not be escaped
    array('NAME', '<>&', true),
    array('NAME', 'no html entities here', true),
    array('NAME', '<>&', true)
  );

  foreach($tokens as $t) {
    _test_escape_token($t);
  }
}

test_balance();
test_escape_token();

Add unit test for Utils module

Add unit test for Utils module


<?php
namespace TYPO3\Flow\Tests\Unit\Property\TypeConverter;

/*
 * This file is part of the TYPO3.Flow package.
 *
 * (c) Contributors of the Neos Project - www.neos.io
 *
 * This package is Open Source Software. For the full copyright and license
 * information, please view the LICENSE file which was distributed with this
 * source code.
 */

use TYPO3\Flow\Property\TypeConverter\ArrayFromObjectConverter;

/**
 * Testcase for the ArrayFromObject converter
 *
 */
class ArrayFromObjectConverterTest extends \TYPO3\Flow\Tests\UnitTestCase
{
    /**
     * @var ArrayFromObjectConverter
     */
    protected $converter;

    public function setUp()
    {
        $this->converter = new ArrayFromObjectConverter();
    }

    /**
     * @test
     */
    public function checkMetadata()
    {
        $this->assertEquals(array('object'), $this->converter->getSupportedSourceTypes(), 'Source types do not match');
        $this->assertEquals('array', $this->converter->getSupportedTargetType(), 'Target type does not match');
        $this->assertEquals(1, $this->converter->getPriority(), 'Priority does not match');
    }

    /**
     * @test
     */
    public function getSourceChildPropertiesToBeConvertedReturnsSubObjectsArray()
    {
        $source = new \stdClass();
        $source->first = 'Foo';
        $source->second = new \stdClass();
        $this->assertEquals(array('second' => new \stdClass()), $this->converter->getSourceChildPropertiesToBeConverted($source));
    }

    public function objectToArrayDataProvider()
    {
        return array(
            array(array('foo' => 'Foo', 'bar' => 'Bar', 'baz' => 'Baz'), array('foo' => 'Foo', 'bar' => 'Bar', 'baz' => 'Baz', '__type' => 'stdClass' )),
            array(array('foo' => 'Foo', 'bar' => array( 'bar' => 'Bar', 'baz' => 'Baz' )), array('foo' => 'Foo', 'bar' => array( 'bar' => 'Bar', 'baz' => 'Baz', '__type' => 'stdClass' ), '__type' => 'stdClass' )),
            array(new \stdClass(), array( '__type' => 'stdClass' ))
        );
    }

    /**
     * @test
     * @dataProvider objectToArrayDataProvider
     */
    public function canConvertFromObjectToArray($source, $expectedResult)
    {
        if (is_array($source)) {
            $source = json_decode(json_encode($source), false);
        }

        $convertedChildProperties = array_map(function($value) {
            return $this->converter->convertFrom($value, 'array', array(), null);
        }, $this->converter->getSourceChildPropertiesToBeConverted($source));
        $this->assertEquals($expectedResult, $this->converter->convertFrom($source, 'array', $convertedChildProperties, null));
    }
}

TASK: Add tests for the ArrayFromObject converter


<?php

namespace vierbergenlars\CliCentral\Command\Application;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Helper\ProcessHelper;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Process\Exception\ProcessFailedException;
use vierbergenlars\CliCentral\Configuration\Application;
use vierbergenlars\CliCentral\Configuration\RepositoryConfiguration;
use vierbergenlars\CliCentral\Exception\Configuration\ApplicationExistsException;
use vierbergenlars\CliCentral\Exception\Configuration\NoSuchApplicationException;
use vierbergenlars\CliCentral\Exception\File\NotAFileException;
use vierbergenlars\CliCentral\Exception\File\UnreadableFileException;
use vierbergenlars\CliCentral\Helper\GlobalConfigurationHelper;
use vierbergenlars\CliCentral\Util;

class OverrideConfigCommand extends Command
{
    protected function configure()
    {
        $this->setName('application:override:config')
            ->addArgument('application', InputArgument::REQUIRED, 'The application to add an override to')
            ->addArgument('config-file', InputArgument::REQUIRED, 'The configuration file to use for the application')
            ->setDescription('Changes the configuration file for an application')
            ->setHelp(<<<'EOF'
The <info>%command.name%</info> command changes the configuration file for the application,
effectively overriding all settings in the packaged <comment>.cliconfig.json</comment>:

  <info>%command.full_name% authserver ~/clic-overrides/authserver/cliconfig.json</info>

Resetting the configuration file back to the defaults is done by passing an empty second argument:

  <info>%command.full_name% authserver ''</info>
EOF
            )
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $configHelper = $this->getHelper('configuration');
        /* @var $configHelper GlobalConfigurationHelper */

        $application = $configHelper->getConfiguration()->getApplication($input->getArgument('application'));
        $configFile = $input->getArgument('config-file');
        if($configFile) {
            $configFile = new \SplFileInfo($configFile);
            if(!$configFile->isFile())
                throw new NotAFileException($configFile);
            if(!$configFile->isReadable())
                throw new UnreadableFileException($configFile);
            $configFile = $configFile->getRealPath();
        }

        $application->setConfigurationFileOverride($configFile);

        $configHelper->getConfiguration()->write();

    }
}

Add application:override:config to replace an applications .cliconfig.json file with an external file


<?php

namespace React\Tests\Filesystem\ChildProcess;

use React\Filesystem\ChildProcess\Adapter;
use React\Tests\Filesystem\TestCase;

/**
 * @requires extension eio
 */
class AdapterTest extends TestCase
{
    public function testInterface()
    {
        $this->assertInstanceOf(
            'React\Filesystem\AdapterInterface',
            new Adapter($this->getMock('React\EventLoop\LoopInterface'), [
                'pool' => [
                    'class' => 'WyriHaximus\React\ChildProcess\Pool\DummyPool',
                ],
            ])
        );
    }

    public function testGetLoop()
    {
        $loop = $this->getMock('React\EventLoop\LoopInterface');
        $filesystem = new Adapter($loop, [
            'pool' => [
                'class' => 'WyriHaximus\React\ChildProcess\Pool\DummyPool',
            ],
        ]);
        $this->assertSame($loop, $filesystem->getLoop());
    }
}

Set up first test for child process adapter


@extends('template')

@section('headers')

@endsection

@section('content')

Oops!

404 Not Found

                Sorry, an error has occurred, and the page you were looking for was not found!

                 Take Me Home
                {{-- Contact Support --}}

@endsection

Add missing 404 error page

Add missing 404 error page


<?php

namespace Tsugi\UI;

use \Tsugi\Util\U;

/**
 * Our class to handle annotation markup
 */
class Annotate {

    /**
     * Provide the header material to support annotations
     */
    public static function header()
    {
        global $CFG;
        return '<link rel="stylesheet" href="'.$CFG->staticroot.'/js/annotator-full.1.2.10/annotator.min.css" />'.PHP_EOL;
    }

    /**
     * Define the function tsugiStartAnnotation(id) to start the annotations on a div
     *
     * @param $LAUNCH The current launch
     * @param $api_endpoint The id of the area to be annotated
     */
    public static function footer($LAUNCH, $api_endpoint=false)
    {
        global $CFG;

        if ( ! $api_endpoint ) {
            $pieces = U::rest_path();
            $api_endpoint = $CFG->wwwroot . '/api/annotate/' . session_id() . ':' . $LAUNCH->result->id;
        }
        ob_start();
?>
<script src="<?= $CFG->staticroot ?>/js/annotator-full.1.2.10/annotator-full.min.js"></script>
<script type="text/javascript">
function tsugiStartAnnotation(id) {
    $(id).annotator()
    .annotator('setupPlugins', {} , {
        Auth: false,
        Tags: false,
        Filter: false,
        Store: {
           prefix: '<?= $api_endpoint ?>',
           loadFromSearch: false
        }
     } );
     console.log('Annotator started id='+id);
}
</script>
<?php
        return ob_get_contents();
    }
}

Add the annotator UI library

Add the annotator UI library


<?php

namespace Tools\Utility;

use Cake\Log\Log as CoreLog;

/**
 * Wrapper class to log data into custom file(s).
 */
class Log
{
    /**
     * Debug configuration.
     *
     * @var mixed|null
     */
    protected static $_debugConfig;

    /**
     * Initialize configurations.
     *
     * @param string $filename Filename to log.
     * @return void
     */
    protected static function _init($filename) {
        if ($filename === null) {
            $filename = 'custom_log';
        }

        CoreLog::setConfig('custom', [
            'className' => 'File',
            'path' => LOGS,
            'levels' => [],
            'scopes' => ['custom'],
            'file' => $filename,
        ]);

        static::$_debugConfig = CoreLog::getConfig('debug');

        CoreLog::drop('debug');
    }

    /**
     * Log data into custom file
     *
     * @param array|string $data Data to store
     * @param string $filename Filename of log file
     * @param bool $traceKey Add trace string key into log data
     * @return bool Success
     */
    public static function write($data, $filename = null, $traceKey = false) {
        static::_init($filename);

        // Pretty print array
        if (is_array($data)) {
            if ($traceKey) {
                try {
                    throw new \Exception('Trace string', 1);
                } catch (\Throwable $t) {
                    $data['trace_string'] = $t->getTraceAsString();
                }
            }

            $data = print_r($data, true);
        }

        $logged = CoreLog::write('debug', $data, ['scope' => 'custom']);

        static::_cleanUp();

        return $logged;
    }

    /**
     * Drop custom log config, set default `debug` config in log registry.
     *
     * @return void
     */
    protected static function _cleanUp() {
        CoreLog::drop('custom');

        CoreLog::setConfig('debug', static::$_debugConfig);
    }
}

Add log file to store logs into custom log files


<?php
namespace pyd\testkit\interfaces;

/**
 * Interface for class that observes the test events.
 *
 * @author Pierre-Yves DELETTRE <pierre.yves.delettre@gmail.com>
 */
interface InterfaceTestEventObserver
{
    public function handleEvent($eventName, $data);
}

Add an interface for test event observers


<?php

namespace Tests\AppBundle\Command;

use AppBundle\Command\CreateWebuserCommand;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Symfony\Component\Console\Tester\CommandTester;

class CreateWebuserCommandTest extends KernelTestCase
{
    public function testExecute()
    {
        self::bootKernel();

        $em = self::$kernel->getContainer()->get('app.orm')->getDefaultManager();
        $testUser = $em->getRepository('AppBundle:Webuser')->findOneBy(array(
            'oauthId' => 'TestWebuserCreate'
        ));
        $this->assertNull($testUser, 'Before creation the "TestWebuserCreate" user does not exist.');

        $application = new Application(self::$kernel);

        $application->add(new CreateWebuserCommand());

        $command = $application->find('app:create-webuser');
        $commandTester = new CommandTester($command);
        $args = array(
            'command'  => $command->getName(),
            '--oauth_provider' => 'TestWebuserCreateProvider',
            'oauth_id' => 'TestWebuserCreate',
        );
        $commandTester->execute($args);

        // the output of the command in the console
        $output = $commandTester->getDisplay();
        $this->assertContains('Webuser successfully created', $output);

        $testUser = $em->getRepository('AppBundle:Webuser')->findOneBy(array(
            'oauthId' => 'TestWebuserCreate'
        ));
        $this->assertNotNull($testUser, 'After creation the "TestWebuserCreate" user does exist.');
        $this->assertEquals('TestWebuserCreateProvider', $testUser->getOauthProvider()->getProvider());

        $commandTester->execute($args);
        $output = $commandTester->getDisplay();
        $this->assertContains('Webuser already exists, nothing to do.', $output);
    }
}

Add test for new command create-webuser

Add test for new command create-webuser


<?php
namespace OCA\dav\Migrations;

use Doctrine\DBAL\Schema\Schema;
use OCP\Migration\ISchemaMigration;

/**
 * Add index to oc_cards to assist with searching with large numbers of rows
 */
class Version20170519091921 implements ISchemaMigration {

	public function changeSchema(Schema $schema, array $options) {
		$prefix = $options['tablePrefix'];
		$table = $schema->getTable("${prefix}cards");
		// Check for existing index spanning these columns
		foreach ($table->getIndexes() as $index) {
			// Check if we have a matching index already
			if(empty(array_diff($index->getColumns(), ['uri', 'addressbookid']))) {
				return;
			}

		}
		// Add the index if we dont have one spanning this column already
		$table->addIndex(['addressbookid', 'uri'], 'addressbookid_uri_index');
	}

}

Add index to oc_cards to assist with searching large number of rows


<?php

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

namespace Predis\Iterator\Scan;

use Predis\ClientInterface;

/**
 * Abstracts the iteration of members stored in a sorted set
 * by leveraging the ZSCAN command (Redis >= 2.8) wrapped in
 * a fully-rewindable PHP iterator.
 *
 * @author Daniele Alessandri <suppakilla@gmail.com>
 * @link http://redis.io/commands/scan
 */
class SortedSetIterator extends AbstractScanIterator
{
    protected $key;

    /**
     * {@inheritdoc}
     */
    public function __construct(ClientInterface $client, $key, $match = null, $count = null)
    {
        $this->requiredCommand($client, 'ZSCAN');

        parent::__construct($client, $match, $count);

        $this->key = $key;
    }

    /**
     * {@inheritdoc}
     */
    protected function executeScanCommand()
    {
        return $this->client->zscan($this->key, $this->cursor, $this->getScanOptions());
    }

    /**
     * {@inheritdoc}
     */
    protected function extractNext()
    {
        $element = array_shift($this->elements);

        $this->position = $element[0];
        $this->current = $element[1];
    }
}

Implement PHP iterator based on the ZSCAN command (Redis 2.8).

This iterator allows to perform full iterations over the members of a sorted
set by wrapping the incremental nature of ZSCAN just like we did for SCAN:

  $client = new Predis\Client('tcp://127.0.0.1', ['profile' => '2.8']);
  $iterator = new Predis\Iterator\Scan\SortedSetIterator($client, "zset_key");

  foreach ($iterator as $member => $rank) {
      echo "$rank => $member" . PHP_EOL;
  }

Being ZSCAN closely related to SCAN, it is subject to the same behaviour,
see http://redis.io/commands/scan for reference.

This iterator implementation returns the member as key and the rank as value
since the rank is a float value which would be truncated when transforming
the iteration to an array (e.g. using iterator_to_array()). Luckily PHP
preserves the insertion order for named arrays members still result sorted.


<?php
namespace CouchDB\Http;

use CouchDB\Logging\LoggingInterface;

/**
 * @author Markus Bachmann <markus.bachmann@bachi.biz>
 */
class LoggingClient implements ClientInterface
{
    /**
     * @var LoggingInterface
     */
    protected $logger;

    /**
     * @var ClientInterface
     */
    protected $client;

    /**
     * @var integer
     */
    protected $totalDuration;

    public function __construct(LoggingInterface $logger, ClientInterface $client)
    {
        $this->client = $client;
        $this->logger = $logger;
        $this->totalDuration = 0;
    }

    /**
     * Connect to server
     */
    public function connect()
    {
        return $this->client->connect();
    }

    /**
     * Check if the client is connected to the server
     *
     * @return boolean
     */
    public function isConnected()
    {
        return $this->client->isConnected();
    }

    /**
     * Request
     *
     * @param string $path
     * @param constant $method
     * @param string $data
     * @param array $headers
     *
     * @return \CouchDB\Http\Response\ResponseInterface
     */
    public function request($path, $method = ClientInterface::METHOD_GET, $data = '', array $headers = array())
    {
        $start = microtime(true);
        $response = $this->client->request($path, $method, $data, $headers);
        $duration = $start - microtime(true);

        $this->logger->log(array(
            'duration'         => $duration,

            'request_method'   => $method,
            'request_path'     => $path,
            'request_data'     => $data,
            'request_headers'  => $headers,

            'response_headers' => $response->getHeaders(),
            'response_status'  => $response->getStatusCode(),
            'response_body'    => $response->getContent()
        ));

        $this->totalDuration += $duration;

        return $response;
    }

    /**
     * Get the logger
     *
     * @return LoggingInterface
     */
    public function getLogger()
    {
        return $this->logger;
    }

    /**
     * Sets the new logger
     *
     * @param LoggingInterface $logger
     */
    public function setLogger(LoggingInterface $logger)
    {
        $this->logger = $logger;
    }
}

Add loggingclient for better debugging

Add loggingclient for better debugging


<?php

namespace Core\ControllerDispatcher;

use PHPUnit\Framework\TestCase;
use Prob\Handler\Proc\ClosureProc;
use Prob\Handler\Proc\FunctionProc;
use Prob\Router\Map;
use Zend\Diactoros\Server;
use Zend\Diactoros\ServerRequest;
use Zend\Diactoros\Uri;

class RequestMatcherTest extends TestCase
{
    public function testGetSetRequest()
    {
        $request = new ServerRequest();

        RequestMatcher::setRequest($request);

        $this->assertEquals($request, RequestMatcher::getRequest());
    }

    public function testGetUrlNameMatching()
    {
        $request = new ServerRequest([], [], new Uri('/account/test'), 'GET');
        $routeMap = new Map();
        $routeMap->get('/account/{id}', function() { });

        RequestMatcher::setRequest($request);
        RequestMatcher::setRouterMap($routeMap);

        $this->assertEquals(['id' => 'test'], RequestMatcher::getUrlNameMatching());
    }

    public function testGetPatternedUrl()
    {
        $request = new ServerRequest([], [], new Uri('/account/test'), 'GET');
        $routeMap = new Map();
        $routeMap->get('/account/{id}', function() { });

        RequestMatcher::setRequest($request);
        RequestMatcher::setRouterMap($routeMap);

        $this->assertEquals('/account/{id}', RequestMatcher::getPatternedUrl());
    }

    public function testGetControllerProc()
    {
        $request = new ServerRequest([], [], new Uri('/account/test'), 'GET');

        $proc = function($arg) {
            return $arg;
        };
        $routeMap = new Map();
        $routeMap->get('/account/{id}', $proc);

        RequestMatcher::setRequest($request);
        RequestMatcher::setRouterMap($routeMap);

        $this->assertEquals('hello', RequestMatcher::getControllerProc()->exec('hello'));
    }
}

Add a ControllerDispatcher unit test

Add a ControllerDispatcher unit test


<?php

namespace Wnx\LaravelStats\Tests\Stubs\Tests;

use Laravel\BrowserKitTesting\TestCase;

class DemoBrowserKit extends TestCase
{
    public function createApplication()
    {
        //
    }

    /** @test */
    public function it_runs_browser_kit_tests()
    {
        $this->assertTrue(true);
    }
}

Add a demo BrowserKit Test

Add a demo BrowserKit Test


<?php
/**
 *
 * @param array &$hookinfo  hookinfo
 */
function consentSimpleAdmin_hook_sanitycheck(&$hookinfo) {
	assert('is_array($hookinfo)');
	assert('array_key_exists("errors", $hookinfo)');
	assert('array_key_exists("info", $hookinfo)');

	try {
		$config = SimpleSAML_Configuration::getInstance();
		$consentconfig = $config->copyFromBase('consentSimpleAdminConfig', 'module_consentSimpleAdmin.php');

		// Parse consent config
		$consent_storage = sspmod_consent_Store::parseStoreConfig($consentconfig->getValue('store'));

		// Get all consents for user
		$stats = $consent_storage->getStatistics();

		$hookinfo['info'][] = '[consentSimpleAdmin] Consent Storage connection OK.';

	} catch (Exception $e) {
		$hookinfo['errors'][] = '[consentSimpleAdmin] Error connecting to storage: ' . $e->getMessage();
	}

}
?>

Add sanity check to check if database connection is OK.


<?php
namespace TYPO3\Eel\Tests\Unit;

/*                                                                        *
 * This script belongs to the Flow package "TYPO3.Eel".                   *
 *                                                                        */

use TYPO3\Eel\Helper\SecurityHelper;

/**
 * Eel SecurityHelper test
 */
class SecurityHelperTest extends \TYPO3\Flow\Tests\UnitTestCase {

	/**
	 * @test
	 */
	public function getAccountReturnsNullIfSecurityContextCannotBeInitialized() {
		$mockSecurityContext = $this->getMock('TYPO3\Flow\Security\Context');
		$mockSecurityContext->expects($this->any())->method('canBeInitialized')->willReturn(FALSE);

		$helper = new SecurityHelper();
		$this->inject($helper, 'securityContext', $mockSecurityContext);

		$this->assertNull($helper->getAccount());
	}

	/**
	 * @test
	 */
	public function getAccountDelegatesToSecurityContextIfSecurityContextCanBeInitialized() {
		$mockSecurityContext = $this->getMock('TYPO3\Flow\Security\Context');
		$mockSecurityContext->expects($this->any())->method('canBeInitialized')->willReturn(TRUE);
		$mockSecurityContext->expects($this->atLeastOnce())->method('getAccount')->willReturn('this would be an account instance');

		$helper = new SecurityHelper();
		$this->inject($helper, 'securityContext', $mockSecurityContext);

		$this->assertSame('this would be an account instance', $helper->getAccount());
	}

	/**
	 * @test
	 */
	public function hasRoleReturnsTrueForEverybodyRole() {
		$helper = new SecurityHelper();
		$this->assertTrue($helper->hasRole('TYPO3.Flow:Everybody'));
	}

	/**
	 * @test
	 */
	public function hasRoleReturnsFalseIfSecurityContextCannotBeInitialized() {
		$mockSecurityContext = $this->getMock('TYPO3\Flow\Security\Context');
		$mockSecurityContext->expects($this->any())->method('canBeInitialized')->willReturn(FALSE);

		$helper = new SecurityHelper();
		$this->inject($helper, 'securityContext', $mockSecurityContext);

		$this->assertFalse($helper->hasRole('Acme.Com:DummyRole'));
	}

	/**
	 * @test
	 */
	public function hasRoleDelegatesToSecurityContextIfSecurityContextCanBeInitialized() {
		$mockSecurityContext = $this->getMock('TYPO3\Flow\Security\Context');
		$mockSecurityContext->expects($this->any())->method('canBeInitialized')->willReturn(TRUE);
		$mockSecurityContext->expects($this->atLeastOnce())->method('hasRole')->with('Acme.Com:GrantsAccess')->willReturn(TRUE);

		$helper = new SecurityHelper();
		$this->inject($helper, 'securityContext', $mockSecurityContext);

		$this->assertTrue($helper->hasRole('Acme.Com:GrantsAccess'));
	}

}

Add unit tests for SecurityHelper

[TASK] Add unit tests for SecurityHelper

Releases: master


<?php

namespace RcmAdmin\Controller;

use Rcm\Http\Response;
use Rcm\View\Model\ApiJsonModel;
use RcmUser\Provider\RcmUserAclResourceProvider;

/**
 * Class ApiAdminCheckPermisionsController
 *
 * PHP version 5
 *
 * @category  Reliv
 * @package   RcmAdmin\Controller
 * @author    James Jervis <jjervis@relivinc.com>
 * @copyright 2014 Reliv International
 * @license   License.txt New BSD License
 * @version   Release: <package_version>
 * @link      https://github.com/reliv
 */
class ApiAdminCheckPermissionsController extends ApiAdminBaseController
{
    /**
     * isAllowed
     *
     * @param $resourceId
     * @param $privilege
     *
     * @return mixed
     */
    protected function isAllowed($resourceId, $privilege)
    {
        $rcmUserService = $this->getRcmUserService();

        return $rcmUserService->isAllowed(
            $resourceId,
            $privilege
        );
    }

    /**
     * getRcmUserService
     *
     * @return \RcmUser\Service\RcmUserService'
     */
    protected function getRcmUserService()
    {
        return $this->getServiceLocator()->get(
            'RcmUser\Service\RcmUserService'
        );
    }

    /**
     * getRequestResourceId
     *
     * @return string
     */
    protected function getRequestResourceId()
    {
        return (string)$this->getEvent()
            ->getRouteMatch()
            ->getParam(
                'resourceId'
            );
    }

    /**
     * getRequestPrivileges
     *
     * @return null|string
     */
    protected function getRequestPrivileges()
    {
        $privileges = (string)$this->getEvent()
            ->getRouteMatch()
            ->getParam(
                'privileges'
            );

        if ($privileges === '_NULL_') {
            $privileges = null;
        }

        return $privileges;
    }

    /**
     * get
     *
     * @param mixed $id
     *
     * @return mixed|ApiJsonModel|\Zend\Stdlib\ResponseInterface
     */
    public function get($id)
    {
        if (!$this->isAllowed(RcmUserAclResourceProvider::RESOURCE_ID_ACL, 'read')) {
            $this->getResponse()->setStatusCode(Response::STATUS_CODE_401);

            return $this->getResponse();
        }

        $rcmUserService = $this->getRcmUserService();

        $requestUser = $rcmUserService->buildNewUser();

        $requestUser->setId($id);

        $userResult = $rcmUserService->readUser($requestUser);

        if (!$userResult->isSuccess()) {
            return new ApiJsonModel(
                null,
                1,
                "User was not found with id {$id}."
            );
        }

        $user = $userResult->getUser();

        $resourceId = $this->getRequestResourceId();
        $privileges = $this->getRequestPrivileges();

        $apiResponse = [
            'hasAccess' => $rcmUserService->isUserAllowed(
                $resourceId,
                $privileges,
                null,
                $user
            ),
            'resourceId' => $resourceId,
            'privileges' => $privileges,
            'user' => $user,
        ];

        return new ApiJsonModel($apiResponse, 0, 'Success');
    }
}

Add API fir check permissions

Add API fir check permissions


<?php

namespace Orbt\StyleMirror\Tests\Resource;

use Orbt\StyleMirror\Resource\SingleUseQueue;
use Orbt\ResourceMirror\Resource\GenericResource;

class SingleUseQueueTest extends \PHPUnit_Framework_TestCase
{
    /**
     * A single use queue can be instantiated.
     */
    public function testCreate()
    {
        $queue = new SingleUseQueue();
        $this->assertInstanceOf('Orbt\StyleMirror\Resource\SingleUseQueue', $queue);
    }

    /**
     * A new single use queue flushes an empty collection.
     *
     * @depends testCreate
     */
    public function testFlush()
    {
        $queue = new SingleUseQueue();
        $this->assertEmpty($queue->flush()->getAll());
    }

    /**
     * A resource is added to a single use queue.
     *
     * @depends testFlush
     */
    public function testAdd()
    {
        $queue = new SingleUseQueue();
        $queue->add(new GenericResource('test'));
        $resources = $queue->flush()->getAll();
        $this->assertInstanceOf('Orbt\ResourceMirror\Resource\Resource', reset($resources));
        $this->assertEmpty($queue->flush()->getAll());
    }

    /**
     * Only one resource with a given path is added once to a single use queue.
     *
     * @depends testFlush
     */
    public function testAddOnce()
    {
        $queue = new SingleUseQueue();
        $queue->add(new GenericResource('test'));
        $queue->add(new GenericResource('test'));
        $this->assertCount(1, $queue->flush()->getAll());
        $queue->add(new GenericResource('test'));
        $this->assertEmpty($queue->flush()->getAll());
    }
}

Test single use resource queue.

Test single use resource queue.


<?php

use App\Permission;
use App\Role;
use Illuminate\Database\Migrations\Migration;

class AddStudentTicketManagePermissionToEas extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        $permStudentTicketManage = Permission::where('name', 'student-ticket.manage')->first();

        /* @var Role $eas */
        $eas = Role::where('name', 'EAS')->first();
        $eas->attachPermission($permStudentTicketManage);
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        $permStudentTicketManage = Permission::where('name', 'student-ticket.manage')->first();

        /* @var Role $eas */
        $eas = Role::where('name', 'EAS')->first();
        $eas->detachPermission($permStudentTicketManage);
    }
}

Add StudentTicket manage permission to EAS


<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;
use App\models\VRRoles;
use App\models\VRUsers;

class CheckIfMember
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $roles = auth()->user()->rolesConnections->pluck('roles_id')->toArray();

        if(in_array("user", $roles) or in_array("check-role-member", $roles))

            return $next($request);

        return abort(403, "no permission!");

//
//        if (Auth::check() && Auth::user()->user()) {
//            return $next($request);
//        } elseif (Auth::check() && Auth::user()->isAdmin()) {
//            return $next($request);
//        }
//
//        return abort(403, "no permission!");
    }
}

Check if User logins created

Check if User logins created


<?php
	class Load{
		private $config;

		public function __construct() {
			$this->config = new Config;
		}

		public function view($name,array $vars = array()){
			$file = $name.'View.php';
			if($file != 'loginView.php') {
				if(!isset($_SESSION['is_logged'])) {
					return header("Location: /login");
				}
			}
			$twig = $this->config->getTemplate();
			echo $twig->render($file, $vars);
		}
		public function model($name){
			$model = $name.'Model';
			return new $model;
		}
	}

Load class para carregamento de views e models


<?php
/**
 * @file
 */

namespace CultuurNet\UDB3\EventSourcing;

use Broadway\Domain\DomainMessageInterface;
use Broadway\Domain\Metadata;
use Broadway\EventHandling\EventListenerInterface;
use Broadway\EventSourcing\MetadataEnrichment\MetadataEnricherInterface;
use CultuurNet\UDB3\CommandHandling\ContextAwareInterface;

class ExecutionContextMetadataEnricher implements MetadataEnricherInterface, ContextAwareInterface
{
    protected $metadata;

    /**
     * @param Metadata $metadata
     */
    public function setContext(Metadata $metadata = null)
    {
        $this->metadata = $metadata;
    }

    /**
     * {@inheritdoc}
     */
    public function enrich(Metadata $metadata)
    {
        if ($this->metadata) {
            return $metadata->merge($this->metadata);
        }
        else {
            return $metadata;
        }
    }

}

Add event stream meta data enricher implementation to add contextual info to events


<?php

/**
 * Class for saving normal exceptions for serialization.
 *
 * This class is used by the SimpleSAML_Auth_State class when it needs
 * to serialize an exception which doesn't subclass the
 * SimpleSAML_Error_Exception class.
 *
 * It creates a new exception which contains the backtrace and message
 * of the original exception.
 *
 * @package simpleSAMLphp
 * @version $Id$
 */
class SimpleSAML_Error_UnserializableException extends SimpleSAML_Error_Exception {

	public function __construct(Exception $original) {

		$msg = get_class($original) . ': ' . $original->getMessage();
		$code = $original->getCode();
		parent::__construct($msg, $code);

		$this->setBacktrace(SimpleSAML_Utilities::buildBacktrace($original));
	}

}

Add exception for serializing unserializable exceptions.

The SimpleSAML_Error_Exception class is a base class for serializable
exceptions. This patch adds SimpleSAML_Error_UnserializableException.
That class saves some of the information from an Exception and saves it
in an serializable exception.


<?php
/**
 * SiteController.php
 *
 * File to display pages
 *
 * PHP 7.0.10
 *
 * @category Controller
 * @author   isma91 <ismaydogmus@gmail.com>
 * @license  http://opensource.org/licenses/gpl-license.php GNU Public License
 */
namespace controller;
use model\Config;
use model\View;
/**
 * SiteController
 *
 * Class to control the front view of the site
 *
 * PHP 7.0.10
 *
 * @category Class
 * @author   isma91 <ismaydogmus@gmail.com>
 * @license  http://www.gnu.org/copyleft/gpl.html GNU General Public License
 */
class SiteController
{
    /*
     * CheckMaintenance
     *
     * Check if the site is in maintenance, display the maintenance page if needed
     *
     * @param string; $page   the page to display
     * @param array;  $array  the item value array to display in the view
     *
     * @return void; render the view
     */
    public function checkMaintenance($page, array $array = array())
    {
        $config = new Config();
        if ($config->getMaintenance() === "true") {
            $view = new View("site#maintenance");
            $view->render();
        } else {
            $view = new View($page);
            if (!empty($array)) {
                foreach ($array as $item => $value) {
                    $view->set($item, $value);
                }
            }
            $view->render();
        }
    }

    public function login()
    {
        self::checkMaintenance("site#login");
    }
}

Add Site controller who control the front view of the site


	<?php if ( is_single() ) : ?>

		<?php the_post_thumbnail( 'store-image', array( 'class' => 'th' ) ); ?>

	<?php else: ?>

		<a href="<?php the_permalink(); ?>">
			<?php the_post_thumbnail( 'archive-image', array( 'class' => 'th' ) ); ?>

	<?php endif; ?>

				<?php if ( is_single() ) : ?>

<?php the_title(); ?>

				<?php else : ?>

					<a href="<?php the_permalink(); ?>"><?php the_title(); ?>

				<?php endif; ?>

					<a href="<?php dabc_the_store_tel_link(); ?>"><?php dabc_the_store_phone_number(); ?>

					<?php dabc_the_store_address(); ?>

				<?php the_content(); ?>

Create store info template part.

Create store info template part.


<?php

namespace SimplyTestable\ApiBundle\Tests\Services\Job\WebsiteResolution;

use SimplyTestable\ApiBundle\Tests\BaseSimplyTestableTestCase;

class TooManyRedirectsTest extends BaseSimplyTestableTestCase {

    const SOURCE_URL = 'http://example.com/';
    const EFFECTIVE_URL = 'http://www.example.com/';

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

        $this->queueHttpFixtures($this->buildHttpFixtureSet(array(
            "HTTP/1.0 301\nLocation: " . self::SOURCE_URL,
            "HTTP/1.0 301\nLocation: " . self::SOURCE_URL,
            "HTTP/1.0 301\nLocation: " . self::SOURCE_URL,
            "HTTP/1.0 301\nLocation: " . self::SOURCE_URL,
            "HTTP/1.0 301\nLocation: " . self::EFFECTIVE_URL,
            "HTTP/1.0 200 OK",
        )));
    }

    public function testFullSiteTestResolvesToEffectiveUrl() {
        $job = $this->getJobService()->getById($this->createJobAndGetId(self::SOURCE_URL));
        $this->resolveJob($job->getWebsite()->getCanonicalUrl(), $job->getId());

        $this->assertEquals(self::EFFECTIVE_URL, $job->getWebsite()->getCanonicalUrl());
    }

    public function testSingleUrlTestResolvesToEffectiveUrl() {
        $job = $this->getJobService()->getById($this->createJobAndGetId(self::SOURCE_URL, null, 'single url'));
        $this->resolveJob($job->getWebsite()->getCanonicalUrl(), $job->getId());

        $this->assertEquals(self::EFFECTIVE_URL, $job->getWebsite()->getCanonicalUrl());
    }

}

Add test to verify previous change

Add test to verify previous change


<?php

/**
 * A class to dismiss messages
 */
final class Whip_WPMessageDismisser {

	/**
	 * Returns the value of the whip_dismissed option.
	 *
	 * @return mixed
	 */
	public function getDismissed() {
		return maybe_unserialize( get_option( 'whip_dismissed' ) );
	}

	/**
	 * Listens to a GET request to fetch the required attributes.
	 */
	public function listen() {

		$action = filter_input( INPUT_GET, 'action' );
		$nonce  = filter_input(INPUT_GET, 'nonce' );

		if ( $action === 'whip_dismiss' && wp_verify_nonce( $nonce, 'whip_dismiss' ) ) {
			$component = (string) filter_input( INPUT_GET, 'component' );
			$version_compare = (string) filter_input( INPUT_GET, 'action' );

			$this->dismiss( $component, $version_compare );
		}
	}

	/**
	 * Dismisses the message for the given component/version.
	 *
	 * @param string $component       The component to dismiss.
	 * @param string $version_compare The version comparison string.
	 */
	private function dismiss( $component, $version_compare ) {
		$dismissed = $this->getDismissed();

		if ( ! isset( $dismissed[ $component ] ) ) {
			$dismissed[ $component ] = array();
		}

		$dismissed[ $component ][ $version_compare ] = time();

		update_option( 'whip_dismissed', $dismissed );
	}

}

Add object for dismissing the message.

Add object for dismissing the message.


<?php
/**
 * SageOne Library
 *
 * @category Library
 * @package  SageOne
 * @author   Igor Sergiichuk <igorsergiichuk@gmail.com>
 * @license  MIT <https://github.com/darrynten/sage-one-php/blob/master/LICENSE>
 * @link     https://github.com/darrynten/sage-one-php
 */

namespace DarrynTen\SageOne\Models;

use DarrynTen\SageOne\BaseModel;

/**
 * Customer Opening Balance Model
 *
 * Details on writable properties for Customer Opening Balance:
 * https://accounting.sageone.co.za/api/1.1.2/Help/ResourceModel?modelName=CustomerOpeningBalance
 */
class CustomerOpeningBalance extends BaseModel
{
    /**
     * The API Endpoint
     *
     * @var string $endpoint
     */
    protected $endpoint = 'CustomerOpeningBalance';

    /**
     * @var array $fields
     */
    protected $fields = [
        'customerId' => [
            'type' => 'integer',
            'nullable' => false,
            'readonly' => false,
        ],
        'customer_CurrencyId' => [
            'type' => 'integer',
            'nullable' => true,
            'readonly' => false,
        ],
        'customer_ExchangeRate' => [
            'type' => 'double',
            'nullable' => true,
            'readonly' => false,
        ],
        'id' => [
            'type' => 'integer',
            'nullable' => false,
            'readonly' => false,
        ],
        'balance' => [
            'type' => 'double',
            'nullable' => false,
            'readonly' => false,
        ],
        'reason' => [
            'type' => 'string',
            'nullable' => false,
            'readonly' => false,
        ],
        'date' => [
            'type' => 'DateTime',
            'nullable' => false,
            'readonly' => false,
        ],
    ];

    /**
     * Features supported by the endpoint
     *
     * @var array $features
     */
    protected $features = [
        'all' => true,
        'get' => true,
        'save' => true,
        'delete' => false,
    ];
}

Add Customer Opening Balance Model

Add Customer Opening Balance Model


<?php
require 'vendor/autoload.php';
use CLIFramework\Component\Table\Table;

$dbh = new PDO('pgsql:host=localhost;dbname=testing', 'postgres');
// $dbh->query('create table authors (confirmed BOOL default false);');
$dbh->query('delete from authors');

$stm = $dbh->prepare('insert into authors (name,confirmed) values (:name, :confirmed)');
if (false === $stm->execute([':confirmed' => 0, ':name' => '0'])) {
    var_dump( $stm->errorInfo() );
}
$stm = $dbh->prepare('insert into authors (name,confirmed) values (:name, :confirmed)');
if (false === $stm->execute([':confirmed' => 1, ':name' => '1'])) {
    var_dump( $stm->errorInfo() );
}

$stm = $dbh->prepare('insert into authors (name, confirmed) values (:name,:confirmed)');
if (false === $stm->execute([':confirmed' => true, ':name' => 'true'])) {
    var_dump( $stm->errorInfo() );
}

$stm = $dbh->prepare('insert into authors (name, confirmed) values (:name,:confirmed)');
if (false === $stm->execute([':confirmed' => false, ':name' => 'false'])) {
    var_dump( $stm->errorInfo() );
}

function dumpQuery($dbh, $query)
{
    $stm = $dbh->query($query);
    if ($stm == false) {
        var_dump($dbh->errorInfo());
        return;
    }

    echo "Result for: $query\n";
    $rows = $stm->fetchAll(PDO::FETCH_ASSOC);
    $table = new Table;
    $table->setHeaders(array_keys($rows[0]));
    foreach($rows as $row) {
        $values = array_map(function($val) { return var_export($val, true); }, array_values($row));
        $table->addRow($values);
    }

    echo $table->render();
}
dumpQuery($dbh,'select * from authors WHERE confirmed is false');
dumpQuery($dbh,'select * from authors WHERE confirmed is true');
// var_dump($dbh->query('select * from authors WHERE confiremd = 0')->fetchAll());
/*
$dbh = new PDO('mysql:host=localhost;dbname=testing', 'root', 'qwer1234');
$stm = $dbh->prepare('insert into authors (name) values (:name)');
$stm->execute([ ':name' => 'John' ]);

var_dump($dbh->query('select * from authors')->fetchAll());

$stm = $dbh->prepare('update authors set name = :name');
$stm->execute([ ':name' => null ]);

var_dump($dbh->query('select * from authors')->fetchAll());

$dbh->query('delete from authors');
 */

Add pgsql boolean value tests

Add pgsql boolean value tests


<?php

namespace Benrowe\Formatter\Test\Examples;

use Benrowe\Formatter\AbstractFormatterProvider;

class NumberSampleProvider extends AbstractFormatterProvider
{
    public function asNumber($value)
    {
        return $this->normalise($value);
    }

    public function asUnsigned($value)
    {
        $value = $this->normalise($value);
        if ($value < 0) {
            $value *= -1;
        }

        return $value;
    }

    private function normalise($value)
    {
        if (!is_numeric($value)) {
            $value = 0;
        }

        return (float)$value;
    }

}

Add additional sample provider for test suite


<?php
namespace nochso\WriteMe\Test\Placeholder;

use nochso\WriteMe\Document;
use nochso\WriteMe\Placeholder\Call;

class CallTest extends \PHPUnit_Framework_TestCase
{
    public function extractFirstCallProvider()
    {
        return [
            ['@identifier@', 'identifier', null, []],
            ['@identifier.method@', 'identifier', 'method', []],
            ['@identifier.method "string param"@', 'identifier', 'method', ['string param']],
            ["@identifier.method 'string param'@", 'identifier', 'method', ['string param']],
            ['@identifier.method 1@', 'identifier', 'method', [1]],
            ['@identifier.method true@', 'identifier', 'method', [true]],
            ['@identifier.method [1]@', 'identifier', 'method', [[1]]],
            ['@identifier.method ["key" => "value"]@', 'identifier', 'method', [['key' => 'value']]],
            ['@identifier.method ["key" => ["nested key" => true, 2]]@', 'identifier', 'method', [['key' => ['nested key' => true, 2]]]],
            ['@identifier.method 1, 2, 3@', 'identifier', 'method', [1, 2, 3]],
            ['@identifier.firstcall@ @identifier.secondcall@', 'identifier', 'firstcall', []],
        ];
    }

    /**
     * @dataProvider extractFirstCallProvider
     *
     * @param string      $rawDocument
     * @param string      $expectedIdentifier
     * @param string|null $expectedMethod
     * @param array       $expectedParameters
     */
    public function testExtractFirstCall($rawDocument, $expectedIdentifier, $expectedMethod, $expectedParameters)
    {
        $document = new Document($rawDocument);
        $call = Call::extractFirstCall($document);
        $this->assertSame($expectedIdentifier, $call->getIdentifier());
        $this->assertSame($expectedMethod, $call->getMethod());
        $this->assertSame($expectedParameters, $call->getParameters());
    }

    public function extractFirstCallNullProvider()
    {
        return [
            ['@invalid'],
            [''],
            ['invalid@'],
            ['some content'],
        ];
    }

    /**
     * @dataProvider extractFirstCallNullProvider
     *
     * @param string $rawDocument
     */
    public function testExtractFirstCall_WhenNoneFound_MustReturnNull($rawDocument)
    {
        $document = new Document($rawDocument);
        $this->assertNull(Call::extractFirstCall($document));
    }
}

Add tests for new class Call

test: Add tests for new class Call


<?php

namespace Becklyn\AssetsBundle\tests\Embed;

use Becklyn\AssetsBundle\Embed\EmbedFileHeader;
use PHPUnit\Framework\TestCase;

class EmbedFileHeaderTest extends TestCase
{
    public function dataProviderFileHeader ()
    {
        return [
            [".js", "/\\*.*?\\*/"],
            ["css", "/\\*.*?\\*/"],
            ["svg", "<!--.*?-->"],
        ];
    }

    /**
     * @dataProvider dataProviderFileHeader
     */
    public function testFileHeader (string $extension, string $matcher)
    {
        $assetPath = "@namespace/file.{$extension}";
        $filePath = "/path/file.{$extension}";

        $embedFileHeader = new EmbedFileHeader();
        $header = $embedFileHeader->getFileHeader($assetPath, $filePath);

        self::assertContains($assetPath, $header);
        self::assertContains($filePath, $header);
        self::assertRegExp("~\\A{$matcher}\\Z~s", $header);
    }

    public function dataProviderEmptyFileHeader ()
    {
        return [
            ["invalid"],
            ["jpg"],
        ];
    }

    /**
     * @dataProvider dataProviderEmptyFileHeader
     */
    public function testEmptyFileHeader (string $extension)
    {
        $assetPath = "@namespace/file.{$extension}";
        $filePath = "/path/file.{$extension}";

        $embedFileHeader = new EmbedFileHeader();
        $header = $embedFileHeader->getFileHeader($assetPath, $filePath);

        self::assertEquals("", $header);
    }
}

Add tests for embed file header

Add tests for embed file header


<?php

namespace App\Http\Middleware;
use Illuminate\Support\Facades\Auth;

use Closure;

class CheckIsParticipant
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $role = Auth::user()->role;
        if(Auth::check()){
            if($role == "participant"){
                return $next($request);
            }else{
                return redirect(route('events.index'));
            }
        }else{
            return redirect(route('events.index'));
        }
    }
}

Add new middleware for participant

Add new middleware for participant


<?php
/**
 * Slim Framework (https://slimframework.com)
 *
 * @link      https://github.com/slimphp/Slim
 * @copyright Copyright (c) 2011-2017 Josh Lockhart
 * @license   https://github.com/slimphp/Slim/blob/3.x/LICENSE.md (MIT License)
 */
namespace Slim\Tests\Http;

use PHPUnit\Framework\TestCase;
use Slim\Exception\HttpNotAllowedException;
use Slim\Exception\HttpNotFoundException;
use Slim\Http\Request;
use Slim\Http\RequestBody;
use Slim\Http\Response;
use Slim\Http\Uri;
use Slim\Http\Headers;

class HttpExceptionTest extends TestCase
{
    public function testThatConstructorWillSetDetailsAccordingly()
    {
        $exceptionWithMessage = new HttpNotAllowedException('Oops..');
        $this->assertEquals($exceptionWithMessage->getMessage(), 'Oops..');

        $details = ['allowedMethods' => 'POST'];
        $exceptionWithDetails = new HttpNotAllowedException($details);
        $this->assertEquals($exceptionWithDetails->getDetails(), $details);
    }

    public function testHttpExceptionRequestReponseGetterSetters()
    {
        // Prepare request and response objects
        $uri = Uri::createFromGlobals($_SERVER);
        $headers = Headers::createFromGlobals($_SERVER);
        $cookies = [];
        $serverParams = $_SERVER;
        $body = new RequestBody();
        $request = new Request('GET', $uri, $headers, $cookies, $serverParams, $body);
        $response = new Response();
        $exception = new HttpNotFoundException;
        $exception->setRequest($request);
        $exception->setResponse($response);

        $this->assertInstanceOf(Request::class, $exception->getRequest());
        $this->assertInstanceOf(Response::class, $exception->getResponse());
    }

    public function testHttpExceptionAttributeGettersSetters()
    {
        $exception = new HttpNotFoundException;
        $exception->setTitle('Title');
        $exception->setDescription('Description');
        $exception->setDetails(['Details']);

        $this->assertEquals('Title', $exception->getTitle());
        $this->assertEquals('Description', $exception->getDescription());
        $this->assertEquals(['Details'], $exception->getDetails());
    }

    public function testHttpNotAllowedExceptionGetAllowedMethods()
    {
        $exception = new HttpNotAllowedException;
        $exception->setAllowedMethods('GET');
        $this->assertEquals('GET', $exception->getAllowedMethods());

        $exception = new HttpNotAllowedException;
        $this->assertEquals('', $exception->getAllowedMethods());
    }
}

Add http named exception supporting unit tests


<?php

/*
 * This file is part of Bens Penhorados, an undergraduate capstone project.
 *
 * (c) Fábio Santos <ffsantos92@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

use App\Models\Attributes\Vehicle\VehicleColor;

/**
 * This is the color extractor test class.
 *
 * @author Fábio Santos <ffsantos92@gmail.com>
 */
class ColorExtractorTest extends AbstractVehicleExtractorTest
{
    public function testExtractColor()
    {
        $text = [
            'preto'         => 'Preto',
            'preta'         => 'Preto',
            'branco'        => 'Branco',
            'esbranquiçado' => 'Branco',
            'esbranquiçada' => 'Branco',
            'cinzento'      => 'Cinzento',
            'cinzenta'      => 'Cinzento',
            'cinza'         => 'Cinzento',
            'acinzentado'   => 'Cinzento',
            'acinzentada'   => 'Cinzento',
            'azul'          => 'Azul',
            'azulado'       => 'Azul',
            'azulada'       => 'Azul',
            'vermelho'      => 'Vermelho',
            'vermelha'      => 'Vermelho',
            'avermelhado'   => 'Vermelho',
            'encarnado'     => 'Vermelho',
            'encarnada'     => 'Vermelho',
            'verde'         => 'Verde',
            'esverdeado'    => 'Verde',
            'esverdeada'    => 'Verde',
            'amarelado'     => 'Amarelo',
            'amarelada'     => 'Amarelo',
            'castanho'      => 'Castanho',
            'castanha'      => 'Castanho',
            'acastanhada'   => 'Castanho',
            'acastanhado'   => 'Castanho',
            'prateado'      => 'Prateado',
            'prateada'      => 'Prateado',
            'dourado'       => 'Dourado',
            'dourada'       => 'Dourado',
            'rosa'          => 'Rosa',
            'roxo'          => 'Roxo',
            'roxa'          => 'Roxo',
            'bege'          => 'Bege',
        ];

        foreach ($text as $input => $expected) {
            $colorId = $this->extractor->color($input);

            $this->assertNotNull($colorId, "Input: $input");
            $this->assertSame($expected, VehicleColor::find($colorId)->name);
        }
    }
}

Add the color extractor test

Add the color extractor test


<?php

namespace Oro\Component\Layout\Tests\Unit\Extension\Theme\Stubs;

use Oro\Component\Layout\LayoutItemInterface;
use Oro\Component\Layout\ImportsAwareLayoutUpdateInterface;
use Oro\Component\Layout\LayoutManipulatorInterface;
use Oro\Component\Layout\LayoutUpdateImportInterface;
use Oro\Component\Layout\LayoutUpdateInterface;
use Oro\Component\Layout\Model\LayoutUpdateImport;

class ImportedLayoutUpdateWithImports implements LayoutUpdateInterface, LayoutUpdateImportInterface, ImportsAwareLayoutUpdateInterface
{
    public function setImport(LayoutUpdateImport $import)
    {
    }

    /**
     * @return array
     */
    public function getImports()
    {
    }

    /**
     * {@inheritDoc}
     */
    public function updateLayout(LayoutManipulatorInterface $layoutManipulator, LayoutItemInterface $item)
    {
    }
}

[WIP] BB-3589: Create generator’s extension for root and namespace replaces
- cs fixes


<?php
	function listdirs($dir) {
	    static $alldirs = array();
	    $dirs = glob($dir . '/*', GLOB_ONLYDIR);
	    if (count($dirs) > 0) {
	        foreach ($dirs as $d) $alldirs[] = $d;
	    }
	    foreach ($dirs as $dir) listdirs($dir);
	    return $alldirs;
	}

	$directory_list = listdirs('http://media.clemson.edu/cgsg/');
	print_r($directory_list);
?>

Test script for dir listing

Test script for dir listing


<?php

/**
 * Search Resource
 *
 * @category Asm
 * @package Asm_Solr
 * @author Ingo Renner <ingo@infielddesign.com>
 */

class Asm_Solr_Model_Resource_Search
{

	/**
	 * An instance of the Solr service
	 *
	 * @var Asm_Solr_Model_Solr_Connection
	 */
	protected $connection = NULL;

	/**
	 * The search query
	 *
	 * @var Asm_Solr_Model_Solr_Query
	 */
	protected $query = NULL;

	/**
	 * The search response
	 *
	 * @var Apache_Solr_Response
	 */
	protected $response = NULL;

	/**
	 * Flag for marking a search
	 *
	 * @var boolean
	 */
	protected $hasSearched = FALSE;

	public function __construct(array $searchParameters = array())
	{
		if (isset($searchParameters['connection'])) {
			$this->connection = $searchParameters['connection'];
		} else {
			$this->connection = Mage::helper('solr/connectionManager')->getConnection();
		}
	}

	/**
	 * Executes a query against a Solr server.
	 *
	 * 1) Gets the query string
	 * 2) Conducts the actual search
	 * 3) Checks debug settings
	 *
	 * @param Asm_Solr_Model_Solr_Query $query The query with keywords, filters, and so on.
	 * @param integer $offset Result offset for pagination.
	 * @param integer $limit Maximum number of results to return. If set to NULL, this value is taken from the query object.
	 * @return Apache_Solr_Response Solr response
	 */
	public function search(Asm_Solr_Model_Solr_Query $query, $offset = 0, $limit = 10) {
		$this->query = $query;

		if (empty($limit)) {
			$limit = $query->getResultsPerPage();
		}

		try {
			$response = $this->connection->search(
				$query->getKeywords(),
				$offset,
				$limit,
				$query->getQueryParameters()
			);
		} catch (RuntimeException $e) {
			$response = $this->connection->getResponse();
		}

		$this->response    = $response;
		$this->hasSearched = TRUE;

		return $this->response;
	}

}

Add Solr search resource model

Add Solr search resource model


<?php

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

namespace Surfnet\StepupMiddleware\ApiBundle\Controller;

use Surfnet\StepupMiddleware\ApiBundle\Configuration\Service\InstitutionWithPersonalRaDetailsService;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;

final class InstitutionWithPersonalRaDetailsController extends Controller
{
    public function getAllAction()
    {
        $institutionsWithPersonalRaDetails = $this->getService()->findAll();

        return new JsonResponse($institutionsWithPersonalRaDetails);
    }

    /**
     * @return InstitutionWithPersonalRaDetailsService
     */
    private function getService()
    {
        return $this->container->get('surfnet_stepup_middleware_api.service.institution_with_personal_ra_details');
    }
}

Add controller for institutions with personal RA details


<?php
/* Created with the help of http://form.guide/email-form/html-email-form.html */

	$name = $_POST['name'];
	$visitor_email = $_POST['email'];
	$message = $_POST['text'];

	function IsInjected($str)
	{
		$injections = array('(\n+)',
			'(\r+)',
			'(\t+)',
			'(%0A+)',
			'(%0D+)',
			'(%08+)',
			'(%09+)'
			);
		$inject = join('|', $injections)
		$inject = "/$inject/i";

		if(preg_match($inject, $str))
		{
			return true;
		}
		else
		{
			return false;
		}
	}

	if(IsInjected($visitor_email))
	{
		echo "Bad email value!";
		exit;
	}

	if(empty($name)||empty($visitor_email))
	{
		echo "All fields required.";
		exit;
	}

	$email_from = "je.deviens.moi@gmail.com"
	$email_subject = 'Message from Portfolio Page';
	$email_body = "Message from $name :\n $message";

	$to = "tiffany.c.stallings@gmail.com";
	$headers = "From: $email_from \r\n";
	$headers .= "Reply-To: $visitor_email \r\n";

	mail($to, $email_subject, $email_body, $headers);
	echo "Message sent!";
?>

Add php to handle email

Add php to handle email


<?php
/**
 *
 * @param array &$hookinfo  hookinfo
 */
function consentSimpleAdmin_hook_sanitycheck(&$hookinfo) {
	assert('is_array($hookinfo)');
	assert('array_key_exists("errors", $hookinfo)');
	assert('array_key_exists("info", $hookinfo)');

	try {
		$config = SimpleSAML_Configuration::getInstance();
		$consentconfig = $config->copyFromBase('consentSimpleAdminConfig', 'module_consentSimpleAdmin.php');

		// Parse consent config
		$consent_storage = sspmod_consent_Store::parseStoreConfig($consentconfig->getValue('store'));

		// Get all consents for user
		$stats = $consent_storage->getStatistics();

		$hookinfo['info'][] = '[consentSimpleAdmin] Consent Storage connection OK.';

	} catch (Exception $e) {
		$hookinfo['errors'][] = '[consentSimpleAdmin] Error connecting to storage: ' . $e->getMessage();
	}

}
?>


<?php
namespace App\Test\TestCase\Controller;

use Cake\Core\Configure;
use Cake\TestSuite\IntegrationTestTrait;
use Cake\TestSuite\TestCase;
use SimpleXMLElement;

class AssetsControllerTest extends TestCase
{
    use IntegrationTestTrait;

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

        // Make sure debug is enabled so that
        // assets are generated on-the-fly
        Configure::write('debug', true);
    }

    public function testSvgSpriteIsWellFormed() {
        // Make sure cached versions are not being served instead
        $caches = [
            CACHE . 'asset_compress' . DS . 'allflags.svg',
            WWW_ROOT . 'cache_svg' . DS . 'allflags.svg',
        ];
        foreach ($caches as $cache) {
            if (file_exists($cache)) {
                unlink($cache);
            }
        }

        $this->get("/cache_svg/allflags.svg");
        $svg = (string)$this->_response->getBody();
        $result = simplexml_load_string($svg);

        $this->assertInstanceOf(SimpleXMLElement::class, $result,
                                "allflags.svg does not contain valid XML");
    }
}

Make sure the SVG sprite contains valid XML


<?php
/**
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link          http://cakephp.org CakePHP(tm) Project
 * @since         3.0.0
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
 */
namespace Cake\Test\TestCase\Console\Command;

use Cake\Console\Command\OrmCacheShell;
use Cake\Cache\Cache;
use Cake\TestSuite\TestCase;

/**
 * OrmCacheShell test.
 */
class OrmCacheShellTest extends TestCase {

/**
 * setup method
 *
 * @return void
 */
	public function setUp() {
		parent::setUp();
		$this->io = $this->getMock('Cake\Console\ConsoleIo');
		$this->Shell = new OrmCacheShell($this->io);
	}

/**
 * Test build() with no args.
 *
 * @return void
 */
	public function testBuildNoArgs() {
		$this->markTestIncomplete();
	}

/**
 * Test build() with one arg.
 *
 * @return void
 */
	public function testBuildNamedModel() {
		$this->markTestIncomplete();
	}

/**
 * Test build() with a non-existing connection name.
 *
 * @return void
 */
	public function testBuildInvalidConnection() {
		$this->markTestIncomplete();
	}

/**
 * Test clear() with no args.
 *
 * @return void
 */
	public function testClearInvalidConnection() {
		$this->markTestIncomplete();
	}

/**
 * Test clear() with once arg.
 *
 * @return void
 */
	public function testClearNoArgs() {
		$this->markTestIncomplete();
	}

/**
 * Test clear() with a model name.
 *
 * @return void
 */
	public function testClearNamedModel() {
		$this->markTestIncomplete();
	}

}

Add test skeleton for orm cache shell.

Add test skeleton for orm cache shell.