<?php

namespace Gaufrette\Filesystem\Adapter;

class LocalTest extends \PHPUnit_Framework_TestCase
{
    public function testComputePath()
    {
        $directory = __DIR__ . '/filesystem';
        $adapter = new Local($directory);

        $this->assertEquals($directory . '/foobar', $adapter->computePath('foobar'));
        $this->assertEquals($directory . '/bar', $adapter->computePath('foo/../bar'));
        $this->assertEquals($directory . '/foo', $adapter->computePath('../filesystem/foo'));

        $this->setExpectedException('OutOfBoundsException');

        $adapter->computePath('../foobar');
    }

    public function testNormalizePath()
    {
        $directory = __DIR__ . '/filesystem';
        $adapter = new Local($directory);

        $this->assertEquals('/foo/bar', $adapter->normalizePath('//foo/foo2/foo3/../..//bar/./foo4/..'));
    }

    public function testComputeKey()
    {
        $directory = __DIR__ . '/filesystem';
        $adapter = new Local($directory);

        $this->assertEquals('foobar', $adapter->computeKey($directory . '/foobar'));
        $this->assertEquals('foo/bar', $adapter->computeKey($directory . '/foo/bar'));
    }
}

Add tests for the local adapter

Add tests for the local adapter


<?php

namespace Clue\Redis\React;

use Evenement\EventEmitter;
use React\Stream\Stream;
use Clue\Redis\Protocol\ProtocolInterface;
use React\Promise\Deferred;

class Client extends EventEmitter
{
    private $stream;
    private $protocol;

    public function __construct(Stream $stream, ProtocolInterface $protocol)
    {
        $that = $this;
        $stream->on('data', function($chunk) use ($protocol, $that) {
            $protocol->pushIncoming($chunk);

            while ($protocol->hasIncoming()) {
                $that->emit('message', array($protocol->popIncoming(), $that));
            }
        });
        $stream->on('close', function () use ($that) {
            $that->close();
        });
        $stream->resume();
        $this->stream = $stream;
        $this->protocol = $protocol;
    }

    public function __call($name, $args)
    {
        /* Build the Redis unified protocol command */
        array_unshift($args, strtoupper($name));

        $this->stream->write($this->protocol->createMessage($args));

        return new Deferred();
    }

    public function end()
    {
        $this->stream->end();
    }

    public function close()
    {
        $this->stream->close();
    }
}

<?php

namespace Clue\Redis\React;

use Evenement\EventEmitter;
use React\Stream\Stream;
use Clue\Redis\Protocol\ProtocolInterface;
use Clue\Redis\Protocol\ParserException;
use React\Promise\Deferred;

class Client extends EventEmitter
{
    private $stream;
    private $protocol;

    public function __construct(Stream $stream, ProtocolInterface $protocol)
    {
        $that = $this;
        $stream->on('data', function($chunk) use ($protocol, $that) {
            try {
                $protocol->pushIncoming($chunk);
            }
            catch (ParserException $error) {
                $that->emit('error', array($error));
                $that->close();
                return;
            }

            while ($protocol->hasIncoming()) {
                $that->emit('message', array($protocol->popIncoming(), $that));
            }
        });
        $stream->on('close', function () use ($that) {
            $that->close();
        });
        $stream->resume();
        $this->stream = $stream;
        $this->protocol = $protocol;
    }

    public function __call($name, $args)
    {
        /* Build the Redis unified protocol command */
        array_unshift($args, strtoupper($name));

        $this->stream->write($this->protocol->createMessage($args));

        return new Deferred();
    }

    public function end()
    {
        $this->stream->end();
    }

    public function close()
    {
        $this->stream->close();
    }
}

Handle protocol errors and disconnect client


<?php

/**
*       This custom class must be placed in the folder /AlloPass/Hipay/Helper
*       You have to personalize  the method getCustomData and return an json of your choice.
*
*/
class Allopass_Hipay_Helper_CustomData extends Mage_Core_Helper_Abstract
{
    /**
	 *  Return yours customs datas in a json for gateway transaction request
     *
     * @param array $payment
	 * @param float $amount
	 *
     */
    public function getCustomData($payment,$amount)
    {
        $customData = array();

        // An example of adding custom data
        if ($payment)
        {
            $customData['my_field_custom_1'] = $payment->getOrder()->getBaseCurrencyCode();
        }

        return json_encode($customData);
    }
}

Add support of custom data

Add support of custom data


<?php
/**
 * PHP SMS
 *
 * @author    Jacques Marneweck <jacques@siberia.co.za>
 * @copyright 2020 Jacques Marneweck.  All rights strictly reserved.
 */

declare(strict_types=1);

namespace Jacques\SMS;

class Version
{
    /**
     * @var string
     */
    const VERSION = '0.0.1';
}

Add class to hold the version number

Add class to hold the version number


<?php
$contactInfo = array();
foreach (array('listingcontactname', 'listingcontactphone') as $property) {
    if (isset($context->event->$property)) {
        $contactInfo[] = $context->event->$property;
    }
}
if (isset($context->event->listingcontactemail)) {
    $contactInfo[] = 'event->listingcontactemail . '">' . $context->event->listingcontactemail . '';
}
?>
<?php if (!empty($contactInfo)): ?>

    <?php echo implode(', ', $contactInfo) ?>

<?php endif; ?>

Add template for rendering event contact information


<?php

class UsersEnlargeTimezone extends CakeMigration {

/**
 * Migration description
 *
 * @var string
 * @access public
 */
	public $description = 'Updating User timezone';

/**
 * Actions to be performed
 *
 * @var array $migration
 * @access public
 */
	public $migration = array(
		'up' => array(
			'alter_field' => array(
				'users' => array(
					'timezone' => array(
						'type' => 'string',
						'length' => 40,
						'after' => 'created',
					),
				),
			),
		),
		'down' => array(
			'alter_field' => array(
				'users' => array(
					'timezone' => array(
						'type' => 'string',
						'length' => 10,
					),
				),
			),
		),
	);

/**
 * Before migration callback
 *
 * @param string $direction, up or down direction of migration process
 * @return boolean Should process continue
 * @access public
 */
	public function before($direction) {
		return true;
	}

/**
 * After migration callback
 *
 * @param string $direction, up or down direction of migration process
 * @return boolean Should process continue
 * @access public
 */
	public function after($direction) {
		return true;
	}
}

Schema: Enlarge users.timezone to store tz names


<?php
/**
 * This file is part of the FreeDSx package.
 *
 * (c) Chad Sikorra <Chad.Sikorra@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace FreeDSx\Ldap\Control;

/**
 * Possible Password Policy Error values. draft-behera-ldap-password-policy-10, Section 6.2.
 *
 * @see https://tools.ietf.org/html/draft-behera-ldap-password-policy-10
 * @author Chad Sikorra <Chad.Sikorra@gmail.com>
 */
class PwdPolicyError
{
    public const PASSWORD_EXPIRED = 0;

    public const ACCOUNT_LOCKED = 1;

    public const CHANGE_AFTER_RESET = 2;

    public const PASSWORD_MOD_NOT_ALLOWED = 3;

    public const MUST_SUPPLY_OLD_PASSWORD = 4;

    public const INSUFFICIENT_PASSWORD_QUALITY = 5;

    public const PASSWORD_TOO_SHORT = 6;

    public const PASSWORD_TOO_YOUNG = 7;

    public const PASSWORD_IN_HISTORY = 8;
}

Add password policy error constants.

Add password policy error constants.


<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class First extends Application
{

	function __construct()
	{
		parent::__construct();
	}

	/**
	 * The default page for the current first quote.
	 */
	public function index()
	{
		// build the list of author we want to pass on to our view
		$firstAuthor = $this->quotes->get(1);
		$this->data['who'] = $firstAuthor['who'];
		$this->data['mug'] = $firstAuthor['mug'];
		$this->data['what'] = $firstAuthor['what'];

		// this is the view we want shown
		$this->data['pagebody'] = 'justone';
		$this->render();
	}

}

Add the First.php controller and add index() method.

Signed-off-by: Wilson Lau <51ca10b964eb3f90521acbc5ab4d054ef62a94b4@gmail.com>


Basket

@if($cart->hasItems())

        Description
        Unit Price
        Quantity
        Net Price

    @foreach($cart->items() as $item)

            {{ $item->image() }} {{ $item->description() }}
            {{ $item->unitPrice() }}
            <input type="text" name="basket[{{ $item->id() }}][quantity]" value="{{ $item->quantity() }}">
            {{ $item->net() }}

    @endforeach

        Shipping:
        {{ $cart->shipping()->net() }}

        Tax:
        {{ $cart->tax() }}

        Total:
        {{ $cart->gross() }}

@else
Your have no items in your basket.
@endif

Create cart concepts folder, add cart view concept


<?php

use RingCentral\Psr7\Response;
use RingCentral\Psr7\Request;
use Legionth\React\Http\Client;

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

$loop = React\EventLoop\Factory::create();

$client = new Client($loop);

$uri = 'tcp://google.com:80';
$request = new Request('GET', 'http://google.com:80');

$promise = $client->request($uri, $request);
$promise->then(
    function (Response $response) {
        echo 'Successfully received a response from the server:' . PHP_EOL;
        echo RingCentral\Psr7\str($response);

        $body = $response->getBody();
        $body->on('data', function ($data) {
            echo "Body-Data: " . $data . PHP_EOL;
        });

        $body->on('end', function () {
            exit(0);
        });
    },
    function (\Exception $exception) {
        echo $exception->getMessage() . PHP_EOL;
    }
);

$loop->run();

Add example to sent a request to google.com


<?php

namespace Bundle\DoctrineUserBundle\Command;

use Symfony\Bundle\FrameworkBundle\Command\Command as BaseCommand;
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 Bundle\DoctrineUserBundle\Document\UserRepository;

class MongoDBMigrateUserPasswordFieldCommand extends BaseCommand
{
    /**
     * @see Command
     */
    protected function configure()
    {
        $this
            ->setName('doctrine:user:migrate-password')
            ->setDescription('Rename User.passwordHash to User.password in a MongoDB Collection');
    }

    /**
     * @see Command
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $userRepo = $this->container->get('doctrine_user.repository.user');
        if(!$userRepo instanceof UserRepository) {
            throw new \RuntimeException('Can only work with MongoDB');
        }

        $dm = $this->container->get('doctrine_user.object_manager');
        $collection = $dm->getDocumentCollection($userRepo->getObjectClass())->getMongoCollection();
        $users = $collection->find(array('passwordHash' => array('$exists' => true)));
        if(!$users->count()) {
            $output->writeLn('Nothing to do');
            return;
        }
        $output->writeLn(sprintf('Will migrate %d users', $users->count()));
        foreach($collection->find() as $user) {
            $user['password'] = $user['passwordHash'];
            unset($user['passwordHash']);
            $collection->update(array('_id' => $user['_id']), $user);
        }
    }
}

Add command to migrate user passwords (mongodb only)


<?php
/*
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
 * and is licensed under the MIT license.
 */

declare(strict_types=1);

namespace ProxyManagerTestAsset;

class VoidMethodTypeHintedClass
{
    public function returnVoid() : void
    {
    }
}

Test asset: class with a `void` return type


<?php

namespace AppBundle\EventListener;

use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class LocaleListener implements EventSubscriberInterface
{
    private $defaultLocale;

    public function __construct($defaultLocale = 'en')
    {
        $this->defaultLocale = $defaultLocale;
    }

    public function onKernelRequest(GetResponseEvent $event)
    {
        $request = $event->getRequest();
        if (!$request->hasPreviousSession()) {
            return;
        }

        if ($locale = $request->attributes->get('_locale')) {
            $request->getSession()->set('_locale', $locale);
        } else {
            $request->setLocale($request->getSession()->get('_locale', $this->defaultLocale));
        }
    }

    public static function getSubscribedEvents()
    {
        return array(
            KernelEvents::REQUEST => array(array('onKernelRequest', 17)),
        );
    }
}

Add eventListener for sticky locale during user session


<?php

namespace OckCyp\CoversValidator\Tests\Application;

use OckCyp\CoversValidator\Application\CoversValidator;
use OckCyp\CoversValidator\Tests\BaseTestCase;

class CoversValidatorTest extends BaseTestCase
{
    /**
     * @covers OckCyp\CoversValidator\Application\CoversValidator
     */
    public function testApplicationIsRight()
    {
        $app = new CoversValidator;
        $defaultCommands = $app->all();
        $definition = $app->getDefinition();

        $this->assertEmpty($definition->getArguments());
        $this->assertArrayHasKey('validate', $defaultCommands);
        $this->assertInstanceOf(
            'OckCyp\CoversValidator\Command\ValidateCommand',
            $defaultCommands['validate']
        );
    }
}

Add test for the console application

Add test for the console application


<?php

/**
 * ATUI - tests
 * This is the scripts to test reporter::Loader
 * @author peter<peter.ziv@hotmail.com>
 */

use PHPUnit\Framework\TestCase;

require_once __DIR__.'/../../src/reporter/Loader.php';

class LoaderTest extends TestCase
{

    public function testInit()
    {

        $filename = getenv('USERPROFILE') . DIRECTORY_SEPARATOR . 'config.json';
        $rs = true;
        if (file_exists($filename)) {
            $rs = unlink($filename);
        }
        if ($rs) {
            $loader = new \ZKit\ATUI\Loader();
            $this->assertEquals(false, $loader->init());

            copy(__DIR__ . '/../../deploy/config.json', $filename);
            $this->assertEquals(true, $loader->init());

            $this->assertEquals(array('product' => 1, 'openedBuild' => 'trunk', 'type' => 'automation', 'severity' => 3), $loader->bug);
            $this->assertEquals('admin', $loader->tracker->user);
            $this->assertEquals('ZenTaoPMS', $loader->tracker->pwd);
            $this->assertEquals('http://127.0.0.1/pms', $loader->tracker->domain);
            $this->assertEquals('target/surefire-reports', $loader->junit);
        }
    }

}

Add test script for Loader

Add test script for Loader


<?php

/**
 * @copyright Copyright (C) 2015-2022 AIZAWA Hina
 * @license https://github.com/fetus-hina/stat.ink/blob/master/LICENSE MIT
 * @author AIZAWA Hina <hina@fetus.jp>
 */

declare(strict_types=1);

use app\components\db\Migration;
use yii\db\Connection;
use yii\db\Expression;
use yii\db\Query;

final class m220910_080437_weapon3_splatnetids extends Migration
{
    /**
     * @inheritdoc
     */
    public function safeUp()
    {
        $db = $this->db;
        if (!$db instanceof Connection) {
            throw new LogicException();
        }

        // Copy splatnet2's ID as weapon3's alias
        $sql = vsprintf('INSERT INTO %1$s ( %2$s, %3$s ) %4$s', [
            $db->quoteTableName('{{%weapon3_alias}}'),
            $db->quoteColumnName('weapon_id'),
            $db->quoteColumnName('key'),
            (new Query())
                ->select([
                    'weapon_id' => '{{%weapon3}}.[[id]]',
                    'key' => new Expression(vsprintf('%s.%s::text', [
                        $db->quoteTableName('{{%weapon2}}'),
                        $db->quoteColumnName('splatnet'),
                    ])),
                ])
                ->from('{{%weapon2}}')
                ->innerJoin('{{%weapon3}}', '{{%weapon2}}.[[key]] = {{%weapon3}}.[[key]]')
                ->orderBy([
                    '{{weapon3}}.[[id]]' => SORT_ASC,
                ])
                ->createCommand($db)
                ->rawSql,
        ]);
        $this->execute($sql);

        return true;
    }

    /**
     * @inheritdoc
     */
    public function safeDown()
    {
        $this->delete('{{%weapon3_alias}}', ['and',
            ['~', '{{%weapon3_alias}}.key', '^[0-9]+$'],
        ]);

        return true;
    }
}

Copy weapon IDs of SplatNet2 to Splatoon 3's weapon


<?php declare(strict_types=1);

namespace hollodotme\Readis\Application\Web\Server\Read;

use hollodotme\Readis\Application\Web\AbstractRequestHandler;
use hollodotme\Readis\Application\Web\Responses\EventSourceStream;
use hollodotme\Readis\Exceptions\LogicException;
use hollodotme\Readis\Exceptions\ServerConfigNotFound;
use hollodotme\Readis\Infrastructure\Redis\Exceptions\ConnectionFailedException;
use IceHawk\IceHawk\Interfaces\HandlesGetRequest;
use IceHawk\IceHawk\Interfaces\ProvidesReadRequestData;
use function ignore_user_abort;
use function usleep;

final class ServerStatsRequestHandler extends AbstractRequestHandler implements HandlesGetRequest
{
	/**
	 * @param ProvidesReadRequestData $request
	 *
	 * @throws ServerConfigNotFound
	 * @throws ConnectionFailedException
	 * @throws LogicException
	 */
	public function handle( ProvidesReadRequestData $request )
	{
		ignore_user_abort( false );

		$input            = $request->getInput();
		$serverKey        = (string)$input->get( 'serverKey', '0' );
		$serverConfigList = $this->getEnv()->getServerConfigList();
		$serverConfig     = $serverConfigList->getServerConfig( $serverKey );
		$serverManager    = $this->getEnv()->getServerManager( $serverConfig );

		$stream = new EventSourceStream();
		$stream->beginStream();

		while ( true )
		{
			$serverInfo = $serverManager->getServerInfo();

			$stream->streamEvent( (string)$serverInfo['connected_clients'], 'clientsConnected' );
			$stream->streamEvent( (string)$serverInfo['instantaneous_input_kbps'], 'inputKbPerSecond' );
			$stream->streamEvent( (string)$serverInfo['instantaneous_output_kbps'], 'outputKbPerSecond' );

			usleep( 500000 );
		}

		$stream->endStream();
	}
}

Add server stats request handler

Add server stats request handler


            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#menu">
                {{ Lang::get('cachet.dashboard.toggle_navigation') }}

            </button>
             Cachet

                @if(Auth::check())

                @endif

Set the Cachet nav header to go back to the dashboard


<?php

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

class UpdateVnTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        if(Schema::hasTable('vn')) {
            Schema::table('vn', function($table) {
                $table->string('alias', 1000)->after('title_jp')->nullable();
            });
        }
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        if(Schema::hasTable('vn')) {
            Schema::table('vn', function($table) {
                $table->dropColumn(['alias']);
            });
        }
    }
}

Make migration to append alias column to vn table


<?php

namespace Tests\AppBundle\Command;

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

class ListWebuserCommandTest extends KernelTestCase
{
    public function testExecute()
    {
        self::bootKernel();
        $application = new Application(self::$kernel);

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

        $command = $application->find('app:list-webuser');
        $commandTester = new CommandTester($command);
        $commandTester->execute(array(
            'command'  => $command->getName(),
        ));

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

Add test for new command list-webuser

Add test for new command list-webuser


<?php namespace Codesleeve\Stapler\Factories;

use PHPUnit_Framework_TestCase;
use Symfony\Component\HttpFoundation\File\UploadedFile as SymfonyUploadedFile;
use Mockery as m;

class StorageTest extends PHPUnit_Framework_TestCase
{
	/**
	 * Setup method.
	 *
	 * @return void
	 */
	public function setUp()
	{
	}

	/**
	 * Teardown method.
	 *
	 * @return void
	 */
	public function tearDown()
	{
		m::close();
	}

	/**
	 * Test that the Storage factory can create an instance of the filesystem
	 * storage driver.
	 *
	 * @test
	 * @return void
	 */
	public function it_should_be_able_to_create_a_filesystem_storeage_instance()
	{
		$attachment = $this->buildMockAttachment('filesystem');

		$storage = Storage::create($attachment);

		$this->assertInstanceOf('Codesleeve\Stapler\Storage\Filesystem', $storage);
	}

	/**
	 * Test that the Storage factory can create an instance of the s3
	 * storage driver.
	 *
	 * @test
	 * @return void
	 */
	public function it_should_be_able_to_create_an_s3_storeage_instance()
	{
		$attachment = $this->buildMockAttachment('s3');

		$storage = Storage::create($attachment);

		$this->assertInstanceOf('Codesleeve\Stapler\Storage\S3', $storage);
	}

	/**
	 * Test that the Storage factory should create an instance of the filesystem
	 * storage driver by default.
	 *
	 * @test
	 * @return void
	 */
	public function it_should_be_able_to_create_a_filesystem_storeage_instance_by_default()
	{
		$attachment = $this->buildMockAttachment();

		$storage = Storage::create($attachment);

		$this->assertInstanceOf('Codesleeve\Stapler\Storage\Filesystem', $storage);
	}

	/**
	 * Build a mock attachment object.
	 *
	 * @param  string $type
	 * @return \Codesleeve\Stapler\Attachment
	 */
	protected function buildMockAttachment($type = null)
	{
		$attachment = m::mock('Codesleeve\Stapler\Attachment')->makePartial();
		$attachmentConfig = new \Codesleeve\Stapler\AttachmentConfig('testAttachmentConfig', ['styles' => []]);
		$attachment->setConfig($attachmentConfig);
		$attachment->storage = $type;

		return $attachment;
	}
}

Create tests for the Storage factory class.

Created tests for the storage factory class.


<?php

/*
 * This "router" (a script that's executed for every request received by PHP's built-in web server) will look
 * for a file in the system's temporary directory, with the PID of the current process as its name, and the
 * '.lock' extension. If the file exists, it will try to include it and preload SimpleSAMLphp's configuration with
 * the $config array defined in that file.
 * This is useful to configure SimpleSAMLphp dynamically when running inside the built-in server, so that
 * we can test different configurations without the need to keep a structure of files.
 *
 * In order to use it:
 *
 * 1. Create an array with the SimpleSAMLphp configuration you would like to use.
 * 2. Start the built-in server passing "configLoader" as the first parameter to the constructor:
 *      $server = new BuiltInServer('configLoader');
 *      $addr = $server->start();
 * 3. Get the PID of the server once it has started:
 *      $pid = $server->getPid();
 * 4. Build the path to the file that this script will use:
 *      $file = sys_get_temp_dir().'/'.$pid.'.lock';
 * 5. Dump the configuration array to the file:
 *      file_put_contents("<?php\n\$config = ".var_export($config, true).";\n");
 * 6. Make a request to the server:
 *      $server->get($query, $parameters);
 * 7. Remove the temporary file when done:
 *      unlink($file);
 */

include_once(sys_get_temp_dir().'/'.getmypid().'.lock');

// load SimpleSAMLphp's autoloader
require_once(dirname(__FILE__).'/../../vendor/autoload.php');

// initialize configuration
if (isset($config)) {
    SimpleSAML_Configuration::loadFromArray($config, '[ARRAY]', 'simplesaml');
}

// let the script proceed
// see: http://php.net/manual/en/features.commandline.webserver.php
return false;

test: Add a router script for the built-in server to initialize SSP's configuration.

With this script, which will be executed for every request performed to the built-in server, we can preload the configuration from a temporary file, making it possible to configure SimpleSAMLphp dynamically when testing.


<?php
// src/AppBundle/Command/CreateUsersCommand.php
namespace AppBundle\Command;

use AppBundle\Entity\FOSUser;
use Composer\Installer\PackageEvent;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;

class CreateUsersCommand extends ContainerAwareCommand
{
    protected function configure()
    {
        $this->setName('poem:user:create')
            ->addArgument(
                'usernames',
                InputArgument::IS_ARRAY | InputArgument::REQUIRED,
                'samaccountnames of users to create.'
            );
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $userManager = $this->getContainer()->get('app.user_manager');
        foreach ($input->getArgument('usernames') as $username) {
            $user = $userManager->findOrCreateUser($username);
            if ($user) {
                $output->writeln($username . " created successfully.");
            } else {
                $output->writeln($username . " not created.");
            }
        }
    }
}

Add create command for FOSUsers.

Add create command for FOSUsers.


<?php

namespace Doctrine\Tests\ORM\Functional\Ticket;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Tests\Models\CMS\CmsArticle;
use Doctrine\Tests\Models\CMS\CmsUser;
require_once __DIR__ . '/../../../TestInit.php';

/**
 * @group DDC-1040
 */
class DDC1040Test extends \Doctrine\Tests\OrmFunctionalTestCase
{
    public function setUp()
    {
        $this->useModelSet('cms');
        parent::setUp();
    }

    public function testReuseNamedEntityParameter()
    {
        $user = new CmsUser();
        $user->name = "John Galt";
        $user->username = "jgalt";
        $user->status = "inactive";

        $article = new CmsArticle();
        $article->topic = "This is John Galt speaking!";
        $article->text = "Yadda Yadda!";
        $article->setAuthor($user);

        $this->_em->persist($user);
        $this->_em->persist($article);
        $this->_em->flush();

        $dql = "SELECT a FROM Doctrine\Tests\Models\CMS\CmsArticle a WHERE a.user = :author";
        $this->_em->createQuery($dql)
                  ->setParameter('author', $user)
                  ->getResult();

        $dql = "SELECT a FROM Doctrine\Tests\Models\CMS\CmsArticle a WHERE a.user = :author AND a.user = :author";
        $this->_em->createQuery($dql)
                  ->setParameter('author', $user)
                  ->getResult();

        $dql = "SELECT a FROM Doctrine\Tests\Models\CMS\CmsArticle a WHERE a.topic = :topic AND a.user = :author AND a.user = :author  AND a.text = :text";
        $farticle = $this->_em->createQuery($dql)
                  ->setParameter('author', $user)
                  ->setParameter('topic', 'This is John Galt speaking!')
                  ->setParameter('text', 'Yadda Yadda!')
                  ->getSingleResult();

        $this->assertSame($article, $farticle);
    }

    public function testUseMultiplePositionalParameters()
    {
        $user = new CmsUser();
        $user->name = "John Galt";
        $user->username = "jgalt";
        $user->status = "inactive";

        $article = new CmsArticle();
        $article->topic = "This is John Galt speaking!";
        $article->text = "Yadda Yadda!";
        $article->setAuthor($user);

        $this->_em->persist($user);
        $this->_em->persist($article);
        $this->_em->flush();

        $dql = "SELECT a FROM Doctrine\Tests\Models\CMS\CmsArticle a WHERE a.topic = ?1 AND a.user = ?2 AND a.user = ?3 AND a.text = ?4";
        $farticle = $this->_em->createQuery($dql)
                  ->setParameter(1, 'This is John Galt speaking!')
                  ->setParameter(2, $user)
                  ->setParameter(3, $user)
                  ->setParameter(4, 'Yadda Yadda!')
                  ->getSingleResult();

        $this->assertSame($article, $farticle);
    }
}

[DDC-1040] Add regression tests for entity as multiple named/positional parameters.


<?php

namespace Doctrine\Tests\ORM\Functional\Ticket;

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

/**
 * @group DDC-1787
 */
class DDC1787Test extends \Doctrine\Tests\OrmFunctionalTestCase
{
    public function setUp()
    {
        parent::setUp();
        $this->_schemaTool->createSchema(array(
            $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1787Foo'),
            $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1787Bar'),
        ));
    }

    public function testIssue()
    {
        $bar = new DDC1787Bar;
        $bar2 = new DDC1787Bar;

        $this->_em->persist($bar);
        $this->_em->persist($bar2);
        $this->_em->flush();

        $this->assertSame(1, $bar->getVersion());
    }
}

/**
 * @Entity
 * @InheritanceType("JOINED")
 * @DiscriminatorColumn(name="discr", type="string")
 * @DiscriminatorMap({"bar" = "DDC1787Bar"})
 */
class DDC1787Foo
{
    /**
     * @Id @Column(type="integer") @GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @Version @Column(type="integer")
     */
    private $version;

    public function getVersion()
    {
        return $this->version;
    }
}

/**
 * @Entity
 */
class DDC1787Bar extends DDC1787Foo
{
}

Add failing test for DDC-1787.

Add failing test for DDC-1787.

Using joined table inheritance, when persisting multiple new entities
that are subclasses of a baseclass that has the @Version attribute set,
only the last persisted entity will have it's version set.


<?php
$_PCONN['cnt']++;
if (function_exists('zend_thread_id')) {
    echo "thread ", zend_thread_id(), "\n";
} else {
    echo "main\n";
}

exit(PCONN_SUCCESS);

Use the status constant for the return code


<?php

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

use Symfony\Component\Console\Output\ConsoleOutput;

class SignCitiIds extends Migration
{

    public function up()
    {

        $output = new ConsoleOutput();

        $tables = DB::select('SHOW TABLES');

        foreach( $tables as $table )
        {

            $table_array = get_object_vars( $table );
            $table_name = $table_array[ key( $table_array ) ];

            Schema::table($table_name, function (Blueprint $table) use ($table_name, $output) {

                if( Schema::hasColumn($table_name, 'citi_id') )
                {
                    $table->dropPrimary('citi_id');
                }

                foreach( Schema::getColumnListing($table_name) as $column )
                {
                    if( ends_with($column, 'citi_id') )
                    {
                        $table->integer($column)->signed()->change();

                        $output->writeln( 'Signed in ' . $table_name . ': ' . $column);
                    }
                }

                if( Schema::hasColumn($table_name, 'citi_id') )
                {
                    $table->primary('citi_id');
                }

            });

        }

    }

    public function down()
    {

        // Once we insert negative ids to the database, I think we can't change it back...
        // TODO: Remove items with negative ids, and change the columns back to unsigned?

    }

}

Add migration to make all CITI ID fields signed

Apparently, some CITI IDs are negative. It seems that CITI started off
using signed IDs, but at some point a decision was made to expand the
range by starting at the lower bound of the number range, rather than
at zero as originally. Surprising that the schema wasn't modified to
be unsigned instead, but hey, so it is.

This modifies any field ending with `citi_id` to be signed. This should
also catch any pseudo-foreign-key field like `agent_citi_id`.

Also +1 to the decision to call the column `citi_id` instead of `id`.
That choice made this process so much easier. Good call.


<?php

namespace App\Http\Controllers;

use SplTempFileObject;
use League\Csv\Writer;
use App\Models\Assembly;
use Illuminate\Http\Request;

class AssembliesController extends Controller
{
    /**
     * Get the list of assemblies.
     *
     * @return \Illuminate\Http\Response|\Illuminate\Contracts\View\View|\Illuminate\Database\Eloquent\Collection
     */
    public function index(Request $request)
    {
        $assemblies = Assembly::all();

        if ($request->acceptsHtml()) {
            return view('assemblies.index_html', compact('assemblies'));

        } elseif ($request->accepts('text/xml')) {

            // We use a Blade view to render the XML tree.
            $xml = view('assemblies.index_xml', compact('assemblies'))->render();

            return response($xml, 200, [
                'Content-Type' => 'text/xml',
            ]);

        } elseif ($request->accepts('text/csv')) {

            // Create file in memory.
            $csv = Writer::createFromFileObject(new SplTempFileObject());

            // Insert the CSV headers.
            $csv->insertOne(['identifier', 'name_en', 'name_fr', 'name_nl']);

            // Insert the data.
            $assemblies->each(function ($item) use ($csv) {
                $csv->insertOne(array_values($item->toArray()));
            });

            // Generate a reponse.
            return response((string) $csv, 200, [
                'Content-Type' => 'text/csv',
                'Content-Transfer-Encoding' => 'binary',
            ]);
        }

        // Fall back on JSON by default.
        return Assembly::all();
    }
}

Add controller action to handle list of assemblies


<?php
namespace Simox;

class Config extends SimoxServiceBase implements \ArrayAccess
{
	public function __construct( $config_array = array() )
    {
        foreach ( $config_array as $key => $value )
        {
            $this->offsetSet( $key, $value );
        }
    }

    public function offsetExists( $key )
    {
        return isset($this->$key);
    }

    public function offsetGet( $key )
    {
        return $this->$key;
    }

    public function offsetSet( $key, $value )
    {
        if ( is_array($value) )
        {
            $this->$key = new self($value);
        }
        else
        {
            $this->$key = $value;
        }
    }

    public function offsetUnset( $key )
    {
        $this->$key = null;
    }
}

Add first iteration of config

Add first iteration of config


<?php

declare(strict_types=1);

namespace Phpcq\Task;

/**
 * Default task list implementation.
 */
class Tasklist implements TasklistInterface
{
    /**
     * @var TaskRunnerInterface[]
     */
    private $tasks;

    public function add(TaskRunnerInterface $taskRunner): void
    {
        $this->tasks[] = $taskRunner;
    }

    public function getIterator(): iterable
    {
        yield from $this->tasks;
    }
}

Add default task list implementation

Add default task list implementation


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

use Aftertime\Log;

class LogTest extends PHPUnit_Framework_TestCase {
	// Not complete
	public function test_log_file() {
		$this->assertEquals(false, Aftertime\Log::log_file());
	}

	// Complete
	public function test_caller() {
		$this->assertEquals('', Log::caller());
		$this->assertEquals('', Log::caller(123));
		$this->assertEquals('caller', Log::caller('caller'));
		$this->assertEquals('caller', Log::caller());
		$this->assertEquals('caller', Log::caller(false));
		$this->assertEquals('another', Log::caller('another'));
		$this->assertEquals('another', Log::caller(true));
	}
}
?>

Test a bit the Log class, as proof of concept


<?php

namespace Monospice\SpicyIdentifiers;

use Monospice\SpicyIdentifiers\DynamicIdentifier;
use Monospice\SpicyIdentifiers\Tools\CaseFormat;
use Monospice\SpicyIdentifiers\Tools\Parser;

/**
 * A factory trait to help instantiate a new DynamicIdentifier instance
 *
 * @author Cy Rossignol <cy.rossignol@yahoo.com>
 */
trait DynamicIdentifierFactory
{
    // Inherit Doc from Interfaces\DynamicIdentifier
    public static function parseFromCamelCase($identifierName)
    {
        $parserClass = get_called_class();
        return new $parserClass(
            Parser::parseFromCamelCase($identifierName),
            CaseFormat::CAMEL_CASE
        );
    }

    // Inherit Doc from Interfaces\DynamicIdentifier
    public static function parseFromUnderscore($identifierName)
    {
        $parserClass = get_called_class();
        return new $parserClass(
            Parser::parseFromUnderscore($identifierName),
            CaseFormat::UNDERSCORE
        );
    }

    // Inherit Doc from Interfaces\DynamicIdentifier
    public static function parseFromHyphen($identifierName)
    {
        $parserClass = get_called_class();
        return new $parserClass(
            Parser::parseFromHyphen($identifierName),
            CaseFormat::HYPHEN
        );
    }
}

Create factory methods for DynamicIdentifiers


<?php
/**
 * Created by PhpStorm.
 * User: Catalin
 * Date: 03-Jun-17
 * Time: 13:59
 */

include ("../../BACK/conectare_db.php");

$username = $_SESSION["username"];
$stid = oci_parse($connection, 'SELECT LINK FROM player WHERE username = :username');
oci_bind_by_name($stid, ':username', $username);
oci_execute($stid);
$row = oci_fetch_array($stid, OCI_BOTH);
$link = $row[0];
oci_free_statement($stid);

if (strcmp($link,'k') == 0)
    echo '';
else
    echo '';

Add functionality for profile picture

Add functionality for profile picture


<?php

abstract class AlgorithmMM extends Algorithm {

    /**
     * Origianl graph
     *
     * @var Graph
     */
    protected $graph;

    /**
     * The given graph where the algorithm should operate on
     *
     * @param Graph $graph
     * @throws Exception if the given graph is not balanced
     */
    public function __construct(Graph $graph){
        $this->graph = $graph;
    }

    /**
     * Get the count of edges that are in the matchin
     *
     * @throws Exception
     * @return AlgorithmMCF $this (chainable)
     */
    public function getMatchingValue(){
        // TODO count the matching edges

        return null;
    }

    /**
     * create new resulting graph with minimum-cost flow on edges
     *
     * @throws Exception if the graph has not enough capacity for the minimum-cost flow
     * @return Graph
     */
    abstract public function createGraph();
}

<?php

abstract class AlgorithmMM extends Algorithm {

    /**
     * Origianl graph
     *
     * @var Graph
     */
    protected $graph;

    /**
     * The given graph where the algorithm should operate on
     *
     * @param Graph $graph
     * @throws Exception if the given graph is not balanced
     */
    public function __construct(Graph $graph){
        $this->graph = $graph;
    }

    /**
     * Get the count of edges that are in the match
     *
     * @throws Exception
     * @return AlgorithmMCF $this (chainable)
     * @uses AlgorithmMM::createGraph()
     * @uses Graph::getNumberOfEdges()
     */
    public function getNumberOfMatches(){
        return $this->createGraph()->getNumberOfEdges();
    }

    /**
     * create new resulting graph with minimum-cost flow on edges
     *
     * @throws Exception if the graph has not enough capacity for the minimum-cost flow
     * @return Graph
     */
    abstract public function createGraph();
}

Add helper method to count number of matches


    {{ Form::textarea('code', null, ['class' => 'editor mousetrap', 'wrap' => 'off']) }}

    Leave this field blank
    <input type="text" name="subject" id="subject">

    {{ Form::textarea('code', null, ['class' => 'editor mousetrap', 'wrap' => 'off']) }}
    <input type="text" name="subject" style="visibility:hidden;position:absolute;bottom:0;left:0;">

Drop js for subject field

Drop js for subject field


<?php

use Fhaculty\Graph\Algorithm\Balance as BalanceAlgorithm;
use Fhaculty\Graph\Graph;

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

        $alg = new BalanceAlgorithm($graph);

        $this->assertEquals(0, $alg->getBalance());
        $this->assertTrue($alg->isBalancedFlow());
    }

    public function testGraphSimple()
    {
        // source(+100) -> sink(-10)
        $graph = new Graph();
        $graph->createVertex('source')->setBalance(100);
        $graph->createVertex('sink')->setBalance(-10);

        $alg = new BalanceAlgorithm($graph);

        $this->assertEquals(90, $alg->getBalance());
        $this->assertFalse($alg->isBalancedFlow());
    }
}

Add tests with 100% code coverage for new Algorithm\Balance


<?php

namespace App\Controller;

use Silex\Api\ControllerProviderInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * Summary :
 *  -> __construct
 *  -> connect
 */
class BaseController implements ControllerProviderInterface
{
    public function __construct(\Freepius\Silex\Application $app)
    {
        $this->app = $app;
    }

    public function connect(\Silex\Application $app)
    {
        $ctrl = $app['controllers_factory'];

        $ctrl->get('/{year}-{month}-{day}', [$this, 'readText']);

        return $ctrl;
    }

    public function readText($year, $month, $day)
    {
        return $this->app->render('text.html.twig', [
            'article' => $this->app['afrikapieText']->findAndTransform($year, $month, $day)
        ]);
    }
}

Add a generic controller to read the Afrikapié texts


<?php

return [
    'mysql' => [
        'dbname' => 'test',
        'user' => 'root',
        'password' => '',
        'host' => 'localhost',
        'driver' => 'pdo_mysql',
    ],
    'sqlite' => [
        'memory' => true,
        'driver' => 'pdo_sqlite',
        'driverClass' => 'Mindy\QueryBuilder\Driver\SqliteDriver',
    ],
    'pgsql' => [
        'dbname' => 'test',
        'user' => 'root',
        'password' => '',
        'host' => 'localhost',
        'driver' => 'pdo_pgsql',
    ]
];

Allow to load file from fs

Allow to load file from fs


<?php

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

class DropBoardFromMembers extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		Schema::table('members', function($table)
		{
			$table->dropColumn('board');
		});
	}

	/**
	 * Reverse the migrations.
	 *
	 * @return void
	 */
	public function down()
	{
		Schema::table('members', function($table)
		{
			$table->boolean('board')->default(0)->after('active');
		});
	}

}

Remove boolean 'board' from members table as we use the member roles to define this now.


<?php

$title = "Boooobs in $controller";
$description = "Find all the boobs in " . ucwords($controller);

$css_files['header'][] = '/css/grids.css';
$css_files['header'][] = '/css/media-queries.css';
$css_files['header'][] = '/fonts/fontsaddict/Fontsaddict.css';
$css_files['header'][] = '//maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css';

$js_files['footer'][] = 'js/landing.js';

$view = $controller;

$search = new Search();
$search->set_max_items(100);

/**
 * Replace possible space replacements by '+' for the youtube search
 *
 * @param String $query
 *
 * @access private
 *
 * @return String
 */
function _sanitize_query($query) {
	$clean_query = str_replace('%20', '+', $query);
	$clean_query = str_replace('_', '+', $clean_query);
	$clean_query = str_replace('.', '+', $clean_query);
	return $clean_query;
}

Add a parent for the social controllers.


<?php
/**
 * @file
 */

namespace CultuurNet\UDB3\UiTID;

use ValueObjects\String\String;
use ValueObjects\Web\EmailAddress;

class CultureFeedUsers implements UsersInterface
{
    /**
     * @var \ICultureFeed
     */
    private $cultureFeed;

    /**
     * @param \ICultureFeed $cultureFeed
     */
    public function __construct(\ICultureFeed $cultureFeed)
    {
        $this->cultureFeed = $cultureFeed;
    }

    /**
     * @inheritdoc
     */
    public function byEmail(EmailAddress $email)
    {
        $query = new \CultureFeed_SearchUsersQuery();
        $query->mbox = $email->toNative();
        $query->mboxIncludePrivate = true;

        return $this->searchSingleUser($query);
    }

    /**
     * @param \CultureFeed_SearchUsersQuery $query
     * @return string|null
     */
    private function searchSingleUser(\CultureFeed_SearchUsersQuery $query)
    {
        /** @var \CultureFeed_ResultSet $results */
        $results = $this->cultureFeed->searchUsers($query);

        /** @var \CultureFeed_SearchUser $user */
        $user = reset($results->objects);

        if ($user) {
            return new String($user->id);
        }

        return;
    }

    /**
     * @inheritdoc
     */
    public function byNick(String $nick)
    {
        $query = new \CultureFeed_SearchUsersQuery();
        $query->nick = $nick->toNative();

        return $this->searchSingleUser($query);
    }
}

III-447: Add CultureFeed implementation of UsersInterface


<?php
if( !class_exists('gtk')) {
    die('Please load the php-gtk2 module in your php.ini' . "\r\n");
} elseif (!class_exists('GtkInfoBar')) {
    return;
}

class InfoBarBox extends GtkWindow
{
    protected $entry1;
    protected $entry2;

    protected $counter = 1;

    function __construct($parent = null)
    {
        parent::__construct();

        if (isset($GLOBALS['framework'])) {
            return;
        }

        if ($parent)
            $this->set_screen($parent->get_screen());
        else
            $this->connect_simple('destroy', array('gtk', 'main_quit'));

        $this->set_title(__CLASS__);
        $this->set_position(Gtk::WIN_POS_CENTER);
        $this->set_border_width(8);

        $this->add($this->__create_box());
        $this->show_all();
    }

    function create_error() {
        $this->messagelabel->set_text('This is an error message to show');
        $this->infobar->set_message_type(Gtk::MESSAGE_ERROR);
        $this->infobar->show_all();
    }

    function __create_box()
    {
        $this->infobar = new GtkInfoBar();
        $this->messagelabel = new GtkLabel('Default shows an Info message');
        $contentarea = $this->infobar->get_content_area();
        $contentarea->add($this->messagelabel);
        $this->infobar->add_button(GTK::STOCK_OK, GTK::RESPONSE_OK);
        $this->infobar->connect_simple('response', array($this->infobar, 'hide'));

        $vbox = new GtkVBox(false);
        $button = new GtkButton('_Create Error Message');
        $button->connect('clicked', array($this, 'create_error'));
        $vbox->pack_start($button, false, false, 0);
        $vbox->pack_start(new GtkHSeparator(), false, false, 0);
        $vbox->pack_start($this->infobar, false, false, 0);
        return $vbox;
    }
}

$GLOBALS['class']       = 'InfoBarBox';
$GLOBALS['description'] = 'Report important messages to the user';

if (!isset($GLOBALS['framework'])) {
    new InfoBarBox();
    Gtk::main();
}

?>

Add demo for new GtkInfoBar

Add demo for new GtkInfoBar


<?php

declare(strict_types=1);

namespace mcordingley\Regression;

use mcordingley\Regression\Linking\Identity;

final class Predictor
{
    private $coefficients;
    private $inputTransformer;
    private $outputTransformer;

    /**
     * __construct
     *
     * @param CoefficientSet $coefficients
     * @param OutputTransformer $outputTransformer
     * @param InputTransformer $inputTransformer
     */
    public function __construct(CoefficientSet $coefficients, OutputTransformer $outputTransformer = null, InputTransformer $inputTransformer = null)
    {
        $identity = new Identity;

        $this->coefficients = $coefficients;
        $this->outputTransformer = $outputTransformer ?: $identity;
        $this->inputTransformer = $inputTransformer ?: $identity;
    }

    /**
     * predict
     *
     * @param array $independent
     * @return float
     */
    public function predict(array $independent): float
    {
        $transformed = [1];

        foreach ($independent as $datum) {
            $transformed[] = $this->inputTransformer->linearize($datum);
        }

        $products = array_map(function ($predictor, $datum) {
            return $predictor * $datum;
        }, $this->coefficients, $transformed);

        return $this->outputTransformer->delinearize(array_sum($products));
    }
}

Create a class to do the work of prediction.


<?php
//Lifted versions of the arithmetic operators.
//For doing arithemtic in the maybe monad.

include_once('maybe.php');

function add($a, $b) {
	return Maybe::just($a + $b);
}
function sub($a, $b) {
	return Maybe::just($a - $b);
}
function mul($a, $b) {
	return Maybe::just($a * $b);
}
function div($a, $b) {
	if($b === 0) {
		return Maybe::error("Evaluation error: Division by zero");
	} else {
		return Maybe::just($a / $b);
	}
}
function expo($a, $b) {
	return Maybe::just(pow($a, $b));
}
?>

Rename andfunc.php to arithemtic.php it now uses the maybe monadd)


<?php

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

   Copyright (C) 2009 Free Software Foundation, Inc

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

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

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

*/

require_once('database.php');
require_once('templating.php');
require_once('data/Album.php');

$artist = new Artist($_GET['artist']);

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

if (isset($_POST['submit'])) {

	if (empty($_POST['name'])) {
		$errors[] = 'An album name must be specified.';
	}

	if (empty($_POST['image'])) {
		$image = '';
	} elseif (!preg_match('/^[a-z0-9\+\.\-]+\:/i', $_POST['image'])) {
		$errors[] = 'Cover image must be a valid URL';
	} elseif (preg_match('/\s/', $_POST['homepage'])) {
		$errors[] = 'Cover image must be a URL, as such it cannot contain whitespace.';
	} else {
		$image = $_POST['image'];
	}

	if($errors) {
		$smarty->assign('errors', $errors);
		$smarty->assign('image', $image);
		$smarty->assign('name', $_POST['name']);
	} else {
		// If the creation was successful send the user back to the view page
		$album = Album::create($_POST['name'], $artist->name, $image);
		header('Location: ' . $album->getURL());
	}
}
$smarty->display('album-add.tpl');

?>

Make it possible for admins and artist managers to create new albums


<?php

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

use Ob\Hex\Domain\Email;
use Ob\Hex\Domain\MeetingRoom;
use Ob\Hex\Domain\Reservation;

// Create a meeting room with capacity for 10 people
$room = MeetingRoom::create(10, 180);

// Make a reservation at noon
$room->makeReservation(new Reservation(
    new DateTimeImmutable('today 12:00'),
    new DateTimeImmutable('today 13:00'),
    new Email('foo@bar.com')
));

// Plan a second reservation at 2 o'clock
$reservation = new Reservation(
    new DateTimeImmutable('today 14:00'),
    new DateTimeImmutable('today 16:15'),
    new Email('foo@bar.com')
);
// Invite 3 employees to the meeting
$reservation->invite(new Email('bar@bar.com'));
$reservation->invite(new Email('baz@bar.com'));
$reservation->invite(new Email('qux@bar.com'));
// Uninvite the last invitee
$reservation->uninvite(new Email('qux@bar.com'));
// Make the reservation
$room->makeReservation($reservation);

// Render the schedule
echo $room->renderScheduleWith(new \Ob\Hex\Application\PlainTextScheduleRenderer()) . PHP_EOL;

// Create an in-memory event store
$store = new \Ob\Hex\EventSourcing\Storage\MemoryStore();
// Persist the room schedule (the events)
$store->write(1, $room->getEvents());

// "Hydrate" the room from the event store
$storedRoom = MeetingRoom::createFromEvents($store->read(1));

// Render the schedule again, it should be identical
echo $room->renderScheduleWith(new \Ob\Hex\Application\PlainTextScheduleRenderer());

Add an event store usage example

Add an event store usage example


<?php

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

class CreateTriosTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('trios', function (Blueprint $table) {
            $table->increments('id');
            $table->string('sentence1');
            $table->string('sentence2');
            $table->string('sentence3');
            $table->string('explanation1');
            $table->string('explanation2');
            $table->string('explanation3');
            $table->string('answer');
            $table->timestamps();
        });
    }

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

Add database migration for trios table.

Add database migration for trios table.


<?php

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

class m150108_131628_modify_group_table extends Migration
{
    public function up()
    {
    	$this->addColumn('{{%group}}', 'study_form_id', Schema::TYPE_INTEGER . ' AFTER `specialty_id`');

        $this->addForeignKey('FK_group_study_form', '{{%group}}', 'study_form_id', '{{%study_form}}', 'id', 'RESTRICT', 'RESTRICT');
    }

    public function down()
    {
        $this->dropForeignKey('FK_group_study_form', '{{%group}}');

        $this->dropColumn('{{%goup}}', 'study_form_id');
    }

}

Add migration to link Group entity with StudyForm entity


<?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.
 */

/**
 * This is the engine displacement extractor test class.
 *
 * @author Fábio Santos <ffsantos92@gmail.com>
 */
class EngineDisplacementExtractorTest extends AbstractVehicleExtractorTest
{
    public function testExtractEngineDisplacement()
    {
        $text = '120 cc';
        $this->assertEquals(120, $this->extractor->engDispl($text));

        $text = '121cc';
        $this->assertEquals(121, $this->extractor->engDispl($text));

        $text = '122 cm3';
        $this->assertEquals(122, $this->extractor->engDispl($text));

        $text = '123 cm³';
        $this->assertEquals(123, $this->extractor->engDispl($text));
    }
}

Add engine displacement extractor test

Add engine displacement extractor test


<?php
header("Content-Security-Policy: script-src 'unsafe-inline' 'nonce-sXXD/nluT6AqhuVwL0IJqA=='");
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sample of CSP nonce-source</title>
</head>
<body>

<script type="text/javascript" nonce="sXXD/nluT6AqhuVwL0IJqA==">
    alert('This works!');
</script>

<script type="text/javascript">
    alert('This does not work!');
</script>

</body>
</html>

Add sample with both unsafe-inline and nonce


<?php
$input  = array("php", 4.0, array("green", "red"));
$reversed = array_reverse($input);
$preserved = array_reverse($input, true);

print_r($input);
print_r($reversed);
print_r($preserved);
?>

Return an array with elements in reverse order


<?php

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

namespace Symfony\Component\HttpClient\Tests;

use Symfony\Contracts\HttpClient\Test\HttpClientTestCase as BaseHttpClientTestCase;

abstract class HttpClientTestCase extends BaseHttpClientTestCase
{
    public function testToStream()
    {
        $client = $this->getHttpClient(__FUNCTION__);

        $response = $client->request('GET', 'http://localhost:8057');

        $stream = $response->toStream();

        $this->assertSame("{\n    \"SER", fread($stream, 10));
        $this->assertSame('VER_PROTOCOL', fread($stream, 12));
        $this->assertFalse(feof($stream));
        $this->assertTrue(rewind($stream));

        $this->assertInternalType('array', json_decode(fread($stream, 1024), true));
        $this->assertSame('', fread($stream, 1));
        $this->assertTrue(feof($stream));
    }
}

<?php

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

namespace Symfony\Component\HttpClient\Tests;

use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait;
use Symfony\Contracts\HttpClient\Test\HttpClientTestCase as BaseHttpClientTestCase;

abstract class HttpClientTestCase extends BaseHttpClientTestCase
{
    use ForwardCompatTestTrait;

    public function testToStream()
    {
        $client = $this->getHttpClient(__FUNCTION__);

        $response = $client->request('GET', 'http://localhost:8057');

        $stream = $response->toStream();

        $this->assertSame("{\n    \"SER", fread($stream, 10));
        $this->assertSame('VER_PROTOCOL', fread($stream, 12));
        $this->assertFalse(feof($stream));
        $this->assertTrue(rewind($stream));

        $this->assertIsArray(json_decode(fread($stream, 1024), true));
        $this->assertSame('', fread($stream, 1));
        $this->assertTrue(feof($stream));
    }
}

Fix assertInternalType deprecation in phpunit 9


<?php

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

class m141216_153407_create_specialty_table extends Migration
{
    public function up()
    {
        $tableOptions = null;
        if ($this->db->driverName === 'mysql') {
            // http://stackoverflow.com/questions/766809/whats-the-difference-between-utf8-general-ci-and-utf8-unicode-ci
            $tableOptions = 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB';
        }

        $this->createTable('{{%specialty}}', [
            'id' => Schema::TYPE_PK,
            'name' => Schema::TYPE_STRING . ' NOT NULL',
            'faculty_id' => Schema::TYPE_INTEGER . ' NOT NULL',
            'study_cycle_id' => Schema::TYPE_INTEGER . ' NOT NULL',
        ], $tableOptions);

        $this->addForeignKey('FK_specialty_faculty', '{{%specialty}}', 'faculty_id', '{{%faculty}}', 'id', 'RESTRICT', 'RESTRICT');
        $this->addForeignKey('FK_specialty_study_cycle', '{{%specialty}}', 'study_cycle_id', '{{%study_cycle}}', 'id', 'RESTRICT', 'RESTRICT');
    }

    public function down()
    {
        $this->dropForeignKey('FK_specialty_faculty', '{{%specialty}}');
        $this->dropForeignKey('FK_specialty_study_cycle', '{{%specialty}}');

        $this->dropTable('{{%specialty}}');
    }
}

Add migration for Specialty entity

Add migration for Specialty entity


<?php
namespace Psalm\Tests;

use PhpParser\ParserFactory;
use PHPUnit_Framework_TestCase;
use Psalm\Checker\FileChecker;
use Psalm\Config;
use Psalm\Context;

class Php71Test extends PHPUnit_Framework_TestCase
{
    protected static $parser;

    public static function setUpBeforeClass()
    {
        self::$parser = (new ParserFactory)->create(ParserFactory::PREFER_PHP7);

        $config = Config::getInstance();
        $config->throw_exception = true;
        $config->use_docblock_types = true;
    }

    public function setUp()
    {
        FileChecker::clearCache();
    }

    public function testNullableReturnType()
    {
        $stmts = self::$parser->parse('<?php
        function a(): ?string
        {
            return rand(0, 10) ? "elePHPant" : null;
        }

        $a = a();
        ');

        $file_checker = new FileChecker('somefile.php', $stmts);
        $context = new Context('somefile.php');
        $file_checker->check(true, true, $context);
        $this->assertEquals('string|null', (string) $context->vars_in_scope['$a']);
    }

    public function testNullableArgument()
    {
        $stmts = self::$parser->parse('<?php
        function test(?string $name) : ?string
        {
            return $name;
        }

        test("elePHPant");
        test(null);
        ');

        $file_checker = new FileChecker('somefile.php', $stmts);
        $context = new Context('somefile.php');
        $file_checker->check(true, true, $context);
    }
}

Add test for PHP 7.1 nullable types

Add test for PHP 7.1 nullable types


<?php

namespace Test\Bee4\UserAgent\Classifier\Bots;

use Bee4\UserAgent\Classifier\Bots\AbstractTaggedBot;

/**
 * Class AbstractBotTest
 * @package Test\Bee4\UserAgent\Classifier\Bots
 */
class AbstractTaggedBotTest extends \PHPUnit_Framework_TestCase
{
	/**
	 * @var AbstractTaggedBot
	 */
	protected $object;

	/**
	 * Sets up the fixture, for example, opens a network connection.
	 * This method is called before a test is executed.
	 */
	protected function setUp()
	{
		$this->object = $this
			->getMockBuilder('\Bee4\UserAgent\Classifier\Bots\AbstractTaggedBot')
			->setMethods(null)
	    ->setMockClassName('FakeTaggedBot')
	    ->getMock();
	}

	public function testTags()
	{
		$this->assertNull($this->object->getTags());

		$tags = ['tag1'];
		$this->object->addTags($tags);
		$this->assertEquals($tags, $this->object->getTags());

		$tags = ['tag1', 'tag2', 'tag3'];
		$this->object->addTags($tags);
		var_dump($this->object->getTags());
		$this->assertEquals($tags, $this->object->getTags());
	}
}

Add test for tagged bots

Add test for tagged bots

Signed-off-by: Stéphane HULARD <a24f38cb8c57ec2778c80a9f0c151933508927e5@chstudio.fr>


<?php

use Aedart\Scaffold\Traits\TaskRunner as TaskRunnerTrait;
use Aedart\Testing\Laravel\TestCases\unit\GetterSetterTraitTestCase;
use Mockery as m;

/**
 * Class TaskRunnerTraitTest
 *
 * @group traits
 * @group taskRunner
 *
 * @coversDefaultClass Aedart\Scaffold\Traits\TaskRunner
 * @author Alin Eugen Deac <aedart@gmail.com>
 */
class TaskRunnerTraitTest extends GetterSetterTraitTestCase
{

    use TaskRunnerUtils;

    /**
     * Returns the class path to the trait in question
     *
     * @return string
     */
    public function getTraitClassPath()
    {
        return TaskRunnerTrait::class;
    }

    /**
     * Returns the name of the property, which the given
     * trait has implemented its getter and setter methods
     *
     * @return string
     */
    public function propertyName()
    {
        return 'taskRunner';
    }

    /***********************************************************
     * Actual tests
     **********************************************************/

    /**
     * @test
     *
     * @covers ::setTaskRunner
     * @covers ::getTaskRunner
     * @covers ::hasTaskRunner
     * @covers ::hasDefaultTaskRunner
     * @covers ::getDefaultTaskRunner
     */
    public function taskRunnerTraitMethods(){
        $this->assertGetterSetterTraitMethods($this->makeConsoleTaskRunnerMock(), null);
    }
}

Add test for Task Runner trait

Add test for Task Runner trait


<?php
/*
 * (c) webfactory GmbH <info@webfactory.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Webfactory\Bundle\LegacyIntegrationBundle\Integration;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\HttpKernelInterface;

class BootstrapFileKernelAdaptor implements HttpKernelInterface
{

    protected $file;

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

    public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true)
    {
        $file = $this->file;
        return LegacyCaptureResponseFactory::create(function () use ($file, $request) {
            include($file);
        });
    }
}

<?php
/*
 * (c) webfactory GmbH <info@webfactory.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Webfactory\Bundle\LegacyIntegrationBundle\Integration;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\HttpKernelInterface;

class BootstrapFileKernelAdaptor implements HttpKernelInterface
{

    protected $file;

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

    public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true)
    {
        $file = $this->file;
        return LegacyCaptureResponseFactory::create(function () use ($file, $request) {
            return include($file);
        });
    }
}

Fix that HTTP status code was not passed on

The bootstrap file is supposed to return the HTTP status code to send to the browser, because `http_response_code()` is only available as of PHP 5.4.

This return value was not passed on from the anonymous function to the ResponseFactory.


<?php
namespace Czim\FileHandling\Test\Unit\Variant\Strategies;

use Czim\FileHandling\Contracts\Storage\ProcessableFileInterface;
use Czim\FileHandling\Support\Image\Optimizer;
use Czim\FileHandling\Test\TestCase;
use Czim\FileHandling\Variant\Strategies\ImageOptimizationStrategy;
use Mockery;

class ImageOptimizationStrategyTest extends TestCase
{

    /**
     * @test
     * @expectedException \Czim\FileHandling\Exceptions\VariantStrategyShouldNotBeAppliedException
     */
    function it_should_throw_an_exception_if_it_is_applied_to_a_non_image()
    {
        /** @var Mockery\MockInterface|Optimizer $optimizer */
        $optimizer = Mockery::mock(Optimizer::class);

        $strategy = new ImageOptimizationStrategy($optimizer);

        /** @var Mockery\MockInterface|ProcessableFileInterface $file */
        $file = Mockery::mock(ProcessableFileInterface::class);
        $file->shouldReceive('mimeType')->andReturn('text/plain');

        $strategy->apply($file);
    }

    /**
     * @test
     */
    function it_optimizes_an_image()
    {
        /** @var Mockery\MockInterface|Optimizer $optimizer */
        $optimizer = Mockery::mock(Optimizer::class);

        /** @var Mockery\MockInterface|ProcessableFileInterface $file */
        $file = Mockery::mock(ProcessableFileInterface::class);
        $file->shouldReceive('mimeType')->andReturn('image/jpeg');
        $file->shouldReceive('path')->andReturn('tmp/test.jpg');

        $options = ['test' => true];

        $optimizer->shouldReceive('optimize')
            ->once()
            ->with(Mockery::type(\SplFileInfo::class), $options)
            ->andReturn(true);

        $strategy = new ImageOptimizationStrategy($optimizer);
        $strategy->setOptions($options);

        static::assertSame($file, $strategy->apply($file));
    }

}

Add test for image optimization strategy


<?php namespace Aedart\Scaffold\Templates;

use Aedart\DTO\DataTransferObject;
use Aedart\Model\Traits\Strings\IdTrait;
use Aedart\Model\Traits\Strings\SourceTrait;
use Aedart\Scaffold\Contracts\Templates\Template as TemplateInterface;
use Aedart\Scaffold\Traits\Destination;

/**
 * Template
 *
 * @see \Aedart\Scaffold\Contracts\Templates\Template
 *
 * @author Alin Eugen Deac <aedart@gmail.com>
 * @package Aedart\Scaffold\Templates
 */
class Template extends DataTransferObject implements TemplateInterface
{
    use IdTrait;
    use SourceTrait;
    use Destination;
}

Add concrete implementation of template

Add concrete implementation of template


<?php

class m160614_085916_patient_is_deceased_flag extends OEMigration
{
	public function up()
	{
		$this->addColumn('patient', 'is_deceased', 'tinyint not null default 0');
		$this->addColumn('patient_version', 'is_deceased', 'tinyint not null default 0');

		$this->update('patient', array('is_deceased' => 1), 'date_of_death IS NOT NULL');
	}

	public function down()
	{
		$this->dropColumn('patient_version', 'is_deceased');
		$this->dropColumn('patient', 'is_deceased');
	}

}

Add migration to create is_deceased flag


<?php

namespace mageekguy\atoum;

use
	mageekguy\atoum,
	mageekguy\atoum\scripts\phar
;

if (extension_loaded('phar') === false)
{
	throw new \runtimeException('Phar extension is mandatory to use this PHAR');
}

define(__NAMESPACE__ . '\phar\name', 'mageekguy.atoum.phar');

\phar::mapPhar(atoum\phar\name);

$versions = unserialize(file_get_contents('phar://' . atoum\phar\name . '/versions'));

require_once 'phar://' . atoum\phar\name . '/' . $versions['current'] . '/classes/autoloader.php';

if (defined(__NAMESPACE__ . '\autorun') === false)
{
	define(__NAMESPACE__ . '\autorun', true);

	phar\stub::autorun(__FILE__);
}

__HALT_COMPILER();

<?php

namespace mageekguy\atoum;

use
	mageekguy\atoum,
	mageekguy\atoum\scripts\phar
;

if (extension_loaded('phar') === false)
{
	throw new \runtimeException('Phar extension is mandatory to use this PHAR');
}

define(__NAMESPACE__ . '\phar\name', 'mageekguy.atoum.phar');

\phar::mapPhar(atoum\phar\name);

$versions = unserialize(file_get_contents('phar://' . atoum\phar\name . '/versions'));

require_once 'phar://' . atoum\phar\name . '/' . $versions['current'] . '/classes/autoloader.php';

if (defined(__NAMESPACE__ . '\scripts\runner') === false)
{
	define(__NAMESPACE__ . '\scripts\runner', __FILE__);
}

if (phar\stub::autorunIsEnabled() === false)
{
	phar\stub::enableAutorun(constant(__NAMESPACE__ . '\scripts\runner'));
}

__HALT_COMPILER();

Remove bug in autorunner management in PHAR.


<?php

namespace Oro\Bundle\UserBundle\Command;

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

use Oro\Bundle\UserBundle\Entity\User;

class ListUserCommand extends ContainerAwareCommand
{
    /**
     * {@inheritdoc}
     */
    protected function configure()
    {
        $this
            ->setName('oro:user:list')
            ->setDescription('Create user.')
            ->addOption('all', 'a', InputOption::VALUE_NONE, 'Also list inactive users')
            ->addOption('limit', 'l', InputOption::VALUE_REQUIRED, 'Limit the result set', 20)
            ->addOption('page', 'p', InputOption::VALUE_REQUIRED, 'Page of the result set', 1)
            ->addOption(
                'roles',
                'r',
                InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY,
                'Filter by roles (ANY)',
                []
            )
        ;
    }

    /**
     * {@inheritdoc}
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $offset = ($input->getOption('page') - 1) * $input->getOption('limit');

        $builder = $this
            ->getContainer()
            ->get('doctrine')
            ->getManager()
            ->getRepository('OroUserBundle:User')
            ->createQueryBuilder('u')
            ->orderBy('u.id', 'ASC')
            ->setMaxResults($input->getOption('limit'))
            ->setFirstResult($offset);

        if (!$input->getOption('all')) {
            $builder
                ->andWhere('u.enabled = :enabled')
                ->setParameter('enabled', true);
        }

        if (!empty($input->getOption('roles'))) {
            $builder
                ->leftJoin('u.roles', 'r')
                ->andWhere('r.label IN (:roles)')
                ->setParameter('roles', $input->getOption('roles'));
        }

        $table = new Table($output);
        $table
            ->setHeaders(['ID', 'Username', 'Status', 'First Name', 'Last Name', 'Roles'])
            ->setRows(array_map([$this, 'getUserRow'], $builder->getQuery()->getResult()))
            ->render()
        ;
    }

    /**
     * @param  User   $user
     * @return array
     */
    protected function getUserRow(User $user)
    {
        return [
            $user->getId(),
            $user->getUsername(),
            $user->isEnabled() ? 'Active' : 'Inactive',
            $user->getFirstName(),
            $user->getLastName(),
            implode(', ', $user->getRoles())
        ];
    }
}

BAP-10780: Access to the application on behalf of the user

- add oro:user:list command


<?php
$transport = array('foot', 'bike', 'car', 'plane');
$mode = current($transport); // $mode = 'foot';
$mode = next($transport);    // $mode = 'bike';
$mode = next($transport);    // $mode = 'car';
$mode = prev($transport);    // $mode = 'bike';
$mode = end($transport);     // $mode = 'plane';
?>

Advance the internal array pointer of an array


<?php

namespace Zend\I18n\View;

use IntlDateFormatter;

// @codingStandardsIgnoreStart
/**
 * Trait HelperTrait
 *
 * The trait provides convenience methods for view helpers,
 * defined by the zend-i18n component. It is designed to be used
 * for type-hinting $this variable inside zend-view templates via doc blocks.
 *
 * The base class is PhpRenderer, followed by the helper trait from
 * the zend-i18n component. However, multiple helper traits from different
 * Zend components can be chained afterwards.
 *
 * @example @var \Zend\View\Renderer\PhpRenderer|\Zend\I18n\View\HelperTrait $this
 *
 * @method string currencyFormat($number, $currencyCode = null, $showDecimals = null, $locale = null, $pattern = null)
 * @method string dateFormat($date, $dateType = IntlDateFormatter::NONE, $timeType = IntlDateFormatter::NONE, $locale = null, $pattern = null)
 * @method string numberFormat($number, $formatStyle = null, $formatType = null, $locale = null, $decimals = null, array $textAttributes = null)
 * @method string plural($strings, $number)
 * @method string translate($message, $textDomain = null, $locale = null)
 * @method string translatePlural($singular, $plural, $number, $textDomain = null, $locale = null)
 */
trait HelperTrait
{
}

Add helper trait to provide type-hinting for zend-view


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>First Steps Into PHP</title>
</head>

<body>
<form>
    N: <input type="text" name="num" />
    <input type="submit" />
</form>

<?php
if (isset($_GET['num'])) {
    $n = intval($_GET['num']);
    echo $n * 2;
}
?>
</body>
</html>

Create Multiply A Number By Two

Create Multiply A Number By Two


<?php

namespace Tests\PHPExif\Common\Collection;

use Mockery as m;
use PHPExif\Common\Collection\AbstractCollection;

/**
 * Class: AbstractCollectionTest
 *
 * @see \PHPUnit_Framework_TestCase
 * @abstract
 * @coversDefaultClass \PHPExif\Common\Collection\AbstractCollection
 * @covers ::<!public>
 */
class AbstractCollectionTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @covers ::__construct
     * @group collection
     *
     * @return void
     */
    public function testConstructorAddsElementsFromParameter()
    {
        $input = array(
            'foo' => 'bar',
            'baz' => 'quux',
        );
        $ctr = array(
            'key' => 0,
            'value' => 0,
        );

        $checker = function ($type) use ($input, &$ctr) {
            return function ($arg) use ($input, $type, &$ctr) {
                $result = false;

                $data = null;
                if ($type === 'key') {
                    $data = array_keys($input);
                } else {
                    $data = array_values($input);
                }

                if ($arg === $data[$ctr[$type]]) {
                    $result = true;
                }

                $ctr[$type]++;

                return $result;
            };
        };

        $mock = m::mock(
            AbstractCollection::class
        )->shouldDeferMissing();
        $mock->shouldReceive('add')
            ->with(
                m::on(
                    $checker('key')
                ),
                m::on(
                    $checker('value')
                )
            )
            ->andReturnNull();

        $mock->__construct($input);

        $this->assertEquals(
            count($input),
            $ctr['key']
        );
        $this->assertEquals(
            count($input),
            $ctr['value']
        );
    }
}

Add constructor test for AbstractCollection

Signed-off-by: Tom Van Herreweghe <96835dd8bfa718bd6447ccc87af89ae1675daeca@theanalogguy.be>


<?php

use Fhaculty\Graph\Algorithm\Loop as AlgorithmLoop;
use Fhaculty\Graph\Graph;

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

        $alg = new AlgorithmLoop($graph);

        $this->assertFalse($alg->hasLoop());
    }

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

        $alg = new AlgorithmLoop($graph);

        $this->assertFalse($alg->hasLoop());
        $this->assertFalse($alg->hasLoopVertex($v1));
        $this->assertFalse($alg->hasLoopVertex($v2));
    }

    public function testGraphUndirectedLoop()
    {
        // 1 -- 1
        $graph = new Graph();
        $graph->createVertex(1)->createEdge($v1 = $graph->getVertex(1));

        $alg = new AlgorithmLoop($graph);

        $this->assertTrue($alg->hasLoop());
        $this->assertTrue($alg->hasLoopVertex($v1));
    }

    public function testGraphDirectedLoop()
    {
        // 1 -> 1
        $graph = new Graph();
        $graph->createVertex(1)->createEdgeTo($v1 = $graph->getVertex(1));

        $alg = new AlgorithmLoop($graph);

        $this->assertTrue($alg->hasLoop());
        $this->assertTrue($alg->hasLoopVertex($v1));
    }
}

Add tests with 100% coverage for new Algorithm\Loop


<?php
namespace Mongolid\Tests\Integration;

use MongoDB\BSON\ObjectId;
use MongoDB\Driver\WriteResult;
use Mongolid\Query\BulkWrite;
use Mongolid\Tests\Stubs\ReferencedUser;

class BulkWriteTest extends IntegrationTestCase
{
    public function testShouldRunMultipleUpdateOperations()
    {
        $bob = $this->createUser('Bob');
        $john = $this->createUser('John');
        $mary = $this->createUser('Mary');

        $bulkWrite = new BulkWrite(new ReferencedUser());

        $bulkWrite->updateOne(
            ['_id' => $bob->_id],
            ['name' => 'Bulk Updated Bob!']
        );
        $bulkWrite->updateOne(
            ['_id' => $john->_id],
            ['name' => 'Bulk Updated John!']
        );
        $bulkWrite->updateOne(
            ['_id' => $mary->_id],
            ['name' => 'Bulk Updated Mary!']
        );
        $bulkWrite->updateOne(
            ['_id' => $bob->_id],
            ['delete_this' => ''],
            [],
            '$unset'
        );
        $bulkWrite->updateOne(
            ['_id' => $john->_id],
            ['delete_this' => ''],
            [],
            '$unset'
        );
        $bulkWrite->updateOne(
            ['_id' => $mary->_id],
            ['delete_this' => ''],
            [],
            '$unset'
        );

        // Before running
        $this->assertSame('Bob', $bob->name);
        $this->assertSame('John', $john->name);
        $this->assertSame('Mary', $mary->name);

        $this->assertSame('xxxxx', $bob->delete_this);
        $this->assertSame('xxxxx', $john->delete_this);
        $this->assertSame('xxxxx', $mary->delete_this);

        // Runs it
        $result = $bulkWrite->execute();

        $this->assertInstanceOf(WriteResult::class, $result);

        // Refresh models
        $bob = $bob->first($bob->_id);
        $john = $john->first($john->_id);
        $mary = $mary->first($mary->_id);

        // After running
        $this->assertSame('Bulk Updated Bob!', $bob->name);
        $this->assertSame('Bulk Updated John!', $john->name);
        $this->assertSame('Bulk Updated Mary!', $mary->name);

        $this->assertNull($bob->delete_this);
        $this->assertNull($john->delete_this);
        $this->assertNull($mary->delete_this);
    }

    private function createUser(string $name): ReferencedUser
    {
        $user = new ReferencedUser();
        $user->_id = new ObjectId();
        $user->name = $name;
        $user->delete_this = 'xxxxx';
        $this->assertTrue($user->save());

        return $user;
    }
}

Add integration test for BulkWrite

Add integration test for BulkWrite


<?php

namespace Roots\Soil\JqueryCDN;

/**
 * Load jQuery from Google's CDN with a local fallback
 *
 * You can enable/disable this feature in functions.php (or lib/config.php if you're using Sage):
 * add_theme_support('soil-jquery-cdn');
 */
function register_jquery() {
  if (!is_admin()) {
    $jquery_version = $GLOBALS['wp_scripts']->registered['jquery']->ver;

    wp_deregister_script('jquery');

    wp_register_script(
      'jquery',
      '//ajax.googleapis.com/ajax/libs/jquery/' . $jquery_version . '/jquery.min.js',
      array(),
      null,
      true
    );

    add_filter('script_loader_src', __NAMESPACE__ . '\\jquery_local_fallback', 10, 2);
  }
}
add_action('wp_enqueue_scripts', __NAMESPACE__ . '\\register_jquery');

/**
 * Output the local fallback immediately after jQuery's <script>
 *
 * @link http://wordpress.stackexchange.com/a/12450
 */
function jquery_local_fallback($src, $handle = null) {
  static $add_jquery_fallback = false;

  if ($add_jquery_fallback) {
    echo '<script>window.jQuery || document.write(\'<script src="' . $add_jquery_fallback .'"><\/script>\')</script>' . "\n";
    $add_jquery_fallback = false;
  }

  if ($handle === 'jquery') {
    $add_jquery_fallback = apply_filters('script_loader_src', \includes_url('/js/jquery/jquery.js'), 'jquery-fallback');
  }

  return $src;
}
add_action('wp_head', __NAMESPACE__ . '\\jquery_local_fallback');


<?php

namespace Turanct\Shack;

final class String implements Sha
{
    /**
     * @var string The sha string
     */
    private $string;

    /**
     * Constructor
     *
     * @param string $string The sha string
     */
    public function __construct($string)
    {
        $this->string = (string) $string;
    }

    /**
     * Get the current sha hash
     *
     * @return string The current sha
     */
    public function get()
    {
        return $this->string;
    }
}

Enable using a simple string as a sha hash


<?php
/*Plugin Name: Create Custom Taxonomy for Tips
Description: This plugin registers the 'topics' custom taxonomy.
Version: 1.0
License: GPLv2
*/

// Register Custom Taxonomy
function tip_topic_taxonomy() {

	$labels = array(
		'name'                       => _x( 'Topics', 'Taxonomy General Name', 'text_domain' ),
		'singular_name'              => _x( 'Topic', 'Taxonomy Singular Name', 'text_domain' ),
		'menu_name'                  => __( 'Topic', 'text_domain' ),
		'all_items'                  => __( 'All Topics', 'text_domain' ),
		'parent_item'                => __( 'Parent Topic', 'text_domain' ),
		'parent_item_colon'          => __( 'Parent Topic:', 'text_domain' ),
		'new_item_name'              => __( 'New Topic Name', 'text_domain' ),
		'add_new_item'               => __( 'Add New Topic', 'text_domain' ),
		'edit_item'                  => __( 'Edit Topic', 'text_domain' ),
		'update_item'                => __( 'Update Topic', 'text_domain' ),
		'view_item'                  => __( 'View Topic', 'text_domain' ),
		'separate_items_with_commas' => __( 'Separate topics with commas', 'text_domain' ),
		'add_or_remove_items'        => __( 'Add or remove topics', 'text_domain' ),
		'choose_from_most_used'      => __( 'Choose from the most used topics', 'text_domain' ),
		'popular_items'              => __( 'Popular Items', 'text_domain' ),
		'search_items'               => __( 'Search topics', 'text_domain' ),
		'not_found'                  => __( 'Not Found', 'text_domain' ),
		'no_terms'                   => __( 'No items', 'text_domain' ),
		'items_list'                 => __( 'Items list', 'text_domain' ),
		'items_list_navigation'      => __( 'Items list navigation', 'text_domain' ),
	);
	$args = array(
		'labels'                     => $labels,
		'hierarchical'               => false,
		'public'                     => true,
		'show_ui'                    => true,
		'show_admin_column'          => true,
		'show_in_nav_menus'          => true,
		'show_tagcloud'              => true,
		'show_in_rest'               => true,
	);
	register_taxonomy( 'topic', array( 'tips' ), $args );

}
add_action( 'init', 'tip_topic_taxonomy', 0 );

?>

Add plugin for creating 'topics' custom taxonomy for


<?php

namespace BlizzardGalaxy\ApiSupervisor\Exception;

/**
 * Class RegionException
 *
 * @package BlizzardGalaxy\ApiSupervisor\Exception
 * @author  Petre Pătrașc <petre@dreamlabs.ro>
 */
class RegionException extends \Exception
{
    public function __construct($message = "The region that you have specified is not defined.")
    {
        parent::__construct($message);
    }
}

Add custom exception when a Region has not been set to a valid value


<?php

namespace mcordingley\Regression\Linking;

class Logistic implements LinkingInterface
{
    public function delinearize($value)
    {
        return 1.0 / (1.0 + exp(-$value));
    }

    public function linearize($value)
    {
        return -log(1.0 / $value - 1);
    }
}

Add the logistic function as a linking function.


<?php

function isJson($filename) {
    $string = file_get_contents($filename);
    json_decode($string);
    return (json_last_error() == JSON_ERROR_NONE);
}

function translationFilename($filename) {
    $filearr = explode('/', $filename);
    end($filearr);
    return prev($filearr).'/'.next($filearr);
}

$translation_files = glob(__DIR__.'/../lang/*/*.json');
$valid_files = array();
$invalid_files = array();

foreach ( $translation_files as $filename ) {
    $shortname = translationFilename($filename);
    // Validate
    if ( isJson($filename) ) {
        $valid_files[] = $shortname;
    } else {
        $invalid_files[] = $shortname;
    }
}

$result = array(
    'invalid_files' => $invalid_files,
    'valid_files'   => $valid_files,
);

var_dump($result);
// echo json_encode($result);

<?php

function isJson($filename) {
    $string = file_get_contents($filename);
    json_decode($string);
    return (json_last_error() == JSON_ERROR_NONE);
}

function translationFilename($filename) {
    $filearr = explode('lang', $filename);
    end($filearr);
    return current($filearr);
}

function globRecursive($Pattern, $Flags = 0) {
    // Search in the Current Directory
    $Return = glob($Pattern, $Flags);
    // FOREACHDIRECTORY
    // Search in ALL sub-directories.
    foreach (glob(dirname($Pattern).'/*', GLOB_ONLYDIR | GLOB_NOSORT) as $Directory) {
        // This is a recursive function.
        // Usually, THIS IS VERY BAD.
        // For searching recursively however,
        // it does make some sense.
        if ( strpos($Directory, '/_') === false ) {
            $Return = array_merge($Return, globRecursive($Directory.'/'.basename($Pattern), $Flags));
        }
    } // FOREACHDIRECTORY
    return $Return;
}

$translation_files = globRecursive(__DIR__.'/../lang/*/*.json');
$valid_files = array();
$invalid_files = array();

foreach ( $translation_files as $filename ) {
    $shortname = translationFilename($filename);
    // Validate
    if ( isJson($filename) ) {
        $valid_files[] = $shortname;
    } else {
        $invalid_files[] = $shortname;
    }
}

$result = array(
    'invalid_files' => $invalid_files,
    'valid_files'   => $valid_files,
);

var_dump($result);
// echo json_encode($result);

Fix Translation Checker for Recursive folders


<?php

class HighlightUtilitiesTest extends PHPUnit_Framework_TestCase
{
    /** @var \Highlight\Highlighter */
    private $hl;

    protected function setUp()
    {
        $this->hl = new \Highlight\Highlighter();
    }

    public function testSplitCodeIntoArray_MultilineComment()
    {
        $raw = <<<PHP
/**
 * Hello World
 *
 * @api
 * @since 1.0.0
 * @param string \$str Some string parameter
 */
PHP;
        $highlighted = $this->hl->highlight('php', $raw);

        $cleanSplit = \HighlightUtilities\splitCodeIntoArray($highlighted->value);
        $dumbSplit = preg_split('/\R/', $highlighted->value);

        $this->assertEquals(1, substr_count($highlighted->value, 'hljs-comment'));
        $this->assertEquals(count($cleanSplit), substr_count(implode(PHP_EOL, $cleanSplit), 'hljs-comment'));

        $this->assertTrue(is_array($cleanSplit));
        $this->assertCount(count($dumbSplit), $cleanSplit);
        $this->assertNotEquals($cleanSplit, $dumbSplit);

        foreach ($cleanSplit as $line) {
            $this->assertStringStartsWith('', trim($line));
            $this->assertStringEndsWith('', trim($line));
        }
    }
}

Add unit test for new splitCodeIntoArray function


<?php

namespace Tests\Feature;

use App\Recurring;
use App\Space;
use App\User;
use Tests\TestCase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\RefreshDatabase;

class RecurringTest extends TestCase {
    public function testUnauthorizedUserCantViewRecurring() {
        $user = factory(User::class)->create();

        $space = factory(Space::class)->create();

        $recurring = factory(Recurring::class)->create([
            'space_id' => $space->id
        ]);

        $this->actingAs($user);

        $response = $this->get('/recurrings/' . $recurring->id);

        $response->assertStatus(403);
    }
}

Create feature test for Recurring model that tests viewing a recurring as an authorized user


<?php

namespace Oro\Bundle\LocaleBundle\Tests\Unit\Entity;

use Oro\Bundle\LocaleBundle\Entity\LocaleSet;
use Oro\Component\Testing\Unit\EntityTestCaseTrait;

class LocaleSetTest extends \PHPUnit_Framework_TestCase
{
    use EntityTestCaseTrait;

    public function testAccessors()
    {
        $this->assertPropertyAccessors(new LocaleSet(), [
            ['id', 1],
            ['name','test_name'],
            ['i18nCode', 'i18n_test_code'],
            ['l10nCode', 'l10n_test_code'],
            ['parentLocaleSet', new LocaleSet()],
            ['createdAt', new \DateTime()],
            ['updatedAt', new \DateTime()],
            ['updatedAtSet', 1]
        ]);
        $this->assertPropertyCollections(new LocaleSet(), [
            ['childLocaleSets', new LocaleSet()],
        ]);
    }
}

BAP-10613: Move Locale Entity from Commerce to Platform
- Added unit test for Entity


<?php

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

class AddSignupIdToEventsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('events', function (Blueprint $table) {
            $table->integer('signup_id')->after('id');
        });
    }

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

Add migration to add signup_id to events table


<?php

namespace Tomahawk\Bundle\DoctrineBundle\Tests;

use Doctrine\ORM\Mapping\ClassMetadataInfo;
use Tomahawk\Bundle\DoctrineBundle\Mapping\ClassMetadataCollection;
use Tomahawk\Test\TestCase;

class ClassMetadataCollectionTest extends TestCase
{
    public function testGetMetadata()
    {
        $class = new ClassMetadataInfo(__CLASS__);
        $collection = new ClassMetadataCollection(array($class));

        $this->assertEquals(array($class), $collection->getMetadata());
    }

    public function testSetGetPath()
    {
        $class = new ClassMetadataInfo(__CLASS__);
        $collection = new ClassMetadataCollection(array($class));
        $collection->setPath('/path');

        $this->assertEquals('/path', $collection->getPath());
    }

    public function testSetGetNamespace()
    {
        $class = new ClassMetadataInfo(__CLASS__);
        $collection = new ClassMetadataCollection(array($class));
        $collection->setNamespace('MyBundle');

        $this->assertEquals('MyBundle', $collection->getNamespace());
    }
}

Add new test for ClassMetadataCollection


<?php
/*
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
 * and is licensed under the MIT license.
 */

namespace StrictPhpTestAsset;

class ClassWithTypedArrayMethodParameterAnnotation
{
    /**
     * @param \stdClass[]|int[] $someParameter
     */
    public function method(array $someParameter)
    {
    }
}

Test assets required for strict parameter checking


<?php declare(strict_types = 1);
/*
 * Copyright (c) 2019, Josef Kufner  <josef@kufner.cz>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

namespace Smalldb\StateMachine\CrudMachine;

use Smalldb\StateMachine\Annotation\State;
use Smalldb\StateMachine\Annotation\Transition;

/**
 * CrudMachine -- a basic CRUD state machine definition.
 */
interface CrudMachine
{

	/**
	 * @State(color = "#baf")
	 */
	const EXISTS = "Exists";

	/**
	 * @Transition("", {"Exists"})
	 */
	public function create(?array $itemData);

	/**
	 * @Transition("Exists", {"Exists"})
	 */
	public function update(array $itemData);

	/**
	 * @Transition("Exists", {""})
	 */
	public function delete();

}

Add default definition of CRUD machine using annotations


<?php

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

class CreateForumTableCategories extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		Schema::create('forum_categories', function(Blueprint $table)
		{
			$table->increments('id');
			$table->integer('parent_category')->unsigned()->nullable();
			$table->string('title');
			$table->string('subtitle');
			$table->integer('weight');
		});
	}

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

}

<?php

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

class CreateForumTableCategories extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		Schema::create('forum_categories', function(Blueprint $table)
		{
			$table->increments('id');
			$table->integer('parent_category')->unsigned()->nullable();
			$table->string('title');
			$table->string('subtitle');
			$table->integer('weight');
		});

		DB::table('forum_categories')->insert(
			array(
				[1, NULL, 'Category', 'Contains categories and threads', 0, '0000-00-00 00:00:00', '0000-00-00 00:00:00'],
				[2, 1, 'Sub-category', 'Contains threads', 1, '0000-00-00 00:00:00', '0000-00-00 00:00:00'],
				[3, 1, 'Second subcategory', 'Contains more threads', 0, '0000-00-00 00:00:00', '0000-00-00 00:00:00']
			)
		);
	}
	/**
	 * Reverse the migrations.
	 *
	 * @return void
	 */
	public function down()
	{
		Schema::drop('forum_categories');
	}

}

Update migrations to insert sample categories