<?php

namespace Lstr\Sprintf;

use PHPUnit_Framework_TestCase;

/**
 * @coversDefaultClass Lstr\Sprintf\ParsedExpression
 */
class ParsedExpressionTest extends PHPUnit_Framework_TestCase
{
    /**
     * @covers ::__construct
     * @covers ::format
     * @dataProvider provideTestParameters
     * @param array $parameters
     */
    public function testParsedFormatIsUsedToFormatString(array $parameters)
    {
        $parsed_expression = $this->getParsedExpression();

        $this->assertSame(
            '98.123450 abc 12 98.123450',
            $parsed_expression->format($parameters)
        );
    }

    /**
     * @covers ::__construct
     * @covers ::format
     * @dataProvider provideTestParameters
     * @param array $parameters
     */
    public function testMiddlewareIsAppliedToEachParameter(array $parameters)
    {
        $parsed_expression = $this->getParsedExpression();

        $middleware = function ($name, callable $value_callback) {
            $value = $value_callback($name);

            if (!is_numeric($value)) {
                return $value;
            }

            return 2 * $value;
        };

        $this->assertSame(
            '196.246900 abc 24 196.246900',
            $parsed_expression->format($parameters, $middleware)
        );
    }

    /**
     * @covers ::__construct
     * @covers ::format
     * @expectedException Lstr\Sprintf\Exception
     */
    public function testMissingParameterCausesAnException()
    {
        $parsed_expression = new ParsedExpression('', [['name' => 'one']]);

        $parsed_expression->format([]);
    }

    /**
     * @return array
     */
    public function provideTestParameters()
    {
        return [
            [[
                'string'  => 'abc',
                'integer' => 12.3,
                'float'   => 98.12345,
            ]],
        ];
    }

    /**
     * @return ParsedExpression
     */
    private function getParsedExpression()
    {
        $parsed_format = '%f %s %d %f';
        $parameter_map = [
            ['name' => 'float'],
            ['name' => 'string'],
            ['name' => 'integer'],
            ['name' => 'float'],
        ];
        return new ParsedExpression($parsed_format, $parameter_map);
    }
}

Add tests specifically for ParsedExpression

Previously, the ParsedExpression class was only being
tested indirectly via the Sprintf tests.


<?php
namespace Ely\TempMailBuster;

class LoaderTest extends \PHPUnit_Framework_TestCase
{
    public function testGetPaths()
    {
        $this->assertTrue(is_array(Loader::getPaths()));
    }

    public function testLoad()
    {
        $this->assertTrue(is_array(Loader::load()));
    }

    public function testLoadExceptionWrongPaths()
    {
        $this->expectException('Exception');
        LoaderWithWrongPaths::load();
    }

    public function testLoadExceptionInvalidJson()
    {
        $this->expectException('Exception');
        LoaderWithInvalidJson::load();
    }
}

class LoaderWithWrongPaths extends Loader
{
    public static function getPaths()
    {
        return [
            __DIR__ . '/virtual_reality.json',
        ];
    }
}

class LoaderWithInvalidJson extends Loader
{
    public static function getPaths()
    {
        return [
            __DIR__ . '/LoaderTest.php',
        ];
    }
}

Return file in valid case

Return file in valid case


<?php

namespace Mila\DAO;

class teamDAO
{
    /*
     * @var \Doctrine\DBAL\Connection
     */
    private $dbCon;

    /*
     * @param \Doctrine\DBAL\Connection $dbCon
     */
    public function __construct($dbCon)
    {
        $this->dbCon = $dbCon;
    }

    public function fetchAll()
    {
        return $this->dbCon->fetchAll('SELECT * FROM teams');
    }
}

Add DAO fetching all available teams in database


<?php

/*
 * This file is part of the Sonata package.
 *
 * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Sonata\AdminBundle\Command;

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

class CreateClassCacheCommand extends ContainerAwareCommand
{

    public function configure()
    {
        $this->setName('cache:create-cache-class');
        $this->setDescription('Generate the classes.php files');
    }

    public function execute(InputInterface $input, OutputInterface $output)
    {
        $kernel = $this->getContainer()->get('kernel');

        $classmap = $kernel->getCacheDir().'/classes.map';

        if (!is_file($classmap)) {
            throw new \RuntimeException(sprintf('The file %s does not exist', $classmap));
        }

        $name = 'classes';
        $extension = '.php';

        $output->write("<info>Writing cache file ...</info>");
        ClassCollectionLoader::load(
            include($classmap),
            $kernel->getCacheDir(),
            $name,
            $kernel->isDebug(),
            false,
            $extension
        );

        $output->writeln(" done!");
    }
}

Add a command to generate the cache class from the classes.map file


<?php

namespace AppBundle\API\Listing;

use AppBundle\Entity\Data\TraitFileUpload;
use AppBundle\Entity\User\FennecUser;
use AppBundle\Entity\User\Project;
use AppBundle\Service\DBVersion;

/**
 * Web Service.
 * Returns information of all users trait files
 */
class TraitFiles
{
    const ERROR_NOT_LOGGED_IN = "Error: You are not logged in.";

    private $data_em;

    /**
     * Projects constructor.
     * @param $dbversion
     */
    public function __construct(DBVersion $dbversion)
    {
        $this->data_em = $dbversion->getDataEntityManager();
    }

    /**
    * @inheritdoc
    * @returns array $result
    * <code>
    * array(array('project_id','import_date','OTUs','sample size'));
    * </code>
    */
    public function execute(FennecUser $user = null)
    {
        $result = array('data' => array());
        if ($user == null) {
            $result['error'] = Projects::ERROR_NOT_LOGGED_IN;
        } else {
            $traitFiles = $this->data_em->getRepository(TraitFileUpload::class)->findBy(array(
                'fennecUserId' => $user->getId(),
                'deletionDate' => null
            ));
            foreach ($traitFiles as $t) {
                $traitFile = array();
                $traitFile['traitFileId'] = $t->getId();
                $traitFile['filename'] = $t->getFilename();
                $traitFile['importDate'] = $t->getImportDate()->format('Y-m-d H:i:s');
                $traitFile['format'] = '';
                $traitFile['traitType'] = '';
                $traits = $t->getCategoricalTraitEntries();
                if(count($traits) > 0){
                    $traitFile['format'] = 'categorical';
                    $traitFile['traitType'] = $traits[0]->getType();
                } else {
                    $traits = $t->getNumericalTraitEntries();
                    if(count($traits) > 0 ){
                        $traitFile['format'] = 'numerical';
                        $traitFile['traitType'] = $traits[0]->getType();
                    }
                }
                $traitFile['entries'] = count($traits);
                $result[] = $traitFile;
            }
        }
        return $result;
    }
}

Define service for listing trait files

Define service for listing trait files


<?php

namespace Tests\Components\Validation;

use App\Validation\DoesNotContainUrlRule;
use Tests\TestCase;

class DoesNotContainUrlRuleTest extends TestCase
{
    const STRING_WITH_URL = 'This is a string http://example.com with an url in it.';
    const STRING_WITHOUT_URL = 'This is a string without an url in it.';
    const STRING_WITH_A_REGRESSION = 'JSON not possible with MSSQL running on Windows platform?';

    /** @test */
    public function it_detects_a_url_in_a_string()
    {
        $this->assertFalse($this->runRule(self::STRING_WITH_URL));
    }

    /** @test */
    public function it_passes_when_no_url_is_present()
    {
        $this->assertTrue($this->runRule(self::STRING_WITHOUT_URL));
    }

    private function runRule(string $value): bool
    {
        return $this->app->make(DoesNotContainUrlRule::class)->validate(null, $value);
    }
}

Add test for url validation rule

Add test for url validation rule


<?php

use yii\db\Migration;

/**
 * Class m180929_200905_drop_init_transaction_status
 */
class m180929_200905_drop_init_transaction_status extends Migration {
    /**
     * {@inheritdoc}
     */
    public function safeUp() {
        $this->execute("UPDATE `transaction` SET `status` = 'pending' where `status` = 'init'");
        $this->execute("UPDATE `transaction_log` SET `status` = 'pending' where `status` = 'init'");

        $this->execute("ALTER TABLE `transaction_log`"
            . "CHANGE `status` `status` ENUM('pending','paid','rejected','error') "
            . "NOT NULL DEFAULT 'pending';");

        $this->execute("ALTER TABLE `transaction_log`"
            . "CHANGE `status` `status` ENUM('pending','paid','rejected','error') "
            . "NOT NULL DEFAULT 'pending';");

    }

    /**
     * {@inheritdoc}
     */
    public function safeDown() {
        $this->execute("ALTER TABLE `transaction_log`"
            . "CHANGE `status` `status` ENUM('init','pending','paid','rejected','error') "
            . "NOT NULL DEFAULT 'pending';");

        $this->execute("ALTER TABLE `transaction_log`"
            . "CHANGE `status` `status` ENUM('init','pending','paid','rejected','error') "
            . "NOT NULL DEFAULT 'pending';");

    }

}

Drop init status for transactions

Drop init status for transactions


<?php

    namespace App\Http\Requests\User;

    use Illuminate\Foundation\Http\FormRequest;

    /**
     * Class Enable2FA
     *
     * @package App\Http\Requests\User
     */
    class Enable2FA extends FormRequest {
        /**
         * Determine if the user is authorized to make this request.
         *
         * @return bool
         */
        public function authorize() {
            return \Auth::check();
        }

        /**
         * Get the validation rules that apply to the request.
         *
         * @return array
         */
        public function rules() {
            return [
                'key' => 'required|string|min:6'
            ];
        }
    }

Allow users to set up 2fa

Allow users to set up 2fa


<?php
use Migrations\AbstractMigration;

class AddTypeToReindexFlags extends AbstractMigration
{
    /**
     * Change Method.
     *
     * More information on this method is available here:
     * http://docs.phinx.org/en/latest/migrations.html#the-change-method
     * @return void
     */
    public function change()
    {
        $table = $this->table('reindex_flags');
        $table->addColumn('type', 'enum', [
            'values' => ['change', 'removal'],
            'null' => false,
        ]);
        $table->update();
    }
}

Add 'type' column to ReindexFlags

Add 'type' column to ReindexFlags

We need this column to distinguish changes (inserts and updates) from
deletions. Changed sentences will be included in the delta index,
deleted sentences will be included in the kill-list.

See #2226 for additional information.


<?php

/*
   ------------------------------------------------------------------------
   FusionInventory
   Copyright (C) 2010-2012 by the FusionInventory Development Team.

   http://www.fusioninventory.org/   http://forge.fusioninventory.org/
   ------------------------------------------------------------------------

   LICENSE

   This file is part of FusionInventory project.

   FusionInventory 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.

   FusionInventory 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 Behaviors. If not, see <http://www.gnu.org/licenses/>.

   ------------------------------------------------------------------------

   @package   FusionInventory
   @author    Vincent Mazzoni
   @co-author
   @copyright Copyright (c) 2010-2012 FusionInventory team
   @license   AGPL License 3.0 or (at your option) any later version
              http://www.gnu.org/licenses/agpl-3.0-standalone.html
   @link      http://www.fusioninventory.org/
   @link      http://forge.fusioninventory.org/projects/fusioninventory-for-glpi/
   @since     2010

   ------------------------------------------------------------------------
 */

if (!defined('GLPI_ROOT')) {
   die("Sorry. You can't access this file directly");
}

class PluginFusioninventorySnmpmodelConstructDeviceWalk extends CommonDBTM {

}

?>

Move data from snmp module to core plugin


<?php

namespace Doctrine\Tests\ORM\Functional\Ticket;

require_once __DIR__ . '/../../../TestInit.php';

/**
 * @group DDC-2645
 */
class DDC2645Test extends \Doctrine\Tests\OrmFunctionalTestCase
{
    public function testIssue()
    {
        $bar = new DDC2645Bar;
        $bar->id = 123;

        $foo = new DDC2645Foo(1, $bar, 'Foo');
        $foo2 = new DDC2645Foo(1, $bar, 'Bar');

        $this->_em->persist($bar);
        $this->_em->persist($foo);

        $foo3 = $this->_em->merge($foo2);

        $this->assertSame($foo, $foo3);
        $this->assertEquals('Bar', $foo->name);
    }
}

/** @Entity */
class DDC2645Foo
{
    /** @Id @Column(type="integer") */
    private $id;

    /** @Id @ManyToOne(targetEntity="DDC2645Bar") */
    private $bar;

    /** @Column */
    public $name;

    public function __construct($id, $bar, $name)
    {
        $this->id = $id;
        $this->bar = $bar;
        $this->name = $name;
    }
}

/** @Entity */
class DDC2645Bar
{
    /** @Id @Column(type="integer") @GeneratedValue(strategy="NONE") */
    public $id;
}

Create failing test for DDC-2645.

Create failing test for DDC-2645.

Merge not dealing correctly with composite primary keys.


<?php

namespace JS\Form;

use Zend\Form\Fieldset;

class AbstractListFieldset extends AbstractFieldset {

    private $buttonBarTop;

    public function init() {
        $this->buttonBarTop = new Fieldset('buttonBarTop');
        $this->add($this->buttonBarTop);
        $this->buttonBarTop->add([
            'type' => 'Button',
            'name' => 'btnAddRegistro',
            'attributes' => [
                'class' => 'btn btn-primary',
                'title' => 'Cadastrar Novo Veículo'
            ],
            'options' => [
                'label' => "",
                'glyphicon' => 'edit'
            ],
        ]);

        $this->buttonBarTop->add([
            'type' => 'Button',
            'name' => 'btnExcluirRegistro',
            'attributes' => [
                'class' => 'btn btn-danger',
                'title' => 'Excluir Veículo'
            ],
            'options' => [
                'label' => "",
                'glyphicon' => 'trash'
            ],
        ]);

        $this->buttonBarTop->add([
            'type' => 'Button',
            'name' => 'btnConsultar',
            'attributes' => [
                'class' => 'btn btn-primary',
                'title' => 'Consultar',
                'style' => 'display:none'
            ],
            'options' => [
                'label' => "",
                'glyphicon' => 'search'
            ],
        ]);

        $this->buttonBarTop->add([
            'type' => 'Button',
            'name' => 'btnClearFilters',
            'attributes' => [
                'class' => 'btn btn-success',
                'title' => 'Limpar Todos Filtros',
            ],
            'options' => [
                'label' => "",
                'glyphicon' => 'unchecked'
            ],
        ]);
    }

}

Add fieldset to works with button bar

Add fieldset to works with button bar


<?php
/**
 * @author        Michael Collette <mcollette@meetingevolution.net>
 * @version       1.0
 * @package       Metrol/DBSql
 * @copyright (c) 2016, Michael Collette
 */

namespace Metrol\DBSql;

/**
 * Describes objects that provide where clauses
 *
 */
interface WhereInterface
{
    /**
     * Produce the text of the clause
     *
     * @return string
     */
    public function output();

    /**
     * Fetch any bindings that may have been used
     *
     * @return array
     */
    public function getBindings();
}

Create a new interface to define a Where clause

This will be used to specify both the parent WHERE as well as the more
specific types of where clauses.

issue #1


<?php
/**
 * Unit test for the PPI Request GetQuery
 *
 * @package   Core
 * @author    Paul Dragoonis <dragoonis@php.net>
 * @license   http://opensource.org/licenses/mit-license.php MIT
 * @link      http://www.ppiframework.com
*/
class PPI_Request_SessionTest extends PHPUnit_Framework_TestCase {
	public function setUp() {
	}

	public function tearDown() {
	}

	public function testIsCollected() {

		$session = new PPI_Request_Session();
		$this->assertTrue($session->isCollected());

		$session = new PPI_Request_Session(array('drink' => 'beer'));
		$this->assertFalse($session->isCollected());

		$session = new PPI_Request_Session(array());
		$this->assertFalse($session->isCollected());
	}

	public function testCustomSession() {
		$session = new PPI_Request_Session(array('drink' => 'beer'));
		$this->assertEquals('beer', $session['drink']);
		$this->assertEquals(null,   $session['foo']);
		$this->assertEquals(null,   $session['random']);
		$this->assertFalse($session->isCollected());
	}
}

Add basic tests for PPI_Request_Session

Add basic tests for PPI_Request_Session


<?php

/* ======================================================================

    WordPress for Web App Options
    Adjust plugin settings from the admin dashboard.

    Forked from code by Michael Fields.
    https://gist.github.com/mfields/4678999

 * ====================================================================== */

require_once( dirname( __FILE__) . '/options/wpwebapp-options-fields.php' );
require_once( dirname( __FILE__) . '/options/wpwebapp-options-defaults.php' );
require_once( dirname( __FILE__) . '/options/wpwebapp-options-sanitize-and-validate.php' );
require_once( dirname( __FILE__) . '/options/wpwebapp-options-render-menu.php' );
require_once( dirname( __FILE__) . '/options/wpwebapp-options-get-settings.php' );

?>

Split options across multiple files.

Split options across multiple files.

Results in more modularized and workable code structure.


<?php

namespace BitWasp\Secp256k1Tests;

class Secp256k1ContextTest extends TestCase
{
    public function testContext()
    {
        $ctx = \secp256k1_context_create(SECP256K1_CONTEXT_VERIFY);
        $clone = \secp256k1_context_clone($ctx);

        // We should have two resources of type secp256k1_context_t
        $this->assertInternalType('resource', $ctx);
        $this->assertInternalType('resource', $ctx);
        $this->assertEquals('secp256k1_context_t', get_resource_type($ctx));
        $this->assertEquals('secp256k1_context_t', get_resource_type($clone));

        // We should be able to destroy it (without affecting the other), and see it's type is now unknown.
        $this->assertTrue(\secp256k1_context_destroy($ctx));
        $this->assertEquals('Unknown', get_resource_type($ctx));
        $this->assertEquals('secp256k1_context_t', get_resource_type($clone));

    }
}

Add test file for secp256k1_context_create / destroy / clone


<?php

/*
 * A demo of a schemaless Mongo structure
 *
 * I'm modelling an e-bike, and its constituent parts, from this URL:
 *
 * http://www.onbike.co.uk/electricbikes/haibike-sduro-allmtn-rc/
 *
 * Bikes and their components will be stored in "components", and will of course have very
 * different properties. For example, a motor will have a voltage property, but this would
 * not be useful for a frame, which will have a colour property.
 */

$m = new MongoClient();

// select a database and clear it
$db = $m->bikes;
zapDatabase($db);

// Let's create some component manufacturers
$manuCollection = $db->manufacturer;

createManufacturer($manuCollection, "Haibike");		// Of the bike itself
createManufacturer($manuCollection, "Yamaha");		// Component manufacturers
createManufacturer($manuCollection, "Shimano");
createManufacturer($manuCollection, "Fox");
createManufacturer($manuCollection, "Selle Royal");
createManufacturer($manuCollection, "FSA");

// Let's create some components
$compCollection = $db->component;
$ids = [];
$ids[] = createDocument($compCollection, "Battery 400Wh", ['watt_hours' => 400, ]);
$ids[] = createDocument($compCollection, "Motor",
	['voltage' => 36, 'wattage' => 250, 'manufacturer' => 'yahama', ]
);

// Iterate through the stored data
echo "Components:\n";
dumpCollection($compCollection);
echo "Manufacturers:\n";
dumpCollection($manuCollection);

/**
 * Lists everything in the specified collection
 *
 * @param MongoCollection $collection
 */
function dumpCollection(MongoCollection $collection)
{
	// Find everything in this collection
	$cursor = $collection->find();

	foreach ($cursor as $document)
	{
		echo "\t{$document['name']}\n";
	}
}

/**
 * Deletes all our known collections
 *
 * @param MongoDB $db
 */
function zapDatabase(MongoDB $db)
{
	$db->component->drop();
	$db->manufacturer->drop();
}

/**
 * Inserts an item into the manufacturer collection, with a shortname
 *
 * @param MongoCollection $collection
 * @param string $name
 * @param array $properties
 */
function createManufacturer(MongoCollection $collection, $name, array $properties = [])
{
	$shortname = str_replace(' ', '-', strtolower($name));
	$allProps = array_merge($properties, ['shortname' => $shortname, ]);
	createDocument($collection, $name, $allProps);
}

/**
 * Creates a document in a collection
 *
 * @param MongoCollection $collection
 * @param string $name
 * @param array $properties
 */
function createDocument(MongoCollection $collection, $name, array $properties = [])
{
	$allProps = array_merge($properties, ['name' => $name, ]);
	$collection->insert($allProps);
}

Add script to create Mongo database

Add script to create Mongo database


<?php

declare(strict_types=1);

namespace Tests\Sylake\SyliusConsumerPlugin\Functional;

use PHPUnit\Framework\Assert;
use Sylake\SyliusConsumerPlugin\Event\ProductUpdated;
use Sylake\SyliusConsumerPlugin\Projector\Product\ProductPostprocessorInterface;
use Sylake\SyliusConsumerPlugin\Projector\ProductProjector;
use Sylius\Component\Core\Model\ProductInterface;

final class ProductPostprocessorSynchronizationTest extends ProductSynchronizationTestCase
{
    /**
     * @test
     */
    public function it_can_modify_projected_product_before_saving_it()
    {
        /** @var ProductProjector $productProjector */
        $productProjector = static::$kernel->getContainer()->get('sylake_sylius_consumer.projector.product');
        $productProjector->addPostprocessor(new class implements ProductPostprocessorInterface {
            public function __invoke(ProductUpdated $event, ProductInterface $product): void
            {
                $product->setCode($product->getCode() . '_POSTPROCESSED');
            }
        });

        $this->consume('{
            "type": "akeneo_product_updated",
            "payload": {
                "identifier": "AKNTS_BPXS",
                "categories": [],
                "enabled": true,
                "values": {
                    "name": [{"locale": null, "scope": null, "data": "Akeneo T-Shirt black and purple with short sleeve"}]
                },
                "created": "2017-04-18T12:30:45+02:30",
                "associations": {}
            }
        }');

        /** @var ProductInterface|null $product */
        $product = $this->productRepository->findOneBy(['code' => 'AKNTS_BPXS_POSTPROCESSED']);

        Assert::assertNotNull($product);
    }
}

Add test for actual use of product postprocessors


<?php

/**
 * Reset and update linking fields between bills (invoices, payments)
 * @param array $accounts Account ids
 */
function rebuildBillsLinks($accounts) {
	echo 'Rebuilding links...' . PHP_EOL;
	if ($accounts) {
		$billsColl = Billrun_Factory::db()->billsCollection();
		foreach ($accounts as $aid) {
			echo 'Rebuilding links to ' . $aid . PHP_EOL;
			$query = array(
				'aid' => $aid,
			);
			$res = $billsColl->query($query)->cursor();
			foreach ($res as $bill) {
				unset($bill['pays']);
				unset($bill['left']);
				unset($bill['paid_by']);
				unset($bill['paid']);
				unset($bill['total_paid']);
				if ($bill['due'] < 0) {
					$bill['left'] = $bill['amount'];
				} else {
					$bill['total_paid'] = 0;
					if (isset($bill['vatable_left_to_pay'])) {
						if (isset($bill['due_before_vat'])) {
							$bill['vatable_left_to_pay'] = $bill['due_before_vat'];
						} else {
							unset($bill['vatable_left_to_pay']);
						}
					}
				}
				if (!$bill->save($billsColl, 1)) {
					echo 'Error resetting bill ' . ($bill['type'] == 'inv' ? $bill['invoice_id'] : $bill['txid']) . PHP_EOL;
				}
			}
			Billrun_Bill::payUnpaidBillsByOverPayingBills($aid);
		}
	}
}

Add rebuildBillsLinks tool which resets and updates linking fields between bills (invoices, payments)


<?php

namespace Zimbra\Mail\Tests\Struct;

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

/**
 * Testcase class for AddRecurrenceInfo.
 */
class AddRecurrenceInfoTest extends ZimbraMailTestCase
{
    public function testAddRecurrenceInfo()
    {
        $add = new AddRecurrenceInfo();
        $this->assertInstanceOf('\Zimbra\Mail\Struct\RecurrenceInfo', $add);

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

        $array = array(
            'add' => array(),
        );
        $this->assertEquals($array, $add->toArray());
    }
}

Add Test case for AddRecurrenceInfo.

Add Test case for AddRecurrenceInfo.


<?php
namespace Matryoshka\Model\Hydrator;

use Zend\Stdlib\Hydrator\ClassMethods as ZendClassMethods;

class ClassMethods extends ZendClassMethods
{
    public function __construct()
    {
        parent::__construct();

        $this->filterComposite->addFilter('model',  new MethodMatchFilter('getModel'), FilterComposite::CONDITION_AND);
        $this->filterComposite->addFilter('hydrator',  new MethodMatchFilter('getHydrator'), FilterComposite::CONDITION_AND);
        $this->filterComposite->addFilter('inputFilter',  new MethodMatchFilter('getInputFilter'), FilterComposite::CONDITION_AND);
    }
}

Add hydrator form abstract object

Add hydrator form abstract object


<?php

namespace Drubo\Robo;

use Robo\Tasks as RoboTasks;

/**
 * Base class for drubo-enabled RoboFile console commands configuration classes.
 */
abstract class Tasks extends RoboTasks {

  /**
   * Install Drupal site.
   */
  public function siteInstall() {
    // TODO Implement Tasks::siteInstall().
  }

  /**
   * Update Drupal site.
   */
  public function siteUpdate() {
    // TODO Implement Tasks::siteUpdate().
  }

}

Add base class for drubo-enabled RoboFile console commands configuration classes


<?php

/**
 * Remove a node from channel tree
 */
$api->delete('/tree/:id', $APIkeyRequired, function($id) use ($api) {
    if (Channel::ById($id)->removeFromTree()) {
        $api->halt(204);
    } else {
        $api->stopAPI('Unable to delete node '.$node);
    }
})->name('Delete channel from channel tree')->help = array(
    'since'       => 'r4',
    'description' => 'Delete channel from channel tree',
    'apikey'      => TRUE
);

Add routes for hierarchy manipulation to API


<?php

namespace Tests\Controllers;

use App\Models\Contest;
use App\Models\User;
use DateTime;
use Illuminate\Http\Testing\File;
use Tests\TestCase;

class ContestEntriesControllerTest extends TestCase
{
    private Contest $contest;
    private User $user;

    public function testStoreEntryWithWrongFileExtension()
    {
        $this->prepareForStore();
        $file = File::fake()->create('entry.osz');

        $this
            ->actingAsVerified($this->user)
            ->postJson('/community/contest-entries', ['entry' => $file, 'contest_id' => $this->contest->id])
            ->assertStatus(422);
    }

    public function testStoreEntryExceedingMaxFileSize()
    {
        $this->prepareForStore();
        $file = File::fake()->create('test.png', 8 * 1024 * 1024 * 2);

        $this
            ->actingAsVerified($this->user)
            ->postJson('/community/contest-entries', ['entry' => $file, 'contest_id' => $this->contest->id])
            ->assertStatus(413);
    }

    public function testStoreEntryWithWrongForcedDimensions()
    {
        $this->prepareForStore();
        $file = File::image('entry.png', 1600, 900);

        $this
            ->actingAsVerified($this->user)
            ->postJson('/community/contest-entries', ['entry' => $file, 'contest_id' => $this->contest->id])
            ->assertStatus(400);
    }

    public function testStoreEntryWithCorrectRequirements()
    {
        $this->prepareForStore();
        $file = File::image('test.png', 1920, 1080);

        $this
            ->actingAsVerified($this->user)
            ->postJson('/community/contest-entries', ['entry' => $file, 'contest_id' => $this->contest->id])
            ->assertStatus(200);
    }

    private function prepareForStore()
    {
        $this->user = User::factory()->create();
        $this->contest = Contest::create([
            'name' => 'Test',
            'description_enter' => 'This is just a test!',
            'description_voting' => 'This is just a test!',
            'entry_starts_at' => new DateTime(),
            'entry_ends_at' => (new DateTime())->modify('+1 day'),
            'extra_options' => ['forced_width' => 1920, 'forced_height' => 1080],
            'header_url' => 'https://assets.ppy.sh/contests/154/header.jpg',
            'max_entries' => 1,
            'max_votes' => 1,
            'show_votes' => true,
            'type' => 'art',
            'visible' => true,
            'voting_ends_at' => (new DateTime())->modify('+2 day'),
            'voting_starts_at' => (new DateTime())->modify('+3 day'),
        ]);
    }
}

Create test case for ContestEntriesController


<?php

use Cake\Core\Configure;

$pluginPaths = Configure::read('plugins');
$pluginPaths['Croogo/Croogo'] = $pluginPaths['Croogo'] . 'Croogo' . DS;

Configure::write('plugins', $pluginPaths);

Make it possible for Croogo to be included as a plugin


<?php
use \Defuse\Crypto\Crypto;
use \Defuse\Crypto\Key;

class CryptoTest extends PHPUnit_Framework_TestCase
{
    # Test for issue #165 -- encrypting then decrypting empty string fails.
    public function testEmptyString()
    {
        $str = '';
        $key = Key::CreateNewRandomKey();
        $cipher = Crypto::encrypt($str, $key);
        $this->assertEquals(
            Crypto::decrypt($cipher, $key),
            $str
        );
    }
}

Add a test to catch a bug in ourSubstr

Add a test to catch a bug in ourSubstr


<?php
$I = new AcceptanceTester($scenario);
$I->wantTo('ensure that the projects index works');
TestCommonAdmin::logMeIn($I);
$I->amOnPage('/tickets');
$I->see('Title', 'th');
$I->see('Updated At', 'th');
$I->see('Priority', 'th');
$I->see('Owner', 'th');
$I->dontSee('whoops');

Add test for projects index

Add test for projects index


<?php
declare(strict_types=1);

/**
 * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
 * Copyright (c) Cake Software Foundation, Inc. (https://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. (https://cakefoundation.org)
 * @link          https://cakephp.org CakePHP(tm) Project
 * @since         4.3.0
 * @license       https://opensource.org/licenses/mit-license.php MIT License
 */
namespace Cake\Test\TestCase\TestSuite;

use Cake\Database\Connection;
use Cake\Database\Driver\Sqlite;
use Cake\Datasource\ConnectionManager;
use Cake\TestSuite\FixtureSchemaExtension;
use Cake\TestSuite\TestCase;

class FixtureSchemaExtensionTest extends TestCase
{
    /**
     * Test connection aliasing during construction.
     *
     * @return void
     */
    public function testConnectionAliasing()
    {
        $this->skipIf(!extension_loaded('pdo_sqlite'), 'Requires SQLite extension');
        ConnectionManager::setConfig('test_fixture_schema', [
            'className' => Connection::class,
            'driver' => Sqlite::class,
            'database' => TMP . 'fixture_schema.sqlite',
        ]);
        $this->assertNotContains('fixture_schema', ConnectionManager::configured());
        $extension = new FixtureSchemaExtension();

        $this->assertContains('test_fixture_schema', ConnectionManager::configured());
        $this->assertSame(
            ConnectionManager::get('test_fixture_schema'),
            ConnectionManager::get('fixture_schema')
        );
        $this->assertSame(
            ConnectionManager::get('test'),
            ConnectionManager::get('default')
        );
        $this->assertNull($extension->executeBeforeFirstTest());
        ConnectionManager::drop('test_fixture_schema');
    }
}

Add some coverage to FixtureSchemaExtension


<?php

$table = new PhabricatorRepositoryRefCursor();
$conn = $table->establishConnection('w');

$map = array();
foreach (new LiskMigrationIterator($table) as $ref) {
  $repository_phid = $ref->getRepositoryPHID();
  $ref_type = $ref->getRefType();
  $ref_hash = $ref->getRefNameHash();

  $ref_key = "{$repository_phid}/{$ref_type}/{$ref_hash}";

  if (!isset($map[$ref_key])) {
    $map[$ref_key] = array(
      'id' => $ref->getID(),
      'type' => $ref_type,
      'hash' => $ref_hash,
      'repositoryPHID' => $repository_phid,
      'positions' => array(),
    );
  }

  // NOTE: When this migration runs, the table will have "commitIdentifier" and
  // "isClosed" fields. Later, it won't. Since they'll be removed, we can't
  // rely on being able to access them via the object. Instead, run a separate
  // raw query to read them.

  $row = queryfx_one(
    $conn,
    'SELECT commitIdentifier, isClosed FROM %T WHERE id = %d',
    $ref->getTableName(),
    $ref->getID());

  $map[$ref_key]['positions'][] = array(
    'identifier' => $row['commitIdentifier'],
    'isClosed' => (int)$row['isClosed'],
  );
}

// Now, write all the position rows.
$position_table = new PhabricatorRepositoryRefPosition();
foreach ($map as $ref_key => $spec) {
  $id = $spec['id'];
  foreach ($spec['positions'] as $position) {
    queryfx(
      $conn,
      'INSERT IGNORE INTO %T (cursorID, commitIdentifier, isClosed)
        VALUES (%d, %s, %d)',
      $position_table->getTableName(),
      $id,
      $position['identifier'],
      $position['isClosed']);
  }
}

// Finally, delete all the redundant RefCursor rows (rows with the same name)
// so we can add proper unique keys in the next migration.
foreach ($map as $ref_key => $spec) {
  queryfx(
    $conn,
    'DELETE FROM %T WHERE refType = %s
      AND refNameHash = %s
      AND repositoryPHID = %s
      AND id != %d',
    $table->getTableName(),
    $spec['type'],
    $spec['hash'],
    $spec['repositoryPHID'],
    $spec['id']);
}

Migrate RefCursor data to RefPosition table

Summary:
Ref T11823. This populates the new RefPosition table based on the existing RefCursor table, and deletes now-duplicate rows in the RefCursor table so the next change can add a unique key.

This change is not standalone, and there need to be separate code updates. I have a rough version of that written, but this migration needs to happen first to test it.

I'll hold this whole series of changes until after the release cut and until the code is updated.

Test Plan: Ran migration, spot-checked database tables. Saw redundant rows remove and correct-looking rows populated into the new RefPosition table.

Reviewers: amckinley

Reviewed By: amckinley

Maniphest Tasks: T11823

Differential Revision: https://secure.phabricator.com/D18612


<?php
namespace EngineWorks\DBAL\Traits;

trait MethodSqlConcatenate
{
    public function sqlConcatenate(...$strings)
    {
        if (! count($strings)) {
            return $this->sqlQuote('');
        }
        return 'CONCAT(' . implode(', ', $strings) . ')';
    }
}

Create trait for sqlConcatenate using CONCAT function


<?php
/**
 * Created by PhpStorm.
 * User: stefan
 * Date: 1/16/17
 * Time: 11:39 PM
 */

namespace particleflux\MaxCube\tests\parser;

use particleflux\MaxCube\messages\Message;
use particleflux\MaxCube\messages\MessageH;
use particleflux\MaxCube\messages\MessageL;
use particleflux\MaxCube\tests\TestCase;

class MessageTest extends TestCase
{
    public function testParse()
    {
        $message = Message::instantiate('');
        $this->assertNull($message);
        $message = Message::instantiate('asdf');
        $this->assertNull($message);
        $message = Message::instantiate("\x0a\x0d");
        $this->assertNull($message);
        $message = Message::instantiate('X:CxUK4gkSGWQ9AK8A');
        $this->assertNull($message);

        $message = Message::instantiate('H:KEQ0643784,09e4f5,0113,00000000,2bb2a0f3,00,32,11010b,143a,03,0000');
        $this->assertNotNull($message);
        $this->assertInstanceOf(MessageH::class, $message);

        $message = Message::instantiate('L:CxUK4gkSGWQ9AK8A');
        $this->assertNotNull($message);
        $this->assertInstanceOf(MessageL::class, $message);

    }
}

Test for Message base class

Test for Message base class


<?php
/**
 * @file
 */

namespace CultuurNet\UDB3\UiTID;

use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerAwareTrait;
use Psr\Log\NullLogger;
use ValueObjects\String\String;
use ValueObjects\Web\EmailAddress;

class InMemoryCacheDecoratedUsers implements UsersInterface, LoggerAwareInterface
{
    use LoggerAwareTrait;

    /**
     * @var UsersInterface
     */
    private $wrapped;

    /**
     * @var String[]
     */
    private $nickMap;

    /**
     * @var String[]
     */
    private $mailMap;

    /**
     * @param UsersInterface $wrapped
     */
    public function __construct(UsersInterface $wrapped)
    {
        $this->wrapped = $wrapped;
        $this->logger = new NullLogger();
    }

    /**
     * @inheritdoc
     */
    public function byEmail(EmailAddress $email)
    {
        $key = $email->toNative();
        if (!isset($this->mailMap[$key])) {
            $this->mailMap[$key] = $this->wrapped->byEmail($email);
        }
        else {
            $this->logger->info('found user id of ' . $email->toNative() . ' in cache');
        }

        return $this->mailMap[$key];
    }

    /**
     * @inheritdoc
     */
    public function byNick(String $nick)
    {
        $key = $nick->toNative();
        if (!isset($this->nickMap[$key])) {
            $this->nickMap[$key] = $this->wrapped->byNick($nick);
        }
        else {
            $this->logger->info('found user id of ' . $nick->toNative() . ' in cache');
        }

        return $this->nickMap[$key];
    }

}

III-447: Add in-memory cache decorated UsersInterface implementation


<?php

declare(strict_types=1);

namespace Tests\Feature;

use Illuminate\Foundation\Testing\RefreshDatabase;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;
use Tests\TestCase;

class PermissionsAndRolesTest extends TestCase
{
    /**
     * Ensure that the admin role has all permissions.
     */
    public function testAdminRoleHasAllPermissions(): void
    {
        $permissions = Role::where('name', 'admin')->first()->permissions;
        $allPermissions = Permission::all();
        $this->assertCount(0, $permissions->diff($allPermissions));
        $this->assertCount(0, $allPermissions->diff($permissions));
    }

    /**
     * Ensure the member and non-member roles have the same permissions.
     */
    public function testMemberAndNonMemberAreSame(): void
    {
        $nonmember = Role::where('name', 'non-member')->first()->permissions;
        $member = Role::where('name', 'member')->first()->permissions;
        $this->assertCount(0, $nonmember->diff($member));
        $this->assertCount(0, $member->diff($nonmember));
    }
}

Add permissions and roles test

Add permissions and roles test


<?php

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

$app = new Silex\Application();

$app->register(new Predis\Silex\ClientServiceProvider(), array(
    'predis.parameters' => [
        'tcp://127.0.0.1:6380?alias=node-01',
        'tcp://127.0.0.1:6381?alias=node-02',
        'tcp://127.0.0.1:6382?alias=node-03',
    ],
    'predis.options'    => array(
        'profile' => '3.0',
        'prefix'  => 'silex:',
    ),
));

/** routes **/
$app->get('/', function () use ($app) {
    $cmdINFO = $app['predis']->createCommand('INFO', array('server'));
    $nodes = $app['predis']->getConnection()
                           ->executeCommandOnNodes($cmdINFO);

    return var_export($nodes, true);
});

/** run application **/
$app->run();

Add example of a configuration for client-side sharding.

[ci skip]


<?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\Extractors\CorporateShareExtractorWrapper;

/**
 * This is the abstract corporate share extractor test class.
 *
 * @author Fábio Santos <ffsantos92@gmail.com>
 */
abstract class AbstractCorporateShareExtractorTest extends AbstractTestCase
{
    protected $extractor;

    public function __construct()
    {
        $this->extractor = new CorporateShareExtractorWrapper();
    }
}

Add abstract corporate share extractor test


<?php

/**
 * The world's most used third-party email providers.
 *
 */
return array(
    'gmail.com'           => 'http://mail.google.com',
    'me.com'              => 'https://www.icloud.com/#mail',
    'icloud.com'          => 'https://www.icloud.com/#mail',
    'hotmail.com'         => 'http://www.hotmail.com',
    'outlook.com'         => 'http://www.outlook.com',
    'yahoo.com'           => 'http://mail.yahoo.com',
    'aol.com'             => 'http://webmail.aol.com',
    'aim.com'             => 'http://webmail.aol.com/?offerId=aimmail-en-us',
    'msn.com'             => 'https://accountservices.msn.com/',
    'mail.com'            => 'http://www.mail.com/int/',
    '126.com'             => 'http://www.126.com',
    '163.com'             => 'http://www.163.com',
    'sina.com'            => 'http://mail.sina.com',
    'vip.163.com'         => 'http://vip.163.com',
    'yeah.net'            => 'http://www.yeah.net',
    'qq.com'              => 'http://mail.qq.com/cgi-bin/loginpage',
    'tom.com'             => 'http://mail.tom.com',
    'sohu.com'            => 'http://mail.sohu.com',
    '139.com'             => 'http://mail.139.com',
    'hexun.com'           => 'http://mail.hexun.com',
    'eyou.com'            => 'http://www.eyou.com',
    '21cn.com'            => 'http://mail.21cn.com'
);

Add email provider mappings file.

Add email provider mappings file.


{{--
    Copyright 2015-2017 ppy Pty. Ltd.

    This file is part of osu!web. osu!web is distributed with the hope of
    attracting more community contributions to the core ecosystem of osu!.

    osu!web is free software: you can redistribute it and/or modify
    it under the terms of the Affero GNU General Public License version 3
    as published by the Free Software Foundation.

    osu!web is distributed WITHOUT ANY WARRANTY; without even the implied
    warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
    See the GNU Affero General Public License for more details.

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

        Terms of Service
        Copyright (DMCA)
        Server Status
        @osustatus

ppy powered 2007-{{ date('Y') }}

{{--
    Copyright 2015-2017 ppy Pty. Ltd.

    This file is part of osu!web. osu!web is distributed with the hope of
    attracting more community contributions to the core ecosystem of osu!.

    osu!web is free software: you can redistribute it and/or modify
    it under the terms of the Affero GNU General Public License version 3
    as published by the Free Software Foundation.

    osu!web is distributed WITHOUT ANY WARRANTY; without even the implied
    warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
    See the GNU Affero General Public License for more details.

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

         'Legal/TOS']) }}" target="_blank">Terms of Service
         'Legal/Copyright'])" target="_blank">Copyright (DMCA)
        Server Status
        @osustatus

ppy powered 2007-{{ date('Y') }}

Add routes for TOS and Copyright

Add routes for TOS and Copyright


<?php

namespace Illuminate\Tests\Integration\Validation;

use Illuminate\Http\Request;
use Orchestra\Testbench\TestCase;
use Illuminate\Validation\ValidationException;

/**
 * @group integration
 */
class RequestValidationTest extends TestCase
{
    public function testValidateMacro()
    {
        $request = Request::create('/', 'GET', ['name' => 'Taylor']);

        $validated = $request->validate(['name' => 'string']);

        $this->assertSame(['name' => 'Taylor'], $validated);
    }

    public function testValidateMacroWhenItFails()
    {
        $this->expectException(ValidationException::class);

        $request = Request::create('/', 'GET', ['name' => null]);

        $request->validate(['name' => 'string']);
    }
}

Add Request::validate() macro test coverage

$request->validate() was never called in the test suite.


<?php

declare(strict_types=1);

/*
 * This file is part of PHP CS Fixer.
 * (c) Fabien Potencier <fabien@symfony.com>
 *     Dariusz Rumiński <dariusz.ruminski@gmail.com>
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

$header = <<<'EOF'
This file is part of PHP CS Fixer.
(c) Fabien Potencier <fabien@symfony.com>
    Dariusz Rumiński <dariusz.ruminski@gmail.com>
This source file is subject to the MIT license that is bundled
with this source code in the file LICENSE.
EOF;

$finder = PhpCsFixer\Finder::create()
    ->exclude('tests/Fixtures')
    ->in(__DIR__.'/src')
    ->append([
        __DIR__.'/tests',
        // __DIR__.'/php-cs-fixer', disabled, as we want to be able to run bootstrap file even on lower PHP version, to show nice message
        __FILE__,
    ])
;

$config = new PhpCsFixer\Config();
$config
    ->setRiskyAllowed(true)
    ->setRules([
        '@PHP71Migration:risky' => true,
        '@PHPUnit75Migration:risky' => true,
        '@PhpCsFixer' => true,
        '@PhpCsFixer:risky' => true,
        'general_phpdoc_annotation_remove' => ['annotations' => ['expectedDeprecation']], // one should use PHPUnit built-in method instead
        'header_comment' => ['header' => $header],
    ])
    ->setFinder($finder)
;

// special handling of fabbot.io service if it's using too old PHP CS Fixer version
if (false !== getenv('FABBOT_IO')) {
    try {
        PhpCsFixer\FixerFactory::create()
            ->registerBuiltInFixers()
            ->registerCustomFixers($config->getCustomFixers())
            ->useRuleSet(new PhpCsFixer\RuleSet($config->getRules()))
        ;
    } catch (PhpCsFixer\ConfigurationException\InvalidConfigurationException $e) {
        $config->setRules([]);
    } catch (UnexpectedValueException $e) {
        $config->setRules([]);
    } catch (InvalidArgumentException $e) {
        $config->setRules([]);
    }
}

return $config;

Add php cs fixer rules

Add php cs fixer rules


<?php namespace Kshabazz\Tests\Interception;
/**
 * Test for use with Guzzle HTTP client.
 */
use GuzzleHttp\Client;
use GuzzleHttp\Ring\Client\StreamHandler;
use Kshabazz\Interception\StreamWrappers\Http;
/**
 * Class GuzzleTest
 *
 * @package Kshabazz\Tests\Interception
 */
class HttpClientTest extends \PHPUnit_Framework_TestCase
{
	static public function setUpBeforeClass()
	{
		\stream_wrapper_unregister( 'http' );
		\stream_register_wrapper(
			'http',
			'\\Kshabazz\\Interception\\StreamWrappers\\Http',
			\STREAM_IS_URL
		);
		Http::setSaveDir( FIXTURES_PATH );
	}

	static public function tearDownAfterClass()
	{
		// Restore the built-in HTTP wrapper for other unit tests.
		\stream_wrapper_restore( 'http' );
		// Clean up all ignore files.
		$removeFiles = \glob( FIXTURES_PATH . DIRECTORY_SEPARATOR . 'ignore*' );
		\array_map( 'unlink', $removeFiles );
	}

	public function test_intercepting_ringphp_stream_handle_request()
	{
		$filename = 'ignore-ringphp-test';
		Http::setSaveFilename( $filename );
		$request = array(
			'http_method' => 'GET',
			'scheme' => 'http',
			'uri' => '/',
			'version' => '1.0',
			'headers' => array( 'Host' => array('www.example.com') ),
			'client' => array(
				// Turn SSL off so no HTTPS, on by default.
				'verify' => FALSE,
				'version' => '1.0'
			)
		);
		// Make the request.
		$streamHandler = new StreamHandler();
		$streamHandler( $request );
		// Verify the request was recorded.
		$requestIntercepted = \file_exists( FIXTURES_PATH . DIRECTORY_SEPARATOR . $filename .'.rsd' );
		$this->assertTrue( $requestIntercepted );

		return $streamHandler;
	}

	/**
	 * @depends test_intercepting_ringphp_stream_handle_request
	 */
	public function test_intercepting_guzzle_client_request( $streamHandler )
	{
		$filename = 'ignore-guzzle-test';
		Http::setSaveFilename( $filename );
		// Force Guzzle to use a PHP stream instead of cURL.
		$httpClient = new Client(
			array(
				'handler' => $streamHandler
			)
		);
		$response = $httpClient->get(
			'http://www.example.com/',
			array(
				'version' => '1.0',
				'verify' => FALSE,
			)
		);

		$requestIntercepted = \file_exists( FIXTURES_PATH . DIRECTORY_SEPARATOR . $filename . '.rsd' );
		$this->assertTrue( $requestIntercepted );
	}
}

Add unit test for RingPHP and Guzzle.

Add unit test for RingPHP and Guzzle.


<?php
if (class_exists('PHPUnit_Runner_Version')) {
    if (version_compare(\PHPUnit_Runner_Version::id(), '5.7', '<')) {
        trigger_error(sprintf('Your PHPUnit Version must be at least 5.7.0 to use CakePHP Testsuite, found %s', \PHPUnit_Runner_Version::id()), E_USER_ERROR);
    }

    class_alias('PHPUnit_Framework_Test', 'PHPUnit\Framework\Test');
    class_alias('PHPUnit_Framework_AssertionFailedError', 'PHPUnit\Framework\AssertionFailedError');
    class_alias('PHPUnit_Framework_TestSuite', 'PHPUnit\Framework\TestSuite');
}

<?php
if (class_exists('PHPUnit_Runner_Version')) {
    if (version_compare(\PHPUnit_Runner_Version::id(), '5.7', '<')) {
        trigger_error(sprintf('Your PHPUnit Version must be at least 5.7.0 to use CakePHP Testsuite, found %s', \PHPUnit_Runner_Version::id()), E_USER_ERROR);
    }

    class_alias('PHPUnit_Framework_Test', 'PHPUnit\Framework\Test');
    class_alias('PHPUnit_Framework_AssertionFailedError', 'PHPUnit\Framework\AssertionFailedError');
    class_alias('PHPUnit_Framework_TestSuite', 'PHPUnit\Framework\TestSuite');
    class_alias('PHPUnit_Framework_Error_Deprecated', 'PHPUnit\Framework\Error\Deprecated');
}

Add an alias for Deprecated to be compatible with PHP5.6


<?php
/**
 * This file is part of the Clastic package.
 *
 * (c) Dries De Peuter <dries@nousefreak.be>
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Clastic\FrontBundle\EventListener;

use Clastic\CoreBundle\Module\ModuleManager;
use Clastic\FrontBundle\Event\FrontNodeEvent;
use Clastic\NodeBundle\Module\NodeModuleInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * NodeListener
 *
 * @author Dries De Peuter <dries@nousefreak.be>
 */
class NodeDetailTemplateListener implements EventSubscriberInterface
{
    /**
     * @var ModuleManager
     */
    private $moduleManager;

    /**
     * @param ModuleManager $manager
     */
    public function __construct(ModuleManager $manager)
    {
        $this->moduleManager = $manager;
    }

    /**
     * {@inheritdoc}
     */
    public static function getSubscribedEvents()
    {
        return array(
            'clastic.node.front' => 'setTemplate',
        );
    }

    /**
     * @param FrontNodeEvent $event
     */
    public function setTemplate(FrontNodeEvent $event)
    {
        $module = $this->moduleManager->getModule($event->getNode()->getType());
        if (!$module instanceof NodeModuleInterface) {
            return;
        }

        $template = $module->getDetailTemplate();
        if (!$template) {
            return;
        }

        $event->setTemplate($template);
    }
}

Insert front detail template for Nodes.

[Front] Insert front detail template for Nodes.


<?php

use Codeception\Util\Fixtures;
use Codeception\Util\Locator;

/**
 * Backend 'author' tests
 *
 * @author Gawain Lynch <gawain.lynch@gmail.com>
 */
class BackendAuthorCest
{
    /** @var array */
    protected $user;
    /** @var array */
    protected $tokenNames;

    /** @var array */
    private $cookies = [];

    /**
     * @param \AcceptanceTester $I
     */
    public function _before(\AcceptanceTester $I)
    {
        $this->user = Fixtures::get('users');
        $this->tokenNames = Fixtures::get('tokenNames');
    }

    /**
     * @param \AcceptanceTester $I
     */
    public function _after(\AcceptanceTester $I)
    {
    }

    /**
     * Login as the author user.
     *
     * @param \AcceptanceTester $I
     */
    public function loginEditorTest(\AcceptanceTester $I)
    {
        $I->wantTo("Login as 'author' user");

        $I->loginAs($this->user['author']);
        $this->cookies[$this->tokenNames['authtoken']] = $I->grabCookie($this->tokenNames['authtoken']);
        $this->cookies[$this->tokenNames['session']] = $I->grabCookie($this->tokenNames['session']);

        $I->see('Dashboard');
    }

    /**
     * Create an 'About' page record.
     *
     * @param \AcceptanceTester $I
     */
    public function editAboutPageTest(\AcceptanceTester $I)
    {
        $I->wantTo("Edit the 'About' page as the 'author' user");

        // Set up the browser
        $I->setCookie($this->tokenNames['authtoken'], $this->cookies[$this->tokenNames['authtoken']]);
        $I->setCookie($this->tokenNames['session'], $this->cookies[$this->tokenNames['session']]);
        $I->amOnPage('/bolt');

        $I->see('Edit', 'a');
        $I->click('Edit', 'a');

        $I->click('Save Page', '#savecontinuebutton');

        $I->see('The new Page has been saved.');
    }
}

[Tests] Check that author user can edit a 'page' record


<?php

namespace Begin\Exceptions;

use Exception;

class ValidationException extends Exception
{
    /**
     * The underlying errors instance.
     *
     * @var \Illuminate\Support\MessageBag
     */
    protected $errors;

    /**
     * Create a new ValidationException exception instance.
     *
     * @param  \Illuminate\Support\MessageBag  $errors
     * @return void
     */
    public function __construct($errors)
    {
        $this->errors = $errors;
    }

    /**
     * Get the request validation errors
     *
     * @return @var \Illuminate\Support\MessageBag
     */
    public function getErrors()
    {
        return $this->errors;
    }
}

Add the ability to use eleoquent in the application


<?php
/* (c) Anton Medvedev <anton@elfet.ru>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

require_once __DIR__ . '/common.php';

// Laravel shared dirs
set('shared_dirs', [
    'storage/app',
    'storage/framework/cache',
    'storage/framework/sessions',
    'storage/framework/views',
    'storage/logs',
]);

// Laravel 5 shared file
set('shared_files', ['.env']);

// Laravel writable dirs
set('writable_dirs', ['bootstrap/cache', 'storage']);

/**
 * Main task
 */
task('deploy', [
    'deploy:prepare',
    'deploy:release',
    'deploy:update_code',
    'deploy:vendors',
    'deploy:shared',
    'deploy:symlink',
    'cleanup',
])->desc('Deploy your project');

after('deploy', 'success');

/**
 * Helper tasks
 */
task('up', function () {
    $output = run('php {{deploy_path}}/current/artisan up');
    writeln('<info>'.$output.'</info>');
})->desc('Disable maintenance mode');

task('down', function () {
    $output = run('php {{deploy_path}}/current/artisan down');
    writeln('<error>'.$output.'</error>');
})->desc('Enable maintenance mode');

<?php
/* (c) Anton Medvedev <anton@elfet.ru>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

require_once __DIR__ . '/common.php';
// This recipe support Laravel 5.1+, with orther version, please see document https://github.com/deployphp/docs

// Laravel shared dirs
set('shared_dirs', [
    'storage/app',
    'storage/framework/cache',
    'storage/framework/sessions',
    'storage/framework/views',
    'storage/logs',
]);

// Laravel 5 shared file
set('shared_files', ['.env']);

// Laravel writable dirs
set('writable_dirs', ['bootstrap/cache', 'storage']);

/**
 * Main task
 */
task('deploy', [
    'deploy:prepare',
    'deploy:release',
    'deploy:update_code',
    'deploy:vendors',
    'deploy:shared',
    'deploy:symlink',
    'cleanup',
])->desc('Deploy your project');

after('deploy', 'success');

/**
 * Helper tasks
 */
task('deploy:up', function () {
    $output = run('php {{deploy_path}}/current/artisan up');
    writeln('<info>'.$output.'</info>');
})->desc('Disable maintenance mode');

task('deploy:down', function () {
    $output = run('php {{deploy_path}}/current/artisan down');
    writeln('<error>'.$output.'</error>');
})->desc('Enable maintenance mode');

Rename task 'up' and 'down' to 'deploy:up' and 'deploy:down'


<?php

/*
 * This file is part of the Active Collab Payments project.
 *
 * (c) A51 doo <info@activecollab.com>. All rights reserved.
 */

declare(strict_types=1);

namespace ActiveCollab\Payments\OrderItem;

interface OrderItemParentInterface
{
}

Add order item payment interface

Add order item payment interface


<?php

namespace Tests\Regis\Infrastructure\Github;

use Github\Api;
use Github\Client as VendorClient;
use Psr\Log\LoggerInterface;

use Regis\Domain\Entity\Github\Repository;
use Regis\Domain\Entity\User;
use Regis\Domain\Model\Github\PullRequest;
use Regis\Domain\Model\Github\ReviewComment;
use Regis\Infrastructure\Github\ClientFactory;

class ClientFactoryTest extends \PHPUnit_Framework_TestCase
{
    private $vendorClient;
    private $logger;
    /** @var ClientFactory */
    private $clientFactory;

    public function setUp()
    {
        $this->vendorClient = $this->getMockBuilder(VendorClient::class)->disableOriginalConstructor()->getMock();
        $this->logger = $this->getMockBuilder(LoggerInterface::class)->getMock();

        $this->clientFactory = new ClientFactory($this->vendorClient, $this->logger);
    }

    public function testCreateForRepository()
    {
        $repository = $this->getMockBuilder(Repository::class)->disableOriginalConstructor()->getMock();
        $owner = $this->getMockBuilder(User::class)->disableOriginalConstructor()->getMock();

        $repository->expects($this->once())
            ->method('getOwner')
            ->will($this->returnValue($owner));

        $owner->expects($this->once())
            ->method('getGithubAccessToken')
            ->will($this->returnValue('access token'));

        $this->clientFactory->createForRepository($repository);
    }
}

Add a few tests for the Github client factory


<?php

namespace Doctrine\Tests\ORM\Functional\Ticket;

use Doctrine\Tests\OrmFunctionalTestCase;
use Doctrine\Tests\Models\ECommerce\ECommerceProduct;
use Doctrine\Tests\Models\ECommerce\ECommerceCategory;
use Doctrine\Common\Collections\Criteria;

final class GH6740Test extends OrmFunctionalTestCase
{
    /**
     * @var int
     */
    private $productId;

    /**
     * @var int
     */
    private $firstCategoryId;

    /**
     * @var int
     */
    private $secondCategoryId;

    public function setUp() : void
    {
        $this->useModelSet('ecommerce');

        parent::setUp();

        $product = new ECommerceProduct();
        $product->setName('First Product');

        $firstCategory  = new ECommerceCategory();
        $secondCategory = new ECommerceCategory();

        $firstCategory->setName('Business');
        $secondCategory->setName('Home');

        $product->addCategory($firstCategory);
        $product->addCategory($secondCategory);

        $this->_em->persist($product);
        $this->_em->flush();
        $this->_em->clear();

        $this->productId        = $product->getId();
        $this->firstCategoryId  = $firstCategory->getId();
        $this->secondCategoryId = $secondCategory->getId();
    }

    /**
     * @group 6740
     */
    public function testCollectionFilteringLteOperator() : void
    {
        $product  = $this->_em->find(ECommerceProduct::class, $this->productId);
        $criteria = Criteria::create()->where(Criteria::expr()->lte('id', $this->secondCategoryId));

        self::assertCount(2, $product->getCategories()->matching($criteria));
    }

    /**
     * @group 6740
     */
    public function testCollectionFilteringLtOperator() : void
    {
        $product  = $this->_em->find(ECommerceProduct::class, $this->productId);
        $criteria = Criteria::create()->where(Criteria::expr()->lt('id', $this->secondCategoryId));

        self::assertCount(1, $product->getCategories()->matching($criteria));
    }

    /**
     * @group 6740
     */
    public function testCollectionFilteringGteOperator() : void
    {
        $product  = $this->_em->find(ECommerceProduct::class, $this->productId);
        $criteria = Criteria::create()->where(Criteria::expr()->gte('id', $this->firstCategoryId));

        self::assertCount(2, $product->getCategories()->matching($criteria));
    }

    /**
     * @group 6740
     */
    public function testCollectionFilteringGtOperator() : void
    {
        $product  = $this->_em->find(ECommerceProduct::class, $this->productId);
        $criteria = Criteria::create()->where(Criteria::expr()->gt('id', $this->firstCategoryId));

        self::assertCount(1, $product->getCategories()->matching($criteria));
    }

    /**
     * @group 6740
     */
    public function testCollectionFilteringEqualsOperator() : void
    {
        $product  = $this->_em->find(ECommerceProduct::class, $this->productId);
        $criteria = Criteria::create()->where(Criteria::expr()->eq('id', $this->firstCategoryId));

        self::assertCount(1, $product->getCategories()->matching($criteria));
    }
}

Add failing test for DCOM-288

Add failing test for DCOM-288

Reported on: https://github.com/doctrine/common/issues/600


<?php

namespace Avalanche\Bundle\ImagineBundle\Imagine\Filter;

use Avalanche\Bundle\ImagineBundle\Imagine\Filter\Loader\LoaderInterface;

use Imagine\Exception\InvalidArgumentException;
use Imagine\Filter\FilterInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

class FilterManager
{
    private $filters;
    private $loaders;
    private $services;

    public function __construct( array $filters = array())
    {
        $this->filters   = $filters;
        $this->loaders   = array();
        $this->services  = array();
    }

    public function addLoader($name, LoaderInterface $loader)
    {
        $this->loaders[$name] = $loader;
    }

    public function get($filter)
    {
        if (!isset($this->filters[$filter])) {
            throw new InvalidArgumentException(sprintf(
                'Could not find image filter "%s"', $filter
            ));
        }

        $options = $this->filters[$filter];

        if (!isset($options['type'])) {
            throw new InvalidArgumentException(sprintf(
                'Filter type for "%s" image filter must be specified', $filter
            ));
        }

        if (!isset($this->loaders[$options['type']])) {
            throw new InvalidArgumentException(sprintf(
                'Could not find loader for "%s" filter type', $options['type']
            ));
        }

        if (!isset($options['options'])) {
            throw new InvalidArgumentException(sprintf(
                'Options for filter type "%s" must be specified', $filter
            ));
        }

        return $this->loaders[$options['type']]->load($options['options']);
    }
}

<?php

namespace Avalanche\Bundle\ImagineBundle\Imagine\Filter;

use Avalanche\Bundle\ImagineBundle\Imagine\Filter\Loader\LoaderInterface;

use Imagine\Exception\InvalidArgumentException;
use Imagine\Filter\FilterInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

class FilterManager
{
    private $filters;
    private $loaders;
    private $services;

    public function __construct(array $filters = array())
    {
        $this->filters   = $filters;
        $this->loaders   = array();
        $this->services  = array();
    }

    public function addLoader($name, LoaderInterface $loader)
    {
        $this->loaders[$name] = $loader;
    }

    public function get($filter)
    {
        if (!isset($this->filters[$filter])) {
            throw new InvalidArgumentException(sprintf(
                'Could not find image filter "%s"', $filter
            ));
        }

        $options = $this->filters[$filter];

        if (!isset($options['type'])) {
            throw new InvalidArgumentException(sprintf(
                'Filter type for "%s" image filter must be specified', $filter
            ));
        }

        if (!isset($this->loaders[$options['type']])) {
            throw new InvalidArgumentException(sprintf(
                'Could not find loader for "%s" filter type', $options['type']
            ));
        }

        if (!isset($options['options'])) {
            throw new InvalidArgumentException(sprintf(
                'Options for filter type "%s" must be specified', $filter
            ));
        }

        return $this->loaders[$options['type']]->load($options['options']);
    }
}

Remove leading whitespace in constructor arg


<?php
/**
 * PHP version 7.1
 *
 * This source file is subject to the license that is bundled with this package in the file LICENSE.
 */
namespace App\Form\GoogleMap;

use Mandragora\FormFactory;
use PHPUnit_Framework_TestCase as TestCase;

class DetailTest extends TestCase
{
    /** @test */
    function it_can_be_created()
    {
        $this->assertInstanceOf(Detail::class, $this->googleForm);
        $this->assertCount(5, $this->googleForm->getElements());
    }

    /** @test */
    function it_initialize_the_address_id_value()
    {
        $addressId = 4;

        $this->googleForm->setAddressId($addressId);

        $this->assertEquals($addressId, $this->googleForm->getElement('addressId')->getValue());
    }

    /** @test */
    function it_removes_the_version_element_before_adding_a_new_map()
    {
        $this->googleForm->prepareForCreating();

        $elements = $this->googleForm->getElements();
        $this->assertCount(4, $elements);
        $this->assertArrayNotHasKey('version', $elements);
    }

    /** @before */
    function createForm()
    {
        $this->googleForm = (new FormFactory(true))->create("Detail", "GoogleMap");
    }

    /** @var Detail */
    private $googleForm;
}

Add tests for google map form.

Add tests for google map form.


<?php

/*
 * This file is part of the Sylius package.
 *
 * (c) Paweł Jędrzejewski
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Sylius\Component\Cart;

final class SyliusCartEvents
{
    const CART_CHANGE            = 'sylius.cart_change';
    const CART_INITIALIZE        = 'sylius.cart.initialize';
    const CART_ABANDON           = 'sylius.cart.abandon';

    const CART_CLEAR_INITIALIZE  = 'sylius.cart_clear.initialize';
    const CART_CLEAR_COMPLETED   = 'sylius.cart_clear.completed';

    const CART_SAVE_INITIALIZE   = 'sylius.cart_save.initialize';
    const CART_SAVE_COMPLETED    = 'sylius.cart_save.completed';

    const ITEM_ADD_INITIALIZE    = 'sylius.cart_item.add.initialize';
    const ITEM_ADD_COMPLETED     = 'sylius.cart_item.add.completed';
    const ITEM_ADD_ERROR         = 'sylius.cart_item.add.error';

    const ITEM_REMOVE_INITIALIZE = 'sylius.cart_item.remove.initialize';
    const ITEM_REMOVE_COMPLETED  = 'sylius.cart_item.remove.completed';
    const ITEM_REMOVE_ERROR      = 'sylius.cart_item.remove.error';
}

Move events definitions into proper components


<?php
namespace Wizard;

use Zend\Form\Form;

class AbstractStepTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var AbstractStep
     */
    protected $step;

    public function setUp()
    {
        $this->step = $this->getMockForAbstractClass('Wizard\AbstractStep');
    }

    public function testSetAndGetTitle()
    {
        $this->assertNull($this->step->getTitle());

        $this->step->setTitle('foo');
        $this->assertEquals('foo', $this->step->getTitle());
    }

    public function testSetAndGetForm()
    {
        $this->assertNull($this->step->getForm());

        $this->step->setForm(new Form);
        $this->assertInstanceOf('Zend\Form\Form', $this->step->getForm());
    }
}

Add unit tests to step

Add unit tests to step


<?php

namespace Tystr\RedisOrm\Metadata;

use Tystr\RedisOrm\DataTransformer\DataTypes;
use Tystr\RedisOrm\Exception\InvalidArgumentException;

/**
 * @author Tyler Stroud <tyler@tylerstroud.com>
 */
class MetadataTest extends \PHPUnit_Framework_TestCase
{
    public function testAddPropertyMappingWithInvalidMappingThrowsException()
    {
        $metadata = new Metadata();
        $this->setExpectedException('InvalidArgumentException');
        $metadata->addPropertyMapping('someProperty', null);
    }

    public function testAddPropertyMappingWithInvalidDataTypeThrowsException()
    {
        $metadata = new Metadata();
        $this->setExpectedException('InvalidArgumentException');
        $metadata->addPropertyMapping('someProperty', array('name' => 'some_property', 'type' => 'INVALID TYPE'));
    }

    public function testAddPropertyMapping()
    {
        $metadata = new Metadata();
        $mapping = array('type' => 'string');
        $metadata->addPropertyMapping('property', $mapping);

        $mapping['name'] = 'property';
        assertEquals($metadata->getPropertyMapping('property'), $mapping);
    }

    public function testAddPropertyMappingWithName()
    {
        $metadata = new Metadata();
        $mapping = array('name' => 'some_property', 'type' => 'string');
        $metadata->addPropertyMapping('someProperty', $mapping);

        assertEquals($metadata->getPropertyMapping('someProperty'), $mapping);
    }

    public function testGetMappingForMappedName()
    {
        $metadata = new Metadata();
        $mapping = array('name' => 'some_property', 'type' => 'string');
        $metadata->addPropertyMapping('someProperty', $mapping);

        $mapping['propertyName'] = 'someProperty';
        assertEquals($mapping, $metadata->getMappingForMappedName('some_property'));
    }

    public function testSetState()
    {
        $data = array(
            'id' => 1,
            'prefix' => 'some_',
            'indexes' => array('index1', 'index2'),
            'sortedIndexes' => array('sortedIndex1', 'sortedIndex2'),
            'propertyMappings' => array(
                array('name' => 'property', 'type' => 'string')
            )
        );

        $metadata = Metadata::__set_state($data);
        assertInstanceOf('Tystr\RedisOrm\Metadata\Metadata', $metadata);
        assertEquals($data['id'], $metadata->getId());
        assertEquals($data['prefix'], $metadata->getPrefix());
        assertEquals($data['indexes'], $metadata->getIndexes());
        assertEquals($data['sortedIndexes'], $metadata->getSortedIndexes());
        assertEquals($data['propertyMappings'], $metadata->getPropertyMappings());
    }
}

Add some tests for Metadata

Add some tests for Metadata


<?php

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

class MakeBucketAndDetailsColumnsNullable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('posts', function (Blueprint $table) {
            $table->string('action_bucket')->nullable()->change();
            $table->text('details')->nullable()->change();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('posts', function (Blueprint $table) {
            $table->string('action_bucket')->nullable(false)->change();
            $table->text('details')->nullable(false)->change();
        });
    }
}

Add migrations to make new post columns nullable


<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use SensioLabs\Security\SecurityChecker;

class SecurityCheck extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'security:check';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Run the SensioLab’s Security Check tool';

    /**
     * The Security Checker intergation service.
     *
     * @var SecurityChecker
     */
    protected $securityChecker;

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

        $this->securityChecker = $securityChecker;
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        return $this->securityChecker->check(base_path() . '/composer.lock');
    }
}

Add the artisan command to check for security vulns


<?php

/*
 * This file is part of the ONGR package.
 *
 * (c) NFQ Technologies UAB <info@nfq.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace ONGR\ApiBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * This controller works with document variants.
 */
class VariantController extends AbstractRestController implements RestControllerInterface
{
    /**
     * @inheritDoc
     */
    public function postAction(Request $request, $id = null)
    {

    }

    /**
     * @inheritDoc
     */
    public function getAction(Request $request, $id, $variantId = null)
    {
        $crud = $this->getCrud();

        try {
            $document = $crud->read($this->getRequestRepository($request), $id);
        } catch (\Exception $e) {
            return $this->renderError($request, $e->getMessage(), Response::HTTP_BAD_REQUEST);
        }

        if (!isset($document['variants'])) {
            return $this->renderError(
                $request,
                'Document does not support variants.',
                Response::HTTP_INTERNAL_SERVER_ERROR
            );
        }

        if ($variantId === null) {
            return $this->renderRest($request, $document['variants']);
        } else if (isset($document['variants'][$variantId])) {
            return $this->renderRest($request, $document['variants'][$variantId]);
        } else {
            return $this->renderError(
                $request,
                'Variant "' . $variantId . '" for object "' . $id . '" does not exist.',
                Response::HTTP_NOT_FOUND
            );
        }
    }

    /**
     * @inheritDoc
     */
    public function putAction(Request $request, $id)
    {
        // TODO: Implement putAction() method.
    }

    /**
     * @inheritDoc
     */
    public function deleteAction(Request $request, $id)
    {
        // TODO: Implement deleteAction() method.
    }
}

Throw an exception if document was not found in Crud service.


<?php
namespace Intercom;

use InvalidArgumentException;
use Guzzle\Common\Collection;
use Guzzle\Service\Client;
use Guzzle\Service\Description\ServiceDescription;

class IntercomBasicAuthClient extends Client
{
    /**
     * @todo: Remove hardcoded constant, discuss with platform how to obtain a service definition
     */
    const DESCRIPTION_FILE = 'src/intercom/Service/config/intercom.json';

    /**
     * Creates a Basic Auth Client with the supplied configuration options
     *
     * @param array $config
     * @return Client|IntercomBasicAuthClient
     */
    public static function factory($config = [])
    {
        $default = [];
        $required = ['app_id', 'api_key'];
        $config = Collection::fromConfig($config, $default, $required);

        $client = new self();

        // v3 Headers
        $client->setDefaultOption('headers', [
            'Content-Type' => 'application/json',
            'Accept' => 'application/vnd.intercom.3+json'
        ]);

        $client->setDefaultOption('auth', [
                $config->get('app_id'),
                $config->get('api_key'),
                'Basic'
        ]);

        $client->setDescription(static::getServiceDescriptionFromFile(self::DESCRIPTION_FILE));

        return $client;
    }

    /**
     * Loads the service description from the service description file
     *
     * @param string $description_file The service description file
     * @return ServiceDescription
     * @throws InvalidArgumentException If the description file doesn't exist or cannot be read
     */
    public function getServiceDescriptionFromFile($description_file) {
        if (!file_exists($description_file) || !is_readable($description_file)) {
            throw new InvalidArgumentException('Unable to read API definition schema');
        }

        return ServiceDescription::factory($description_file);
    }
}

Add an API client that uses Basic Auth & Service Descriptions


<?php
// Version: 1.0: Module.php
namespace ShinyBear\Services\Modules;

if (!defined('SMF')) {
	die('Hacking attempt...');
}

/**
 * @package ShinyBear
 * @since 1.0
 */
interface iModule
{
	public function __construct($field);

	function output();
}

abstract class Module implements iModule
{
	protected $fields;
	protected $err;

	/*
	 * Constructs the module.
	 *
	 * @param array $field
	 * @access public
	 * @return void
	 */
	public function __construct($fields = null)
	{
		$this->fields = $fields;
		$this->err = false;
	}

	/*
	 * Gets the error generated by the validation method.
	 *
	 * @access public
	 * @return mixed The error string or false for no error.
	 */
	function getError()
	{
		return $this->err;
	}

	function error($type = 'error', $error_type = 'general', $log_error = false, $echo = true)
	{
		global $txt;

		// All possible pre-defined types.
		$valid_types = array(
			'mod_not_installed' => $type == 'mod_not_installed' ? 1 : 0,
			'not_allowed' => $type == 'not_allowed' ? 1 : 0,
			'no_language' => $type == 'no_language' ? 1 : 0,
			'query_error' => $type == 'query_error' ? 1 : 0,
			'empty' => $type == 'empty' ? 1 : 0,
			'error' => $type == 'error' ? 1 : 0,
		);

		//sb_call_hook('echo $this->error', array(&$type));

		$error_string = !empty($valid_types[$type]) ? $txt['sb_module_' . $type] : $type;
		$error_html = $error_type == 'critical' ? array('
', '
') : array('', '');

		// Don't need this anymore!
		unset($valid_types);

		// Should it be logged?
		if ($log_error)
			log_error($error_string, $error_type);

		$this->err = implode($error_string, $error_html);

		return $this->err;
	}
}

Split modules into their own files

Split modules into their own files


<?php

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

class AddStripeCustomerIdColumnToUsersTable extends Migration
{
    public function up(): void
    {
        Schema::table('users', function (Blueprint $table) {
            $table->string('stripe_customer_id')->nullable()->after('remember_token');
        });
    }

    public function down(): void
    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropColumn('stripe_customer_id');
        });
    }
}

Add stripe_customer_id column to users table


<?php
/**
 * @file
 */

namespace CultuurNet\UDB3\Event\Events;

use Broadway\Serializer\SerializableInterface;
use CultuurNet\UDB3\Label;
use CultuurNet\UDB3\LabelCollection;
use ValueObjects\String\String;

class LabelsMergedTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @test
     */
    public function it_can_be_serialized_to_an_array()
    {
        $labelsMerged = new LabelsMerged(
            new String('foo'),
            new LabelCollection(
                [
                    new Label('label 1', true),
                    new Label('label 2', false),
                ]
            )
        );

        $this->assertInstanceOf(SerializableInterface::class, $labelsMerged);

        $expectedSerializedEvent = [
            'event_id' => 'foo',
            'labels' => [
                [
                    'text' => 'label 1',
                    'visible' => true,
                ],
                [
                    'text' => 'label 2',
                    'visible' => false,
                ],
            ],
        ];

        $this->assertEquals(
            $expectedSerializedEvent,
            $labelsMerged->serialize()
        );
    }

    /**
     * @test
     */
    public function it_can_deserialize_an_array()
    {
        $serializedEvent = [
            'event_id' => 'foo',
            'labels' => [
                [
                    'text' => 'label 1',
                    'visible' => true,
                ],
                [
                    'text' => 'label 2',
                    'visible' => false,
                ],
            ],
        ];

        $expectedLabelsMerged = new LabelsMerged(
            new String('foo'),
            new LabelCollection(
                [
                    new Label('label 1', true),
                    new Label('label 2', false),
                ]
            )
        );

        $this->assertEquals(
            $expectedLabelsMerged,
            LabelsMerged::deserialize($serializedEvent)
        );
    }
}

III-481: Add test for LabelsMerged (de)serialization


<?php
/*
 * HiPay fullservice SDK
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the MIT License
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/mit-license.php
 *
 * @copyright      Copyright (c) 2016 - HiPay
 * @license        http://opensource.org/licenses/mit-license.php MIT License
 *
 */
namespace HiPay\FullserviceMagento\Model\ResourceModel\PaymentProfile;

class Collection extends \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection
{
    /**
     * Initialize resource
     *
     * @return void
     */
    protected function _construct()
    {
        $this->_init('HiPay\FullserviceMagento\Model\PaymentProfile', 'HiPay\FullserviceMagento\Model\ResourceModel\PaymentProfile');
    }

}

Add Payment profile collection class

Add Payment profile collection class


<?php

// Small helper array that may be used on some page controllers to
// fetch the crons we wish to monitor
$aMonitorCrons = array('statistics','payouts','tables_cleanup','blockupdate','findblock','notifications','tickerupdate');

switch ($config['payout_system']) {
case 'pplns':
    $aMonitorCrons[] = $config['payout_system'] . '_payout';
      break;
case 'pps':
    $aMonitorCrons[] = $config['payout_system'] . '_payout';
      break;
case 'prop':
    $aMonitorCrons[] = 'proportional_payout';
      break;
}

<?php

// Small helper array that may be used on some page controllers to
// fetch the crons we wish to monitor
switch ($config['payout_system']) {
  case 'pplns':
    $sPayoutSystem = $config['payout_system'] . '_payout';
    break;
  case 'pps':
    $sPayoutSystem = $config['payout_system'] . '_payout';
    break;
  case 'prop':
    $sPayoutSystem = 'proportional_payout';
    break;
}

$aMonitorCrons = array('statistics','tickerupdate','notifications','tables_cleanup','findblock',$sPayoutSystem,'blockupdate','payouts');

Rearrange cron in UI to correspond to the actual order of work


<?php

namespace CultuurNet\UDB3\Place;

use Broadway\CommandHandling\CommandBusInterface;
use Broadway\Repository\RepositoryInterface;
use Broadway\UuidGenerator\UuidGeneratorInterface;
use CultuurNet\UDB3\Address;
use CultuurNet\UDB3\Calendar;
use CultuurNet\UDB3\Event\EventType;
use CultuurNet\UDB3\Event\ReadModel\DocumentRepositoryInterface;
use CultuurNet\UDB3\Location;
use CultuurNet\UDB3\Offer\Commands\OfferCommandFactoryInterface;
use CultuurNet\UDB3\Title;

class DefaultPlaceEditingServiceTest extends \PHPUnit_Framework_TestCase
{

    /**
     * @var DefaultPlaceEditingService
     */
    protected $placeEditingService;

    /**
     * @var CommandBusInterface|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $commandBus;

    /**
     * @var UuidGeneratorInterface|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $uuidGenerator;

    /**
     * @var OfferCommandFactoryInterface|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $commandFactory;

    /**
     * @var DocumentRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $readRepository;

    /**
     * @var RepositoryInterface|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $writeRepository;

    public function setUp()
    {
        $this->commandBus = $this->getMock(CommandBusInterface::class);

        $this->uuidGenerator = $this->getMock(
            UuidGeneratorInterface::class
        );

        $this->commandFactory = $this->getMock(OfferCommandFactoryInterface::class);

        /** @var DocumentRepositoryInterface $repository */
        $this->readRepository = $this->getMock(DocumentRepositoryInterface::class);

        $this->writeRepository = $this->getMock(RepositoryInterface::class);

        $this->placeEditingService = new DefaultPlaceEditingService(
            $this->commandBus,
            $this->uuidGenerator,
            $this->readRepository,
            $this->commandFactory,
            $this->writeRepository
        );
    }

    /**
     * @test
     */
    public function it_can_create_a_new_place()
    {
        $placeId = 'generated-uuid';
        $title = new Title('Title');
        $eventType = new EventType('0.50.4.0.0', 'concert');
        $address = new Address('$street', '$postalcode', '$locality', '$country');
        $calendar = new Calendar('permanent', '', '');
        $theme = null;

        $place = Place::createPlace($placeId, $title, $eventType, $address, $calendar, $theme);

        $this->uuidGenerator->expects($this->once())
            ->method('generate')
            ->willReturn('generated-uuid');

        $this->writeRepository->expects($this->once())
            ->method('save')
            ->with($place);

        $this->placeEditingService->createPlace($title, $eventType, $address, $calendar, $theme);
    }
}

Add test for creation of a place

III-765: Add test for creation of a place


<?php

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

/*
 * You can use an closure or a class that implements TestInterface.
 *
 * Data that will be processed by the tested function can be executed
 * without including its execution time. This will provide more accurate data.
 */

abstract class AbstractTest implements \mre\PHPench\TestInterface
{
    protected $text;
    protected $placeholders;

    public function setUp($arrSize)
    {
        $this->text = $this->createText(10);
        $this->placeholders = $this->createPlaceholders($arrSize);
    }

    protected function createText($n)
    {
        $text = 'Lorem Ipsum Text ';

        for ($i = 0; $i < $n; $i++) {
            $text .= ' placeholder: $placeholder_' . $i;
        }

        return $text;
    }

    protected function createPlaceholders($n)
    {
        $placeholders = [];

        for ($i = 0; $i < $n; $i++) {
            $placeholders['$placeholder_' . $i] = $i;
        }

        return $placeholders;
    }
}

class TestStringReplaceForeach extends AbstractTest
{
    public function execute() {
        foreach ($this->placeholders as $search => $replace) {
            $this->text = str_replace($search, $replace, $this->text);
        }
    }
}

class TestStringReplaceArrayValue extends AbstractTest
{
    public function execute() {
        $this->text = str_replace(array_keys($this->placeholders), array_values($this->placeholders), $this->text);
    }
}

class TestPregReplaceCallback extends AbstractTest
{
    public function execute() {
        $this->text = preg_replace_callback('/(\$[\w\d]+)\s/', function($matches) {
            return isset($this->placeholder[$matches[0]]) ? $this->placeholder[$matches[0]] : $matches[0];
        }, $this->text);
    }
}

// Create a new benchmark instance
$phpench = new mre\PHPench(new \mre\PHPench\Aggregator\MedianAggregator);
$phpench->setTitle('Compare placeholder replacement');

// Add your test to the instance
$phpench->addTest(new TestStringReplaceForeach, 'TestStringReplaceForeach');
$phpench->addTest(new TestStringReplaceArrayValue, 'TestStringReplaceArrayValue');
$phpench->addTest(new TestPregReplaceCallback, 'TestPregReplaceCallback');

// Run the benchmark and plot the results in realtime.
// With the second parameter you can specify
// the start, end and step for each call
$phpench->setInput(range(0, 200, 2));
$phpench->setRepetitions(10);
$phpench->run();
$phpench->save('test3.png', 1024, 768);

Add example for string replacements

Add example for string replacements


<?php

/*
 * This file is part of the HWIOAuthBundle package.
 *
 * (c) Hardware.Info <opensource@hardware.info>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace HWI\Bundle\OAuthBundle\Tests\OAuth\ResourceOwner;

use HWI\Bundle\OAuthBundle\OAuth\ResourceOwner\TwitterResourceOwner;

class TwitterResourceOwnerTest extends GenericOAuth1ResourceOwnerTest
{
    protected $userResponse = <<<json
{
    "id": "1",
    "screen_name": "bar"
}
json;
    protected $paths = array(
        'identifier' => 'id',
        'nickname'   => 'screen_name',
        'realname'   => 'name',
    );

    protected function setUpResourceOwner($name, $httpUtils, array $options)
    {
        $options = array_merge(
            array(
                'authorization_url'   => 'https://api.twitter.com/oauth/authenticate',
                'request_token_url'   => 'https://api.twitter.com/oauth/request_token',
                'access_token_url'    => 'https://api.twitter.com/oauth/access_token',
                'infos_url'           => 'http://api.twitter.com/1/account/verify_credentials.json',
            ),
            $options
        );

        return new TwitterResourceOwner($this->buzzClient, $httpUtils, $options, $name, $this->storage);
    }
}

Add missing test for Twitter provider

Add missing test for Twitter provider


<?php

use Cake\Core\Configure;
use Cake\Database\Type;

Configure::write('Muffin/Tokenize', [
    'lifetime' => '3 days',
    'length' => 32,
]);

if (!Type::map('json')) {
    Type::map('json', 'Muffin\Tokenize\Database\Type\JsonType');
}

Add basic out of the box configuration

Add basic out of the box configuration


<?php

namespace Kanboard\Controller;

use Kanboard\Core\Base;

/**
 * Class AppController
 *
 * @package Kanboard\Controller
 * @author  Frederic Guillot
 */
class AppController extends Base
{
    /**
     * Forbidden page
     *
     * @access public
     * @param  bool   $withoutLayout
     * @param  string $message
     */
    public function accessForbidden($withoutLayout = false, $message = '')
    {
        if ($this->request->isAjax()) {
            $this->response->json(array('message' => $message ?: t('Access Forbidden')), 403);
        } else {
            $this->response->html($this->helper->layout->app('app/forbidden', array(
                'title' => t('Access Forbidden'),
                'no_layout' => $withoutLayout,
            )));
        }
    }

    /**
     * Page not found
     *
     * @access public
     * @param  boolean $withoutLayout
     */
    public function notFound($withoutLayout = false)
    {
        $this->response->html($this->helper->layout->app('app/notfound', array(
            'title' => t('Page not found'),
            'no_layout' => $withoutLayout,
        )));
    }
}

<?php

namespace Kanboard\Controller;

use Kanboard\Core\Base;

/**
 * Class AppController
 *
 * @package Kanboard\Controller
 * @author  Frederic Guillot
 */
class AppController extends Base
{
    /**
     * Forbidden page
     *
     * @access public
     * @param  bool   $withoutLayout
     * @param  string $message
     */
    public function accessForbidden($withoutLayout = false, $message = '')
    {
        if ($this->request->isAjax()) {
            $this->response->json(array('message' => $message ?: t('Access Forbidden')), 403);
        } else {
            $this->response->html($this->helper->layout->app('app/forbidden', array(
                'title' => t('Access Forbidden'),
                'no_layout' => $withoutLayout,
            )), 403);
        }
    }

    /**
     * Page not found
     *
     * @access public
     * @param  boolean $withoutLayout
     */
    public function notFound($withoutLayout = false)
    {
        $this->response->html($this->helper->layout->app('app/notfound', array(
            'title' => t('Page not found'),
            'no_layout' => $withoutLayout,
        )));
    }
}

Return HTTP 403 when access is forbidden


<?php
require_once('../functions.php');
require_once('../../global_functions.php');
require_once('../../connections/parameters.php');

$db = new dbWrapper($hostname_gds_site, $username_gds_site, $password_gds_site, $database_gds_site, true);

if ($db) {
    //MOD-HERO BREAKDOWN
    {
        $db->q("DROP TABLE IF EXISTS `cron_mod_heroes_temp`;");

        $sqlResult = $db->q(
            "CREATE TABLE IF NOT EXISTS `cron_mod_heroes_temp`
                SELECT
                  `mod_id`,
                  `player_hero_id`,
                  COUNT(*) AS numPicks
                FROM `mod_match_players`
                GROUP BY `mod_id`, `player_hero_id`
                ORDER BY `mod_id`, `player_hero_id`;"
        );

        echo $sqlResult
            ? "[SUCCESS] Table created!
"
            : "[FAILURE] Table not created!
";

        if ($sqlResult) {
            $db->q(
                "CREATE TABLE IF NOT EXISTS `cron_mod_heroes` (
                  `mod_id` varchar(255) NOT NULL,
                  `player_hero_id` int(255) NOT NULL,
                  `numPicks` bigint(21) NOT NULL DEFAULT '0',
                  PRIMARY KEY (`mod_id`,`player_hero_id`)
                ) ENGINE=InnoDB DEFAULT CHARSET=latin1;"
            );

            $db->q(
                "TRUNCATE TABLE `cron_mod_heroes`;"
            );

            $sqlResult = $db->q(
                "INSERT INTO `cron_mod_heroes`
                    SELECT * FROM `cron_mod_heroes_temp`;"
            );

            echo $sqlResult
                ? "[SUCCESS] Final table populated!
"
                : "[FAILURE] Final table not populated!
";

            $db->q("DROP TABLE IF EXISTS `cron_mod_heroes_temp`;");
        }
    }
}

Add cronjob for extracting hero usages per mod


<?php

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

class PaymentgroupsFixEventgroupId extends Migration {

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('paymentgroups', function(Blueprint $table) {
            $table->foreign('eventgroup_id')->references('id')->on('eventgroups');
        });
    }

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

}

Fix missing foreign key reference on payments-table


<?php
$db = "";
$user = "";
$password = "";

printf("Connecting...\n");

$conn = odbc_connect($db, $user, $password);

if (!$conn) {
	die("Could not connect to " . $db);
}

printf("Getting tables...\n");

$result = odbc_tables($conn);

if (!$result)
	die("Could not get tables.");

$tables = array();

while (odbc_fetch_row($result))
	array_push($tables, odbc_result($result, "TABLE_NAME") );

foreach ($tables as $table) {
	$handle = fopen($table . ".csv", "w");

	$result = odbc_columns($conn, "", "", $table);

	if (!$result) {
		printf("Could not get columns for: %s\n", $table);
		fclose($handle);
		continue;
	}

	$column_names = array();

	while ($row = odbc_fetch_array($result)) {
		$column_names[] = $row["COLUMN_NAME"];
	}

	$x = 0;

	foreach ($column_names as $column) {
		$result = odbc_exec($conn, "select " . $column . " from " .
		    $table;

		if (odbc_num_row($result) == 0)
			unset($column_names[$x]);

		$x++;
	}

	$column_names = array_values($column_names);

	fputcsv($handle, $column_names);

	$query = "select * from " . $table;

	$result = odbc_exec($conn, $query);

	if (!$result) {
		printf("Could not execute query: %s\n", $query);
		fclose($handle);
		continue;
	}

	while ($row = odbc_fetch_array($result)) {
		fputcsv($handle, $row);
	}

	fclose($handle);
}

odbc_close($conn);

?>

Add script to dump ODBC database to CSV files.


#!/usr/bin/env drush

<?php
$result = db_query("SELECT n.nid, n.title FROM {node} n WHERE language = 'und'");
foreach ($result as $record) {
  print "Loaded: {$record->title} [{$record->nid}]\n";
  $node = node_load($record->nid);
  $node->language = 'ru';
  node_save($node);
}

Add sample script updating node language.