<?php namespace Modules\Translation\Services;

use Illuminate\Foundation\Bus\DispatchesJobs;
use Modules\Translation\Events\TranslationNotFoundInCache;
use Modules\Translation\Repositories\CacheTranslation;
use Modules\Translation\Repositories\TranslationRepository;

class Translator extends \Illuminate\Translation\Translator
{
    use DispatchesJobs;
    /**
     * Have we already triggered the Cache Rebuild on this page load?
     * This stops the cache rebuild being triggered hundreds of times on the same page load if multiple items can't be found.
     * @var bool
     */
    protected $cacheRebuildQueued = false;
    /**
     * @var array Keys to ignore, don't rebuild cache if these keys cant be found.
     */
    protected $ignore = [
        'core::sidebar.content'
    ];
    /**
     * Get the translation for the given key.
     *
     * @param  string  $key
     * @param  array   $replace
     * @param  string  $locale
     * @param  bool  $fallback
     * @return string
     */
    public function get($key, array $replace = [], $locale = null, $fallback = true)
    {
        /** @var CacheTranslation $cacheTranslation */
        $cacheTranslation = app(CacheTranslation::class);
        if ($translation = $cacheTranslation->get($key, $locale)) {
            return $this->makeReplacements($translation, $replace);
        }
        if ($this->shouldRebuildCache($key)) {
            event(new TranslationNotFoundInCache($key));
            $this->cacheRebuildQueued = true;
        }
        return parent::get($key, $replace, $locale);
    }
    /**
     * Should we trigger a Translation cache rebuild?
     * @param string $key   Translation Key
     * @return bool
     */
    protected function shouldRebuildCache($key)
    {
        if (! app()->isBooted()) {
            return false;
        }
        if ($this->isTranslationCachedInEnglish($key)) {
            return false;
        }
        if (in_array($key, $this->ignore)) {
            return false;
        }
        if ($this->cacheRebuildQueued === false) {
            return true;
        }
        return false;
    }
    /**
     * Do we have an English version of the key? If we do, it usually means that
     * there hasn't been a translation entered in the CMS, so we don't need to rebuild the
     * translation cache just because it's not been entered in the CMS.
     * @param $key
     * @return bool
     */
    protected function isTranslationCachedInEnglish($key)
    {
        $translation = parent::get($key, [], 'en');
        return $key !== $translation;
    }
}

Create a custom translator class

Create a custom translator class


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

namespace Repositories;

use \TestCase;
use Nestor\Entities\ExecutionStatuses;
use Nestor\Repositories\ExecutionStatusesRepository;
use Illuminate\Foundation\Testing\DatabaseTransactions;

class ExecutionStatusesRepositoryTest extends TestCase
{

    use DatabaseTransactions;

    public function testRepositoryModelClass()
    {
        $repository = $this->app->make(\Nestor\Repositories\ExecutionStatusesRepository::class);
        $this->assertEquals(ExecutionStatuses::class, $repository->model());
    }
}

Add execution statuses repository test

Add execution statuses repository test


<?php

namespace MCordingley\LaravelSapient;

use Illuminate\Support\ServiceProvider;
use MCordingley\LaravelSapient\Console\GenerateSealingKeyPair;
use MCordingley\LaravelSapient\Console\GenerateSharedAuthenticationKey;
use MCordingley\LaravelSapient\Console\GenerateSharedEncryptionKey;
use MCordingley\LaravelSapient\Console\GenerateSigningKeyPair;
use ParagonIE\ConstantTime\Base64UrlSafe;

final class Provider extends ServiceProvider
{
    /**
     * @return void
     */
    public function register()
    {
        $this->app->when(Sapient::class)->needs(AdapterInterface::class)->give(SymfonyAdapter::class);

        $this->bindKey(SealingSecretKey::class, 'sapient.sealing.private_key')
            ->bindKey(SharedAuthenticationKey::class, 'sapient.shared.authentication_key')
            ->bindKey(SharedEncryptionKey::class, 'sapient.shared.encryption_key')
            ->bindKey(SigningSecretKey::class, 'sapient.signing.private_key');
    }

    /**
     * @param string $concrete
     * @param string $configKey
     * @return Provider
     */
    private function bindKey(string $concrete, string $configKey): self
    {
        $this->app->when($concrete)->needs('$key')->give(Base64UrlSafe::decode(config($configKey)));

        return $this;
    }

    /**
     * @return void
     */
    public function boot()
    {
        $this->commands([
            GenerateSealingKeyPair::class,
            GenerateSharedAuthenticationKey::class,
            GenerateSharedEncryptionKey::class,
            GenerateSigningKeyPair::class,
        ]);

        $this->publishes([
            __DIR__ . '/config.php' => config_path('sapient.php'),
        ]);
    }
}

Create service provider to wire things into the framework.


<?php

abstract class Worker_Communicator{
    /**
     * get stream to read from
     *
     * @return resource
     */
    abstract public function getStreamRead();

    /**
     * get stream to write to
     *
     * @return resource
     */
    abstract public function getStreamWrite();

    /**
     * close all communication streams
     */
    abstract public function close();
}

Add missing communicator base class

Add missing communicator base class


<?php

namespace Geocoder\Tests\HttpAdapter;

use Geocoder\Tests\TestCase;

use Geocoder\HttpAdapter\BuzzHttpAdapter;

/**
 * @author William Durand <william.durand1@gmail.com>
 */
class BuzzHttpAdapterTest extends TestCase
{
    public function testGetNullContent()
    {
        $buzz = new BuzzHttpAdapter();
        $this->assertNull($buzz->getContent(null));
    }

    public function testGetFalseContent()
    {
        $buzz = new BuzzHttpAdapter();
        $this->assertNull($buzz->getContent(false));
    }

    public function testGetContentWithCustomBrowser()
    {
        $content = 'foobar content';
        $browser = $this->getBrowserMock($content);

        $buzz = new BuzzHttpAdapter($browser);
        $this->assertEquals($content, $buzz->getContent('http://www.example.com'));
    }

    protected function getBrowserMock($content)
    {
        $mock = $this->getMock('\Buzz\Browser');
        $mock
            ->expects($this->once())
            ->method('get')
            ->will($this->returnValue($this->getResponseMock($content)))
            ;

        return $mock;
    }

    protected function getResponseMock($content)
    {
        $mock = $this->getMock('\Buzz\Message\Response');
        $mock
            ->expects($this->once())
            ->method('getContent')
            ->will($this->returnValue($content));

        return $mock;
    }
}

<?php

namespace Geocoder\Tests\HttpAdapter;

use Geocoder\Tests\TestCase;

use Geocoder\HttpAdapter\BuzzHttpAdapter;

/**
 * @author William Durand <william.durand1@gmail.com>
 */
class BuzzHttpAdapterTest extends TestCase
{
    protected function setUp()
    {
        if (!class_exists('Buzz\Browser')) {
            $this->markTestSkipped('Buzz library has to be installed');
        }
    }

    public function testGetNullContent()
    {
        $buzz = new BuzzHttpAdapter();
        $this->assertNull($buzz->getContent(null));
    }

    public function testGetFalseContent()
    {
        $buzz = new BuzzHttpAdapter();
        $this->assertNull($buzz->getContent(false));
    }

    public function testGetContentWithCustomBrowser()
    {
        $content = 'foobar content';
        $browser = $this->getBrowserMock($content);

        $buzz = new BuzzHttpAdapter($browser);
        $this->assertEquals($content, $buzz->getContent('http://www.example.com'));
    }

    protected function getBrowserMock($content)
    {
        $mock = $this->getMock('\Buzz\Browser');
        $mock
            ->expects($this->once())
            ->method('get')
            ->will($this->returnValue($this->getResponseMock($content)))
            ;

        return $mock;
    }

    protected function getResponseMock($content)
    {
        $mock = $this->getMock('\Buzz\Message\Response');
        $mock
            ->expects($this->once())
            ->method('getContent')
            ->will($this->returnValue($content));

        return $mock;
    }
}

Check if Buzz library is installed.

Check if Buzz library is installed.


<?php namespace Illuminate\Foundation\Debug;

use Exception;
use Psr\Log\LoggerInterface;
use Symfony\Component\Debug\ExceptionHandler as SymfonyDisplayer;
use Illuminate\Contracts\Debug\ExceptionHandler as ExceptionHandlerContract;

class ExceptionHandler implements ExceptionHandlerContract {

	/**
	 * The log implementation.
	 *
	 * @var \Psr\Log\LoggerInterface
	 */
	protected $log;

	/**
	 * Create a new exception handler instance.
	 *
	 * @param  \Psr\Log\LoggerInterface  $log
	 * @return void
	 */
	public function __construct(LoggerInterface $log)
	{
		$this->log = $log;
	}

	/**
	 * Report or log an exception.
	 *
	 * @param  \Exception  $e
	 * @return void
	 */
	public function report(Exception $e)
	{
		$this->log->error((string) $e);
	}

	/**
	 * Render an exception into a response.
	 *
	 * @param  \Illuminate\Http\Request  $request
	 * @param  \Exception  $e
	 * @return \Symfony\Component\HttpFoundation\Response
	 */
	public function render($request, Exception $e)
	{
		return (new SymfonyDisplayer)->createResponse($e);
	}

	/**
	 * Render an exception to the console.
	 *
	 * @param  \Symfony\Component\Console\Output\OutputInterface  $output
	 * @param  \Exception  $e
	 * @return void
	 */
	public function renderForConsole($output, Exception $e)
	{
		$output->writeln((string) $e);
	}

}

Add default implementation of exception handler.


<?php

namespace Mimic\Test;

use PHPUnit_Framework_TestCase;
use Mimic\Functional as F;

/**
 * Unit Test for flattenDot Mimic library function.
 *
 * @since 0.1.0
 *
 * @todo Need to use QuickTest library.
 */
class FlattenDotFuncTest extends PHPUnit_Framework_TestCase {
	public function dataProvider() {
		return array(
			array(
				array('0' => 1, '1' => 2, '2' => 3, '3.0' => 1, '3.1' => 2, '3.2' => 3),
				array(1, 2, 3, array(1, 2, 3))
			),
			array(
				array(
					'0' => 1, '1' => 2, '2' => 3,
					'3.0' => 4, '3.1' => 5, '3.2' => 6,
					'4.0.0' => 7, '4.0.1' => 8, '4.0.2' => 9),
				array(1, 2, 3, array(4, 5, 6), array(array(7,8, 9)))
			),
			array(
				array(
					'index1' => 1,
					'index2' => 2,
					'index3' => 3,
					'index4.something1' => 4,
					'index4.something2' => 5,
					'index4.something3' => 6,
					'index5.something4.else1' => 7,
					'index5.something4.else2' => 8,
					'index5.something4.else3' => 9,
				),
				array(
					'index1' => 1,
					'index2' => 2,
					'index3' => 3,
					'index4' => array(
						'something1' => 4,
						'something2' => 5,
						'something3' => 6,
					),
					'index5' => array(
						'something4' => array(
							'else1' => 7,
							'else2' => 8,
							'else3' => 9,
						)
					)
				)
			),
		);
	}

	/**
	 * @dataProvider dataProvider
	 * @covers ::Mimic\Functional\flattenDot
	 */
	public function testResults($expected, $collection) {
		$this->assertEquals($expected, F\flattenDot($collection));
	}
}

Add flatten dot function test suite.

Add flatten dot function test suite.


<?php

/**
 * Autoloaded file to handle deprecation such as class aliases.
 *
 * NOTE:
 * If for any reason arrays are required in this file, only ever use array()
 * syntax to prevent breakage on PHP < 5.4 and allow the legacy warnings.
 */

// Class aliases for BC
class_alias('\Bolt\Asset\Target', '\Bolt\Extensions\Snippets\Location');
class_alias('\Bolt\Legacy\Content', '\Bolt\Content');
class_alias('\Bolt\Storage\Field\Base', '\Bolt\Field\Base');
class_alias('\Bolt\Storage\Field\FieldInterface', '\Bolt\Field\FieldInterface');
class_alias('\Bolt\Storage\Field\Manager', '\Bolt\Field\Manager');

<?php

/**
 * Autoloaded file to handle deprecation such as class aliases.
 *
 * NOTE:
 * If for any reason arrays are required in this file, only ever use array()
 * syntax to prevent breakage on PHP < 5.4 and allow the legacy warnings.
 */

// Class aliases for BC
class_alias('\Bolt\Asset\Target', '\Bolt\Extensions\Snippets\Location');
class_alias('\Bolt\Legacy\Content', '\Bolt\Content');
class_alias('\Bolt\Legacy\Storage', '\Bolt\Storage');
class_alias('\Bolt\Storage\Field\Base', '\Bolt\Field\Base');
class_alias('\Bolt\Storage\Field\FieldInterface', '\Bolt\Field\FieldInterface');
class_alias('\Bolt\Storage\Field\Manager', '\Bolt\Field\Manager');

Add deprecation class alias for Bolt\Storage


<?php

namespace Inisiatif\Tests;

use PDO;
use PHPUnit\Framework\TestCase;
use Illuminate\Events\Dispatcher;
use Illuminate\Database\Connection;
use Illuminate\Database\SQLiteConnection;
use Illuminate\Database\Eloquent\Model as Eloquent;
use Illuminate\Database\ConnectionResolverInterface;

class ModelHasNumberGenerateTraitTest extends TestCase
{
    /**
     * Bootstrap Eloquent.
     *
     * @return void
     */
    public static function setUpBeforeClass()
    {
        Eloquent::setConnectionResolver(
            new DatabaseIntegrationTestConnectionResolver
        );

        Eloquent::setEventDispatcher(
            new Dispatcher
        );
    }

    /**
     * Tear down Eloquent.
     */
    public static function tearDownAfterClass()
    {
        Eloquent::unsetEventDispatcher();
        Eloquent::unsetConnectionResolver();
    }

    /**
     * Setup the database schema.
     *
     * @return void
     */
    public function setUp()
    {
        $this->schema()->create('users', function ($table) {
            $table->increments('id');
            $table->string('number_generated')->unique();
            $table->string('name');
            $table->timestamps();
        });

        $this->schema()->create('generators', function ($table) {
            $table->string('code', 100);
            $table->string('year');
            $table->string('month');
            $table->string('day');
            $table->integer('sequence');
            $table->timestamps();
            $table->softDeletes();
        });
    }

    /**
     * Tear down the database schema.
     *
     * @return void
     */
    public function tearDown()
    {
        $this->schema()->drop('users');
        $this->schema()->drop('generators');
    }
}

class DatabaseIntegrationTestConnectionResolver implements ConnectionResolverInterface
{
    protected $connection;

    public function connection($name = null)
    {
        if (isset($this->connection)) {
            return $this->connection;
        }
        return $this->connection = new SQLiteConnection(new PDO('sqlite::memory:'));
    }

    public function getDefaultConnection()
    {
        return 'default';
    }

    public function setDefaultConnection($name)
    {
        //
    }
}

Add testing and setting for eloquent connection


<?php
require_once __DIR__ . '/code/Calendar.php';
require_once __DIR__ . '/code/Data.php';
require_once __DIR__ . '/code/Exception.php';
require_once __DIR__ . '/code/Exception/BadArgumentType.php';
require_once __DIR__ . '/code/Exception/BadDataFileContents.php';
require_once __DIR__ . '/code/Exception/DataFileNotFound.php';
require_once __DIR__ . '/code/Exception/DataFileNotReadable.php';
require_once __DIR__ . '/code/Exception/DataFolderNotFound.php';
require_once __DIR__ . '/code/Exception/InvalidDataFile.php';
require_once __DIR__ . '/code/Exception/InvalidLocale.php';
require_once __DIR__ . '/code/Exception/NotImplemented.php';
require_once __DIR__ . '/code/Exception/ValueNotInList.php';
require_once __DIR__ . '/code/Language.php';
require_once __DIR__ . '/code/Misc.php';
require_once __DIR__ . '/code/Number.php';
require_once __DIR__ . '/code/Plural.php';
require_once __DIR__ . '/code/Territory.php';
require_once __DIR__ . '/code/Unit.php';

Add file to load all the Punic components


<?php

use Faker\Generator as Faker;

use Carbon\Carbon;

$factory->define(RadDB\CTDailyQCRecord::class, function (Faker $faker) {
    return [
        'machine_id' => '130',
        'qcdate' => $faker->dateTimeThisMonth()->format('Y-m-d'),
        'scan_type' => $faker->randomElement(['Axial', 'Helical']),
        'water_hu' => $faker->randomFloat(1, -10, 10),
        'water_sd' => $faker->randomFloat(1, 0, 10),
        'artifacts' => $faker->randomElement(['Y', 'N']),
        'initials' => 'EM',
        'notes' => $faker->sentence(),
    ];
});

Add model factory to generate random CT QC data


<?php

class AimeosTestAbstract extends Orchestra\Testbench\TestCase
{
	protected function getEnvironmentSetUp($app)
	{
		$app['config']->set('database.default', 'mysql');
		$app['config']->set('database.connections.mysql', [
			'driver' => 'mysql',
			'host' => env('DB_HOST', 'localhost'),
			'database' => env('DB_DATABASE', 'laravel'),
			'username' => env('DB_USERNAME', 'root'),
			'password' => env('DB_PASSWORD', ''),
		]);

		$app['config']->set('app.key', 'SomeRandomStringWith32Characters');
		$app['config']->set('app.cipher', 'AES-256-CBC');

		$app['config']->set('shop.routes.account', ['prefix' => '{site}']);
		$app['config']->set('shop.routes.default', ['prefix' => '{site}']);
	}

	protected function getPackageProviders($app)
	{
		return ['Aimeos\Shop\ShopServiceProvider'];
	}
}

<?php

class AimeosTestAbstract extends Orchestra\Testbench\TestCase
{
	protected function getEnvironmentSetUp($app)
	{
		$app['config']->set('database.default', 'mysql');
		$app['config']->set('database.connections.mysql', [
			'driver' => 'mysql',
			'host' => env('DB_HOST', 'localhost'),
			'database' => env('DB_DATABASE', 'laravel'),
			'username' => env('DB_USERNAME', 'root'),
			'password' => env('DB_PASSWORD', ''),
		]);

		$app['config']->set('app.key', 'SomeRandomStringWith32Characters');
		$app['config']->set('app.cipher', MCRYPT_RIJNDAEL_128);

		$app['config']->set('shop.routes.account', ['prefix' => '{site}']);
		$app['config']->set('shop.routes.default', ['prefix' => '{site}']);
	}

	protected function getPackageProviders($app)
	{
		return ['Aimeos\Shop\ShopServiceProvider'];
	}
}

Use encryption available for Laravel 5.0 and 5.1 in tests


<?php
if (strpos($_SERVER["SCRIPT_NAME"], basename(__FILE__)) !== false) {
	header("location: index.php");
	exit;
}

/**
 * In some upgrade cases pages without a name can cause a "No wiki page specified" error on tiki-index.php
 * Also the pref wikiHomePage can be set to NULL causing the same error
 *
 * @param Installer $installer
 */
function upgrade_20171016_no_homepage_specificed_tiki($installer)
{
	$tiki_pages = $installer->table('tiki_pages');

	$namelessPages = $tiki_pages->fetchAll(['page_id'], ['pageName' => '']);

	foreach ($namelessPages as $page) {
		$tiki_pages->update(
			[
				'pageName' => "Page id #{$page['page_id']}",
				'comment' => 'Renamed by installer 20171016_no_homepage_specificed_tiki (pageName was empty)',
			],
			[
				'page_id' => $page['page_id'],
			]
		);
	}

	// null value prefs (e.g. wikiHomePage) count as being set but have no value, so cause errors.
	$installer->query('DELETE FROM `tiki_preferences` WHERE ISNULL(`value`);');

}

[FIX] homepages: Add a patch file to rename wiki pages without a name, and also remove prefs with value NULL, which both can contribute to a "No wiki page specified" error on tiki-index.php

git-svn-id: a7fabbc6a7c54ea5c67cbd16bd322330fd10cc35@64287 b456876b-0849-0410-b77d-98878d47e9d5


<?php

return [
    [
        'command' => 'Dummy',
        'defaults' => 'MartiAdrogue\Console\DummyCommand',
    ],
    [
        'command' => 'NotFound',
        'defaults' => 'MartiAdrogue\Console\AidCommand\NotFoundCommand',
    ],
    [
        'command' => 'Error',
        'defaults' => 'MartiAdrogue\Console\AidCommand\ErrorCommand',
    ],
];

Create example of routing confing

Create example of routing confing


<?php
/**
 * Copyright 2011 Victor Farazdagi
 *
 * 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.
 *
 * @category    Phrozn
 * @package     Phrozn\Twig
 * @author      Victor Farazdagi
 * @copyright   2011 Victor Farazdagi
 * @license     http://www.apache.org/licenses/LICENSE-2.0
 */

namespace Phrozn\Twig\Loader;
require_once(dirname(__FILE__) . '/../../Vendor/Twig/Loader/String.php');

/**
 * Twig String Loader
 *
 * @category    Phrozn
 * @package     Phrozn\Processor
 * @author      Victor Farazdagi
 */
class String
    extends \Twig_Loader_String
    implements \Twig_LoaderInterface
{
    /**
     * Gets the source code of a template, given its name.
     *
     * @param  string $name Template content
     *
     * @return string The template source code
     */
    public function getSource($name)
    {
        // strip front-matter
        $parts = preg_split('/[\n]*[-]{3}[\n]/', $name, 2);
        if (count($parts) === 2) {
            return ltrim($parts[1]);
        }
        return $name;
    }
}

Add custom string loader for twig processor


<?php

namespace Tests;

use TightenCo\Jigsaw\Jigsaw;
use org\bovigo\vfs\vfsStream;

class EventsTest extends TestCase
{
    public function test_user_can_add_event_listeners_as_closures()
    {
        $this->app['events']->beforeBuild(function ($jigsaw) use (&$a) {
            $a = $jigsaw->getConfig('a');
        });
        $this->app['events']->afterCollections(function ($jigsaw) use (&$b) {
            $b = $jigsaw->getConfig('b');
        });
        $this->app['events']->afterBuild(function ($jigsaw) use (&$c) {
            $c = $jigsaw->getConfig('c');
        });
        $this->buildSite($this->setupSource(), [
            'a' => 123,
            'b' => 456,
            'c' => 789,
        ]);

        $this->assertEquals(123, $a);
        $this->assertEquals(456, $b);
        $this->assertEquals(789, $c);
    }

    public function test_user_can_add_event_listeners_as_classes()
    {
        $this->app['events']->beforeBuild(TestListener::class);
        $jigsaw = $this->buildSite($this->setupSource(), ['variable_a' => 'set in config.php']);

        $this->assertEquals('set in TestListener', $jigsaw->getConfig('variable_a'));
    }

    public function test_multiple_event_listeners_are_fired_in_the_order_they_were_defined()
    {
        $this->app['events']->beforeBuild([TestListener::class, TestListenerTwo::class]);
        $jigsaw = $this->buildSite($this->setupSource(), ['variable_a' => 'set in config.php']);

        $this->assertEquals('set in SecondTestListener', $jigsaw->getConfig('variable_a'));
        $this->assertEquals('set in TestListener', $jigsaw->getConfig('variable_b'));
    }
}

class TestListener
{
    public function handle($jigsaw)
    {
        $jigsaw->setConfig('variable_a', 'set in TestListener');
        $jigsaw->setConfig('variable_b', 'set in TestListener');
    }
}

class TestListenerTwo
{
    public function handle($jigsaw)
    {
        $jigsaw->setConfig('variable_a', 'set in SecondTestListener');
    }
}

Add initial tests for Events

Add initial tests for Events


<?php
/**
 * @author Todd Burry <todd@vanillaforums.com>
 * @copyright 2009-2014 Vanilla Forums Inc.
 * @license MIT
 */

use Garden\Cli\Cli;

/**
 * Provides tests for the sample code in README.md.
 */
class ReadmeTest extends PHPUnit_Framework_TestCase {

    /**
     * Test the basic example help.
     *
     * @expectedException \Exception
     */
    public function testBasicHelp() {
        $cli = $this->getBasicCli();
        $argv = ['dbdump.php', '--help'];

        // Parse and return cli args.
        $args = $cli->parse($argv, false);
    }

    /**
     * Test the basic example error output.
     *
     * @expectedException \Exception
     */
    public function testBasicError() {
        $cli = $this->getBasicCli();
        $argv = ['dbdump.php', '-P', 'foo'];

        $args = $cli->parse($argv, false);
    }

    /**
     * Test the basic exmple args.
     */
    public function testBasicArgs() {
        $cli = $this->getBasicCli();
        $argv = ['dbdump.php', '-hlocalhost', '-uroot', '--database=testdb'];

        $args = $cli->parse($argv, false);

        $host = $args->getOpt('host', '127.0.0.1'); // get host with default 127.0.0.1
        $user = $args->getOpt('user'); // get user
        $database = $args['database']; // use the args like an array too
        $port = $args->getOpt('port', 123); // get port with default 123

        $this->assertEquals('localhost', $host);
        $this->assertEquals('root', $user);
        $this->assertEquals('testdb', $database);
        $this->assertEquals(123, $port);
    }

    /**
     * Get the basic cli example.
     *
     * @return Cli
     */
    public function getBasicCli() {
        // Define the cli options.
        $cli = new Cli();

        $cli->description('Dump some information from your database.')
            ->opt('host', 'Connect to host.', false, 'string', 'h')
            ->opt('port', 'Port number to use.', false, 'integer', 'P')
            ->opt('user', 'User for login if not current user.', true, 'string', 'u')
            ->opt('password', 'Password to use when connecting to server.', false, 'string', 'p')
            ->opt('database', 'The name of the database to dump.', true, 'string', 'd');

        return $cli;
    }
}

Add some unit tests for the readme examples.


<?php

namespace Tests;

use org\bovigo\vfs\vfsStream;

class SiteBuilderTest extends TestCase
{
    /**
     * @test
     */
    public function destination_directory_is_deleted_when_building_site()
    {
        $files = vfsStream::setup('virtual', null, [
            'build' => [
                'old.blade.php' => 'Old file',
            ],
            'source' => [
                'new.blade.php' => 'New file',
            ],
        ]);

        $this->buildSite($files);

        $this->assertCount(1, $files->getChild('build')->getChildren());
    }

    /**
     * @test
     */
    public function existing_files_in_destination_directory_are_replaced_when_building_site()
    {
        $files = vfsStream::setup('virtual', null, [
            'build' => [
                'test.blade.php' => 'Old file',
            ],
            'source' => [
                'test.blade.php' => 'New file',
            ],
        ]);

        $this->buildSite($files);

        $this->assertCount(1, $files->getChild('build')->getChildren());
        $this->assertEquals('New file', $files->getChild('build')->getChild('build/test.html')->getContent());
    }
}

Add test for SiteBuilder deleting/replacing old build files


<?php
/*
 * Copyright 2017, 2018 Alexey Kopytko <alexey@kopytko.com>
 *
 * 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.
 */

declare(strict_types=1);

namespace Tests\Pipeline;

use PHPUnit\Framework\TestCase;
use Pipeline\Principal;
use function Pipeline\fromArray;
use function Pipeline\take;

/**
 * @covers \Pipeline\Principal
 */
class EagerWithArraysTest extends TestCase
{
    public function testEagerArrayFilter()
    {
        $reflectionClass = new \ReflectionClass(Principal::class);
        $reflectionProperty = $reflectionClass->getProperty('pipeline');
        $reflectionProperty->setAccessible(true);

        foreach ([
            take([0, 0, 1, 2, 3]),
            fromArray([0, 0, 1, 2, 3]),
        ] as $pipeline) {
            $pipeline->filter();
            // At this point $pipeline contains exactly [1, 2, 3]

            $this->assertSame([2 => 1, 2, 3], $reflectionProperty->getValue($pipeline));

            $this->assertSame([1, 2, 3], $pipeline->toArray());

            // This does nothing more
            $this->assertSame([1, 2, 3], $pipeline->filter()->toArray());
        }
    }
}

Test that filter() works with arrays eagerly


<?php

use PHPUnit\Framework\TestCase;

class ScheduleTest extends TestCase
{
    public function testMasterScheduleEquivalency()
    {
        $teams = ['Team 1', 'Team 2', 'Team 3', 'Team 4'];
        $scheduleBuilder = new ScheduleBuilder();
        $scheduleBuilder->setTeams($teams);
        $scheduleBuilder->doNotShuffle();
        $schedule = $scheduleBuilder->build();
        $this->assertEquals($schedule->master(), $schedule->get());
        $this->assertEquals($schedule->master(), $schedule());
        $scheduleArray = [];
        foreach($schedule as $round => $matchups) {
            $scheduleArray[$round] = $matchups;
        }
        $this->assertEquals($schedule->master(), $scheduleArray);
    }

    public function testIndividualScheduleEquivalency()
    {
        $teams = ['Team 1', 'Team 2', 'Team 3', 'Team 4'];
        $scheduleBuilder = new ScheduleBuilder();
        $scheduleBuilder->setTeams($teams);
        $schedule = $scheduleBuilder->build();
        $this->assertEquals($schedule->forTeam('Team 1'), $schedule->get('Team 1'));
        $this->assertEquals($schedule->forTeam('Team 1'), $schedule('Team 1'));
    }

    public function testIndividualSchedule1()
    {
        $teams = ['Team 1', 'Team 2', 'Team 3', 'Team 4', 'Team 5'];
        $scheduleBuilder = new ScheduleBuilder();
        $scheduleBuilder->setTeams($teams);
        $schedule = $scheduleBuilder->build();
        $teamSchedule = [];
        foreach($schedule as $round => $matchups) {
            foreach($matchups as $matchup) {
                $team1 = $matchup[0];
                $team2 = $matchup[1];
                $teamSchedule[$team1][$round] = ['team' => $team2, 'home' => false];
                $teamSchedule[$team2][$round] = ['team' => $team1, 'home' => true];
            }
        }
        $this->assertEquals($teamSchedule['Team 1'], $schedule->forTeam('Team 1'));
    }

    public function testIndividualSchedule2()
    {
        $master = [
            1 => [['Team 1', 'Team 2'], [null, 'Team 3']],
            2 => [['Team 2', null], ['Team 3', 'Team 1']]
        ];
        $expected = [
            1 => ['team' => 'Team 1', 'home' => true],
            2=> ['team' => null, 'home' => false]
        ];
        $schedule = new Schedule($master);
        $this->assertEquals($expected, $schedule->forTeam('Team 2'));
    }
}

Add unit tests for Schedule object

Add unit tests for Schedule object


    {{ Form::open([
      'method' => 'POST',
      'route' => ['hardware/bulkedit'],
      'class' => 'form-inline',
      'id' => 'bulkForm']) }}

            {{ trans('button.bulk_actions') }}

    <select name="bulk_actions" class="form-control select2" aria-label="bulk_actions">
        <option value="edit">{{ trans('button.edit') }}</option>
        <option value="delete">{{ trans('button.delete') }}</option>
        <option value="labels">{{ trans_choice('button.generate_labels', 2) }}</option>
    </select>

    <button class="btn btn-primary" id="bulkEdit" disabled>{{ trans('button.go') }}</button>
    {{ Form::close() }}

Create a new partial for asset bulk actions

Signed-off-by: snipe <e9c017fc53f27c86a4fb6d4f0de7d332b596a185@snipe.net>


<?php
/**
 * Zend Framework (http://framework.zend.com/)
 *
 * @link      http://github.com/zendframework/zf2 for the canonical source repository
 * @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd New BSD License
 */

namespace Zend\Mvc\Service;

use Zend\ServiceManager\ServiceLocatorInterface;

class SerializerAdapterPluginManagerFactory extends AbstractPluginManagerFactory
{
    const PLUGIN_MANAGER_CLASS = 'Zend\Serializer\AdapterPluginManager';

    /**
     * {@inheritDoc}
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        /** @var $serviceListener \Zend\ModuleManager\Listener\ServiceListener */
        $serviceListener = $serviceLocator->get('ServiceListener');

        // This will allow to register new serializers easily, either by implementing the SerializerProviderInterface
        // in your Module.php file, or by adding the "serializers" key in your module.config.php file
        $serviceListener->addServiceManager(
            $serviceLocator,
            'serializers',
            'Zend\ModuleManager\Feature\SerializerProviderInterface',
            'getSerializerConfig'
        );

        return parent::createService($serviceLocator);
    }
}

Allow to add serializers through config

Allow to add serializers through config


<?php

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

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

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

Add column `user_id` in Company table as foreign key


<?php

declare (strict_types = 1);

namespace Crell\Document\Document\Test;

use Crell\Document\Document\Document;
use Crell\Document\Document\SimpleDocumentSet;

class FieldTest extends \PHPUnit_Framework_TestCase
{

    public function testReadExample()
    {

        $doc = new Document();

        // Get list of field names. Or objects?
        $fields = $doc->fields();

        // Returns Field object for "field" property.
        $f = $doc->field;

        $doc->field->prop;

        $doc->field[2]->prop;

        $doc->field->method();
    }

    public function testWrite()
    {
        $doc->field->setProperty('foo', 'bar');

    }

}

Add initial working-draft for tests.

Add initial working-draft for tests.


<?php

use Illuminate\Http\Response;
use Illuminate\Http\Request;
use Illuminate\Routing\Router;
use Illuminate\Container\Container;
use Illuminate\Encryption\Encrypter;
use Illuminate\Cookie\Middleware\EncryptCookies;
use Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse;
use Symfony\Component\HttpFoundation\Cookie;

class EncryptCookiesTest extends PHPUnit_Framework_TestCase
{
    /**
     * @var Illuminate\Routing\Router
     */
    protected $router;

    protected $setCookiePath = 'cookie/set';
    protected $queueCookiePath = 'cookie/queue';

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

        $container = new Container;
        $container->singleton('Illuminate\Contracts\Encryption\Encrypter', function () {
            return new Encrypter(str_repeat('a', 16));
        });

        $this->router = new Router(new Illuminate\Events\Dispatcher, $container);
    }
    public function testSetCookieEncryption()
    {
        $this->router->get($this->setCookiePath, [
            'middleware' => 'EncryptCookiesTestMiddleware',
            'uses'=>'EncryptCookiesTestController@setCookies'
        ]);

        $response = $this->router->dispatch(Request::create($this->setCookiePath, 'GET'));

        $cookies = $response->headers->getCookies();
        $this->assertEquals(2, count($cookies));
        $this->assertEquals('encrypted_cookie', $cookies[0]->getName());
        $this->assertNotEquals('value', $cookies[0]->getValue());
        $this->assertEquals('unencrypted_cookie', $cookies[1]->getName());
        $this->assertEquals('value', $cookies[1]->getValue());
    }
    public function testQueuedCookieEncryption()
    {
        $this->router->get($this->queueCookiePath, [
            'middleware' => ['EncryptCookiesTestMiddleware', 'AddQueuedCookiesToResponseTestMiddleware'],
            'uses'=>'EncryptCookiesTestController@queueCookies'
        ]);

        $response = $this->router->dispatch(Request::create($this->queueCookiePath, 'GET'));

        $cookies = $response->headers->getCookies();
        $this->assertEquals(2, count($cookies));
        $this->assertEquals('encrypted_cookie', $cookies[0]->getName());
        $this->assertNotEquals('value', $cookies[0]->getValue());
        $this->assertEquals('unencrypted_cookie', $cookies[1]->getName());
        $this->assertEquals('value', $cookies[1]->getValue());
    }
}

class EncryptCookiesTestController extends Illuminate\Routing\Controller
{
    public function setCookies()
    {
        $response = new Response();
        $response->headers->setCookie(new Cookie('encrypted_cookie', 'value'));
        $response->headers->setCookie(new Cookie('unencrypted_cookie', 'value'));

        return $response;
    }
    public function queueCookies()
    {
        return new Response();
    }
}

class EncryptCookiesTestMiddleware extends EncryptCookies
{
    protected $except = [
        'unencrypted_cookie',
    ];
}

class AddQueuedCookiesToResponseTestMiddleware extends AddQueuedCookiesToResponse
{
    public function __construct()
    {
        $cookie = new Illuminate\Cookie\CookieJar;
        $cookie->queue(new Cookie('encrypted_cookie', 'value'));
        $cookie->queue(new Cookie('unencrypted_cookie', 'value'));

        $this->cookies = $cookie;
    }
}

Add Middleware test for set and queued cookie encryption


<?php
use Phinx\Migration\AbstractMigration;

class AlterTalkColumnsAllowNull extends AbstractMigration
{
    /**
     * Migrate Up.
     */
    public function up()
    {
        $this->table('talks')
            ->changeColumn('other', 'text', ['null' => true])
            ->changeColumn('slides', 'string', ['null' => true])
            ->save();
    }
    /**
     * Migrate Down.
     */
    public function down()
    {
        $this->table('talks')
            ->changeColumn('other', 'text')
            ->changeColumn('slides', 'string')
            ->save();
    }
}

Allow null for optional talk fields

Allow null for optional talk fields


<?php

use Phinx\Migration\AbstractMigration;

class LongerImageUuid extends AbstractMigration
{
    public function change()
    {
      $table= $this->table('image', [ 'signed' => false ]);
      $table
        ->changeColumn('uuid', 'string', [ 'limit' => 255 ])
        ->update();
    }
}

Allow longer UUID for image

Allow longer UUID for image


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

namespace Brain\Hierarchy\Branch;

/**
 * @author  Giuseppe Mazzapica <giuseppe.mazzapica@gmail.com>
 * @license http://opensource.org/licenses/MIT MIT
 * @package Hierarchy
 */
final class BranchEmbed implements BranchInterface
{

    /**
     * @inheritdoc
     */
    public function name()
    {
        return 'embed';
    }

    /**
     * @inheritdoc
     */
    public function is(\WP_Query $query)
    {
        return $query->is_embed();
    }

    /**
     * @inheritdoc
     */
    public function leaves(\WP_Query $query)
    {
        $post = $query->get_queried_object();
        $leaves = [];

        if ($post instanceof \WP_Post) {
            $post_format = get_post_format($post);
            $post_format and $leaves[] = "embed-{$post->post_type}-{$post_format}";
            $leaves[] = "embed-{$post->post_type}";
        }

        $leaves[] = 'embed';

        return $leaves;
    }
}

Add missing branch "embed" branch

Add missing branch "embed" branch


<?php

namespace Common\Tests\Core\Header;

use Common\Core\Header\Priority;
use PHPUnit\Framework\TestCase;

class PriorityTest extends TestCase
{
    public function testPriorityEquals(): void
    {
        $this->assertTrue(Priority::widget()->equals(Priority::widget()));
    }

    public function testPriorityNotEquals(): void
    {
        $this->assertFalse(Priority::widget()->equals(Priority::core()));
    }

    public function testPriorityComparison(): void
    {
        $priorities = [
            Priority::debug(),
            Priority::standard(),
            Priority::widget(),
            Priority::core(),
            Priority::module(),
        ];

        $sortedPriorities = [
            Priority::core(),
            Priority::standard(),
            Priority::module(),
            Priority::widget(),
            Priority::debug(),
        ];

        usort(
            $priorities,
            function (Priority $priority1, Priority $priority2) {
                return $priority1->compare($priority2);
            }
        );

        foreach ($sortedPriorities as $key => $priority) {
            $this->assertTrue($priorities[$key]->equals($priority), 'Priorities not sorted correctly');
        }
    }

    public function testPriorityForModule(): void
    {
        $this->assertTrue(Priority::core()->equals(Priority::forModule('Core')));
        $this->assertTrue(Priority::module()->equals(Priority::forModule('Blog')));
        $this->assertTrue(Priority::module()->equals(Priority::forModule('ContentBlocks')));
    }
}

Add tests for the priority class

Add tests for the priority class


<?php

Mock::generate('Pheanstalk_Socket', 'MockSocket');

/**
 * Tests exceptions thrown to represent non-command-specific error responses.
 *
 * @author Paul Annesley
 * @package Pheanstalk
 * @licence http://www.opensource.org/licenses/mit-license.php
 */
class Pheanstalk_ServerErrorExceptionTest
	extends UnitTestCase
{
	private $_command;

	public function setUp()
	{
		$this->_command = new Pheanstalk_Command_UseCommand('tube5');
	}

	/**
	 * A connection with a mock socket, configured to return the given line.
	 * @return Pheanstalk_Connection
	 */
	private function _connection($line)
	{
		$socket = new MockSocket();
		$socket->setReturnValue('getLine', $line);

		$connection = new Pheanstalk_Connection(null, null);
		$connection->setSocket($socket);
		return $connection;
	}

	public function testCommandsHandleOutOfMemory()
	{
		$this->expectException('Pheanstalk_Exception_ServerOutOfMemoryException');
		$this->_connection('OUT_OF_MEMORY')->dispatchCommand($this->_command);
	}

	public function testCommandsHandleInternalError()
	{
		$this->expectException('Pheanstalk_Exception_ServerInternalErrorException');
		$this->_connection('INTERNAL_ERROR')->dispatchCommand($this->_command);
	}

	public function testCommandsHandleDraining()
	{
		$this->expectException('Pheanstalk_Exception_ServerDrainingException');
		$this->_connection('DRAINING')->dispatchCommand($this->_command);
	}

	public function testCommandsHandleBadFormat()
	{
		$this->expectException('Pheanstalk_Exception_ServerBadFormatException');
		$this->_connection('BAD_FORMAT')->dispatchCommand($this->_command);
	}

	public function testCommandsHandleUnknownCommand()
	{
		$this->expectException('Pheanstalk_Exception_ServerUnknownCommandException');
		$this->_connection('UNKNOWN_COMMAND')->dispatchCommand($this->_command);
	}
}

Test coverage for non-command-specific server error handling.


<?php

use Phinx\Migration\AbstractMigration;

class ExtendCachedDeviationsColumnLengths extends AbstractMigration {
	public function change() {
		$this->table('cached_deviations')
			->changeColumn('preview','string', ['length' => 300])
			->changeColumn('fullsize','string', ['length' => 300])
			->update();
	}
}

Increase cached deviations' image column lengths


@if($isHorizontal)

@endif

                {{ $options['label'] }}

                @if(! $errors->isEmpty() && $errors->has($name))
                    {{ implode(' ', $errors->get($name)) }}
                @endif

            <canvas class="embed-responsive-item"></canvas>
            <button type="button" class="btn btn-default btn-xs pull-right" onclick="clearSignature('{{ $name }}');"> {{ $options['clearButton'] }} </button>
            {!! $controlHtml !!}

@if($isHorizontal)

@endif

Create initial signature form field view


<?php

namespace Slate\Courses;

use DB, SQL;

$oldTable = 'narrative_section_notes';

if (!static::tableExists($oldTable)) {
    return static::STATUS_SKIPPED;
}

$totalSectionNotes = DB::oneValue('SELECT COUNT(*) FROM `%s`', $oldTable);
// history table
$totalHistoricSectionNotes = DB::oneValue('SELECT COUNT(*) FROM `%s`', 'history_'.$oldTable);

if (!empty($totalSectionNotes) || !empty($totalHistoricSectionNotes)) {
    if (!static::tableExists(SectionTermData::$tableName)) {
        // create table
        $createTableSql = SQL::getCreateTable(SectionTermData::class);
        DB::multiQuery($createTableSql);
    }
}

$query = '
    INSERT INTO `%s` (`ID`, `TermID`, `SectionID`, `TermReportNotes`, `Created`, `CreatorID`, `Modified`, `ModifierID`, `Class`)
    SELECT ID, TermID, CourseSectionID as SectionID, Notes as TermReportNotes, Created, CreatorID, Modified, ModifierID, "%s" as Class
      FROM `%s`
     ORDER BY ID ASC
';

if (!empty($totalSectionNotes)) {
    DB::nonQuery($query, [SectionTermData::$tableName, DB::escape(SectionTermData::class), $oldTable]);
}

if (!empty($totalHistoricSectionNotes)) {
    DB::nonQuery($query, ['history_'.SectionTermData::$tableName, DB::escape(SectionTermData::class), 'history_'.$oldTable]);
}

$createdNotes = DB::oneValue('SELECT COUNT(*) FROM `%s`', SectionTermData::$tableName);

if ($createdNotes != $totalSectionNotes) {
    return static::STATUS_FAILED;
}

return static::STATUS_EXECUTED;

Create migration script for section term notes


<?php

use Phinx\Migration\AbstractMigration;

class AddStripePaymentIntent extends AbstractMigration
{
    public function change()
    {
      $table= $this->table('sale');
      $table
        ->addColumn('stripe_payment_intent_id', 'string', [
          'limit' => 255,
          'null' => true,
          'after' => 'amz_order_reference_id',
        ])
        ->save();

    }
}

Add field for Stripe Payment Intent API

Add field for Stripe Payment Intent API


<?php
session_start();
if(isset($_GET['logout']))
unset($_SESSION['userid']);
if(isset($_SESSION['userid']))
echo '<meta http-equiv="Refresh" content="0;http://localhost/cart/user.php" />';
mysql_connect('localhost','root','root');
mysql_select_db('osc') or die(mysql_error());
$tq="";

if(isset($_POST["submit"]))
{
$uid=$_POST["username"];
$password=$_POST["pass"];
$query="select * from users where uid='$uid' and password='$password'";
$tq.=$query;
if(mysql_num_rows(mysql_query($query)))
{
$_SESSION['userid']=$uid;
echo '<meta http-equiv="Refresh" content="0;http://localhost/cart/user.php" />';
}
else
echo "Sorry the Username and Password do not Match .
";
}
?>

<form method="post">
Username : <input type="text" name="username" />

Password : <input type="password" name="pass" />

<input type="submit" name="submit" value="Login" />
</form>

<?php
echo $tq;
?>

Index page updated. Admin and user login.


<?php

class m141208_135800_audit_model_unique extends CDbMigration
{
	public function safeUp()
	{
		$this->alterColumn("audit_model", "name", "string");
		$this->createIndex("audit_model_unique", "audit_model", "name", "true");
	}

	public function safeDown()
	{
		$this->dropIndex("audit_model_unique", "audit_model");
	}
}

[OE-5235] Increase the length of audit model names and make them unique.


<?php
namespace Vmwarephp\Extensions;

class VirtualMachine extends \Vmwarephp\ManagedObject {

	function takeSnapshot($name, $memory = null, $quiesce = null) {
		$snapshotTask = $this->CreateSnapshot_Task(array('name' => $name, 'memory' => $memory, 'quiesce' => $quiesce));
		return $snapshotTask;
	}

	function isAccessible() {
		return in_array($this->configStatus, array('green', 'gray'));
	}

	function isTemplate() {
		return $this->summary->config->template;
	}

	function getParentDatastoreName() {
		preg_match('/\[(.*)\]/', $this->summary->config->vmPathName, $matches);
		return $matches[1];
	}

	function getParentDatastore() {
		foreach ($this->datastore as $datastore)
			if ($datastore->name == $this->getParentDatastoreName()) return $datastore;
	}

	function hasSnapshots() {
		return $this->snapshot ? true : false;
	}

	function getUsedSpace() {
		return $this->summary->storage->committed;
	}

	function getProvisionedSpace() {
		return $this->summary->storage->committed + $this->summary->storage->uncommitted;
	}
}

Introduce virtual machine managed object extension


<?php

namespace LaraComponents\Seo;

class Meta
{
    protected $attributes = [];

    public function __construct(array $attributes = [])
    {
        $this->setAttributes($attributes);
    }

    public static function make(array $attributes = [])
    {
        return new self($attributes);
    }

    public function setAttributes(array $attributes)
    {
        foreach ($attributes as $key => $value) {
            $this->setAttribute($key, $value);
        }
    }

    public function getAttributes()
    {
        return $this->attributes;
    }

    public function setAttribute($key, $value)
    {
        $this->attributes[$key] = $value;
    }

    public function getAttribute($key)
    {
        if (array_key_exists($key, $this->attributes)) {
            return $this->attributes[$key];
        }
    }

    public function toString()
    {
        if (count($this->attributes)) {
            return '<meta'.$this->getHtmlAttributes().'/>';
        }

        return '';
    }

    protected function getHtmlAttributes()
    {
        $html = [];
        foreach ($this->attributes as $key => $value) {
            $attribute = $key.'="'.e($value).'"';

            if (! is_null($attribute)) {
                $html[] = $attribute;
            }
        }

        return count($html) > 0 ? ' '.implode(' ', $html) : '';
    }

    public function __toString()
    {
        return $this->toString();
    }
}

Add class for meta tags

Add class for meta tags


<?php // phpcs:ignoreFile

/**
 * This contains the information needed to convert the function signatures for php 8.2 to php 8.1 (and vice versa)
 *
 * This file has three sections.
 * The 'added' section contains function/method names from FunctionSignatureMap (And alternates, if applicable) that do not exist in php 8.1
 * The 'removed' section contains the signatures that were removed in php 8.2
 * The 'changed' section contains functions for which the signature has changed for php 8.2.
 *     Each function in the 'changed' section has an 'old' and a 'new' section,
 *     representing the function as it was in PHP 8.1 and in PHP 8.2, respectively
 *
 * @see CallMap.php
 *
 * @phan-file-suppress PhanPluginMixedKeyNoKey (read by Phan when analyzing this file)
 */
return [
  'added' => [
    'mysqli_execute_query' => ['mysqli_result|bool', 'mysqli'=>'mysqli', 'query'=>'non-empty-string', 'params='=>'list<string>|null'],
    'mysqli::execute_query' => ['mysqli_result|bool', 'query'=>'non-empty-string', 'params='=>'list<string>|null'],
    'openssl_cipher_key_length' => ['positive-int|false', 'cipher_algo'=>'non-empty-string'],
    'curl_upkeep' => ['bool', 'handle'=>'CurlHandle'],
    'ini_parse_quantity' => ['int', 'shorthand'=>'non-empty-string'],
    'memory_reset_peak_usage' => ['void'],
  ],

  'changed' => [
    'str_split' => [
       'old' => ['non-empty-list<string>', 'string'=>'string', 'length='=>'positive-int'],
       'new' => ['list<string>', 'string'=>'string', 'length='=>'positive-int'],
    ],
  ],
];

Add dictionary delta for PHP 8.2

Add dictionary delta for PHP 8.2


<?php

namespace ChangeTests\Rbs\Payment;

class PaymentManagerTest extends \ChangeTests\Change\TestAssets\TestCase
{

	public static function setUpBeforeClass()
	{
		static::initDocumentsDb();
	}

	public static function tearDownAfterClass()
	{
		static::clearDB();
	}

	public function testOnDefaultGetMailCode()
	{
		$commerceServices = new \Rbs\Commerce\CommerceServices($this->getApplication(), $this->getEventManagerFactory(), $this->getApplicationServices());
		$paymentManager = $commerceServices->getPaymentManager();
		$this->assertInstanceOf('\Rbs\Payment\PaymentManager', $paymentManager);

		/* @var $transaction \Rbs\Payment\Documents\Transaction */
		$transaction = $this->getNewReadonlyDocument('Rbs_Payment_Transaction', 100);
		$transaction->setProcessingStatus(\Rbs\Payment\Documents\Transaction::STATUS_PROCESSING);
		$code = $paymentManager->getMailCode($transaction);
		$this->assertEquals('rbs_payment_transaction_processing', $code);

		$transaction->setProcessingStatus(\Rbs\Payment\Documents\Transaction::STATUS_SUCCESS);
		$code = $paymentManager->getMailCode($transaction);
		$this->assertEquals('rbs_payment_transaction_success', $code);

		$transaction->setProcessingStatus(\Rbs\Payment\Documents\Transaction::STATUS_FAILED);
		$code = $paymentManager->getMailCode($transaction);
		$this->assertEquals('rbs_payment_transaction_failed', $code);
	}
}

Add new Unit Test for PaymentManager

Add new Unit Test for PaymentManager


<?php

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

class RemoveBernTimezone extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        $users = User::all();
        foreach ($users as $user) {
            if ($user->timezone == 'Europe/Bern') {
                $user->timezone = 'Europe/Berlin';
                $user->save();
            }
        }
    }
}

Add migration to get rid of Bern timezone


<?php
/**
 * Modify Previous Page / Next Page to use Bootstrap styling
 *
 * To generate the proper markup, we've recreated genesis_posts_nav()
 * and genesis_prev_next_posts_nav() since there was not a good way
 * to hook in and modify the markup.
 *
 * @since 0.7.0
 */

add_filter( 'genesis_prev_link_text', 'bsg_genesis_prev_link_text_numeric' );
add_filter( 'genesis_next_link_text', 'bsg_genesis_next_link_text_numeric' );

function bsg_genesis_prev_link_text_numeric( $text ) {
    if ( 'numeric' === genesis_get_option( 'posts_nav' ) ) {
        return '«'
            . '' . __( 'Previous Page', 'genesis' ) . '';
    }
    return $text;
}

function bsg_genesis_next_link_text_numeric( $text ) {
    if ( 'numeric' === genesis_get_option( 'posts_nav' ) ) {
        return '' . __( 'Next Page', 'genesis' ) . ''
            . '»';
    }
    return $text;
}

Remove words from numeric pagination

Remove words from numeric pagination

The default numeric pagination includes the words "Previous Page" and
"Next Page".

The Bootstrap example pagination uses only the laquo and raquo
characters.

Remove the words "Previous Page" and "Next Page" from pagination
controls.

Fixes #77


<?php

//Function to query the db and return the correct columns for the cases table html.

function columns_array($dbh)

	{

		$get_columns = $dbh->prepare('SELECT * from cm_columns');
		$get_columns->execute();
		$result = $get_columns->fetchAll(PDO::FETCH_ASSOC);

		return $result;

	}

Add function to read columns from the db and generate appropriate html.

git-svn-id: 245d8f85226f8eeeaacc1269b037bb4851d63c96@897 54a900ba-8191-11dd-a5c9-f1483cedc3eb


<?php
namespace Peazie\BuildDeliveryBundle\Controller;

use Aws\Common\Aws;
use Aws\Ec2\Ec2Client;
use Aws\ElasticLoadBalancing\ElasticLoadBalancingClient;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

/**
 * @Route("/deploy")
 * @Template()
 */
class DeployController extends Controller
{
    /**
     * @Route("/{strategy}/{elb}", name="prod_deploy", defaults={ "strategy":null, "elb":null })
     * @Template()
     */
    public function deployAction($strategy, $elb)
    {
        if( is_null($strategy) || is_null($elb) ) {
            throw new \Exception('Required parameters cannot be null');
        }

        $data['LoadBalancerName' ] = $elb;
        $data['DeployStrategy']    = $strategy;

        return array( 'data' => $data );

    }//deploy
}

Refactor deploy, style up instace details


<?php

use Illuminate\Database\Migrations\Migration;
use OpenDominion\Helpers\NotificationHelper;
use OpenDominion\Models\User;

class SetDefaultNotificationSettings extends Migration
{
    /** @var NotificationHelper */
    protected $notificationHelper;

    /**
     * SetDefaultNotificationSettings constructor.
     */
    public function __construct()
    {
        $this->notificationHelper = app(NotificationHelper::class);
    }

    /**
     * Run the migrations.
     *
     * @return void
     * @throws Throwable
     */
    public function up()
    {
        DB::transaction(function () {
            User::each(function (User $user) {
                $user->settings = [
                    'notifications' => $this->notificationHelper->getDefaultUserNotificationSettings(),
                    'notification_digest' => 'hourly',
                ];
                $user->save();
            });
        });

    }

    /**
     * Reverse the migrations.
     *
     * @return void
     * @throws Throwable
     */
    public function down()
    {
        DB::transaction(function () {
            User::each(function (User $user) {
                $user->settings = null;
                $user->save();
            });
        });
    }
}

Add migration to set default user (notification) settings


<?php
/**
 * @author e 13.01.2016
 */

namespace e;

use PDO;

class PhoneNumberValidator
{
	private $_db;

	/**
	 * PhoneNumberValidator constructor.
	 */
	public function __construct()
	{
		try {
			$db = new PDO('mysql:host=localhost;dbname=test;port=3306,root,1');
			$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
			$db->exec("SET NAMES 'utf8'");
			$this->_db = $db;
		} catch (\Exception $e) {
			echo 'Could not connect to the database.';
			exit();
		}
	}

	public function validate()
	{

	}
}

Add class... the magic one

Add class... the magic one


<?php
namespace DrestTests;

class ManagerTest extends DrestTestCase
{

    public function testExecutingOnANamedRoute()
    {
        $dm = $this->_getDrestManager();

        $dm->dispatch()

    }
}

Add a few more tests

Add a few more tests


<?php

namespace Oro\Bundle\ActionBundle\DependencyInjection\CompilerPass;

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

use Oro\Component\DependencyInjection\Compiler\TaggedServicesCompilerPassTrait;

class ButtonProviderPass implements CompilerPassInterface
{
    use TaggedServicesCompilerPassTrait;

    const EXTENSION_TAG = 'oro.action.extension.button_provider';
    const SERVICE_ID = 'oro_action.provider.buttons';

    /**
     * {@inheritdoc}
     */
    public function process(ContainerBuilder $container)
    {
        $this->registerTaggedServices($container, self::SERVICE_ID, self::EXTENSION_TAG, 'addExtension');
    }
}

<?php

namespace Oro\Bundle\ActionBundle\DependencyInjection\CompilerPass;

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

use Oro\Component\DependencyInjection\Compiler\TaggedServicesCompilerPassTrait;

class ButtonProviderPass implements CompilerPassInterface
{
    use TaggedServicesCompilerPassTrait;

    const EXTENSION_TAG = 'oro.action.extension.button_provider';
    const SERVICE_ID = 'oro_action.provider.button';

    /**
     * {@inheritdoc}
     */
    public function process(ContainerBuilder $container)
    {
        $this->registerTaggedServices($container, self::SERVICE_ID, self::EXTENSION_TAG, 'addExtension');
    }
}

BAP-12474: Add compiler pass for provider extensions
- fix service id after merge


<?php
$IP = getenv( 'MW_INSTALL_PATH' );
if ( $IP === false ) {
	$IP = __DIR__ . '/../../..';
}
require_once "$IP/maintenance/Maintenance.php";

/**
 * Purges all pages that use <maplink> or <mapframe>, using the tracking category.
 */
class PurgeMapPages extends Maintenance {
	public function __construct() {
		parent::__construct();
		$this->addDescription( 'Purge all pages that use <maplink> or <mapframe>.' );
		$this->addOption( 'dry-run', 'Only print page names, do not purge them', false, false );
		$this->setBatchSize( 100 );
	}

	public function execute() {
		$categoryMessage = wfMessage( 'kartographer-tracking-category' );
		if ( $categoryMessage->isDisabled() ) {
			$this->error( "Tracking category for maps pages is disabled\n" );
			return;
		}
		$categoryTitle = Title::makeTitle( NS_CATEGORY, $categoryMessage->inContentLanguage()->text() );
		$dryRun = $this->hasOption( 'dry-run' );
		$iterator = new BatchRowIterator(
			wfGetDB( DB_REPLICA ),
			[ 'categorylinks', 'page' ],
			[ 'cl_type', 'cl_sortkey', 'cl_from' ],
			$this->getBatchSize()
		);
		$iterator->addConditions( [ 'cl_to' => $categoryTitle->getDBkey() ] );
		$iterator->addJoinConditions( [ 'page' => [ 'INNER JOIN', [ 'page_id=cl_from' ] ] ] );
		$iterator->setFetchColumns( [ 'page_id', 'page_namespace', 'page_title' ] );

		$pages = 0;
		$failures = 0;
		foreach ( $iterator as $batch ) {
			foreach ( $batch as $row ) {
				$title = Title::newFromRow( $row );
				if ( $dryRun ) {
					$this->output( $title->getPrefixedText() . "\n" );
				} else {
					$page = WikiPage::factory( $title );
					if ( $page->doPurge() ) {
						$this->output( "Purged {$title->getPrefixedText()}\n" );
					} else {
						$this->error( "FAILED TO PURGE {$title->getPrefixedText()}\n" );
						$failures++;
					}
				}
			}
			$pages += count( $batch );
		}
		$this->output( "\nFinished. Total: $pages pages. Failed: $failures.\n" );
	}
}

$maintClass = PurgeMapPages::class;
require_once RUN_MAINTENANCE_IF_MAIN;

Add maintenance script to purge pages with map tags

Also has a --dry-run option to just list these pages instead.

Bug: T193525
Change-Id: Ib382a7b14f80da8c6caf5e2b3dc4696797e7d477


<?php

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

class AddEstebanEntities extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        DB::transaction(function() {
            $names = ['Channel Islands', 'Melanesia', 'Polynesia', 'Caribbean Netherlands', 'Northern Cyprus', 'Turkish Republic of Northern Cyprus', 'North Cyprus'];
            foreach ($names as $name) {
                DB::statement("INSERT INTO entities (name, validated, fk_ent_t_id) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE validated=1;", [$name, 1, 5]);
            }
        });
    }
}

Add Esteban's new validated entities

Add Esteban's new validated entities


<?php
/**
 * Used to store saved customer payment cards
 */

$installer = $this;
$installer->startSetup();

$installer->run("
CREATE TABLE {$this->getTable('ebanx_user_cards')} (
    `ebanx_card_id` int(11) unsigned NOT NULL auto_increment,
    `user_id` int(11) NOT NULL default 0,
    `token` varchar(255) NOT NULL default '',
    `masked_number` varchar(20) NOT NULL default '',
    `brand` varchar(255) NOT NULL default '',
     PRIMARY KEY (ebanx_card_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

");

$installer->endSetup();

Create table to save credit cards

Create table to save credit cards


<?php

/**
 * Data object containing the SQL and PHP code to migrate the database
 * up to version 1432824532.
 * Generated on 2015-05-28 16:48:52 by root
 */
class PropelMigration_1432824532
{

    public function preUp($manager)
    {
        // add the pre-migration code here
    }

    public function postUp($manager)
    {
        // add the post-migration code here
    }

    public function preDown($manager)
    {
        // add the pre-migration code here
    }

    public function postDown($manager)
    {
        // add the post-migration code here
    }

    /**
     * Get the SQL statements for the Up migration
     *
     * @return array list of the SQL strings to execute for the Up migration
     *               the keys being the datasources
     */
    public function getUpSQL()
    {
        return array (
  'centreon' => '
# This is a fix for InnoDB in MySQL >= 4.1.x
# It "suspends judgement" for fkey relationships until are tables are set.
SET FOREIGN_KEY_CHECKS = 0;

ALTER TABLE `cfg_forms_fields` CHANGE `attributes` `attributes` TEXT;

ALTER TABLE `cfg_forms_fields` CHANGE `type` `type` VARCHAR(255) NOT NULL;

# This restores the fkey checks, after having unset them earlier
SET FOREIGN_KEY_CHECKS = 1;
',
);
    }

    /**
     * Get the SQL statements for the Down migration
     *
     * @return array list of the SQL strings to execute for the Down migration
     *               the keys being the datasources
     */
    public function getDownSQL()
    {
        return array (
  'centreon' => '
# This is a fix for InnoDB in MySQL >= 4.1.x
# It "suspends judgement" for fkey relationships until are tables are set.
SET FOREIGN_KEY_CHECKS = 0;

ALTER TABLE `cfg_forms_fields` CHANGE `attributes` `attributes` VARCHAR(255);

ALTER TABLE `cfg_forms_fields` CHANGE `type` `type` VARCHAR(45) NOT NULL;

# This restores the fkey checks, after having unset them earlier
SET FOREIGN_KEY_CHECKS = 1;
',
);
    }

}

Add migration class for cfg_forms_fields table


<?php

namespace Application\Migrations;

use SimplyTestable\BaseMigrationsBundle\Migration\EntityModificationMigration,
 SimplyTestable\WorkerBundle\Entity\Task\Type\Type,
 SimplyTestable\WorkerBundle\Entity\Task\Type\TaskTypeClass,
 Doctrine\DBAL\Schema\Schema;

/**
 * Auto-generated Migration: Please modify to your need!
 */
class Version20121113145829_add_JavaScript_Static_Analysis_TaskType extends EntityModificationMigration
{
    private $taskTypes = array(
        'JS static analysis' => array(
            'description' => 'JavaScript static code analysis (via jslint)',
            'class' => 'verification'
        )
    );

    public function postUp(Schema $schema)
    {
        foreach ($this->taskTypes as $name => $properties) {
            $class = $taskTypeClass = $this->getEntityManager()->getRepository('SimplyTestable\WorkerBundle\Entity\Task\Type\TaskTypeClass')->findOneByName($properties['class']);

            $taskType = new Type();
            $taskType->setClass($class);
            $taskType->setDescription($properties['description']);
            $taskType->setName($name);

            $this->getEntityManager()->persist($taskType);
            $this->getEntityManager()->flush();
        }
    }

    public function postDown(Schema $schema)
    {
        foreach ($this->taskTypes as $name => $properties) {
            $taskType = $this->getEntityManager()->getRepository('SimplyTestable\WorkerBundle\Entity\Task\Type\Type')->findOneByName($properties[$name]);
            $this->getEntityManager()->remove($taskType);
            $this->getEntityManager()->flush();
        }
    }
}

Add js static analysis task type

Add js static analysis task type


<?php

namespace Oro\Tests\Unit\Component\Layout\Block\Type;

use Oro\Component\Layout\Block\Type\Options;

class OptionsTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var Options
     */
    protected $options;

    protected function setUp()
    {
        $this->options = new Options(['value' => 'test']);
    }

    public function testGet()
    {
        $this->assertEquals('test', $this->options->get('value'));

        $this->setExpectedException('OutOfBoundsException');
        $this->assertFalse($this->options->get('nameNotExist'));
    }

    public function testOffsetGet()
    {
        $this->assertEquals('test', $this->options->offsetGet('value'));
    }

    public function testOffsetSet()
    {
        $this->options->offsetSet('attribute', 'bar');
        $this->assertSame(['value' => 'test', 'attribute' => 'bar'], $this->options->toArray());
    }

    public function testOffsetUnset()
    {
        $this->options->offsetUnset('value');
        $this->assertSame([], $this->options->toArray());
    }

    public function testOffsetExists()
    {
        $this->assertTrue($this->options->offsetExists('value'));
        $this->assertFalse($this->options->offsetExists('attr'));
    }

    public function testGetAll()
    {
        $this->assertSame(['value' => 'test'], $this->options->toArray());
    }
}

<?php

namespace Oro\Tests\Unit\Component\Layout\Block\Type;

use Oro\Component\Layout\Block\Type\Options;

class OptionsTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var Options
     */
    protected $options;

    protected function setUp()
    {
        $this->options = new Options(['value' => 'test']);
    }

    public function testGet()
    {
        $this->assertEquals('test', $this->options->get('value'));

        $this->setExpectedException('OutOfBoundsException');
        $this->assertFalse($this->options->get('nameNotExist'));
    }

    public function testOffsetGet()
    {
        $this->assertEquals('test', $this->options->offsetGet('value'));
    }

    public function testOffsetSet()
    {
        $this->options->offsetSet('attribute', 'bar');
        $this->assertSame(['value' => 'test', 'attribute' => 'bar'], $this->options->toArray());
    }

    public function testOffsetUnset()
    {
        $this->options->offsetUnset('value');
        $this->assertSame([], $this->options->toArray());
    }

    public function testOffsetExists()
    {
        $this->assertTrue($this->options->offsetExists('value'));
        $this->assertFalse($this->options->offsetExists('attr'));
    }

    public function testGetAll()
    {
        $this->assertSame(['value' => 'test'], $this->options->toArray());
    }

    public function testSetMultiple()
    {
        $values = ['value'=> 'test1', 'value2'=> 'test2', 'value3'=> 'test3'];
        $this->options->setMultiple($values);
        $this->assertEquals($values, $this->options->toArray());
    }
}

[WIP] BB-4325: Refactor block types, move expressions in vars from buildView to finishView
- added test for Options:setMultiple


<?php
/**
 * This file is part of the bee4/transport package.
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @copyright Bee4 2015
 * @author  Stephane HULARD <s.hulard@chstudio.fr>
 * @package Bee4\Transport\Handle
 */

namespace Bee4\Transport\Handle;

use Bee4\Transport\Collection;

/**
 * Handle execution informations implementation
 * @package Bee4\Transport\Handle
 */
class ExecutionInfos
{
    /**
     * Handle used to perform the execution
     */
    private $handle;

    /**
     * Execution status code
     * @var integer
     */
    private $status;

    /**
     * Header collection
     * @var string
     */
    private $headers;

    /**
     * Effective URL
     * @var string
     */
    private $effectiveUrl;

    /**
     * Transaction time
     * @var float
     */
    private $transactionTime;

    /**
     * Content type for the request
     * @var string
     */
    private $contentType;

    /**
     * Build an ExecutioInfos instance
     * @param HandleInterface $handle
     */
    public function __construct(
        HandleInterface $handle,
        callable $resolver = null
    ) {
        $this->handle = $handle;
    }

    /**
     * Retrieve current handle
     * @return HandleInterface
     */
    public function getHandle()
    {
        return $this->handle;
    }

    /**
     * Retrieve a property value
     * @param  string $name Property name
     * @return mixed
     */
    public function __get($name)
    {
        if (!property_exists($this, $name)) {
            throw new BadMethodCallException('Invalid property name: '.$name);
        }

        if (null === $this->$name && isset($this->resolver)) {
            $this->$name = call_user_func($this->resolver, $name);
        }

        return $this->$name;
    }

    /**
     * Set a property
     * @param  string $name
     * @param  array  $arguments
     * @return ExecutionInfos
     */
    public function __call($name, array $arguments)
    {
        //Define getter and setter for each valid property
        if (property_exists($this, $name) && count($arguments) == 1) {
            $this->$name = $arguments[0];
            return $this;
        } else {
            throw new BadMethodCallException('Invalid method: '.$name);
        }
    }
}

Introduce a new object to store execution details


<?php

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

class AddForeignKeys extends Migration {

    private $relations = [
        'channels' => ['server:server_settings.id'],
        'custom_commands' => ['server:server_settings.id'],
        'groups' => ['server_id:server_settings.id'],
        'guild_member_roles' => ['server_id:server_settings.id', 'role_id:roles.id'],
        'guild_members' => ['server_id:server_settings.id'],
        'music_settings' => ['id:server_settings.id'],
        'permission_overrides' => ['server_id:server_settings.id'],
        'quotes' => ['server_id:server_settings.id'],
        'roles' => ['server_id:server_settings.id'],
        'rss_feed_items' => ['rss_feed_id:rss_feeds.id'],
        'server_messages' => ['server_id:server_settings.id'],
        'log' => ['server_id:server_settings.id'],
        'user_groups' => ['group_id:groups.id']
    ];

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up() {
        // Make the groups id column unique so we can add a foreign key to it
        Schema::table('groups', function (Blueprint $table){
            $table->unique('id');
        });
        foreach ($this->relations as $table => $relations) {
            foreach ($relations as $relation) {
                $exploded = explode(':', $relation);
                $key_name = $exploded[0];
                $foreign_reference = $exploded[1];

                $foreign_table = explode('.', $foreign_reference)[0];
                $foreign_key = explode('.', $foreign_reference)[1];

                Schema::table($table, function (Blueprint $table) use ($key_name, $foreign_table, $foreign_key) {
                    $table->foreign($key_name)->references($foreign_key)->on($foreign_table)->onDelete("cascade");
                });
            }
        }
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down() {
        Schema::table('groups', function (Blueprint $table){
            $table->dropUnique(['id']);
        });

        foreach ($this->relations as $table => $relations) {
            foreach ($relations as $relation) {
                $key = explode(':', $relation)[0];
                Schema::table($table, function (Blueprint $table) use ($key) {
                    $table->dropForeign([$key]);
                });
            }
        }
    }
}

Add foreign keys to the database

Add foreign keys to the database


<?php
require_once('api/service/account.php');

describe('Account service', function () {

  describe('register', function () {
    $this->data = [];
    $this->data['email'] = 'user@test.com';
    $this->data['password'] = 'testPassword';
    $this->data['firstName'] = 'testFirstName';
    $this->data['lastName'] = 'testLastName';
    $this->data['address'] = '1 Broadway';
    $this->data['city'] = 'new york';
    $this->data['state'] = 'ny';
    $this->data['zipcode'] = '10012';

    $this->registerResult = AccountService::register($this->data);
    it('should return an array', function () {
      $type = gettype($this->registerResult);
      expect($type) -> toEqual('array');
    });
  });

});

?>

Create unit test for AccountService class


<?php

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

class m141220_143106_create_activity_type_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('{{%activity_type}}', [
            'id' => Schema::TYPE_PK,
            'name' => Schema::TYPE_STRING . ' NOT NULL',
        ], $tableOptions);

        $this->createIndex('NAME', '{{%activity_type}}', 'name', true);
    }

    public function down()
    {
        $this->dropIndex('NAME', '{{%activity_type}}');

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

Add migration for ActivityType entity

Add migration for ActivityType entity


<?php

namespace atk4\data\tests;

use atk4\data\Model;
use atk4\data\Persistence_SQL;

class FieldHereditaryTest extends \atk4\schema\PHPUnit_SchemaTestCase
{
    public function testDirty1()
    {
        $p = new \atk4\data\Persistence_Static(['hello', 'world']);

        // default title field
        $m = new \atk4\data\Model($p);
        $m->addField('caps', ['Callback', function($m){ return strtoupper($m['name']); }]);

        $m->load(1);
        $this->assertEquals('world', $m['name']);
        $this->assertEquals('WORLD', $m['caps']);
    }
}

Add test for a Callback type

Add test for a Callback type


<?php

/*
Copyright (C) 2010-2016 by the FusionInventory Development Team
Copyright (C) 2016 Teclib'

This file is part of Armadito Plugin for GLPI.

Armadito Plugin for GLPI 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.

Armadito Plugin for GLPI 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 Armadito Plugin for GLPI. If not, see <http://www.gnu.org/licenses/>.

**/

include_once("../../../../inc/includes.php");
include_once("../../api/common.php");

$rawdata = file_get_contents("php://input");
if (isValidPOSTRequest($rawdata))
{
    checkPluginInstallation();
    initGLPISession();

    PluginArmaditoLastContactStat::increment();

    try
    {
        $jobj = PluginArmaditoToolbox::parseJSON($rawdata);
        $scheduler = new PluginArmaditoScheduler();
        $scheduler->initFromJson($jobj);
        $scheduler->run();

        writeHttpOKResponse("");
    }
    catch(PluginArmaditoJsonException $e)
    {
        writeHttpErrorResponse($e->getMessage(), 400);
    }
    catch(Exception $e)
    {
        writeHttpErrorResponse($e->getMessage(), 500);
    }

    session_destroy();
}
else
{
    writeHttpErrorResponse("Invalid request sent to plugin index", 400);
}

?>

Add api rest scheduler entry point

Add api rest scheduler entry point


<?php
/**
 * Box packing (3D bin packing, knapsack problem)
 * @package BoxPacker
 * @author Doug Wright
 */
namespace DVDoug\BoxPacker;

/**
 * An item to be packed
 * @author Doug Wright
 * @package BoxPacker
 */
class OrientatedItem
{

    /**
     * @var Item
     */
    protected $item;

    /**
     * @var int
     */
    protected $width;

    /**
     * @var int
     */
    protected $length;

    /**
     * @var int
     */
    protected $depth;

    /**
     * Constructor.
     * @param Item $item
     * @param int $width
     * @param int $length
     * @param int $depth
     */
    public function __construct(Item $item, $width, $length, $depth) {
        $this->item = $item;
        $this->width = $width;
        $this->length = $length;
        $this->depth = $depth;
    }

    /**
     * Item
     * @return Item
     */
    public function getItem() {
        return $this->item;
    }

    /**
     * Item width in mm in it's packed orientation
     * @return int
     */
    public function getWidth() {
        return $this->width;
    }

    /**
     * Item length in mm in it's packed orientation
     * @return int
     */
    public function getLength() {
        return $this->length;
    }

    /**
     * Item depth in mm in it's packed orientation
     * @return int
     */
    public function getDepth() {
        return $this->depth;
    }
  }

Add new object to represent an item in it's packed orientation


<?php

namespace ModuleGenerator;

use Matthias\SymfonyConsoleForm\Bundle\SymfonyConsoleFormBundle;
use Symfony\Bundle\FrameworkBundle\FrameworkBundle;
use Symfony\Component\Config\Loader\LoaderInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Kernel;

class AppKernel extends Kernel
{
    public function registerBundles()
    {
        return [
            new FrameworkBundle(),
            new SymfonyConsoleFormBundle(),
        ];
    }

    public function registerContainerConfiguration(LoaderInterface $loader)
    {
        $loader->load(__DIR__.'/config.yml');
    }

    public function getCacheDir()
    {
        return __DIR__.'/temp/cache';
    }

    public function getLogDir()
    {
        return __DIR__.'/temp/logs';
    }

    /**
     * @throws \RuntimeException
     *
     * @return ContainerBuilder The compiled service container
     */
    protected function buildContainer()
    {
        $container = parent::buildContainer();

        $container->setParameter('cwd', getcwd());

        return $container;
    }
}

Create an app kernel for our application


<?php
namespace Aura\Cli;

/**
 *
 * An object-oriented wrapper for resource streams.
 *
 */
class StdioResource
{
    protected $handle;

    protected $filename;

    protected $mode;

    public function __construct($filename, $mode)
    {
        $this->filename = $filename;
        $this->mode     = $mode;
        $this->handle   = fopen($this->filename, $this->mode);
    }

    public function __destruct()
    {
        fclose($this->handle);
    }

    public function fread()
    {
        return fread($this->handle, 8192);
    }

    public function fwrite($string)
    {
        return fwrite($this->handle, $string);
    }

    public function rewind()
    {
        return rewind($this->handle);
    }

    public function fgets()
    {
        return fgets($this->handle);
    }

    public function isPosixTty()
    {
        return @posix_isatty($this->handle);
    }
}

<?php
/**
 *
 * This file is part of the Aura project for PHP.
 *
 * @package Aura.Cli
 *
 * @license http://opensource.org/licenses/bsd-license.php BSD
 *
 */
namespace Aura\Cli;

/**
 *
 * An object-oriented wrapper for resource streams.
 *
 * @package Aura.Cli
 *
 */
class StdioResource
{
    /**
     *
     * file pointer
     *
     * @var resource
     *
     */
    protected $handle;

    /**
     *
     * filename
     *
     * @var string
     *
     */
    protected $filename;

    /**
     *
     * The mode parameter specifies the type of access you require to the stream.
     *
     * @var string
     *
     */
    protected $mode;

    /**
     *
     * Constructor
     *
     * @param string $filename
     *
     * @param string $mode
     *
     */
    public function __construct($filename, $mode)
    {
        $this->filename = $filename;
        $this->mode     = $mode;
        $this->handle   = fopen($this->filename, $this->mode);
    }

    /**
     *
     * Destructor
     *
     */
    public function __destruct()
    {
        fclose($this->handle);
    }

    /**
     *
     * Binary-safe file read
     *
     * @return string
     *
     */
    public function fread()
    {
        return fread($this->handle, 8192);
    }

    /**
     *
     * Binary-safe file write
     *
     * @param string $string
     *
     * @return int
     *
     */
    public function fwrite($string)
    {
        return fwrite($this->handle, $string);
    }

    /**
     *
     * Rewind the position of a file pointer
     *
     * @return type
     *
     */
    public function rewind()
    {
        return rewind($this->handle);
    }

    /**
     *
     * Gets line from file pointer
     *
     * @return string
     *
     */
    public function fgets()
    {
        return fgets($this->handle);
    }

    /**
     *
     * Determine if a file descriptor is an interactive terminal
     *
     * @return bool
     *
     */
    public function isPosixTty()
    {
        return @posix_isatty($this->handle);
    }
}

Fix psr and add doclox

Fix psr and add doclox


<?php

namespace Mimic\Test;

use PHPUnit_Framework_TestCase;
use Mimic\Functional as F;

/**
 * Unit Test for hash_array Mimic library function.
 *
 * @since 0.1.0
 */
class HashArrayFuncTest extends PHPUnit_Framework_TestCase {
	public function dataProvider() {
		return array(
			array(),
			array(1, 2, 3),
			array(new Stub\InvokeTrue, new Stub\InvokeFalse, 1, 2),
			array(1, 2, new Stub\InvokeTrue, new Stub\InvokeFalse),
			array(function() { return true; }),
			array(1, function() { return true; }),
			array(0, 1, function() { return true; }),
			array(0, 1, function() { return true; }, new Stub\InvokeTrue),
		);
	}

	/**
	 * @dataProvider dataProvider
	 * @covers ::Mimic\Functional\hash_array
	 */
	public function testResults($args, $expected) {
		$this->assertEquals($expected, F\hash_array($args));
	}
}

Add hash array function test suite.

Add hash array function test suite.


<?php

/**
 * Various SAML 2 constants.
 *
 * @package simpleSAMLphp
 * @version $Id$
 */
class sspmod_saml2_Const {

	/**
	 * Top-level status code indicating successful processing of the request.
	 */
	const STATUS_SUCCESS = 'urn:oasis:names:tc:SAML:2.0:status:Success';

	/**
	 * Top-level status code indicating that there was a problem with the request.
	 */
	const STATUS_REQUESTER = 'urn:oasis:names:tc:SAML:2.0:status:Requester';

	/**
	 * Top-level status code indicating that there was a problem generating the response.
	 */
	const STATUS_RESPONDER = 'urn:oasis:names:tc:SAML:2.0:status:Responder';

	/**
	 * Top-level status code indicating that the request was from an unsupported version of the SAML protocol.
	 */
	const STATUS_VERSION_MISMATCH = 'urn:oasis:names:tc:SAML:2.0:status:VersionMismatch';

	/**
	 * Second-level status code for NoPassive errors.
	 */
	const STATUS_NO_PASSIVE = 'urn:oasis:names:tc:SAML:2.0:status:NoPassive';

}

?>

Add a class for SAML2 constants.

saml2: Add a class for SAML2 constants.

This patch adds the SimpleSAML_XML_SAML2 class, which currently contain
SAML 2 status codes constants. New SAML2 constants should be added to this
class.


<?php

namespace Overblog\WsClientBundle\Client;

interface WsClientInterface
{
    /**
     * Get Request
     * @param string $uri
     * @param array $param
     * @return array
     */
    public function get($uri, Array $param = array());

    /**
     * Exec stocked requests
     * @return array
     */
    public function exec();

    /**
     * Get connection and save it into object
     *
     * @param string $name
     * @return WsClient
     */
    public function getConnection($name);
}

Add an interface to be able to inject a wsClient stub in type-constrained methods


<?php declare(strict_types=1);
/**
 * @author    Igor Nikolaev <igor.sv.n@gmail.com>
 * @copyright Copyright (c) 2019, Darvin Studio
 * @link      https://www.darvin-studio.ru
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Darvin\ImageBundle\Traits;

use Doctrine\ORM\QueryBuilder;

/**
 * Imageable entity repository trait
 */
trait ImageableRepositoryTrait
{
    /**
     * @param \Doctrine\ORM\QueryBuilder $qb        Query builder
     * @param string|null                $locale    Locale
     * @param bool                       $addSelect Whether to add select
     * @param string                     $join      Join
     */
    protected function innerJoinImage(QueryBuilder $qb, ?string $locale = null, bool $addSelect = true, string $join = 'o.image')
    {
        $qb
            ->innerJoin($join, 'image')
            ->innerJoin('image.translations', 'image_translations');

        if (null !== $locale) {
            $qb
                ->andWhere('image_translations.locale = :locale')
                ->setParameter('locale', $locale);
        }
        if ($addSelect) {
            $qb
                ->addSelect('image')
                ->addSelect('image_translations');
        }
    }

    /**
     * @param \Doctrine\ORM\QueryBuilder $qb        Query builder
     * @param string|null                $locale    Locale
     * @param bool                       $addSelect Whether to add select
     * @param string                     $join      Join
     */
    protected function leftJoinImage(QueryBuilder $qb, ?string $locale = null, bool $addSelect = true, string $join = 'o.image')
    {
        $qb
            ->leftJoin($join, 'image')
            ->leftJoin('image.translations', 'image_translations');

        if (null !== $locale) {
            $qb
                ->andWhere($qb->expr()->orX(
                    'image_translations.locale IS NULL',
                    'image_translations.locale = :locale'
                ))
                ->setParameter('locale', $locale);
        }
        if ($addSelect) {
            $qb
                ->addSelect('image')
                ->addSelect('image_translations');
        }
    }
}

Add imageable entity repository trait.

Add imageable entity repository trait.


<?php

namespace DMS\DMS\Bundle\FilterBundle\Tests\Integration;

use DMS\Bundle\FilterBundle\DependencyInjection\DMSFilterExtension;
use Doctrine\Common\Annotations\AnnotationReader;
use Symfony\Component\DependencyInjection\ContainerBuilder;

class ContainerTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var ContainerBuilder
     */
    private $container;

    /**
     * @before
     * @return void
     */
    public function buildContainer()
    {
        $this->container = new ContainerBuilder();

        // Cover external dependencies
        $this->container->set('annotation_reader', $this->prophesize(AnnotationReader::class)->reveal());

        $extension = new DMSFilterExtension();
        $extension->load([], $this->container);

        $this->container->compile();
    }

    public function testContainerBoots()
    {
        $this->container->get('dms.filter');

        if (method_exists($this->container, 'isCompiled')) {
            self::assertTrue($this->container->isCompiled());
        } else {
            self::assertTrue($this->container->isFrozen());
        }

    }
}

Add test for container compilation

Add test for container compilation

To help catch changes in symfony container such as the ones in 3.3


<?php

namespace Tests\Unit;

use App\Repositories\AttachmentRepository;
use Tests\TestCase;

class AttachmentTest extends TestCase
{
    public function testFileTypeAccessor(): void
    {
        $attachmentRepository = new AttachmentRepository();

        $cases = [
            [
                'file_path' => 'grass.png',
                'expected' => 'png'
            ],
            [
                'file_path' => 'water.pdf',
                'expected' => 'pdf'
            ],
            [
                'file_path' => 'night.jpeg',
                'expected' => 'jpeg'
            ]
        ];

        foreach ($cases as $case) {
            $attachment = $attachmentRepository->create('spending', 1, $case['file_path']);

            $this->assertEquals($case['expected'], $attachment->file_type);
        }
    }
}

Test Attachment model's file_path accessor


<?php

declare(strict_types=1);

namespace Ray\Compiler\Deep;

final class FakeDemand
{
    public $dep;
    public function __construct(
        FakeDep $dep
    )
    {
        $this->dep = $dep;
    }
}

Add script injector serialize test

Add script injector serialize test


<?php

use OpenSRS\Ops;

class OpsTest extends PHPUnit_Framework_TestCase
{
    /**
     * Should convert specials chars, & encode in utf8
     *
     * @return void
     */
    public function testQuoteXMLChars()
    {
        $ops = new Ops;
        $data = 'This is my & < > \' " string';
        $result = $ops->_quoteXMLChars($data);

        /// chars should be converted
        $this->assertEquals($result, 'This is my & < > ' " string');

        // should be utf8
        $this->assertTrue(mb_check_encoding($result, 'UTF-8'));
    }

    /**
     * Should return true for associative, and false for plain
     *
     * @return void
     */
    public function testIsAssoc()
    {
        $ops = new Ops;
        $no = array(1, 2, 3, 4);
        $yes = array('this' => 'is', 'associative');

        $this->assertFalse($ops->_is_assoc($no));
        $this->assertTrue($ops->_is_assoc($yes));
    }

    /**
     * Should convert php array to formmated xml
     *
     * @return void
     */
    public function testPhp2Xml()
    {
        $ops = new Ops;
        $data = array('convert' => 'this');
        $result = $ops->PHP2XML($data);

        $this->assertEquals($result, "  <data_block>\n   <dt_assoc>\n   <item key=\"convert\">this</item>\n   </dt_assoc>\n  </data_block>");
    }

    /**
     * Should convert php arrays to valid xml recursivly
     *
     * @return void
     */
    public function testConvertData()
    {
        $ops = new Ops;
        $data = array('please' => 'convert', 'me');

        $result = $ops->_convertData($data);

        $xml = XMLReader::xml($result);

        // The validate parser option must be enabled for
        // this method to work properly
        $xml->setParserProperty(XMLReader::VALIDATE, true);

        // make sure this is xml
        $this->assertTrue($xml->isValid());
    }

    /**
     * Should convert php arrays to valid xml
     *
     * @return void
     */
    public function testEncode()
    {
        $ops = new Ops;
        $data = array('protocol' => '', 'action' => '', 'object' => '');

        $result = $ops->encode($data);

        $xml = XMLReader::xml($result);

        // The validate parser option must be enabled for
        // this method to work properly
        $xml->setParserProperty(XMLReader::VALIDATE, true);

        // make sure this is xml
        $this->assertTrue($xml->isValid());
    }

    /**
     * should convert xml to php array
     *
     * @return void
     */
    public function testXml2Php()
    {
        $ops = new Ops;
        $data = array('convert' => 'this');

        // use our built in php to xml to test
        $result = $ops->PHP2XML($data);

        // converting back, they should be the same
        $this->assertSame($data, $ops->XML2PHP($result));
    }
}

Add coverage for Ops class

Add coverage for Ops class


<?php

/**
 * PHP Version 5.3
 *
 * @copyright   (c) 2015 brian ridley
 * @author      brian ridley <ptlis@ptlis.net>
 * @license     http://opensource.org/licenses/MIT MIT
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace ptlis\ShellCommand;

use ptlis\ShellCommand\Interfaces\CommandInterface;
use ptlis\ShellCommand\Interfaces\EnvironmentInterface;
use ptlis\ShellCommand\Interfaces\ProcessObserverInterface;
use ptlis\ShellCommand\Interfaces\RunningProcessInterface;

/**
 * Implementation of a Windows environment.
 */
class WindowsEnvironment implements EnvironmentInterface
{
    /**
     * @inheritDoc
     */
    public function validateCommand($command, $cwdOverride = '')
    {
        // TODO: Implement validateCommand() method.
    }

    /**
     * @inheritDoc
     */
    public function buildProcess(
        CommandInterface $command,
        $cwd,
        ProcessObserverInterface $processObserver = null,
        $timeout = -1,
        $pollTimeout = 1000
    ) {
        // TODO: Implement buildProcess() method.
    }

    /**
     * @inheritDoc
     */
    public function sendSignal($process, $signal)
    {
        // TODO: Implement sendSignal() method.
    }

}

Add stub class for Windows Environments

Add stub class for Windows Environments


<?php
App::uses('AppController', 'Controller');

/**
 * Search controller
 *
 * Handles site-wide search.
 */
class SearchController extends AppController
{
	public function this($description, $start = 0)
	{
		$products = $this->requestAction(array(
			'controller' => 'products',
			'action' => 'search'),
			array('pass' => array($description, $start)));

		$this->set('products', $products);
		$this->set('_serialize', array('products'));
	}
}

Implement the site-wide search controller.