<?php

class Logger {

	const LOGFILE = 'weather.log';

	public static function log($message = '') {
		date_default_timezone_set('America/Edmonton');
		$message = date('D j M Y g:i a') . ' -- ' . $message . "\n";
		@file_put_contents(self::LOGFILE, $message, FILE_APPEND);
	}
}
?>

Add static logging class to repo.

Add static logging class to repo.


<?php
/**
 * This file is part of the Imbo package
 *
 * (c) Christer Edvartsen <cogo@starzinger.net>
 *
 * For the full copyright and license information, please view the LICENSE file that was
 * distributed with this source code.
 */

namespace Imbo\EventListener\AccessToken;

/**
 * Implementation of the default SHA256 access token generator
 *
 * @author Mats Lindh <mats@lindh.no>
 * @package AccessToken
 */
class SHA256 extends AccessTokenGenerator {
    public function generateSignature($data, $privateKey) {
        return hash_hmac('sha256', $data, $privateKey);
    }
}

Implement default access token algorithm as an access token generator


<?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 Entities;

use Illuminate\Http\Request;
use Nestor\Http\Middleware\ProjectPosition;
use \TestCase;

class FakeResponse extends \stdClass
{
    public function __construct()
    {
        $this->name = '';
        $this->value = '';
    }
    public function header($name, $value)
    {
        $this->name = $name;
        $this->value = $value;
    }
}

class ProjectPositionTest extends TestCase
{

    public function setUp()
    {
        parent::setUp();
        $this->createApplication();
    }

    public function testNoProjectId()
    {
        //$this->assertViewHas('X-NESTORQA-PROJECT-ID', null);

        $guard = $this->mock('Illuminate\Contracts\Auth\Guard');
        $mw = new ProjectPosition($guard);

        \Session::setDefaultDriver('array');
        $manager = app('session');

        $request = new Request();
        $request->setSession($manager->driver());

        $response = new FakeResponse();

        $mw->handle($request, function ($request) use ($response) {
            return $response;
        });

        $this->assertEquals('', $response->name);
        $this->assertEquals('', $response->value);
    }

    public function testWithProjectId()
    {
        //$this->assertViewHas('X-NESTORQA-PROJECT-ID', null);

        $guard = $this->mock('Illuminate\Contracts\Auth\Guard');
        $mw = new ProjectPosition($guard);

        \Session::setDefaultDriver('array');
        $manager = app('session');

        $request = new Request();
        $request->setSession($manager->driver());
        $projectId = $this->faker->numberBetween(1, 10);
        $request->session()->set('project_id', $projectId);

        $response = new FakeResponse();

        $mw->handle($request, function ($request) use ($response) {
            return $response;
        });

        $this->assertEquals('X-NESTORQA-PROJECT-ID', $response->name);
        $this->assertEquals($projectId, $response->value);
    }
}

Add middleware tests (project position)

Add middleware tests (project position)


<?php

declare(strict_types=1);

namespace PhpSchool\PhpWorkshopTest;

use PHPUnit\Framework\TestCase;
use Symfony\Component\Filesystem\Filesystem;

abstract class BaseTest extends TestCase
{
    private $tempDirectory;

    public function getTemporaryDirectory(): string
    {
        if (!$this->tempDirectory) {
            $tempDirectory = sprintf('%s/%s', realpath(sys_get_temp_dir()), $this->getName());
            mkdir($tempDirectory, 0777, true);

            $this->tempDirectory = realpath($tempDirectory);
        }

        return $this->tempDirectory;
    }

    public function tearDown(): void
    {
        if ($this->tempDirectory) {
            (new Filesystem())->remove($this->tempDirectory);
        }
    }
}

Add base test class to ease testing

Add base test class to ease testing


<?php

require_once __DIR__ . '/../../../lib/__init__.php';

class WebDriverClickAndHoldActionTest extends PHPUnit_Framework_TestCase
{
    /**
     * @type WebDriverClickAndHoldAction
     */
    private $webDriverClickAction;

    private $webDriverMouse;
    private $locationProvider;

    public function setUp()
    {
        $this->webDriverMouse = $this->getMock('WebDriverMouse');
        $this->locationProvider = $this->getMock('WebDriverLocatable');
        $this->webDriverClickAction = new WebDriverClickAndHoldAction(
            $this->webDriverMouse,
            $this->locationProvider
        );
    }

    public function testPerformSendsMouseDownCommand()
    {
        $coords = $this->getMockBuilder('WebDriverCoordinates')->disableOriginalConstructor()->getMock();
        $this->webDriverMouse->expects($this->once())->method('mouseDown');
        $this->locationProvider->expects($this->once())->method('getCoordinates')->will($this->returnValue($coords));
        $this->webDriverClickAction->perform();
    }
}

Add unit test for WebDriverClickAndHoldAction


<?php

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

class InsertAfricanCurrencies extends Migration {
    public function up() {
        DB::table('currencies')->insert([
            [
                'name' => 'Libyan Dinar',
                'symbol' => 'LYD'
            ], [
                'name' => 'Tunisian Dinar',
                'symbol' => 'TND'
            ], [
                'name' => 'Ghanaian Cedis',
                'symbol' => 'GHS'
            ], [
                'name' => 'Sudanese Pound',
                'symbol' => 'SDG'
            ], [
                'name' => 'Moroccan Dirham',
                'symbol' => 'MAD'
            ], [
                'name' => 'Botswana Pula',
                'symbol' => 'BWP'
            ], [
                'name' => 'South African Rand',
                'symbol' => 'ZAR'
            ], [
                'name' => 'Egyptian Pound',
                'symbol' => 'EGP'
            ], [
                'name' => 'Eritrean Nakfa',
                'symbol' => 'ERN'
            ], [
                'name' => 'Zambian Kwacha',
                'symbol' => 'ZMW'
            ], [
                'name' => 'Angolan Kwanza',
                'symbol' => 'AKZ'
            ]
        ]);
    }

    public function down() {
        //
    }
}

Create migration for inserting African currencies


<?php
namespace Math\Probability\Distribution\Continuous;

class CauchyTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider dataProviderForPDF
     */
    public function testPDF($x, $x₀, $γ, $pdf)
    {
        $this->assertEquals($pdf, Cauchy::PDF($x, $x₀, $γ), '', 0.0001);
    }

    public function dataProviderForPDF()
    {
        return [
            [1, 0, 1, 0.1591549430918953357689],
            [0, 1, 1, 0.1591549430918953357689],
            [1, 1, 1, 0.3183098861837906715378],
            [2, 3, 4, 0.07489644380795074624418],
            [4, 3, 2, 0.1273239544735162686151],
            [5, 5, 5, 0.06366197723675813430755],
        ];
    }

    /**
     * @dataProvider dataProviderForCDF
     */
    public function testCDF($x, $x₀, $γ, $cdf)
    {
        $this->assertEquals($cdf, Cauchy::CDF($x, $x₀, $γ), '', 0.0001);
    }

    public function dataProviderForCDF()
    {
        return [
            [1, 0, 1, 0.75],
            [0, 1, 1, 0.25],
            [1, 1, 1, 0.5],
            [2, 3, 4, 0.4220208696226306745395],
            [4, 3, 2, 0.6475836176504332741754],
            [5, 5, 5, 0.5],
        ];
    }

    public function testMean()
    {
        $this->assertNull(Cauchy::mean(1, 1));
        $this->assertNull(Cauchy::mean(2, 3));
    }

    public function testMedian()
    {
        $x₀ = 5;
        $γ  = 3;
        $this->assertEquals($x₀, Cauchy::median($x₀, $γ));
    }

    public function testMode()
    {
        $x₀ = 5;
        $γ  = 3;
        $this->assertEquals($x₀, Cauchy::median($x₀, $γ));
    }
}

Add unit tests for Cauchy distribution.

Add unit tests for Cauchy distribution.


<?php

namespace LAG\AdminBundle\Tests\Utils;

use LAG\AdminBundle\Tests\AdminTestBase;
use LAG\AdminBundle\Utils\FormUtils;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\NumberType;
use Symfony\Component\Form\Extension\Core\Type\TextType;

class FormUtilsTest extends AdminTestBase
{
    public function testConvertShortFormType()
    {
        $this->assertEquals(ChoiceType::class, FormUtils::convertShortFormType('choice'));
        $this->assertEquals(ChoiceType::class, FormUtils::convertShortFormType('array'));
        $this->assertEquals(TextType::class, FormUtils::convertShortFormType('string'));
        $this->assertEquals(EntityType::class, FormUtils::convertShortFormType('entity'));
        $this->assertEquals(DateType::class, FormUtils::convertShortFormType('date'));
        $this->assertEquals(DateType::class, FormUtils::convertShortFormType('datetime'));
        $this->assertEquals(TextType::class, FormUtils::convertShortFormType('text'));
        $this->assertEquals(NumberType::class, FormUtils::convertShortFormType('number'));
        $this->assertEquals(NumberType::class, FormUtils::convertShortFormType('integer'));
        $this->assertEquals(NumberType::class, FormUtils::convertShortFormType('smallint'));
        $this->assertEquals(CheckboxType::class, FormUtils::convertShortFormType('boolean'));
        $this->assertEquals('my_custom_type', FormUtils::convertShortFormType('my_custom_type'));
    }
}

Add tests for the FormUtils class

Add tests for the FormUtils class


<?php

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

class CreateSessionsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('sessions', function (Blueprint $table) {
            $table->string('id')->unique();
            $table->integer('user_id')->nullable();
            $table->string('ip_address', 45)->nullable();
            $table->text('user_agent')->nullable();
            $table->text('payload');
            $table->integer('last_activity');
        });
    }

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

Implement session table -> database

Implement session table -> database


<?php

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

class AddIndexForUserIp extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('activities', function (Blueprint $table) {
            $table->index('ip', 'ip_address_index');
        });
    }

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

Add index for user IP address

Add index for user IP address


<?php
require_once '../../src/apiClient.php';
require_once '../../src/contrib/apiCalendarService.php';
session_start();

$client = new apiClient();
$client->setApplicationName("Google Calendar PHP Starter Application");

// Visit https://code.google.com/apis/console?api=calendar to generate your
// client id, client secret, and to register your redirect uri.
// $client->setClientId('insert_your_oauth2_client_id');
// $client->setClientSecret('insert_your_oauth2_client_secret');
// $client->setRedirectUri('insert_your_oauth2_redirect_uri');
// $client->setDeveloperKey('insert_your_developer_key');
$cal = new apiCalendarService($client);
if (isset($_GET['logout'])) {
  unset($_SESSION['token']);
}

if (isset($_GET['code'])) {
  $client->authenticate();
  $_SESSION['token'] = $client->getAccessToken();
  header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}

if (isset($_SESSION['token'])) {
  $client->setAccessToken($_SESSION['token']);
}

if ($client->getAccessToken()) {
  $calList = $cal->calendarList->listCalendarList();
  print "
Calendar List

" . print_r($calList, true) . "
";

$_SESSION['token'] = $client->getAccessToken();
} else {
  $authUrl = $client->createAuthUrl();
  print "Connect Me!";
}

Add the Google Calendar starter application.


// These all yield the same result
$class_name = get_called_class();
$class_name = static::class;
$class_name = static();

// Instantiate
$instance = new get_called_class(); // Error
$instance = new static::class; // Error
$instance = new static();
$instance = new $class_name;

Add techniques for getting PHP class names


<?php

namespace ProcessWire\GraphQL\Test\Field\Page\Fieldtype;

use ProcessWire\GraphQL\Utils;
use ProcessWire\GraphQL\Test\GraphQLTestCase;
use ProcessWire\GraphQL\Test\Field\Page\Fieldtype\FieldtypeTestTrait;

class FieldtypeImageDimensionsTest extends GraphQLTestCase {

	const TEMPLATE_NAME = 'skyscraper';
	const FIELD_NAME = 'images';
	const FIELD_TYPE = 'FieldtypeImage';

	use FieldtypeTestTrait;

	public function testDimensions()
	{
		$skyscraper = Utils::pages()->find("template=skyscraper, images.count>0, sort=random")->first();
		$query = "{
			skyscraper (s: \"id=$skyscraper->id\") {
				list {
					images {
						height
						width
					}
				}
			}
		}";
		$res = $this->execute($query);
		$this->assertEquals(
			$skyscraper->images->first()->height,
			$res->data->skyscraper->list[0]->images[0]->height,
			'Retrieves image height.'
		);
		$this->assertEquals(
			$skyscraper->images->first()->width,
			$res->data->skyscraper->list[0]->images[0]->width,
			'Retrieves image width.'
		);
	}

}

Test `FieldtypeImage` width & height.

Test `FieldtypeImage` width & height.


<?php

namespace Listabierta\Bundle\MunicipalesBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Validator\Constraints as Assert;

class CandidateStep3Type extends AbstractType
{
	public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
	            ->add('continue', 'submit', array('attr' => array('class' => 'submit')));
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
    }

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

Add stub for candidate step 3 form type

Add stub for candidate step 3 form type


<?php
/**
 * PHP VIN Utility Library
 *
 * LICENSE
 *
 * 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.
 *
 * @package		libphp-vin
 * @subpackage	Vin
 * @copyright	Copyright (c) 2010 Chris Smith (http://www.cs278.org/)
 * @license		http://www.opensource.org/licenses/mit-license.php MIT License
 * @version
 */
namespace libphpvin\Vin;

/**
 * @package		libphp-vin
 * @subpackage	Vin
 * @copyright	Copyright (c) 2010 Chris Smith (http://www.cs278.org/)
 * @license		http://www.opensource.org/licenses/mit-license.php MIT License
 */
abstract class Base extends Component\Base implements \libphpvin\Vin
{
	protected $_validator;

	public function getValidator()
	{
		return $this->_validator;
	}

	public function setValidator(\libphpvin\Vin\Validator $validator)
	{
		$this->_validator = $validator;

		return $this;
	}
}

Add an abstract for complete VIN concrete classes to build upon.


<?php

namespace OpenCFP\Test\Unit\Infrastructure\Auth;

use Cartalyst\Sentinel\Sentinel;
use Mockery;
use Mockery\Adapter\Phpunit\MockeryPHPUnitIntegration;
use OpenCFP\Domain\Services\AccountManagement;
use OpenCFP\Infrastructure\Auth\SentinelAccountManagement;
use OpenCFP\Infrastructure\Auth\SentinelUser;
use OpenCFP\Infrastructure\Auth\UserNotFoundException;

/**
 * @covers \OpenCFP\Infrastructure\Auth\SentinelAccountManagement
 */
class SentinelAccountManagementTest extends \PHPUnit\Framework\TestCase
{
    use MockeryPHPUnitIntegration;

    public function testInstanceOfAccountManagement()
    {
        $sentinel = (new \Cartalyst\Sentinel\Native\Facades\Sentinel())->getSentinel();
        $account  = new SentinelAccountManagement($sentinel);
        $this->assertInstanceOf(AccountManagement::class, $account);
    }

    public function testFindByIdThrowsCorrectError()
    {
        $sentinel = Mockery::mock(Sentinel::class);
        $sentinel->shouldReceive('getUserRepository->findById')->andReturn(null);
        $account = new SentinelAccountManagement($sentinel);
        $this->expectException(UserNotFoundException::class);
        $account->findById(3);
    }

    public function testFindByIdReturnsSentinelUser()
    {
        $user     = Mockery::mock(\Cartalyst\Sentinel\Users\UserInterface::class)->makePartial();
        $sentinel = Mockery::mock(Sentinel::class);
        $sentinel->shouldReceive('getUserRepository->findById')->andReturn($user);
        $account = new SentinelAccountManagement($sentinel);
        $this->assertInstanceOf(SentinelUser::class, $account->findById(3));
    }

    public function testFindByLoginThrowsCorrectError()
    {
        $sentinel = Mockery::mock(Sentinel::class);
        $sentinel->shouldReceive('getUserRepository->findByCredentials')->andReturn(null);
        $account = new SentinelAccountManagement($sentinel);
        $this->expectException(UserNotFoundException::class);
        $account->findByLogin('mail@mail.mail');
    }

    public function testFindByLoginReturnsSentinelUser()
    {
        $user     = Mockery::mock(\Cartalyst\Sentinel\Users\UserInterface::class)->makePartial();
        $sentinel = Mockery::mock(Sentinel::class);
        $sentinel->shouldReceive('getUserRepository->findByCredentials')->andReturn($user);
        $account = new SentinelAccountManagement($sentinel);
        $this->assertInstanceOf(SentinelUser::class, $account->findByLogin('mail@mail.mail'));
    }
}

Add tests for sentinel account management

Addition of unit tests for teh account management


<?php

use Phinx\Migration\AbstractMigration;

class CreateSentinelUser extends AbstractMigration
{
    /**
     * Change Method.
     *
     * Write your reversible migrations using this method.
     *
     * More information on writing migrations is available here:
     * http://docs.phinx.org/en/latest/migrations.html#the-abstractmigration-class
     *
     * The following commands can be used in this method and Phinx will
     * automatically reverse them when rolling back:
     *
     *    createTable
     *    renameTable
     *    addColumn
     *    renameColumn
     *    addIndex
     *    addForeignKey
     *
     * Remember to call "create()" or "update()" and NOT "save()" when working
     * with the Table class.
     */
    public function up()
    {
        $query = file_get_contents(__DIR__.'/../../../vendor/cartalyst/sentinel/schema/mysql.sql');

        $this->execute($query);
    }

    public function down()
    {

    }
}

Add migration user with Sentinel

Add migration user with Sentinel


<?php

namespace AbleCore\Modules;

class ImageStyleManager {

	private $generated = array();

	public static function init()
	{
		return new self();
	}

	public function define($name, $label, $effects = array())
	{
		$this->generated[$name] = array(
			'label' => $label,
			'effects' => $effects,
		);
		return $this;
	}

	public function defineScale($name, $label, $width = null, $height = null, $upscale = false)
	{
		$effects = array();
		$scale_effect = array(
			'name' => 'image_scale',
			'data' => array(),
		);
		if ($width !== null)
			$scale_effect['data']['width'] = $width;
		if ($height !== null)
			$scale_effect['data']['height'] = $height;
		$scale_effect['data']['upscale'] = $upscale;
		$effects[] = $scale_effect;
		return $this->define($name, $label, $effects);
	}

}

Add basic image styles class.

Add basic image styles class.


<?php

// Add X-UA-Compatible tag
add_action( 'genesis_meta', 'bsg_x_ua_compatible' );

function bsg_x_ua_compatible() {
    ?>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<?php
}

Add X-UA-Compatible tag for IE compatibility

Add X-UA-Compatible tag for IE compatibility, see
https://www.modern.ie/en-us/performance/how-to-use-x-ua-compatible
and
http://stackoverflow.com/questions/19784822/does-meta-http-equiv-x-ua-compatible-content-ie-edge-impact-on-non-ie-explor

Fixes #21


<?php

/**
 * Class CacheIncludeSiteTreeExtension
 */
class CacheIncludeSiteTreeExtension extends DataExtension
{
    /**
     * @return array
     */
    public function extraStatics()
    {
        return array(
            'db' => array(
                'FullLink' => 'Varchar(255)'
            )
        );
    }
    /**
     *
     */
    public function onBeforeWrite()
    {
        parent::onBeforeWrite();

        // Ensure that the method exists
        if (method_exists($this->owner, 'RelativeLink')) {
            $this->owner->FullLink = $this->owner->RelativeLink();
        }
    }
}

Add DataExtension for silverstripe 3

UPDATE: Add DataExtension for silverstripe 3


<?php

/*
 * This file is part of Flarum.
 *
 * For detailed copyright and license information, please view the
 * LICENSE file that was distributed with this source code.
 */

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Schema\Builder;

return [
    'up' => function (Builder $schema) {
        $schema->table('discussions', function (Blueprint $table) {
            $table->integer('comment_count')->default(1)->change();
        });
    },

    'down' => function (Builder $schema) {
        $schema->table('discussions', function (Blueprint $table) {
            $table->integer('comment_count')->default(0)->change();
        });
    }
];

Change default discussion comment count

Change default discussion comment count

This allows new public discussions to be immediately visible by users.


<?php

namespace ATP\Application;

class Config
{
	public static function defaultOptions($appOptions, $env)
	{
		return array_merge($appOptions, array(
			'module_listener_options' => array(
				'module_paths' => array(
					'./module',
					'./vendor',
				),

				'config_glob_paths' => array(
					"config/autoload/{,*.}{global,{$env},local}.php",
				),

				'config_cache_enabled' => ($env == 'production'),
				'config_cache_key' => 'app_config',
				'module_map_cache_enabled' => ($env == 'production'),
				'module_map_cache_key' => 'module_map',
				'cache_dir' => 'data/config/',
				'check_dependencies' => ($env != 'production')
			),
		));
	}
}

Move default app options into ATP

Move default app options into ATP


<?php
namespace Elastification\Client\Tests\Fixtures\Unit\Transport\Thrift;

use Elastification\Client\Transport\Thrift\ThriftTransportConnectionFactory;

class ThriftTransportConnectionFactoryTest extends \PHPUnit_Framework_TestCase
{

    private function guardExtensionPresent()
    {
        if (!extension_loaded('thrift_protocol')) {
            $this->markTestSkipped('Thrift Extension not installed, skipping test.');
        }
    }

    public function testFactoryDefaultParams()
    {
        $this->guardExtensionPresent();
        $restClient = ThriftTransportConnectionFactory::factory('localhost', 9500);
        $this->assertInstanceOf('Elasticsearch\RestClient', $restClient);
    }

    public function testFactoryWithSendTimeout()
    {
        $this->guardExtensionPresent();
        $restClient = ThriftTransportConnectionFactory::factory('localhost', 9500, 100);
        $this->assertInstanceOf('Elasticsearch\RestClient', $restClient);
    }

    public function testFactoryWithReceiveTimeout()
    {
        $this->guardExtensionPresent();
        $restClient = ThriftTransportConnectionFactory::factory('localhost', 9500, null, 100);
        $this->assertInstanceOf('Elasticsearch\RestClient', $restClient);
    }

    public function testFactoryWithBothTimeouts()
    {
        $this->guardExtensionPresent();
        $restClient = ThriftTransportConnectionFactory::factory('localhost', 9500, 100, 100);
        $this->assertInstanceOf('Elasticsearch\RestClient', $restClient);
    }

    public function testFactoryWithBothTimeoutsAndFramedTransport()
    {
        $this->guardExtensionPresent();
        $restClient = ThriftTransportConnectionFactory::factory('localhost', 9500, 100, 100, true);
        $this->assertInstanceOf('Elasticsearch\RestClient', $restClient);
    }
}

Add integration test for thrift client factory


<?php

use \PHPUnit\Framework\TestCase;
use \AdobeConnectClient\Helpers\SetEntityAttributes;
use \AdobeConnectClient\Entities\Permission;

class SetEntityAttributesTest extends TestCase
{

    public function testSetAttributes()
    {
        $data = [
            'acl-id' => 5,
            'permission-id' => Permission::PRINCIPAL_HOST,
            'imaginary' => [
                'principal-id' => 10
            ]
        ];

        $permission = new Permission();

        SetEntityAttributes::setAttributes($permission, $data);

        $this->assertEquals($data['acl-id'], $permission->getAclId());
        $this->assertEquals($data['permission-id'], $permission->getPermissionId());
        $this->assertEquals($data['imaginary']['principal-id'], $permission->getPrincipalId());
    }
}

Create tests for SetEntityAttributes helper


<?php

namespace Becklyn\AssetsBundle\tests\Processor;

use Becklyn\AssetsBundle\Processor\AssetProcessor;
use Becklyn\AssetsBundle\Processor\ProcessorRegistry;
use PHPUnit\Framework\TestCase;

class ProcessorRegistryTest extends TestCase
{
    public function testGetter ()
    {
        $cssProcessor = self::getMockBuilder(AssetProcessor::class)
            ->getMock();

        $registry = new ProcessorRegistry([
            "css" => $cssProcessor,
        ]);

        self::assertEquals($cssProcessor, $registry->get("test.css"));
        self::assertTrue($registry->has("test.css"));
        self::assertNull($registry->get("test.js"));
        self::assertFalse($registry->has("test.js"));
    }
    public function testEmpty ()
    {
        $registry = new ProcessorRegistry([]);

        self::assertNull($registry->get("test.css"));
        self::assertFalse($registry->has("test.css"));
        self::assertNull($registry->get("test.js"));
        self::assertFalse($registry->has("test.js"));
    }
}

Add tests for processor registry

Add tests for processor registry


<?php

final class PhabricatorProjectListController
  extends PhabricatorProjectController {

  private $queryKey;

  public function shouldAllowPublic() {
    return true;
  }

  public function willProcessRequest(array $data) {
    $this->queryKey = idx($data, 'queryKey');
  }

  public function processRequest() {
    $controller = id(new PhabricatorApplicationSearchController())
      ->setQueryKey($this->queryKey)
      ->setSearchEngine(new PhabricatorProjectSearchEngine())
      ->setNavigation($this->buildSideNavView());

    return $this->delegateToController($controller);
  }

  public function buildApplicationCrumbs() {
    $crumbs = parent::buildApplicationCrumbs();

    $can_create = $this->hasApplicationCapability(
      ProjectCreateProjectsCapability::CAPABILITY);

    $crumbs->addAction(
      id(new PHUIListItemView())
        ->setName(pht('Create Project'))
        ->setHref($this->getApplicationURI('create/'))
        ->setIcon('fa-plus-square')
        ->setWorkflow(!$can_create)
        ->setDisabled(!$can_create));

    return $crumbs;
  }

}

<?php

final class PhabricatorProjectListController
  extends PhabricatorProjectController {

  private $queryKey;

  public function shouldAllowPublic() {
    return true;
  }

  public function willProcessRequest(array $data) {
    $this->queryKey = idx($data, 'queryKey');
  }

  public function processRequest() {
    $controller = id(new PhabricatorApplicationSearchController())
      ->setQueryKey($this->queryKey)
      ->setSearchEngine(new PhabricatorProjectSearchEngine())
      ->setNavigation($this->buildSideNavView());

    return $this->delegateToController($controller);
  }

  public function buildApplicationMenu() {
    return $this->buildSideNavView(true)->getMenu();
  }

  public function buildApplicationCrumbs() {
    $crumbs = parent::buildApplicationCrumbs();

    $can_create = $this->hasApplicationCapability(
      ProjectCreateProjectsCapability::CAPABILITY);

    $crumbs->addAction(
      id(new PHUIListItemView())
        ->setName(pht('Create Project'))
        ->setHref($this->getApplicationURI('create/'))
        ->setIcon('fa-plus-square')
        ->setWorkflow(!$can_create)
        ->setDisabled(!$can_create));

    return $crumbs;
  }

}

Add mobile app menu to Project Lists

Add mobile app menu to Project Lists

Summary: Using Project lists on mobile is missing the query menu, this adds it.

Test Plan: test mobile layout, click menu, see query list

Reviewers: btrahan, epriestley

Reviewed By: epriestley

Subscribers: Korvin, epriestley

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


<?php

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

class CreateFailedJobsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('failed_jobs', function (Blueprint $table) {
            $table->increments('id');
            $table->text('connection');
            $table->text('queue');
            $table->longText('payload');
            $table->timestamp('failed_at')->useCurrent();
        });
    }

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

Create table for failed queue jobs

Create table for failed queue jobs


<?php

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

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

        $this->addForeignKey('FK_group_specialty', '{{%group}}', 'specialty_id', '{{%specialty}}', 'id', 'RESTRICT', 'RESTRICT');
        $this->createIndex('NAME', '{{%group}}', ['name', 'specialty_id'], true);
    }

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

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

Add migration for Group entity

Add migration for Group entity


<?php

namespace Listabierta\Bundle\MunicipalesBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class SMSInboundController extends Controller
{
	public function indexAction(Request $request = NULL)
	{
		return new Response('OK', 200);
	}
}

Implement sms inbound controller as stub


<?php

namespace Equip\Dispatch;

use Eloquent\Phony\Phpunit\Phony;
use Interop\Http\Middleware\DelegateInterface;
use Psr\Http\Message\RequestInterface;

class DelegateProxyTest extends TestCase
{
    public function testWrap()
    {
        $request = $this->mockRequest();
        $response = $this->mockResponse();

        $delegate = Phony::mock(DelegateInterface::class);

        $delegate->process->does(function (RequestInterface $request) use ($response) {
            return $response;
        });

        // Run
        $proxy = new DelegateProxy($delegate->get());
        $output = $proxy($request);

        // Verify
        Phony::inOrder(
            $delegate->process->calledWith($request)
        );

        $this->assertTrue(is_callable($proxy));
        $this->assertSame($response, $output);
    }
}

Add separate test for delegate proxy

Add separate test for delegate proxy


<?php
/**
 * @author: Koshkin Alexey <koshkin.alexey@gmail.com>
 */

if (!$model->isNewRecord) {
	$form = $this->beginWidget(
		CActiveForm::class,
		[
			'method' => 'post',
		]
	);

	echo CHtml::tag('button',
		[
			'name'=> CHtml::resolveName($model, $attribute),
			'value' => 1,
		],
		$model->getAttributeLabel($attribute)
	);

	$this->endWidget();
}

Remove external class usage, add 2 types


<?php

	/**
	 * queueRunner.php
	 * Usage:
	 * > php queueRunner.php -q queueName
	 */

	(PHP_SAPI === "cli") ?: die("Command line usage only");

	require("vendor/autoload.php");

	define("ROOT_SERVER", __DIR__ . "/");

	require_once(ROOT_SERVER . "library/config.php");

	#set_error_handler(array("Cube\\Handler", "error"), E_ALL & ~E_NOTICE);
	#set_exception_handler(array("Cube\\Handler", "exception"));

	$options = getopt("q:");

	if (!$options['q'] || preg_match('/[^a-z_\-0-9]/i', $options['q']))
	{
		die("Invalid queue name");
	}

	$connection = new App\Connections\Aws\Sqs();
	$connection->queue($options['q']);

	$worker = new Queue\Worker($connection);
	$worker->start();
?>

Add basic queue runner cli script

Add basic queue runner cli script


<?php
$city  = "San Francisco";
$state = "CA";
$event = "SIGGRAPH";

$location_vars = array("city", "state");

$result = compact("event", "nothing_here", $location_vars);
print_r($result);
?>

Create array containing variables and their values


<?php

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

use Doctrine\Common\Collections\ArrayCollection;

use Oro\Bundle\LocaleBundle\Entity\LocalizedFallbackValue;
use Oro\Bundle\LocaleBundle\Helper\LocalizationHelper;
use Oro\Bundle\LocaleBundle\Layout\LocaleProvider;

class LocaleProviderTest extends \PHPUnit_Framework_TestCase
{
    /** @var LocalizationHelper|\PHPUnit_Framework_MockObject_MockObject */
    protected $localizationHelper;

    /** @var LocaleProvider */
    protected $provider;

    /**
     * {@inheritdoc}
     */
    public function setUp()
    {
        $this->localizationHelper = $this->getMockBuilder(LocalizationHelper::class)
            ->disableOriginalConstructor()
            ->getMock();

        $this->provider = new LocaleProvider($this->localizationHelper);
    }

    public function testGetLocalizedValue()
    {
        $value = new LocalizedFallbackValue();
        $collection = new ArrayCollection();

        $this->localizationHelper->expects($this->once())
            ->method('getLocalizedValue')
            ->with($collection)
            ->willReturn($value);

        $this->assertSame($value, $this->provider->getLocalizedValue($collection));
    }
}

BB-4163: Refactor localized_value expression to data provider
- updated tests


<?php

require_once('boston_food_trucks.php');

class Request {
	public $parameters;

	public function parse_parameters () {
		$parameters = array();

		if (isset($_SERVER['QUERY_STRING'])) {
			parse_str($_SERVER['QUERY_STRING'], $parameters);
		}

		$this->parameters = $parameters;
	}

}

class Filters {
	public $filters;
	private $keys;

	public function __construct () {
		$this->keys = array('trucks',
							'days_of_week',
							'times_of_day',
							'locations');
	}

	public function get_filters ($array) {
		// If our array includes expected keys, add those to $this->filters
		foreach ($this->keys as $value) {
			if (isset($array[$value]) and is_array($array[$value])) {
				$this->filters[$value] = $array[$value];
			}
		}
	}
}

// Parse GET parameters
$R = new Request;
$R->parse_parameters();

// Get filters from GET parameters
$Filters = new Filters;
$Filters->get_filters($R->parameters);

// Output JSON from food truck API
$BostonFoodTrucks = new BostonFoodTrucks;
echo $BostonFoodTrucks->schedule($Filters->filters);

Add HTTP version of API

Add HTTP version of API


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

   Copyright (C) 2009 Free Software Foundation, Inc

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

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

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

 */

class JSONEncoder {

	/**
	 * Encode a SimpleXML object in JSON format matching Last.fm's output
	 *
	 * @param $xml - A SimpleXMLElement
	 * @return A JSON formatted string
	 */
	public static function encodeXML($xml) {
		if($xml->getName() == 'lfm') {
			$xml = $xml->children();
		}
		$json_data[$xml->getName()] = JSONEncoder::recursivelyEncodeXML($xml);
		return json_encode($json_data);

	}

	public static function recursivelyEncodeXML($xml) {
		$json_data = array();

		if(count($xml->children())) {
			foreach($xml->children() as $child) {
				if(array_key_exists($child->getName(), $json_data)) {
					if(!array_key_exists(0, $json_data[$child->getName()])) {
						$a = array();
						$a[] = $json_data[$child->getName()];
						$json_data[$child->getName()] = $a;
					}
					$json_data[$child->getName()][] = JSONEncoder::recursivelyEncodeXML($child);
				} else {
					$json_data[$child->getName()] = JSONEncoder::recursivelyEncodeXML($child);
				}
			}
			if(count($xml->attributes())) {
				$json_data['@attr'] = array();
				foreach($xml->attributes() as $k => $v) {
					$json_data['@attr'][$k] = (string) $v;
				}
			}
		} else {
			// Leaf node
			if(count($xml->attributes())) {
				$json_data['#text'] = (string) $xml;
				foreach($xml->attributes() as $k => $v) {
					$json_data[$k] = (string) $v;
				}
			} else {
				$json_data = (string) $xml;
			}
		}

		return $json_data;
	}

}

Add class for encoding SimpleXML elements into Last.fm compatible JSON output


<?php
/**
 * @file
 */

namespace CultuurNet\UDB3\Event;

use Broadway\CommandHandling\CommandBusInterface;
use CultuurNet\UDB3\EventNotFoundException;
use CultuurNet\UDB3\EventServiceInterface;
use CultuurNet\UDB3\Language;

class DefaultEventEditingServiceTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var EventEditingServiceInterface
     */
    protected $eventEditingService;

    /**
     * @var EventServiceInterface|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $eventService;

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

    public function setUp()
    {
        $this->eventService = $this->getMock(
            'CultuurNet\\UDB3\\EventServiceInterface'
        );

        $this->commandBus = $this->getMock(
            'Broadway\\CommandHandling\\CommandBusInterface'
        );

        $this->eventEditingService = new DefaultEventEditingService(
            $this->eventService,
            $this->commandBus
        );
    }

    /**
     * @test
     */
    public function it_refuses_to_translate_title_of_unknown_event()
    {
        $id = 'some-unknown-id';

        $this->setExpectedException('CultuurNet\\UDB3\\EventNotFoundException');

        $this->eventService->expects($this->once())
            ->method('getEvent')
            ->with($id)
            ->willThrowException(new EventNotFoundException());

        $this->eventEditingService->translateTitle($id, new Language('nl'), 'new title');
    }

    public function it_refuses_to_translate_description_of_unknown_event()
    {
        $id = 'some-unknown-id';

        $this->setExpectedException('CultuurNet\\UDB3\\EventNotFoundException');

        $this->eventService->expects($this->once())
            ->method('getEvent')
            ->with($id)
            ->willThrowException(new EventNotFoundException());

        $this->eventEditingService->translateDescription($id, new Language('nl'), 'new description');
    }
}

iii-89: Add test for handling of unknown events in DefaultEventEditingService


<?php

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

class AddSourceDetailsColumnToPosts extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('posts', function (Blueprint $table) {
            $table->string('source_details')->after('source')->nullable()->comment('Extra details about the post source, like newsletter ID');
        });
    }

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

Add migration to add source_details column


<?php

/*
 * This file is part of the Zephir.
 *
 * (c) Zephir Team <team@zephir-lang.com>
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Zephir\Test\Backends\ZendEngine3;

use PHPUnit\Framework\TestCase;
use Zephir\Backends\ZendEngine3\Backend;
use Zephir\CompilationContext;
use Zephir\Config;
use Zephir\Variable;

class BackendTest extends TestCase
{
    public function stringDataProvider()
    {
        return [
            'regexp1' => ['/(\w+)\s*=\s*(\[[^\]]*\]|\"[^\"]*\"|[^,)]*)\s*(?:,|$)/', '/(\\w+)\\s*=\\s*(\\[[^\\]]*\\]|\"[^\"]*\"|[^,)]*)\\s*(?:,|$)/'],
            'regexp2' => ['/@(\w+)(?:\s*(?:\(\s*)?(.*?)(?:\s*\))?)??\s*(?:\n|\*\/)/', '/@(\\w+)(?:\\s*(?:\\(\\s*)?(.*?)(?:\\s*\\))?)??\\s*(?:\n|\\*\\/)/'],
            'simple string' => ['zephir', 'zephir'],
            'string with slashed' => ['\\Zephir', '\Zephir'],
            'string with \n' => ['\\Zephir\n', '\Zephir\\n'],
            'string with \null' => ['\\null', '\null'],
        ];
    }

    /**
     * @test
     * @dataProvider stringDataProvider
     */
    public function shouldEscapeStringWithRegexp(string $testString, string $expectedString)
    {
        $backend = new Backend(new Config(), null, null);
        $variable = new Variable('variable', 'name');
        $context = new CompilationContext();

        $actual = $backend->assignString($variable, $testString, $context, false);
        $expected = 'ZVAL_STRING(&name, "'.$expectedString.'");';

        $this->assertSame($expected, $actual);
    }
}

Add test for code generation with regexp string


<?php

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

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

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

Add Facebook event to schools table

Add Facebook event to schools table


<?php

namespace Walrus\core\entity;

class Route
{

    /**
    * URL of this Route
    * @var string
    */
    private $url;

    /**
    * Accepted HTTP methods for this route
    * @var array
    */
    private $methods = array('GET','POST','PUT','DELETE');

    /**
    * Target for this route, can be anything.
    * @var mixed
    */
    private $target;

    /**
    * The name of this route, used for reversed routing
    * @var string
    */
    private $name;

    /**
    * Custom parameter filters for this route
    * @var array
    */
    private $filters = array();

    /**
    * Array containing parameters passed through request URL
    * @var array
    */
    private $parameters = array();

    public function getUrl()
    {
        return $this->url;
    }

    public function setUrl($url)
    {
        $url = (string) $url;

        // make sure that the URL is suffixed with a forward slash
        if (substr($url, -1) !== '/') {
            $url .= '/';
        }

        $this->url = $url;
    }

    public function getTarget()
    {
        return $this->target;
    }

    public function setTarget($target)
    {
        $this->target = $target;
    }

    public function getMethods()
    {
        return $this->methods;
    }

    public function setMethods(array $methods)
    {
        $this->methods = $methods;
    }

    public function getName()
    {
        return $this->name;
    }

    public function setName($name)
    {
    	$this->name = (string) $name;
    }

    public function setFilters(array $filters) {
    	$this->filters = $filters;
    }

    public function getRegex() {
    	return preg_replace_callback("/:(\w+)/", array(&$this, 'substituteFilter'), $this->url);
    }

    private function substituteFilter($matches) {
    	if (isset($matches[1]) && isset($this->filters[$matches[1]])) {
        		return $this->filters[$matches[1]];
        	}

        	return "([\w-]+)";
    }

    public function getParameters() {
    	return $this->parameters;
    }

    public function setParameters(array $parameters) {
    	$this->parameters = $parameters;
    }

}

Create entity directory for core Class

Core: Create entity directory for core Class


<?php

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

class AddStylingColumnsToGroupsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('groups', function(Blueprint $table) {
            // How should this groups username be styled in html. The keyword $username will be replaced with the users username.
            $table->string('username_formatting')->default('$username');

            // A path relative to the public directory to a small image to be placed below a users name on their posts.
            $table->string('badge');
        });
    }

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

Add database migrations for group username styling and badges.


<?php return

within('objects',
    describe('method',
        it('calls a method with params on an object', function() {
            $object = new _MethodTestDummy;

            return expect(method('myMethod', [a, b], $object), toBe([a, b]));
        })
    )
);

final class _MethodTestDummy
{
    public function myMethod()
    {
        return func_get_args();
    }
}

Add omikron tests for objects

Add omikron tests for objects


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

use Concrete\Core\File\File;
use Concrete\Core\Updater\Migrations\AbstractMigration;
use Doctrine\DBAL\Schema\Schema;

class Version20170513000000 extends AbstractMigration
{
    public function up(Schema $schema)
    {
        // Find all files that have no FileVersions as these are invalid and are left over from a bug
        $query = 'SELECT F.fID FROM Files F WHERE F.fID NOT IN (SELECT FV.fID FROM FileVersions FV)';
        $orphan_files = $this->connection->executeQuery($query);
        while ($fID = $orphan_files->fetchColumn()) {
            $f = File::getByID($fID);
            if (is_object($f)) {
                $f->delete();
            }
        }
    }

    public function down(Schema $schema)
    {
    }
}

Remove invalid (Unknown) files from the file manager


<?php

/*
 * This file is part of the Doctrine MigrationsBundle
 *
 * The code was originally distributed inside the Symfony framework.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 * (c) Doctrine Project, Benjamin Eberlei <kontakt@beberlei.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Doctrine\Bundle\MigrationsBundle\Command;

use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Input\InputOption;
use Doctrine\Bundle\DoctrineBundle\Command\Proxy\DoctrineCommandHelper;
use Doctrine\DBAL\Migrations\Tools\Console\Command\LatestCommand;

/**
 * Command for outputting the latest version number.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 * @author Jonathan H. Wage <jonwage@gmail.com>
 */
class MigrationsLatestDoctrineCommand extends LatestCommand
{
    protected function configure()
    {
        parent::configure();

        $this
            ->setName('doctrine:migrations:latest')
            ->addOption('em', null, InputOption::VALUE_OPTIONAL, 'The entity manager to use for this command.')
        ;
    }

    public function execute(InputInterface $input, OutputInterface $output)
    {
        DoctrineCommandHelper::setApplicationEntityManager($this->getApplication(), $input->getOption('em'));

        $configuration = $this->getMigrationConfiguration($input, $output);
        DoctrineCommand::configureMigrations($this->getApplication()->getKernel()->getContainer(), $configuration);

        parent::execute($input, $output);
    }
}

Add command for outputting the latest version number


<?php
/**
 * Created by PhpStorm.
 * User: Utente
 * Date: 02/12/2016
 * Time: 13:32
 */

    /**
    * @param $data
    * @return string
     *
     *This function delete the white space, the "\" and html special character.
    */
    function testInput($data)
    {
        $data = trim($data);
        $data = stripslashes($data);
        $data = htmlspecialchars($data);
        return $data;
    }

    /**
     * @param $string
     * @return int
     * This function check if a string is alphanumeric
     * return -1 if the regular expression not is satisfied
     * else return 1
     */
    function isAlphanumeric($string)
    {
        return preg_match("/^[A-Za-z0-9_. ]*$/", $string);
    }

    /**
     * @param $string
     * @return int
     * This function check if a string is composed of only character
     * and return -1 if the regular expression not is satisfied else
     * return 1.
     *
     */
    function isAlpha($string)
    {
        return preg_match("/^[A-Za-z_. ]*$/", $string);
    }

Add controll utils: some function for check the input


<?php
function make_dev_versions() {
	file_put_contents("../versions/versions-test-" . rand(0, 3) . "." . rand(0, 3) . "." . rand(0, 3) . ".", "");
}

for($i = 0; $i < 10; $i ++) {
	make_dev_versions();
}

Add script to create development version files


<?php

define('PATH_PROJECT',   		__DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR);
define('PATH_APP',          	PATH_PROJECT . 'app' . DIRECTORY_SEPARATOR);
define('PATH_FRAMEWORK',    	PATH_PROJECT . 'fw' . DIRECTORY_SEPARATOR);
define('PATH_FEATURE',      	PATH_FRAMEWORK . 'feature' . DIRECTORY_SEPARATOR);
define('PATH_STORAGE',      	PATH_PROJECT . 'storage' . DIRECTORY_SEPARATOR);
define('PATH_VENDORS',      	PATH_PROJECT . 'vendors' . DIRECTORY_SEPARATOR);
define('PATH_COMMANDLINE',  	PATH_FRAMEWORK . 'commandline' . DIRECTORY_SEPARATOR);
define('PATH_CONTROLLERS',  	PATH_APP . 'controllers' . DIRECTORY_SEPARATOR);
define('PATH_MODELS',     		PATH_APP . 'models' . DIRECTORY_SEPARATOR);
define('PATH_VIEWS',      		PATH_APP . 'views' . DIRECTORY_SEPARATOR);
define('PATH_APP_COMMANDLINE',  PATH_APP . 'commandline' . DIRECTORY_SEPARATOR);

define('RET', PHP_EOL);
define('TAB', "\t");

$_config = array(
    // *** Required Configurations *** //
	// * Add require configurations to array in Bootstrap::existConfig()
    'debug' => false, // False = debug mode off, true = basic mode on, Make array for additional validiaton
    'dev' => false, // Is site in development mode; if not set then false
    'https' => true, // URL secure or not
    'lock' => false, // Turns on HTTP authentication headers; mostly for locking a site but allowing only specific access
    'maint' => false, // Is in maintenance mode
    'domain' => 'localhost',
    'timezone' => 'UTC', // America/New_York',
    // *** Optional Configurations *** //
    'db' => array(
        'local' => array(
            'name' => 'local',
            'type' => 'mysql',
            'hostname' => 'localhost',
            'database' => '',
            'username' => '',
            'password' => '',
        )
    ),
	'role' => array(
		'default' => 4,
	),

	// 'set_time_out' => 60,

    /*
	// * Only Need if debug is not false and is array * //
    'debug' => array(
        'validation' => false, // Outputs debugging when doing validation into results
        'script_runtime' => false, // Outputs at end how long code took
    )
     */

	// * Only need if lock = true */
	/*
    'lock_user' => '',
    'lock_pass' => '',
	*/

	/* Currently not used or working
    'password_cost' => 11,
    'upload' => array(
        'path' => PATH_STORAGE,
        'max' => 1024*1024*10,
        'types' => array(),
    ),
    'robotstxt' => array(
        'access' => false
    ),
	*/
);

Move folder fw to its own git and composer package


<?php

function bar($arg) {
  $foo = 42;
  echo $foo;

  unset($foo);
  echo $foo/*!PHP3007!*/;

  $foo = 24;

  if ($arg == 1) {
    unset($foo);
  }

  echo $foo/*!PHP3007!*/;

  $foo = 24;
  for ($i = 0; $i < 10; $i++) {
    echo $foo/*!PHP3007!*/;

    unset($foo);

    echo $foo/*!PHP3007!*/;
  }
}

Add diagnostic tests for unset()

Add diagnostic tests for unset()


<?php

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

class RemoveCountryFromItems extends Migration {

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

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

}

Remove country col from items migration

Remove country col from items migration


<?php

namespace BlueTea\AjaxResponseBundle\Tests\Response;

use BlueTea\AjaxResponseBundle\Response\AjaxResponse;

class AjaxResponseTest extends \PHPUnit_Framework_TestCase
{
    public function testData()
    {
        $ajaxResponse = new AjaxResponse('content', AjaxResponse::TYPE_EVENT, ['data']);

        $expectedData = array(
            'type' => AjaxResponse::TYPE_EVENT,
            'content' => 'content',
            'data' => ['data']
        );

        $this->assertEquals($expectedData, $ajaxResponse->getData());
    }

    public function testContentType()
    {
        $ajaxResponse = new AjaxResponse();

        $this->assertEquals('application/json', $ajaxResponse->headers->get('Content-Type'));
    }
}

Create unit test for Response\AjaxResponse


<?php

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

namespace Sylius\Component\Resource\Storage;

/**
 * @author Kamil Kokot <kamil.kokot@lakion.com>
 */
interface StorageInterface
{
    /**
     * @param string $name
     *
     * @return bool
     */
    public function has($name);

    /**
     * @param string $name
     * @param mixed $default
     *
     * @return mixed
     */
    public function get($name, $default = null);

    /**
     * @param string $name
     * @param mixed $value
     */
    public function set($name, $value);

    /**
     * @param string $name
     */
    public function remove($name);

    /**
     * @return array
     */
    public function all();
}

Rework currency context internals, store it in a cookie


<?php

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

class AddAdditionalColumnsToUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->string('picture');
            $table->string('link');
            $table->bigInteger('fbid');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropColumn(['picture','link','fbid']);
        });
    }
}

Add additional columns to users table migration


<?php

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

class A {
    private $a;
    private $b;

    public function __construct(stdClass $a, stdClass $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function print() {
        print $this->a->foo;
        print $this->b->foo;
        print PHP_EOL;
    }
}

$injector = new Auryn\Injector;

$injector->define(A::class, [
    "+a" => function () {
        $std = new stdClass;
        $std->foo = "foo";
        return $std;
    },
    "+b" => function () {
        $std = new stdClass;
        $std->foo = "bar";
        return $std;
    },
]);

$a = $injector->make(A::class);
$a->print();

Add example to delegate parameters

Add example to delegate parameters

Resolves #148.


<?php

/*
 * This file is part of the `liip/LiipImagineBundle` project.
 *
 * (c) https://github.com/liip/LiipImagineBundle/graphs/contributors
 *
 * For the full copyright and license information, please view the LICENSE.md
 * file that was distributed with this source code.
 */

namespace Liip\ImagineBundle\DependencyInjection\Compiler;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;

/**
 * Changes the `liip_imagine.mime_type_guesser` and `liip_imagine.extension_guesser` services to be aliases of the
 * `mime_types` service provided by the FrameworkBundle when available.
 *
 * This compiler pass can be removed when dropping support for Symfony 4.2 and earlier.
 *
 * @internal
 */
final class MaybeSetMimeServicesAsAliasesCompilerPass extends AbstractCompilerPass
{
    /**
     * {@inheritdoc}
     */
    public function process(ContainerBuilder $container): void
    {
        if ($container->hasDefinition('mime_types')) {
            $container->removeDefinition('liip_imagine.mime_type_guesser');
            $container->removeDefinition('liip_imagine.extension_guesser');

            $container->setAlias('liip_imagine.mime_type_guesser', 'mime_types');
            $container->setAlias('liip_imagine.extension_guesser', 'mime_types');

            $message = 'Replaced the "%s" and "%s" service definitions with aliases to "%s"';

            $this->log($container, $message, 'liip_imagine.mime_type_guesser', 'liip_imagine.extension_guesser', 'mime_types');
        }
    }
}

Create a compiler pass to alias the mime and extension guessers to the `mime_types` service


<?php

namespace Palladium\Exception\Authentication;

use Palladium\Component\AppException as Exception;

class InvalidCookieToken extends Exception
{
    protected $code = 0;
    protected $message = 'message.error.invalid-cookie-token';
}

Test for CookieIdentity class, which cause the previous improvements


<?php

namespace EE\Migration;

use EE;
use EE\Migration\Base;

class InsertDockerImagesVersion extends Base {

	private static $pdo;

	public function __construct() {

		try {
			self::$pdo = new \PDO( 'sqlite:' . DB );
			self::$pdo->setAttribute( \PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION );
		} catch ( \PDOException $exception ) {
			EE::error( $exception->getMessage() );
		}

	}

	/**
	 * Execute create table query for site and sitemeta table.
	 *
	 * @throws EE\ExitException
	 */
	public function up() {

		EE::log( 'Checking/Pulling required images' );
		$images = [
			'easyengine/cron'        => 'v4.0.0-beta.5',
			'easyengine/mailhog'     => 'v4.0.0-beta.5',
			'easyengine/mariadb'     => 'v4.0.0-beta.5',
			'easyengine/nginx-proxy' => 'v4.0.0-beta.6',
			'easyengine/nginx'       => 'v4.0.0-beta.5',
			'easyengine/php'         => 'v4.0.0-beta.6',
			'easyengine/phpmyadmin'  => 'v4.0.0-beta.5',
			'easyengine/postfix'     => 'v4.0.0-beta.5',
			'easyengine/redis'       => 'v4.0.0-beta.5',
		];

		$query = '';
		foreach ( $images as $image => $tag ) {
			EE::debug( "Checking/Pulling docker image $image:$tag" );
			if ( ! \EE::exec( "docker pull ${image}:${tag}" ) ) {
				throw new \Exception( "Unable to pull ${image}:${tag}. Please check logs for more details." );
			}
			$query .= "INSERT INTO options VALUES( '${image}', '${tag}' );";
		}

		try {
			self::$pdo->exec( $query );
		} catch ( PDOException $exception ) {
			EE::error( 'Encountered Error while inserting in "options" table: ' . $exception->getMessage(), false );
		}
	}

	/**
	 * Execute drop table query for site and sitemeta table.
	 *
	 * @throws EE\ExitException
	 */
	public function down() {

		$query = "DELETE FROM options WHERE key LIKE 'easyengine/%';";

		try {
			self::$pdo->exec( $query );
		} catch ( PDOException $exception ) {
			EE::error( 'Encountered Error while deleting from "options" table: ' . $exception->getMessage(), false );
		}
	}
}

Add docker image info migration

Add docker image info migration


<?php

class Stripe_CouponTest extends Stripe_TestCase
{
  public function testSave()
  {
    self::authorizeFromEnv();
    $id = 'test_coupon-' . self::randomString();
    $c = Stripe_Coupon::create(
        array(
            'percent_off' => 25,
            'duration' => 'repeating',
            'duration_in_months' => 5,
            'id' => $id,
        )
    );
    $this->assertSame($id, $c->id);
    // @codingStandardsIgnoreStart
    $this->assertSame(25, $c->percent_off);
    // @codingStandardsIgnoreEnd
    $c->metadata['foo'] = 'bar';
    $c->save();

    $stripeCoupon = Stripe_Coupon::retrieve($id);
    $this->assertEquals($c->metadata, $stripeCoupon->metadata);
  }
}

Add PHPUnit test for Stripe_Coupon

Add PHPUnit test for Stripe_Coupon


<?php

class Crime extends Module {

    public $url = "https://data.bathhacked.org/resource/e46f-mhfs.json";
    public $pc  = "";

    function __construct($postcode) {
        $this->postcode = $postcode;

        //TODO: Get lat / long for postcode.
        $postcodelat = $this->postCodeLoc[0];
        $postcodelat = $this->postCodeLoc[1];

        $this->url .= '?$where=within_circle(location,'.$postcodelat.','.$postcodelong.',100)';
    }

    function getData() {

        $crimes = json_decode($this->fetch(), true);
        foreach($crimes as $crime) {
            var_dump($crime);
        }
    }

}

?>

Add vagrant to boot apache to localhost:30080


<?php
/**
 * Plugin Name: Restrict Content Pro - Generic Login Error
 * Description: Makes the login form error more generic to prevent revealing whether or not the account exists.
 * Version: 1.0
 * Author: Restrict Content Pro team
 * License: GPL2
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Display one single generic error message.
 *
 * @param string $html     Formatted HTML code.
 * @param array  $errors   Array of error codes.
 * @param string $error_id Form ID for these errors.
 *
 * @return string
 */
function ag_rcp_login_error_message( $html, $errors, $error_id ) {
	if ( 'login' == $error_id && ! empty( $errors ) ) {
		$error_message = __( 'Invalid login' ); // Edit as desired.

		$html = '

' . $error_message . '

';
	}

	return $html;
}
add_filter( 'rcp_error_messages_html', 'ag_rcp_login_error_message', 10, 3 );

Add snippet for displaying generic login error message.


<?php

final class PhabricatorNotificationClearController
  extends PhabricatorNotificationController {

  public function processRequest() {
    $request = $this->getRequest();
    $user = $request->getUser();

    if ($request->isDialogFormPost()) {
      $table = new PhabricatorFeedStoryNotification();

      queryfx(
        $table->establishConnection('w'),
        'UPDATE %T SET hasViewed = 1 WHERE
          userPHID = %s AND hasViewed = 0',
        $table->getTableName(),
        $user->getPHID());

      return id(new AphrontReloadResponse())
        ->setURI('/notification/');
    }

    $dialog = new AphrontDialogView();
    $dialog->setUser($user);
    $dialog->setTitle('Really mark all notifications as read?');
    $dialog->appendChild(
      "You can't ignore your problems forever, you know.");
    $dialog->addCancelButton('/notification/');
    $dialog->addSubmitButton('Mark All Read');

    return id(new AphrontDialogResponse())->setDialog($dialog);
  }
}

<?php

final class PhabricatorNotificationClearController
  extends PhabricatorNotificationController {

  public function processRequest() {
    $request = $this->getRequest();
    $user = $request->getUser();

    if ($request->isDialogFormPost()) {
      $table = new PhabricatorFeedStoryNotification();

      queryfx(
        $table->establishConnection('w'),
        'UPDATE %T SET hasViewed = 1 WHERE
          userPHID = %s AND hasViewed = 0',
        $table->getTableName(),
        $user->getPHID());

      return id(new AphrontReloadResponse())
        ->setURI('/notification/');
    }

    $dialog = new AphrontDialogView();
    $dialog->setUser($user);
    $dialog->setTitle('Really mark all notifications as read?');

    $is_serious = PhabricatorEnv::getEnvConfig('phabricator.serious-business');
    if ($is_serious) {
      $dialog->appendChild(
        pht(
          "All unread notifications will be marked as read. You can not ".
          "undo this action."));
    } else {
      $dialog->appendChild(
        pht(
          "You can't ignore your problems forever, you know."));
    }

    $dialog->addCancelButton('/notification/');
    $dialog->addSubmitButton('Mark All Read');

    return id(new AphrontDialogResponse())->setDialog($dialog);
  }
}

Fix unacceptably light-hearted string in serious business mode

Summary: A serious business lost a bunch of serious business partners today because of this string, I assume.

Test Plan: Enabled serious mode, clicked button, was relieved to see no jokes.

Reviewers: btrahan

Reviewed By: btrahan

CC: aran

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


<?php
	require_once __DIR__.'/_puff/sitewide.php';
	$Page['Type']        = 'Index';
	$Page['Title']       = 'Puff Sys';
	$Page['Description'] = 'Puff is Awesome';
	$Page['JS'][]        = 'http://anothercdn.example.com/js/script.js';
	$Page['CSS'][]       = 'http://anothercdn.example.com/css/style.css';
	require_once $Sitewide['Templates']['Header'];
?>

Welcome to Puff.

<?php
	require_once $Sitewide['Templates']['Footer'];

Add example apge for CSS/JS

Add example apge for CSS/JS


<?php

namespace Pipe\Test\Util;

use Pipe\Util\ProcessorRegistry;

class ProcessorRegistryTest extends \PHPUnit_Framework_TestCase
{
    protected $registry;

    function setup()
    {
        $this->registry = new ProcessorRegistry;
    }

    /**
     * @test
     * @expectedException \InvalidArgumentException
     */
    function prependThrowsExceptionIfClassDoesNotExist()
    {
        $this->registry->prepend('text/css', '\foo');
    }

    /**
     * @test
     * @expectedException \InvalidArgumentException
     */
    function registerThrowsExceptionIfClassDoesNotExist()
    {
        $this->registry->register('text/css', '\foo');
    }

    /**
     * @test
     */
    function testRegister()
    {
        $this->registry->register('text/css', '\MetaTemplate\Template\VoidTemplate');

        $this->assertTrue($this->registry->isRegistered('text/css', '\MetaTemplate\Template\VoidTemplate'));

        $this->registry->unregister('text/css', '\MetaTemplate\Template\VoidTemplate');

        $this->assertFalse($this->registry->isRegistered('text/css', '\MetaTemplate\Template\VoidTemplate'));
    }

    /**
     * @test
     */
    function registerAppendsToMimeType()
    {
        $this->registry->register('text/css', '\MetaTemplate\Template\VoidTemplate');
        $this->registry->register('text/css', '\MetaTemplate\Template\SassTemplate');

        $processors = $this->registry->all('text/css');

        $this->assertEquals('\MetaTemplate\Template\VoidTemplate', $processors[0]);
        $this->assertEquals('\MetaTemplate\Template\SassTemplate', $processors[1]);
    }

    /**
     * @test
     */
    function prependPrependsToMimeType()
    {
        $this->registry->register('text/css', '\MetaTemplate\Template\VoidTemplate');
        $this->registry->prepend('text/css', '\MetaTemplate\Template\SassTemplate');

        $processors = $this->registry->all('text/css');

        $this->assertEquals('\MetaTemplate\Template\SassTemplate', $processors[0]);
        $this->assertEquals('\MetaTemplate\Template\VoidTemplate', $processors[1]);
    }
}

Add test for processor registry

Add test for processor registry


<?php

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

class AddSettingsToProjects extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		Schema::table('projects', function($t)
		{
			$t->string('closed_statuses');
			$t->boolean('workboard_mode')->default(false);
		});
	}

	/**
	 * Reverse the migrations.
	 *
	 * @return void
	 */
	public function down()
	{
		Schema::table('projects', function($t)
		{
			$t->dropColumn('closed_statuses');
			$t->dropColumn('workboard_mode');
		});
	}

}

Add migration for project settings.

Add migration for project settings.


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

namespace StrictPhpTestAsset;

class ClassWithMultipleParamsTypedMethodAnnotation
{
    /**
     * @param \stdClass[]|int[] $someParameter
     * @param string[][]        $anotherParam
     * @param boolean           $simpleParam
     */
    public function method(array $someParameter, array $anotherParam, $simpleParam)
    {
    }
}

Add new asset test class to test method check with multiple params


<?php

namespace BitWasp\Stratum;

use BitWasp\Stratum\Request\Request;
use BitWasp\Stratum\Request\RequestFactory;
use React\EventLoop\LoopInterface;
use React\Promise\Deferred;
use React\SocketClient\ConnectorInterface;
use React\Stream\Stream;

class Executor {

    /**
     * @var LoopInterface
     */
    private $loop;

    /**
     * @var string
     */
    private $host;

    /**
     * @var int|string
     */
    private $port;

    /**
     * @var RequestFactory
     */
    private $requestFactory;
    /**
     * @var int
     */
    private $timeout;

    /**
     * @param LoopInterface $loop
     * @param $host
     * @param $port
     */
    public function __construct(LoopInterface $loop, ConnectorInterface $connector, RequestFactory $requestFactory, $host, $port, $timeout = 5)
    {
        $this->loop = $loop;
        $this->requestFactory = $requestFactory;
        $this->connector = $connector;
        $this->host = $host;
        $this->port = $port;
        $this->timeout = $timeout;
    }

    /**
     * @param Request $request
     * @return \React\Promise\Promise
     */
    public function query(Request $request)
    {
        $deferred = new Deferred();

        $this->createConnection()->then(function (Stream $stream) use ($deferred, $request, &$steamBuffer) {
            $streamBuffer = '';
            $stream->on('data', function ($data) use ($deferred, $stream, $request, &$streamBuffer) {
                if (substr($data, strlen($data) - 1) == "\n") {
                    $stream->close();
                    $deferred->resolve($this->requestFactory->response($streamBuffer . $data));
                } else {
                    $streamBuffer .= $data;
                    $deferred->notify('Received partial response');
                }
                return;
            });

            $stream->write($request->write());
        }, function () use ($deferred) {
            $deferred->reject(new \ErrorException('Failed to connect to host'));
        });

        return $deferred->promise();
    }

    /**
     * @return \React\Promise\Promise
     */
    protected function createConnection()
    {
        return $this->connector->create($this->host, $this->port);
    }
}

Add executor file to git

Add executor file to git


<?php

namespace Doctrine\Tests\Common\Annotations\Fixtures;

use Doctrine\Tests\Common\Annotations\Fixtures\Annotation\Route;
use Doctrine\Tests\Common\Annotations\Fixtures\Traits\TraitThatUsesAnotherTrait;

/**
 * @Route("/someprefix")
 */
class ClassThatUsesTraitThatUsesAnotherTrait
{
    use TraitThatUsesAnotherTrait;
}

Test asset - class that uses multiple traits indirectly


<?php

class m170314_104129_add_new_system_setting_require_exam_before_booking extends CDbMigration
{
    public function up()
    {
        $this->insert('setting_metadata', array('display_order' => 0, 'field_type_id' => 3, 'key' => 'require_exam_before_booking', 'name' => 'Require exam before booking', 'data' => 'a:2:{s:2:"on";s:2:"On";s:3:"off";s:3:"Off";}', 'default_value' => 'off'));
    }

    public function down()
    {
        $this->delete('setting_metadata', '`key`="require_exam_before_booking"');
    }
}

Add new system setting - 'Require exam before booking'


<?php

namespace Nam\Realtime;

use Illuminate\Support\ServiceProvider;
use Nam\Realtime\Connectors\PubnubConnector;

class RealtimeServiceProvider extends ServiceProvider
{
    protected $defer = false;

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->package('nam/realtime');

        $this->registerManager();
    }

    private function registerManager()
    {
        $this->app->bindShared('stream', function ($app) {
            // Once we have an instance of the queue manager, we will register the various
            // resolvers for the queue connectors. These connectors are responsible for
            // creating the classes that accept queue configs and instantiate queues.
            $manager = new StreamManager($app);

            $this->registerConnectors($manager);

            return $manager;
        });

        $this->app->bindShared('stream.connection', function ($app) {
            return $app['stream']->connection();
        });
    }

    private function registerConnectors($manager)
    {
        foreach ([ 'Pusher', 'Pubnub' ] as $connector) {
            $this->{"register{$connector}Connector"}($manager);
        }
    }

    private function registerPubnubConnector(StreamManager $manager)
    {
        $app = $this->app;

        $manager->addConnector('pubnub', function () use ($app) {
            return new PubnubConnector;
        });
    }

    private function registerPusherConnector(StreamManager $manager)
    {
        $app = $this->app;

        $manager->addConnector('pubnub', function () use ($app) {
            return new PusherConnector;
        });
    }
}

Add ServiceProvider for Laravel 4

Add ServiceProvider for Laravel 4


<?php
//use to set values in the database

include_once(dirname(__FILE__) . "/../../config/environment.php");
$mysqli =& $GLOBALS['mysqli_connection'];

$query="update info_items set info_items.label = 'Key' where info_items.schema_value = 'http://rs.tdwg.org/ontology/voc/SPMInfoItems#Key'";
$update = $mysqli->query($query);

print "\n\n --end-- \n\n";
?>

Set info_items label to 'Key' instead of 'Keys'.

git-svn-id: d46fe582d22b46b457d3ac1c55a88da2fbe913a1@1697 baf6b65b-9124-4dc3-b1c0-01155b4af546


<?php

namespace Zimbra\Mail\Tests\Struct;

use Zimbra\Mail\Tests\ZimbraMailTestCase;

/**
 * Testcase class for AttachSpec.
 */
class AttachSpecTest extends ZimbraMailTestCase
{
    public function testAttachSpec()
    {
        $stub = $this->getMockForAbstractClass('Zimbra\Mail\Struct\AttachSpec');
        $stub->setOptional(true);
        $this->assertTrue($stub->getOptional());
    }
}

Add Test case for AttachSpec.

Add Test case for AttachSpec.


<?php

namespace AdobeConnectClient\Helper;

abstract class StatusValidate
{
    public static function validate(array $status)
    {
        switch ($status['code']) {
            case 'invalid':
                $invalid = $status['invalid'];
                throw new \AdobeConnectClient\Exception\InvalidException(
                    "{$invalid['field']} {$invalid['subcode']}"
                );

            case 'no-access':
                throw new \AdobeConnectClient\Exception\NoAccessException($status['subcode']);

            case 'no-data':
                throw new \AdobeConnectClient\Exception\NoDataException();

            case 'too-much-data':
                throw new \AdobeConnectClient\Exception\TooMuchDataException();
        }
    }
}

Add a helper to validate status from WS

Add a helper to validate status from WS


<?PHP

/**
 *  A Money Doctrine Embeddable object.
 *
 * This embeddable can be used to persist a money
 * value using Doctrine.
 *
 * @package  Serendipity\Framework
 * @subpackage ValueObjects
 *
 *  @author      Adamo Crespi <hello@aerendir.me>
 *  @copyright   Copyright (c) 2015, Adamo Crespi
 *  @license     MIT License
 */

namespace SerendipityHQ\Component\ValueObjects\MoneyEmbeddable;

use \SerendipityHQ\Component\ValueObjects\Currency\CurrencyInterface;
use SerendipityHQ\Component\ValueObjects\Money\Money;

/**
 * @Embeddable
 */
class MoneyEmbeddable
{
    /** @Column(type = "int") */
    private $amount;

    /** @Column(type = "string") */
    private $currency;
}

Add a Money Embeddable Object.

Add a Money Embeddable Object.


<?php

/*
 * This file is part of Flarum.
 *
 * For detailed copyright and license information, please view the
 * LICENSE file that was distributed with this source code.
 */

namespace Flarum\Tests\integration;

use Carbon\Carbon;
use Flarum\Api\ApiKey;
use Illuminate\Support\Str;
use Psr\Http\Message\ServerRequestInterface;

abstract class AuthenticatedTestCase extends TestCase
{
    use RetrievesAuthorizedUsers;

    protected function genKey(int $user_id = null): ApiKey
    {
        return ApiKey::unguarded(function () use ($user_id) {
            return ApiKey::query()->firstOrCreate([
                'key'        => Str::random(),
                'user_id'    => $user_id,
                'created_at' => Carbon::now()
            ]);
        });
    }

    /**
     * Build an authenticated HTTP request that can be passed through middleware.
     *
     * This method simplifies building HTTP request for use in our HTTP-level
     * integration tests. It provides options for all features repeatedly being
     * used in those tests.
     *
     * @param string $method
     * @param string $path
     * @param array $options
     *   An array of optional request properties.
     *   Currently supported:
     *   - "json" should point to a JSON-serializable object that will be
     *     serialized and used as request body. The corresponding Content-Type
     *     header will be set automatically.
     *   - "cookiesFrom" should hold a response object from a previous HTTP
     *     interaction. All cookies returned from the server in that response
     *     (via the "Set-Cookie" header) will be copied to the cookie params of
     *     the new request.
     * @param int $userId Which user should be emulated? User ID 1 will return a
     * user with admin perms unless this has been modified in your test case.
     * @return ServerRequestInterface
     */
    protected function authenticatedRequest(string $method, string $path, array $options = [], int $userId = 1): ServerRequestInterface
    {
        $request = $this->request($method, $path, $options);

        $this->prepareDatabase([
            'users' => [
                $this->adminUser(),
                $this->normalUser(),
            ],
        ]);

        if (! isset($this->key)) {
            $this->key = $this->genKey();
        }

        return $request->withAddedHeader('Authorization', "Token {$this->key->key}; userId=$userId");
    }
}

Add Authenticated Test Case utility

Add Authenticated Test Case utility


<?php
/**
 * Laconica, the distributed open-source microblogging tool
 *
 * Section for featured users
 *
 * PHP version 5
 *
 * LICENCE: This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @category  Widget
 * @package   Laconica
 * @author    Evan Prodromou <evan@controlyourself.ca>
 * @copyright 2009 Control Yourself, Inc.
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
 * @link      http://laconi.ca/
 */

if (!defined('LACONICA')) {
    exit(1);
}

/**
 * Section for featured users
 *
 * @category Widget
 * @package  Laconica
 * @author   Evan Prodromou <evan@controlyourself.ca>
 * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
 * @link     http://laconi.ca/
 */

class FeaturedUsersSection extends ProfileSection
{
    function getProfiles()
    {
        $featured_nicks = common_config('nickname', 'featured');

        if (!$featured_nicks) {
            return null;
        }

        $quoted = array();

        foreach ($featured_nicks as $nick) {
            $quoted[] = "'$nick'";
        }

        $qry = 'SELECT profile.* ' .
          'FROM profile JOIN user on profile.id = user.id ' .
          'WHERE user.nickname in (' . implode(',', $quoted) . ') ' .
          'ORDER BY profile.created DESC ';

        $limit = PROFILES_PER_SECTION + 1;
        $offset = 0;

        if (common_config('db','type') == 'pgsql') {
            $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
        } else {
            $qry .= ' LIMIT ' . $offset . ', ' . $limit;
        }

        $profile = Memcached_DataObject::cachedQuery('Profile',
                                                     $qry,
                                                     6 * 3600);
        return $profile;
    }

    function title()
    {
        return _('Featured users');
    }

    function divId()
    {
        return 'featured_users';
    }
}

Add a featured user section

Add a featured user section


<?php
require_once '../admin/php/connection.php';

$index = isset($_GET['index'])? $_GET['index'] : 0;
$count = isset($_GET['count'])? $_GET['count'] : 20;

$db = open_connection();
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = 'SELECT title, COUNT(reveiw.book_isbn) AS reviews
  FROM book
  LEFT JOIN reveiw
  ON book.isbn = reveiw.book_isbn
  GROUP BY book.isbn
  LIMIT :index, :count';

$stmt = $db->prepare($query);
$stmt->execute([
    'index' => $index,
    'count' => $count
]);

$books = [];
while($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
  array_push($books, [
  'title' => $result['title'],
  'reviews' => intval($result['reviews'])
  ]);
}

echo json_encode($books);

?>

Add book api to get the number of reviews


<?php

namespace Doctrine\ODM\MongoDB\Tests\Functional\Ticket;

use Doctrine\ODM\MongoDB\Events;
use Doctrine\ODM\MongoDB\Event\OnFlushEventArgs;
use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;
use Doctrine\ODM\MongoDB\Tests\QueryLogger;

class GH____Test extends \Doctrine\ODM\MongoDB\Tests\BaseTest
{
    /**
     * @var Doctrine\ODM\MongoDB\Tests\QueryLogger
     */
    private $ql;

    protected function getConfiguration()
    {
        if ( ! isset($this->ql)) {
            $this->ql = new QueryLogger();
        }

        $config = parent::getConfiguration();
        $config->setLoggerCallable($this->ql);

        return $config;
    }

    public function testUpdatingDocumentBeforeItsInsertionShouldNotEntailMultipleQueries()
    {
        $listener = new GH____Listener();
        $this->dm->getEventManager()->addEventListener(Events::onFlush, $listener);

        $doc = new GH____Document();
        $doc->name = 'foo';

        $this->dm->persist($doc);
        $this->dm->flush();

        $this->assertCount(1, $this->ql, 'Changing a document before its insertion requires one query');
        $this->assertEquals('foo-changed', $doc->name);
        $this->assertEquals(1, $listener->inserts);
        $this->assertEquals(0, $listener->updates);
    }
}

/** @ODM\Document */
class GH____Document
{
    const CLASSNAME = __CLASS__;

    /** @ODM\Id */
    public $id;

    /** @ODM\String */
    public $name;
}

class GH____Listener
{
    public $inserts = 0;
    public $updates = 0;

    public function onFlush(OnFlushEventArgs $args)
    {
        $dm = $args->getDocumentManager();
        $uow = $dm->getUnitOfWork();

        foreach ($uow->getScheduledDocumentInsertions() as $document) {
            $this->inserts++;
            if ($document instanceof GH____Document) {
                $document->name .= '-changed';
                $cm = $dm->getClassMetadata(GH____Document::CLASSNAME);
                $uow->recomputeSingleDocumentChangeSet($cm, $document);
            }
        }

        foreach ($uow->getScheduledDocumentUpdates() as $document) {
            $this->updates++;
        }
    }
}

Test for document scheduled for both insertion and update


<?php

namespace Oro\Bundle\EmailBundle\Migrations\Schema\v1_20;

use Doctrine\DBAL\Schema\Schema;

use Oro\Bundle\MigrationBundle\Migration\Migration;
use Oro\Bundle\MigrationBundle\Migration\ParametrizedSqlMigrationQuery;
use Oro\Bundle\MigrationBundle\Migration\QueryBag;
use Oro\Bundle\MigrationBundle\Migration\SqlMigrationQuery;

class OroEmailBundle implements Migration
{
    /**
     * {@inheritdoc}
     */
    public function up(Schema $schema, QueryBag $queries)
    {
        self::oroEmailTable($schema);
        $this->deleteBodySyncProcess($queries);
    }

    /**
     * @param Schema $schema
     */
    public static function oroEmailTable(Schema $schema)
    {
        $table = $schema->getTable('oro_email');
        if (!$table->hasColumn('body_synced')) {
            $table->addColumn('body_synced', 'boolean', ['notnull' => false, 'default' => false]);
        }
    }

    /**
     * Delete sync_email_body_after_email_synchronize process definition
     *
     * @param QueryBag $queries
     */
    protected function deleteBodySyncProcess(QueryBag $queries)
    {
        $queries->addQuery(
            new ParametrizedSqlMigrationQuery(
                'DELETE FROM oro_process_definition WHERE name = :processName',
                ['processName' => 'sync_email_body_after_email_synchronize']
            )
        );
    }
}

<?php

namespace Oro\Bundle\EmailBundle\Migrations\Schema\v1_20;

use Doctrine\DBAL\Schema\Schema;

use Oro\Bundle\MigrationBundle\Migration\Migration;
use Oro\Bundle\MigrationBundle\Migration\ParametrizedSqlMigrationQuery;
use Oro\Bundle\MigrationBundle\Migration\QueryBag;
use Oro\Bundle\MigrationBundle\Migration\SqlMigrationQuery;

class OroEmailBundle implements Migration
{
    /**
     * {@inheritdoc}
     */
    public function up(Schema $schema, QueryBag $queries)
    {
        self::oroEmailTable($schema);
        $this->deleteBodySyncProcess($schema, $queries);
    }

    /**
     * @param Schema $schema
     */
    public static function oroEmailTable(Schema $schema)
    {
        $table = $schema->getTable('oro_email');
        if (!$table->hasColumn('body_synced')) {
            $table->addColumn('body_synced', 'boolean', ['notnull' => false, 'default' => false]);
        }
    }

    /**
     * Delete sync_email_body_after_email_synchronize process definition
     *
     * @param Schema   $schema
     * @param QueryBag $queries
     */
    protected function deleteBodySyncProcess(Schema $schema, QueryBag $queries)
    {
        if ($schema->hasTable('oro_process_definition')) {
            $queries->addQuery(
                new ParametrizedSqlMigrationQuery(
                    'DELETE FROM oro_process_definition WHERE name = :processName',
                    ['processName' => 'sync_email_body_after_email_synchronize']
                )
            );
        }
    }
}

CRM-4904: Refactor email body sync
 - Fix migrations


<?php
/*
 * File: ViewsProcessorTest.php
 * Holds: Testes the Processor view
 * Created: 29.05.2016
 * Project: Youkok2
 *
 */

namespace Youkok2\Tests\Views;

use Youkok2\Youkok2;
use Youkok2\Utilities\ClassParser;

class ViewsProcessorTest extends \Youkok2\Tests\YoukokTestCase
{
    public function testProcessorView() {
        $processor_wrapper = new Youkok2();
        $processor_wrapper->load('processor/foobar', [
            'close_db' => false,
            'application' => true
        ]);
        $this->assertEquals('application/json', $processor_wrapper->getHeader('Content-Type'));

    }

}

Add test for processor view

Add test for processor view


<?php
/**
 * Created by PhpStorm.
 * User: Faramarz Salehpour
 */

use PersianToolkit\PersianToolkit;
use PHPUnit\Framework\TestCase;

class PersianToolkitTest extends TestCase
{
    /**
     * @test
     */
    public function it_returns_a_string_with_converted_chars()
    {
        $arabic = 'ابپتثجچحخدذرزژسشصضطظعغفقكگلمنوهي';
        $persian = 'ابپتثجچحخدذرزژسشصضطظعغفقکگلمنوهی';
        $this->assertEquals($persian, PersianToolkit::arabic2Persian($arabic));
    }
}

Add test for conversion funcs

Add test for conversion funcs


<?php

namespace Backend\Modules\ContentBlocks\Tests\Action;

use Common\WebTestCase;

class EditThemeTemplateTest extends WebTestCase
{
    public function testAuthenticationIsNeeded(): void
    {
        $client = static::createClient();
        $this->logout($client);

        $client->setMaxRedirects(1);
        $client->request('GET', '/private/en/extensions/edit_theme_template?token=68ozixmy4j&id=3');

        // we should get redirected to authentication with a reference to blog index in our url
        self::assertStringEndsWith(
            '/private/en/authentication?querystring=%2Fprivate%2Fen%2Fextensions%2Fedit_theme_template%3Ftoken%3D68ozixmy4j%26id%3D3',
            $client->getHistory()->current()->getUri()
        );
    }

    public function testFormIsDisplayed(): void
    {
        $client = static::createClient();
        $this->login($client);

        $client->request('GET', '/private/en/extensions/edit_theme_template?token=68ozixmy4j&id=3');
        self::assertContains(
            'The user can upload a file.',
            $client->getResponse()->getContent()
        );
        self::assertContains(
            'Positions',
            $client->getResponse()->getContent()
        );
        self::assertContains(
            'If you want a position to display wider or higher in it\'s graphical representation',
            $client->getResponse()->getContent()
        );
    }
}

Add tests for the content extentions edit theme template page


<?
// authed.php:
// Returns whether an email address has signed up to a TWFY alert for an MP.
// Uses shared secret for authentication.
//
// Copyright (c) 2006 UK Citizens Online Democracy. All rights reserved.
// Email: matthew@mysociety.org. WWW: http://www.mysociety.org
//
// $Id: authed.php,v 1.1 2006/05/26 08:44:46 matthew Exp $

include_once "../../includes/easyparliament/init.php";
include_once INCLUDESPATH . '../../../phplib/auth.php';

header("Content-Type: text/plain");

$email = get_http_var('email');
$sign = get_http_var('sign');
$pid = get_http_var('pid');
if (!$pid || !ctype_digit($pid)) print 'not valid';
else {
	$authed = auth_verify_with_shared_secret($email, OPTION_AUTH_SHARED_SECRET, $sign);
	if ($authed) {
		$db = new ParlDB;
		$email = mysql_escape_string($email);
		$q = $db->query('select alert_id from alerts where email="' . $email . '" and criteria="speaker:' . $pid . '" and confirmed and not deleted');
		$already_signed = $q->rows();
		if ($already_signed)
			print "already signed";
		else
			print "not signed";
	} else {
		print "not authed";
	}
}

Check whether user already has TWFY alert before showing TWFY advert.


<?php

namespace Inanimatt\SiteBuilder\Transformer;

use \Mockery as m;

class PagecontextTransformerTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var PagecontextTransformer
     */
    protected $object;

    public function testTransformRootPage()
    {
        $event = m::mock('Inanimatt\SiteBuilder\Event\FileCopyEvent')
            ->shouldReceive('getTarget')
            ->andReturn('output'.DIRECTORY_SEPARATOR.'index.html')
            ->mock();

        $event->data = new \PhpCollection\Map();
        $object = new PagecontextTransformer('output');
        $object->transform($event);

        $this->assertEquals($event->data->get('siteroot')->get() , '');
        $this->assertEquals(count($event->data->get('breadcrumbs')->get()) , 0);
        $this->assertEquals($event->data->get('pagename')->get() , 'index');

    }

    public function testTransformSectionPage()
    {
        $event = m::mock('Inanimatt\SiteBuilder\Event\FileCopyEvent')
            ->shouldReceive('getTarget')
            ->andReturn('output'.DIRECTORY_SEPARATOR.'section'.DIRECTORY_SEPARATOR.'subsection'.DIRECTORY_SEPARATOR.'content.html')
            ->mock();

        $event->data = new \PhpCollection\Map();
        $object = new PagecontextTransformer('output');
        $object->transform($event);

        $this->assertEquals($event->data->get('siteroot')->get() , '../../');
        $this->assertEquals(count($event->data->get('breadcrumbs')->get()) , 2);
        $this->assertEquals($event->data->get('pagename')->get() , 'content');
    }

}

Add unit tests for Pagecontext transformer


<?php

namespace OpenConext\EngineBlockBundle\Authentication\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Note: this entity is currently only used to configure doctrine to create
 * the schema on installation.
 *
 * @ORM\Entity()
 * @ORM\Table(indexes={
 *     @ORM\Index(name="service_provider_entity_id", columns={"service_provider_entity_id"}),
 * })
 */
class ServiceProviderUuid
{
    /**
     * @var string
     *
     * @ORM\Id
     * @ORM\Column(type="string", length=36, options={"fixed": true})
     */
    public $uuid;

    /**
     * @var string
     *
     * @ORM\Column(type="string", length=1024)
     */
    public $serviceProviderEntityId;
}

Add doctrine configuration for service_provider_uuid