<?php
namespace TYPO3\FLOW3\Core\Migrations;

/*                                                                        *
 * This script belongs to the FLOW3 package "FLOW3".                      *
 *                                                                        *
 * It is free software; you can redistribute it and/or modify it under    *
 * the terms of the GNU Lesser General Public License, either version 3   *
 * of the License, or (at your option) any later version.                 *
 *                                                                        *
 * The TYPO3 project - inspiring people to share!                         *
 *                                                                        */

use TYPO3\FLOW3\Utility\Files;

/**
 * Move all code to PSR-0 compatible directory structure, remove Package.xml,
 * add composer.json.
 */
class Version201209201112 extends AbstractMigration {

	/**
	 * @return void
	 */
	public function up() {
		$packageKeyAsDirectory = str_replace('.', '/', $this->targetPackageData['packageKey']);
		$this->moveFile('Classes/*', 'Classes/' . $packageKeyAsDirectory . '/');

		$this->writeComposerManifest();

		$this->deleteFile('Meta/Package.xml');

		$packageKeyAsNamespace = str_replace('.', '\\', $this->targetPackageData['packageKey']);
		$this->showNote('You may now remove your "' . $packageKeyAsNamespace . '\Package" class if it does not contain any code.');
	}

	/**
	 * @return void
	 */
	protected function writeComposerManifest() {
		$manifest = array();

		$nameParts = explode('.', $this->targetPackageData['packageKey']);
		$vendor = array_shift($nameParts);
		$manifest['name'] = strtolower($vendor . '/' . implode('-', $nameParts));

		switch ($this->targetPackageData['category']) {
			case 'Application':
				$manifest['type'] = 'flow3-package';
			break;
			default:
				$manifest['type'] = strtolower('flow3-' . $this->targetPackageData['category']);
		}

		$manifest['description'] = $this->targetPackageData['meta']['description'];
		$manifest['version'] = $this->targetPackageData['meta']['version'];
		$manifest['require'] = array('typo3/flow3' => '*');
		$manifest['autoload'] = array('psr-0' => array(str_replace('.', '\\', $this->targetPackageData['packageKey']) => 'Classes'));

		if (defined('JSON_PRETTY_PRINT')) {
			file_put_contents(Files::concatenatePaths(array($this->targetPackageData['path'], 'composer.json')), json_encode($manifest, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT));
		} else {
			file_put_contents(Files::concatenatePaths(array($this->targetPackageData['path'], 'composer.json')), json_encode($manifest));
		}
	}
}

?>

[TASK] Add code migration to "composerify" a package

The migration moves all class files into a PSR-0 compatible directory
structure and adds a composer manifest; Package.xml is removed.

Change-Id: I2054b3ece5b98ed6d3232e0da06ce36fb2bf41e9
Related: #41031
Releases: 1.2
Original-Commit-Hash: 613025176356c63973da4db8635cb99eb0f00338


<?php
/**
 * @see       https://github.com/zendframework/zend-di for the canonical source repository
 * @copyright Copyright (c) 2017 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   https://github.com/zendframework/zend-di/blob/master/LICENSE.md New BSD License
 */

namespace ZendTest\Di\Container;

use PHPUnit\Framework\TestCase;
use Psr\Container\ContainerInterface;
use Zend\Di\InjectorInterface;
use Zend\Di\Injector;
use Zend\Di\Container\GeneratorFactory;
use Zend\Di\CodeGenerator\InjectorGenerator;
use Zend\Di\ConfigInterface;
use Zend\Di\Config;

/**
 * @covers Zend\Di\Container\GeneratorFactory
 *
 */
class GeneratorFactoryTest extends TestCase
{
    public function testInvokeCreatesGenerator()
    {
        $injector = new Injector();
        $factory = new GeneratorFactory();

        $result = $factory($injector->getContainer());
        $this->assertInstanceOf(InjectorGenerator::class, $result);
    }

    public function testFactoryUsesServicesFromContainer()
    {
        $container = $this->getMockBuilder(ContainerInterface::class)->getMockForAbstractClass();
        $container->expects($this->atLeastOnce())
            ->method('has')
            ->with(InjectorInterface::class)
            ->willReturn(true);

        $container->expects($this->atLeastOnce())
            ->method('has')
            ->with(ConfigInterface::class)
            ->willReturn(true);

        $container->method('has')->willReturn(false);

        $container->expects($this->atLeastOnce())
            ->method('get')
            ->with(InjectorInterface::class)
            ->willReturn(new Injector());

        $container->expects($this->atLeastOnce())
            ->method('get')
            ->with(ConfigInterface::class)
            ->willReturn(new Config());

        $factory = new GeneratorFactory();
        $factory($container);
    }
}

Add test case for generator factory

Add test case for generator factory


<?php

namespace Tests;

use Illuminate\Contracts\Console\Kernel;

trait CreatesApplication
{
    /**
     * Creates the application.
     *
     * @return \Illuminate\Foundation\Application
     */
    public function createApplication()
    {
        require __DIR__.'/../vendor/tastyigniter/flame/src/Support/helpers.php';

        $app = require __DIR__.'/../bootstrap/app.php';

        $app->make(Kernel::class)->bootstrap();

        return $app;
    }
}

<?php

namespace Tests;

use Illuminate\Contracts\Console\Kernel;

trait CreatesApplication
{
    /**
     * Creates the application.
     *
     * @return \Illuminate\Foundation\Application
     */
    public function createApplication()
    {
        $app = require __DIR__.'/../bootstrap/app.php';

        $app->make(Kernel::class)->bootstrap();

        $app['cache']->setDefaultDriver('array');
        $app->setLocale('en');

        return $app;
    }
}

Use array cache in tests

Use array cache in tests


<?php
/**
 * Eadrax Entity/Auth.php
 *
 * @package   Entity
 * @author    Dion Moult <dion@thinkmoult.com>
 * @copyright (c) 2012 Dion Moult
 * @license   ISC http://opensource.org/licenses/isc-license.txt
 * @link      http://wipup.org/
 */

namespace Eadrax\Eadrax\Entity;

/**
 * Allows for user authentication
 *
 * @package Entity
 */
interface Auth
{
    /**
     * Checks whether or not the user is currently logged in.
     *
     * Example:
     * $auth = new Auth_Class;
     * if ($auth->logged_in() === TRUE) {} // Use is logged in
     *
     * @return bool
     */
    public function logged_in();

    /**
     * Retrieves the currently logged in user in the form of a Model\User.
     *
     * Example:
     * $auth->get_user()->get_username();
     *
     * @return Eadrax\Eadrax\Model\User
     */
    public function get_user();

    /**
     * Logs in the user with the details provided
     *
     * Example:
     * $auth->login('username', 'password');
     * var_dump($auth->logged_in()); // bool(true)
     *
     * @param string username The username of the user
     * @param string password The password of the user
     * @return bool Whether or not the login operation succeeded
     */
    public function login($username, $password);

    /**
     * Logs out the currently logged in user.
     *
     * Example:
     * $auth->logout();
     *
     * @return void
     */
    public function logout();
}

Add interface for auth entity

Add interface for auth entity


<?php

namespace PHPExiftool\Driver\Metadata;

require_once dirname(__FILE__) . '/../../../../../lib/PHPExiftool/Driver/Metadata/Metadata.php';

class TagTest extends \PHPExiftool\Driver\Tag
{

}

class MetadataTest extends \PHPUnit_Framework_TestCase
{

  /**
   * @var Metadata
   */
  protected $object;
  protected $tag;
  protected $value;

  /**
   * Sets up the fixture, for example, opens a network connection.
   * This method is called before a test is executed.
   */
  protected function setUp()
  {
    $this->tag = new TagTest();
    $this->value = 'valeur';
    $this->object = new Metadata(new TagTest, $this->value, new \SplFileInfo(__FILE__));
  }

  /**
   * @covers \PHPExiftool\Driver\Metadata\Metadata::reset
   */
  public function testReset()
  {
    $this->object->reset();
    $this->assertNull($this->object->getValue());
  }

  /**
   * @covers \PHPExiftool\Driver\Metadata\Metadata::getTag
   */
  public function testGetTag()
  {
    $this->assertEquals($this->object->getTag(), $this->tag);
  }

  /**
   * @covers \PHPExiftool\Driver\Metadata\Metadata::getValue
   */
  public function testGetValue()
  {
    $this->assertEquals($this->object->getValue(), $this->value);
  }

}

Add unit tests for Metadata

Add unit tests for Metadata


<?php

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

class MakeCampaignRunNullable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('signups', function (Blueprint $table) {
            $table->integer('campaign_run_id')->nullable()->change();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('signups', function (Blueprint $table) {
            $table->integer('campaign_run_id')->nullable(false)->change();
        });
    }
}

Make campaign run id nullable

Make campaign run id nullable


<?php
declare(strict_types = 1);

namespace Apha\Saga;

use Apha\Domain\Identity;
use Apha\Message\Event;

class SimpleAssociationValueResolverTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @test
     */
    public function extractAssociationValuesOnIdentity()
    {
        $identity = Identity::createNew();
        $event = new SimpleAssociationValueResolverTest_Event($identity);
        $resolver = new SimpleAssociationValueResolver();
        $associationValues = $resolver->extractAssociationValues($event);

        $associationValuesArray = $associationValues->getArrayCopy();
        self::assertEquals($identity->getValue(), $associationValuesArray[0]->getValue());
    }
}

class SimpleAssociationValueResolverTest_Event extends Event
{
    /**
     * @param Identity $identity
     */
    public function __construct(Identity $identity)
    {
        $this->setIdentity($identity);
    }
}

Add test for AssociationValue resolver.

Add test for AssociationValue resolver.


<?php

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

    $query="update resources set resource_status_id = 11 where id = 201";
    $result = $mysqli->query($query);
    $num_rows = $mysqli->affected_rows();
    print $num_rows;

?>

Set MCZ to 'publish pending'.

Set MCZ to 'publish pending'.

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


<?php
namespace backend\controllers;

use Yii;
use yii\web\Controller;

/**
 * Site controller
 */
class SurveyController extends Controller
{
	public function actionActivate()
	{
		$surveyId = \Yii::$app->get('survey')->surveyId;
		Yii::$app->survey->activateSurvey($surveyId);
		Yii::$app->survey->setSurveyProperties($surveyId, ['expires' => '']);

		return $this->goHome();
	}

	public function actionDeactivate()
	{
		$surveyId = \Yii::$app->get('survey')->surveyId;
		Yii::$app->survey->setSurveyProperties($surveyId, ['expires' => date("Y-m-d H:i:s")]);

		return $this->goHome();
	}

}

Add controller to control survey in Backend context


<?php
/*
Plugin Name: Add network users to main site
Description: MU Plugin that adds users across the network subscribers in the main site.
Author: Jude Rosario
Author URI: http://premium.wpmudev.org/
Version: 1.1
*/

function wpms_add_user_to_main_site( $user_id = null ) {

	global $wpdb;

	    if ( ! is_multisite() )
	        return ;

	    if ( ! $user_id )
        	$user_id = get_current_user_id() ;

		if ( defined( 'BLOG_ID_CURRENT_SITE' ) )
	        $main_site = BLOG_ID_CURRENT_SITE;
	   	else
	   		$main_site = 1;

	add_user_to_blog( $main_site, $user_id, 'subscriber' );
}

add_action( 'wpmu_new_user', 'wpms_add_user_to_main_site');

Add MU plugin that add network users to main site


<?php

namespace Ddeboer\Imap\Message;

class EmailAddress
{
    protected $mailbox;
    protected $hostname;
    protected $name;
    protected $address;

    public function __construct($mailbox, $hostname, $name = null)
    {
        $this->mailbox = $mailbox;
        $this->hostname = $hostname;
        $this->name = $name;
        $this->address = $mailbox . '@' . $hostname;
    }

    public function getAddress()
    {
        return $this->address;
    }

    public function getMailbox()
    {
        return $this->mailbox;
    }

    public function getHostname()
    {
        return $this->hostname;
    }

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

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

    public static function fromString($address)
    {
        $parts = explode('@', $address);

        return new self($parts[0], $parts[1]);
    }
}

Move email address to message

Move email address to message


<?php

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

class DropSoftDeletes extends Migration
{
    // aka the `deleted_at` column
    private $tables = [
        'articles',
        'educator_resources',
        'event_programs',
        'events',
        'generic_pages',
        'highlights',
        'issue_articles',
        'issues',
        'press_releases',
        'printed_catalogs',
        'web_artists',
        'web_exhibitions',
    ];

    public function up()
    {
        foreach ($this->tables as $table) {
            Schema::table($table, function (Blueprint $table) {
                $table->dropSoftDeletes();
            });
        }
    }

    public function down()
    {
        foreach ($this->tables as $table) {
            Schema::table($table, function (Blueprint $table) {
                $table->softDeletes()->after('updated_at');
            });
        }
    }
}

Remove `deleted_at` from all tables

Remove `deleted_at` from all tables [API-309]


<?php

declare(strict_types=1);

namespace Phpcq\Test\Runner\Repository;

use Phpcq\RepositoryDefinition\Plugin\PluginVersionInterface;
use Phpcq\RepositoryDefinition\Tool\ToolVersionInterface;
use Phpcq\Runner\Repository\InstalledPlugin;
use PHPUnit\Framework\TestCase;
use function array_values;
use function iterator_to_array;

/** @covers \Phpcq\Runner\Repository\InstalledPlugin */
final class InstalledPluginTest extends TestCase
{
    public function testInstantiation(): void
    {
        $version = $this->getMockForAbstractClass(PluginVersionInterface::class);
        $version->expects(self::once())->method('getName')->willReturn('plugin1');

        $tools   = ['tool1' => $this->getMockForAbstractClass(ToolVersionInterface::class)];
        $plugin  = new InstalledPlugin($version, $tools);

        self::assertSame('plugin1', $plugin->getName());
        self::assertSame($version, $plugin->getPluginVersion());
        self::assertSame(array_values($tools), iterator_to_array($plugin->iterateTools()));

        self::assertTrue($plugin->hasTool('tool1'));
        self::assertFalse($plugin->hasTool('tool2'));
    }

    public function testAddTool(): void
    {
        $version = $this->getMockForAbstractClass(PluginVersionInterface::class);
        $plugin  = new InstalledPlugin($version);

        self::assertFalse($plugin->hasTool('foo'));

        $tool = $this->getMockForAbstractClass(ToolVersionInterface::class);
        $tool->expects(self::once())->method('getName')->willReturn('foo');
        $plugin->addTool($tool);

        self::assertTrue($plugin->hasTool('foo'));
    }
}

Add unit test for installed plugin

Add unit test for installed plugin


<?php

declare(strict_types=1);

/**
 * @copyright 2020 Daniel Kesselberg <mail@danielkesselberg.de>
 *
 * @author 2020 Daniel Kesselberg <mail@danielkesselberg.de>
 *
 * @license GNU AGPL version 3 or any later version
 *
 * 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/>.
 *
 */

namespace Test\AppFramework\Middleware;

use OC\AppFramework\OCS\BaseResponse;

class BaseResponseTest extends \Test\TestCase {

	public function testToXml(): void {

		/** @var BaseResponse $response */
		$response = $this->createMock(BaseResponse::class);

		$writer = new \XMLWriter();
		$writer->openMemory();
		$writer->setIndent(false);
		$writer->startDocument();

		$data = [
			'hello' => 'hello',
			'information' => [
				'@test' => 'some data',
				'someElement' => 'withAttribute',
			],
			'value without key',
		];

		$this->invokePrivate($response, 'toXml', [$data, $writer]);
		$writer->endDocument();

		$this->assertEquals(
			"<?xml version=\"1.0\"?>\n<hello>hello</hello><information test=\"some data\"><someElement>withAttribute</someElement></information><element>value without key</element>\n",
			$writer->outputMemory(true)
		);
	}

}

Add test to trigger "Trying to access array offset on value of type int"

Signed-off-by: Daniel Kesselberg <1d6e1cf70ec6f9ab28d3ea4b27a49a77654d370e@danielkesselberg.de>


<?php
/**
 * The template for displaying all single posts and attachments
 *
 * @package WordPress
 * @subpackage FoundationPress
 * @since FoundationPress 1.0.0
 */

get_header(); ?>

  <?php do_action( 'foundationpress_before_content' ); ?>

  <?php while ( have_posts() ) : the_post(); ?>
    <article <?php post_class() ?> id="post-<?php the_ID(); ?>">

<?php the_title(); ?>

        <?php foundationpress_entry_meta(); ?>

      <?php do_action( 'foundationpress_post_before_entry_content' ); ?>

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

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

      <?php endif; ?>

      <?php the_content(); ?>

        <?php wp_link_pages( array('before' => '
' . __( 'Pages:', 'foundationpress' ), 'after' => '
' ) ); ?>

<?php the_tags(); ?>

      <?php do_action( 'foundationpress_post_before_comments' ); ?>
      <?php comments_template(); ?>
      <?php do_action( 'foundationpress_post_after_comments' ); ?>

  <?php endwhile;?>

  <?php do_action( 'foundationpress_after_content' ); ?>

  <?php get_sidebar(); ?>

<?php get_footer(); ?>

Add pet specific single page

Add pet specific single page


<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;

class CreateTeamRolesPermissions extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        // Reset cached roles and permissions
        app()['cache']->forget('spatie.permission.cache');

        Permission::firstOrCreate(['name' => 'create-teams']);
        Permission::firstOrCreate(['name' => 'read-teams']);
        Permission::firstOrCreate(['name' => 'update-teams']);
        Permission::firstOrCreate(['name' => 'delete-teams']);

        $role = Role::firstOrCreate(['name' => 'admin']);
        $role->givePermissionTo('create-teams');
        $role->givePermissionTo('read-teams');
        $role->givePermissionTo('update-teams');
        $role->givePermissionTo('delete-teams');

        $role = Role::firstOrCreate(['name' => 'officer-ii']);
        $role->givePermissionTo('create-teams');
        $role->givePermissionTo('read-teams');
        $role->givePermissionTo('update-teams');

        $role = Role::firstOrCreate(['name' => 'officer-i']);
        $role->givePermissionTo('create-teams');
        $role->givePermissionTo('read-teams');
        $role->givePermissionTo('update-teams');

        $role = Role::firstOrCreate(['name' => 'core']);
        $role->givePermissionTo('create-teams');
        $role->givePermissionTo('read-teams');

        $role = Role::firstOrCreate(['name' => 'member']);
        $role->givePermissionTo('read-teams');

        $role = Role::firstOrCreate(['name' => 'non-member']);
        $role->givePermissionTo('read-teams');
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        // Reset cached roles and permissions
        app()['cache']->forget('spatie.permission.cache');

        Permission::where('name', 'create-teams')->delete();
        Permission::where('name', 'read-teams')->delete();
        Permission::where('name', 'update-teams')->delete();
        Permission::where('name', 'delete-teams')->delete();
    }
}

Add permissions and update roles for Team endpoints


<?php
class PHPUnitStandard_Sniffs_Testing_NoOutputStatements implements PHP_CodeSniffer_Sniff
{
    public function register()
    {
        return array(T_ECHO);
        return array(T_PRINT);
    }

    public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
    {
        $phpcsFile->addError(
          'The use of the "echo" and "print" keywords is forbidden in tests',
          $stackPtr,
          'NotAllowed',
          array()
        );
    }
}

Add sniff for echo and print.

Add sniff for echo and print.


<?php

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

class AddExpirationDateToCompaniesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('companies', function (Blueprint $table) {
            $table->date('licence_expire_at')->nullable();
        });
    }

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

Add licence expiration date for company

Add licence expiration date for company


<?php
/**
 * Created by PhpStorm.
 * User: Tarek Rjili
 * Date: 3/23/15
 * Time: 23:20 PM
 */

namespace Trjili\Silex;

use Goutte\Client;
use Psr\Log\InvalidArgumentException;
use Silex\Application;
use Silex\ServiceProviderInterface;

class SilexGoutteServiceProvider implements ServiceProviderInterface
{
    /** @var string */
    private $prefix;

    /**
     * @param string $prefix
     */
    public function __construct($prefix = 'goutte')
    {
        if (!is_string($prefix) || empty($prefix)) {
            throw new InvalidArgumentException(sprintf('$prefix must be a valid string, %s given', gettype($prefix)));
        }
        $this->prefix = $prefix;
    }

    /**
     * @param Application $app
     */
    public function register(Application $app)
    {
        $app[$this->prefix] = $app->share(function (Application $app) {
            return new Client();
        });
    }

    /**
     * @param Application $app
     */
    public function boot(Application $app)
    {
    }
}

Create the goutte service provider.

[ServiceProvider] Create the goutte service provider.


<?php

class Stripe_DiscountTest extends Stripe_TestCase
{
  public function testDeletion()
  {
    self::authorizeFromEnv();
    $id = 'test-coupon-' . self::randomString();
    $coupon = Stripe_Coupon::create(
        array(
            'percent_off' => 25,
            'duration' => 'repeating',
            'duration_in_months' => 5,
            'id' => $id,
        )
    );
    $customer = self::createTestCustomer(array('coupon' => $id));

    $this->assertTrue(isset($customer->discount));
    $this->assertTrue(isset($customer->discount->coupon));
    $this->assertSame($id, $customer->discount->coupon->id);

    $customer->deleteDiscount();
    $this->assertFalse(isset($customer->discount));

    $customer = Stripe_Customer::retrieve($customer->id);
    $this->assertFalse(isset($customer->discount));
  }
}

Add PHPUnit test for Stripe_Discount

Add PHPUnit test for Stripe_Discount


<?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;
use Listabierta\Bundle\MunicipalesBundle\Validator\Constraints\DNI;

class CandidacyStep4Type extends AbstractType
{
	public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
        	->add('address', 'text', array(
        		'required' => true,
        		'constraints' => array(
        				new Assert\NotBlank(),
        				new Assert\Length(array(
        						'min'        => 2,
        						'max'        => 255,
        						'minMessage' => 'Your address must be at least {{ limit }} characters long',
        						'maxMessage' => 'Your address cannot be longer than {{ limit }} characters long',
        				))
        		)))
        	->add('continue', 'submit', array('attr' => array('class' => 'submit')));
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
    }

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

Create form type for step 4

Create form type for step 4


<?php

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

class AddTheftStatsToDominions extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up(): void
    {
        Schema::table('dominions', static function (Blueprint $table) {
            $table->unsignedInteger('stat_total_platinum_stolen')->after('stat_total_land_conquered')->default(0);
            $table->unsignedInteger('stat_total_food_stolen')->after('stat_total_platinum_stolen')->default(0);
            $table->unsignedInteger('stat_total_lumber_stolen')->after('stat_total_food_stolen')->default(0);
            $table->unsignedInteger('stat_total_mana_stolen')->after('stat_total_lumber_stolen')->default(0);
            $table->unsignedInteger('stat_total_ore_stolen')->after('stat_total_mana_stolen')->default(0);
            $table->unsignedInteger('stat_total_gems_stolen')->after('stat_total_ore_stolen')->default(0);
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down(): void
    {
        Schema::table('dominions', static function (Blueprint $table) {
            $table->dropColumn([
                'stat_total_platinum_stolen',
                'stat_total_food_stolen',
                'stat_total_lumber_stolen',
                'stat_total_mana_stolen',
                'stat_total_ore_stolen',
                'stat_total_gems_stolen',
            ]);
        });
    }
}

Add migration for acculumated theft stats fields


<?php

namespace Backend\Modules\ContentBlocks\Tests\Action;

use Common\WebTestCase;

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

        $client->setMaxRedirects(1);
        $client->request('GET', '/private/en/extensions/detail_theme?theme=Fork');

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

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

        $client->request('GET', '/private/en/extensions/detail_theme?theme=Fork');
        self::assertContains(
            'Core/Layout/Templates/Home.html.twig',
            $client->getResponse()->getContent()
        );
        self::assertContains(
            'class="positions">top, main',
            $client->getResponse()->getContent()
        );

        self::assertContains(
            'Version',
            $client->getResponse()->getContent()
        );

        self::assertContains(
            'Description',
            $client->getResponse()->getContent()
        );
    }
}

Add tests for the content extentions theme detail page


<?php
namespace ZBateson\MailMimeParser;

use PHPUnit_Framework_TestCase;
use ZBateson\MailMimeParser\Header\HeaderFactory;
use ZBateson\MailMimeParser\Header\Consumer\ConsumerService;
use ZBateson\MailMimeParser\Header\Part\HeaderPartFactory;

/**
 * Description of UUEncodedPartTest
 *
 * @group UUEncodedPart
 * @author Zaahid Bateson
 */
class UUEncodedPartTest extends PHPUnit_Framework_TestCase
{
    public function testUUEncodedPartHeadersAndMembers()
    {
        $pf = new HeaderPartFactory();
        $cs = new ConsumerService($pf);
        $hf = new HeaderFactory($cs, $pf);

        $part = new UUEncodedPart($hf, 0754, 'test-file.ext');
        $this->assertNotNull($part);

        $this->assertEquals('application/octet-stream', $part->getHeaderValue('Content-Type'));
        $this->assertEquals('test-file.ext', $part->getHeaderParameter('Content-Type', 'name'));
        $this->assertEquals('x-uuencode', $part->getHeaderValue('Content-Transfer-Encoding'));
        $this->assertEquals('attachment', $part->getHeaderValue('Content-Disposition'));
        $this->assertEquals('test-file.ext', $part->getHeaderParameter('Content-Disposition', 'filename'));
        $this->assertEquals('test-file.ext', $part->getFilename());
        $this->assertEquals(0754, $part->getUnixFileMode());
    }
}

Add unit tests for UUEncodedPart

Add unit tests for UUEncodedPart


#!/usr/bin/php
<?php

// Don't allow from Apache
if (PHP_SAPI !== 'cli')
{
    die('Nope.');
}

if (count($argv) < 2) {
    die("Usage: checkconfig.php <spells.yml>\n");
}

error_reporting(E_ALL);
ini_set('display_errors', 1);

$spellConfig =  dirname(__FILE__) . '/' . $argv[1];

if (!file_exists($spellConfig))
{
    die("File not found: $spellConfig\n");
}

$handle = fopen($spellConfig, "r");
if ($handle) {
    $keys = array();
    while (($line = fgets($handle)) !== false) {
        $trimmedLine = trim($line);
        $isEmpty = strlen($trimmedLine) == 0;
        $isComment = substr($line, 0, 1) == '#';
        if (!$isComment && !$isEmpty && substr($line, 0, 1) != ' ' && substr($line, 0, 1) != '-') {
            $newKey = substr(trim($line), 0, -1);
            if (isset($keys[$newKey])) {
                echo "Duplicate entry: $newKey\n";
            } else {
                $keys[$newKey] = true;
            }
        }
    }
    fclose($handle);
} else {
    die("Error opening file: $spellConfig\n");
}

echo "Done.\n";

Add a script that can be used to check for duplicate entries in config files, since that apparently makes SnakeYaml lose its mind now.


<?php
/*
 * Telegram Bot Sample
 * ===================
 * UWiClab, University of Urbino
 * ===================
 * API sample, using Microsoft Bing reverse geolocation API.
 */

define('BING_API', '');

include ('../lib.php');

if(count($argv) < 3) {
    echo ('Must pass geographic coordinates (lat and long) as command line parameter.' . PHP_EOL);
    exit;
}

$lat = floatval($argv[1]);
$lng = floatval($argv[2]);

$handle = prepare_curl_api_request("http://dev.virtualearth.net/REST/v1/Locations/$lat,$lng?key=" . BING_API, 'GET');

$response = perform_curl_request($handle);
if($response === false) {
    error_log('Failed to perform request.');
    exit;
}

$json = json_decode($response, true);
if(!$json['resourceSets']) {
    error_log('Response contains no resource sets');
    exit;
}

$sets = $json['resourceSets'];
$s = 1;

foreach($sets as $set) {
    echo "Resource set #$s" . PHP_EOL;

    $resources = $sets[0]['resources'];
    $r = 1;

    foreach($resources as $resource) {
        echo "Resource #$r" . PHP_EOL;

        $address = $resource['address'];
        $confidence = $resource['confidence'];

        echo 'Address: ';
        print_r($address);

        echo "Confidence: $confidence" . PHP_EOL;

        $r++;
    }

    $s++;
}
?>

Add Bing reverse geocoding API sample

Add Bing reverse geocoding API sample


<?php

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

require 'SharedConfigurations.php';

// Predis supports master / slave replication scenarios where write operations are
// performed on the master server and read operations are executed against one of
// the slaves. The behaviour of commands or EVAL scripts can be customized at will.
// As soon as a write operation is performed, all the subsequent requests (reads
// or writes) will be served by the master server.
//
// This example must be executed with the second Redis server acting as the slave
// of the first one using the SLAVEOF command.
//

$parameters = array(
    'tcp://127.0.0.1:6379?database=15&alias=master',
    'tcp://127.0.0.1:6379?database=15&alias=slave',
);

$options = array('replication' => true);

$client = new Predis\Client($parameters, $options);

// Read operation.
$exists = $client->exists('foo') ? 'yes' : 'no';
$current = $client->getConnection()->getCurrent()->getParameters();
echo "Does 'foo' exist on {$current->alias}? $exists.\n";

// Write operation.
$client->set('foo', 'bar');
$current = $client->getConnection()->getCurrent()->getParameters();
echo "Now 'foo' has been set to 'bar' on {$current->alias}!\n";

// Read operation.
$bar = $client->get('foo');
$current = $client->getConnection()->getCurrent()->getParameters();
echo "We just fetched 'foo' from {$current->alias} and its value is '$bar'.\n";

/* OUTPUT:
Does 'foo' exist on slave? yes.
Now 'foo' has been set to 'bar' on master!
We just fetched 'foo' from master and its value is 'bar'.
*/

Add example for master / slave replication.


<?php
$ch = curl_init();
curl_setopt( $ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; rv:1.7.3) Gecko/20041001 Firefox/0.10.1" );
curl_setopt($ch, CURLOPT_URL, "http://us.playstation.com/support/systemupdates/ps4/index.htm");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$html = curl_exec($ch);
curl_close($ch);

$dom = new DOMDocument();
@$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$hrefs = $xpath->evaluate("/html/body//a");
for ($i = 0; $i < $hrefs->length; $i++) {
       $href = $hrefs->item($i);
       $url = $href->getAttribute('href');
       $wanted = strpos($url, 'PUP');
       if ($wanted !== false)
       	echo $url;
}
?>

Print url from PS4 sytemupdate

Print url from PS4 sytemupdate


<?php

namespace Drush\Commands;

use Drush\Drush;
use Consolidation\SiteAlias\SiteAliasManagerAwareInterface;
use Consolidation\SiteAlias\SiteAliasManagerAwareTrait;

class CheckBootstrapCommands extends DrushCommands implements SiteAliasManagerAwareInterface {
  use SiteAliasManagerAwareTrait;

  /**
   * This command executes successfully if Drupal has been fully bootstrapped.
   *
   * @see DRUSH_BOOTSTRAP_DRUPAL_FULL
   *
   * @command check-bootstrap:full
   * @aliases check-bootstrap, cb
   * @bootstrap max
   */
  public function isBootstrapFull() {
    $this->checkBootstrapPhase(DRUSH_BOOTSTRAP_DRUPAL_FULL);
  }

  /**
   * This command executes successfully if Drupal's database has been bootstrapped.
   *
   * @see DRUSH_BOOTSTRAP_DRUPAL_DATABASE
   *
   * @command check-bootstrap:db
   * @bootstrap max
   */
  public function isBootstrapDatabase() {
    $this->checkBootstrapPhase(DRUSH_BOOTSTRAP_DRUPAL_DATABASE);
  }

  /**
   * This command executes successfully if Drupal's settings.php have been read.
   *
   * @see DRUSH_BOOTSTRAP_DRUPAL_CONFIGURATION
   *
   * @command check-bootstrap:config
   * @bootstrap max
   */
  public function isBootstrapConfiguration() {
    $this->checkBootstrapPhase(DRUSH_BOOTSTRAP_DRUPAL_CONFIGURATION);
  }

  /**
   * This command executes successfully if Drupal's settings.php was found.
   *
   * @see DRUSH_BOOTSTRAP_DRUPAL_SITE
   *
   * @command check-bootstrap:site
   * @bootstrap max
   */
  public function isBootstrapSite() {
    $this->checkBootstrapPhase(DRUSH_BOOTSTRAP_DRUPAL_SITE);
  }

  /**
   * This command executes successfully if a Drupal site was found.
   *
   * @see DRUSH_BOOTSTRAP_DRUPAL_ROOT
   *
   * @command check-bootstrap:root
   * @bootstrap max
   */
  public function isBootstrapRoot() {
    $this->checkBootstrapPhase(DRUSH_BOOTSTRAP_DRUPAL_ROOT);
  }

  protected function checkBootstrapPhase($phase) {
    if (Drush::bootstrapManager()->hasBootstrapped($phase)) {
      drush_set_context('DRUSH_EXIT_CODE', DRUSH_SUCCESS);
    }
    else {
      drush_set_context('DRUSH_EXIT_CODE', DRUSH_FRAMEWORK_ERROR);
    }
  }
}

Install our custom drush command for check if drush has been bootstrapped.


<?php
/**
 * @package deployment
 * @subpackage jupiter.roles_and_permissions
 */

$script = realpath(dirname(__FILE__) . '/../../../../') . '/alpha/scripts/utils/permissions/addPermissionsAndItems.php';
$config = realpath(dirname(__FILE__)) . '/../../../permissions/service.flavorasset.ini';
passthru("php $script $config");

Add script to update flavorasset permissions SUP-4739


<?php

use \UniEngine\Utils\Migrations as Migrations;

/**
 * Changelog:
 *  - Removes the last trace of the old "updater.php" admin panel script
 *
 */
class Migration_20190219_024600 implements Migrations\Interfaces\Migration {
    protected $configProvider;

    public function __construct() {
        $self = $this;

        $this->configProvider = new Migrations\PHPConfigProvider();
    }

    public function up() {
        $db = $this->getDBDriver();

        $db->executeQuery(
            "DELETE FROM `{{table(config)}}` " .
            "WHERE `config_name` = 'UniEngine_Updater_LastUpdateApplied' " .
            "LIMIT 1;"
        );
    }

    public function down() {
        $db = $this->getDBDriver();

        $db->executeQuery(
            "INSERT INTO `{{table(config)}}` (`config_name`, `config_value`) " .
            "VALUES ('UniEngine_Updater_LastUpdateApplied', '2');"
        );
    }

    public function isPriorManualActionRequired() {
        return false;
    }

    public function getPreviousProjectVersion() {
        return "1.0.0";
    }

    private function getDBDriver() {
        $self = $this;
        $db = new Migrations\DBDriver([
            "configProvider" => function () use ($self) {
                return $self->configProvider->getDatabaseConfig();
            }
        ]);

        return $db;
    }
}

?>

Create new migration to get rid of "UniEngine_Updater_LastUpdateApplied" config DB row


<?php

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

namespace Symfony\Bridge\Doctrine\DataFixtures;

use Doctrine\Common\DataFixtures\FixtureInterface;
use Doctrine\Common\DataFixtures\Loader as BaseLoader;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Doctrine data fixtures loader that injects the service container for
 * fixtures objects that implement ContainerAwareInterface.
 *
 * Note: This class cannot be used without the Doctrine data fixtures extension,
 * which is not listed as a required dependency for Symfony.
 */
class Loader extends BaseLoader
{
    private $container;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    /**
     * {@inheritdoc}
     */
    public function addFixture(FixtureInterface $fixture)
    {
        if ($fixture instanceof ContainerAwareInterface) {
            $fixture->setContainer($this->container);
        }

        parent::addFixture($fixture);
    }
}

Add common data fixtures loader

[DoctrineBridge] Add common data fixtures loader


<?php
defined('C5_EXECUTE') or die("Access Denied.");

$a = $b->getBlockAreaObject();
$container = $formatter->getLayoutContainerHtmlObject();
?>

        <?php
        foreach ($columns as $column) {
            $html = $column->getColumnHtmlObject();
            if (!empty($container)) {
                $container->appendChild($html);
            } else {
                print $html;
            }
        }

        echo $container;
        ?>

Add core area layout gray

Add core area layout gray


<?php
/*
Plugin Name: Decisions
Description: Not Options
Author: John P Bloch
Author URI: https://johnpbloch.com
License: MIT
*/

if ( ! class_exists( 'Closure' ) ) {
	_doing_it_wrong( __FILE__, 'This plugin requires PHP 5.3 or higher', '1.0' );

	return;
} else {
	require_once dirname( __FILE__ ) . '/src/load.php';
}

Add a main plugin file

Add a main plugin file


<?php

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

namespace Symfony\Component\HttpKernel\Tests\Controller\ArgumentResolver;

use PHPUnit\Framework\TestCase;
use Symfony\Component\DependencyInjection\ServiceLocator;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Controller\ArgumentResolver\ServiceValueResolver;
use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata;

class ServiceValueResolverTest extends TestCase
{
    public function testDoNotSupportWhenControllerDoNotExists()
    {
        $resolver = new ServiceValueResolver(new ServiceLocator(array()));
        $argument = new ArgumentMetadata('dummy', DummyService::class, false, false, null);
        $request = $this->requestWithAttributes(array('_controller' => 'my_controller'));

        $this->assertFalse($resolver->supports($request, $argument));
    }

    public function testExistingController()
    {
        $resolver = new ServiceValueResolver(new ServiceLocator(array(
            'App\\Controller\\Mine::method' => function () {
                return new ServiceLocator(array(
                    'dummy' => function () {
                        return new DummyService();
                    },
                ));
            },
        )));

        $request = $this->requestWithAttributes(array('_controller' => 'App\\Controller\\Mine::method'));
        $argument = new ArgumentMetadata('dummy', DummyService::class, false, false, null);

        $this->assertTrue($resolver->supports($request, $argument));
        $this->assertYieldEquals(array(new DummyService()), $resolver->resolve($request, $argument));
    }

    public function testControllerNameIsAnArray()
    {
        $resolver = new ServiceValueResolver(new ServiceLocator(array(
            'App\\Controller\\Mine::method' => function () {
                return new ServiceLocator(array(
                    'dummy' => function () {
                        return new DummyService();
                    },
                ));
            },
        )));

        $request = $this->requestWithAttributes(array('_controller' => array('App\\Controller\\Mine', 'method')));
        $argument = new ArgumentMetadata('dummy', DummyService::class, false, false, null);

        $this->assertTrue($resolver->supports($request, $argument));
        $this->assertYieldEquals(array(new DummyService()), $resolver->resolve($request, $argument));
    }

    private function requestWithAttributes(array $attributes)
    {
        $request = Request::create('/');

        foreach ($attributes as $name => $value) {
            $request->attributes->set($name, $value);
        }

        return $request;
    }

    private function assertYieldEquals(array $expected, \Generator $generator)
    {
        $args = array();
        foreach ($generator as $arg) {
            $args[] = $arg;
        }

        $this->assertEquals($expected, $args);
    }
}

class DummyService
{
}

Add service value resolver tests Prove that the service value resolver will not work with the array notation


Upgrade safe setting default quote template


<?php

namespace MarcusJaschen\Collmex\Type;

/**
 * Collmex Subscription Get Type
 *
 * @author   Jewel Ahmed <tojibon@gmail.com>
 * @author   Marcus Jaschen <mjaschen@gmail.com>
 * @author   Jesus Ortiz <ortizko@gmail.com>
 * @license  http://www.opensource.org/licenses/mit-license MIT License
 * @link     https://github.com/mjaschen/collmex
 */
class SubscriptionGet extends AbstractType implements TypeInterface
{
    /**
     * Type data template
     *
     * @var array
     */
    protected $template = array(
        'type_identifier'     => 'ABO_GET',
        'customer_id'         => null,
        'client_id'           => null,
        'product_id'          => null,
    );

    /**
     * Formally validates the type data in $data attribute.
     *
     * @return bool Validation success
     */
    public function validate()
    {
        return true;
    }
}

Add subscription get type class

Add subscription get type class


<?php

namespace Listabierta\Bundle\MunicipalesBundle\Form\Type\Census;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Validator\Constraints as Assert;
use Listabierta\Bundle\MunicipalesBundle\Validator\Constraints\DNI;

class CensusStepVerifyType 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 'census_step_verify';
    }
}

Update names in census step verify

Update names in census step verify


<?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. The ConsentService and ConsentRepository do not
 * use entities.
 *
 * @ORM\Entity()
 * @ORM\Table(indexes={
 *     @ORM\Index(name="hashed_user_id", columns={"hashed_user_id"}),
 *     @ORM\Index(name="service_id", columns={"service_id"}),
 * })
 */
class Consent
{
    /**
     * @var DateTime
     *
     * @ORM\Column(name="consent_date", type="datetime", options={"default": 0})
     */
    public $date;

    /**
     * @var string
     *
     * @ORM\Id
     * @ORM\Column(type="string", length=80)
     */
    public $hashedUserId;

    /**
     * @var string
     *
     * @ORM\Id
     * @ORM\Column(type="string")
     */
    public $serviceId;

    /**
     * @var string
     *
     * @ORM\Column(type="string", length=80)
     */
    public $attribute;

    /**
     * @var string
     *
     * @ORM\Column(name="consent_type", type="string", nullable=true, length=20, options={"default": "explicit"})
     */
    public $type;
}

Add doctrine configuration for the consent table


<?php

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

class AlterLeadTableAddColumnStatus extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('lead', function (Blueprint $table) {
            $table->string('linkedin')->nullable()->after('website');
            $table->string('facebook')->nullable()->after('linkedin');
            $table->string('instagram')->nullable()->after('facebook');
            $table->string('twitter')->nullable()->after('instagram');
            $table->string('youtube')->nullable()->after('twitter');
            $table->enum('status', ['open', 'first_contact', 'recall', 'quote', 'quoted', 'waiting_for_answer', 'standby', 'closed'])->nullable()->default('open')->after('country_id');
        });
    }

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

Update last lead migration adding missing social media fields


#!/usr/bin/env php
<?php

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

$root = dirname(dirname(dirname(__FILE__)));
require_once $root.'/scripts/__init_script__.php';

$args = new PhutilArgumentParser($argv);
$args->setTagline('load files as image macros');
$args->setSynopsis(<<<EOHELP
**add_macro.php** __image__ [--as __name__]
    Add an image macro. This can be useful for importing a large number
    of macros.
EOHELP
);
$args->parseStandardArguments();

$args->parse(
  array(
    array(
      'name'  => 'as',
      'param' => 'name',
      'help'  => 'Use a specific name instead of the first part of the image '.
                 'name.',
    ),
    array(
      'name'      => 'more',
      'wildcard'  => true,
    ),
  ));

$more = $args->getArg('more');
if (count($more) !== 1) {
  $args->printHelpAndExit();
}

$path = head($more);
$data = Filesystem::readFile($path);

$name = $args->getArg('as');
if ($name === null) {
  $name = head(explode('.', basename($path)));
}

$existing = id(new PhabricatorFileImageMacro())->loadOneWhere(
  'name = %s',
  $name);
if ($existing) {
  throw new Exception("A macro already exists with the name '{$name}'!");
}

$file = PhabricatorFile::newFromFileData(
  $data,
  array(
    'name' => basename($path),
  ));

$macro = id(new PhabricatorFileImageMacro())
  ->setFilePHID($file->getPHID())
  ->setName($name)
  ->save();

$id = $file->getID();

echo "Added macro '{$name}' (F{$id}).\n";

Add a script to programmatically add image macros

Summary: Urgent request.

Test Plan: Ran "add_macro.php" on some things; verified results in web console.

Reviewers: btrahan, tcook

Reviewed By: btrahan

CC: aran, epriestley

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


<?php
namespace Oro\Bundle\WorkflowBundle\Tests\Functional\EventListener;

use Oro\Bundle\TestFrameworkBundle\Test\WebTestCase;
use Oro\Bundle\WorkflowBundle\EventListener\ProcessCollectorListener;

class ProcessCollectorListenerTest extends WebTestCase
{
    public function setUp()
    {
        parent::setUp();

        $this->initClient();
    }

    public function testCouldBeGetFromContainerAsService()
    {
        $listener = self::getContainer()->get('oro_workflow.listener.process_collector');

        self::assertInstanceOf(ProcessCollectorListener::class, $listener);
    }
}

BAP-11602: Move ExecuteProcessJobCommand's logic to Message processor.

- attempt to fix cycrular service relations.


<?php
// (c) Copyright 2002-2013 by authors of the Tiki Wiki CMS Groupware Project
//
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id$

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

function upgrade_20140812_convert_tiki_connect_data_to_json($installer)
{
	$tiki_connect = TikiDb::get()->table('tiki_connect');

	$rows = $tiki_connect->fetchAll(array('id', 'created', 'type', 'data', 'guid', 'server'));

	foreach ($rows as $row) {
		if (!empty($row['data'])) {
			$data = unserialize($row['data']);
			if ($data) {
				$tiki_connect->update(
					array('data' => json_encode($data)),
					array('id' => $row['id'])
				);
			}
		}
	}

}

[MOD] Convert Tiki Connect data to json encoding (only for mother.tiki.org really, thanks again Xavi)

git-svn-id: 3582b35ee56d9e99405df4322499343324934860@52315 b456876b-0849-0410-b77d-98878d47e9d5


<?php

namespace Environaut\Tests;

use Environaut\Application;

use Symfony\Component\Console\Tester\ApplicationTester;

class ApplicationTest extends BaseTestCase
{
    public function testConstruct()
    {
        $application = new Application('1337');

        $this->assertEquals('1337', $application->getVersion());
    }

    public function testProfileRun()
    {
        $application = new Application('1337');
        $application->setAutoExit(false);
        $application->setCatchExceptions(false);

        $tester = new ApplicationTester($application);
        $tester->run(array('--profile' => true), array('decorated' => false));

        $output = $tester->getDisplay(true);

        $this->assertContains('Environaut version 1337', $output);
        $this->assertContains('Memory usage: ', $output);
    }
}

Add simple application run test

Add simple application run test


<?php
/*
 * Xibo - Digital Signage - http://www.xibo.org.uk
 * Copyright (C) 2018 Spring Signage Ltd
 *
 * This file is part of Xibo.
 *
 * Xibo 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
 * any later version.
 *
 * Xibo 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 Xibo.  If not, see <http://www.gnu.org/licenses/>.
 */

use Phinx\Migration\AbstractMigration;

/**
 * Class FixCaseOnHelpTextFieldMigration
 */
class FixCaseOnHelpTextFieldMigration extends AbstractMigration
{
    /** @inheritdoc */
    public function change()
    {
        $table = $this->table('setting');
        if ($table->hasColumn('helptext')) {
            $table->renameColumn('helptext', 'helpText')->save();
        }
    }
}

Fix issue with helpText/helptext casing on setting table.


<?php
/**
 * @file
 * Contains \Drupal\example\Form\ExampleForm.
 */

namespace Drupal\example\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * Implements an example form.
 */
class SocialMediaAggregatorForm extends FormBase {

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'socialmediaaggregator_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['social_media_aggregator_admin'] = array(
      '#type' => 'tel',
      '#title' => $this->t('Your phone number'),
    );
    $form['actions']['#type'] = 'actions';
    $form['actions']['submit'] = array(
      '#type' => 'submit',
      '#value' => $this->t('Save'),
      '#button_type' => 'primary',
    );
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    if (strlen($form_state->getValue('social_media_aggregator_admin')) < 3) {
      $form_state->setErrorByName('social_media_aggregator_admin', $this->t('The phone number is too short. Please enter a full phone number.'));
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    drupal_set_message($this->t('Your phone number is @number', array('@number' => $form_state->getValue('social_media_aggregator_admin'))));
  }

}
?>

Add Form directory including SocialMediaAggregatorForm class


<?php

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

class AddIdIndexToMessages extends Migration
{
    public function up()
    {
        $this->schema->table('messages', function (Blueprint $table) {
            $table->index('id');
        });
    }

    public function down()
    {
        $this->schema->table('messages', function (Blueprint $table) {
            $table->dropIndex('messages_id_index');
        });
    }
}

Add index on messages(id) to boost performances


<?php

namespace OpenCFP\Test\Http\Controller\Reviewer;

use OpenCFP\Test\TestCase;

class DashboardControllerTest extends TestCase
{
    /**
     * @test
     */
    public function indexActionWorksWithoutTalks()
    {
        $this->asReviewer()
            ->get('/reviewer/')
            ->assertSuccessful()
            ->assertNotSee('title="I want to see this talk"')
            ->assertSee('Recent Talks');
    }
}

Add a dashboard controller test

Add a dashboard controller test


<?php

namespace Doctrine\ODM\PHPCR\Tools\Console\Command;

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

/**
 * Command to register system node types.
 *
 * This command registers the necessary node types to get phpcr odm working
 */

class RegisterSystemNodeTypesCommand extends Command
{
   /**
     * @see Console\Command\Command
     */
    protected function configure()
    {
        $this
        ->setName('odm:phpcr:register-system-node-types')
        ->setDescription('Register system node types in the PHPCR repository')
        ->setDefinition(array(
            new InputOption('allow-update', '', InputOption::VALUE_NONE, 'Overwrite existig node types'),
        ))
        ->setHelp(<<<EOT
Register system node types in the PHPCR repository.

This command registers the node types necessary for the ODM to work.

If you use --allow-update existing node type definitions will be overwritten
in the repository.
EOT
        );
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $dm = $this->getHelper('dm')->getDocumentManager();

        $cnd = <<<CND
<phpcr='http://www.doctrine-project.org/phpcr-odm'>
[phpcr:managed]
  mixin
  - phpcr:alias (STRING)
CND
        ;
        $allowUpdate = $input->getOption('allow-update');

        $session = $dm->getPhpcrSession();
        $ntm = $session->getWorkspace()->getNodeTypeManager();

        try {
            $ntm->registerNodeTypesCnd($cnd, $allowUpdate);
        } catch (\PHPCR\NodeType\NodeTypeExistsException $e) {
            if (!$allowUpdate) {
                $output->write(PHP_EOL.'<error>The node type(s) you tried to register already exist.</error>'.PHP_EOL);
                $output->write(PHP_EOL.'If you want to override the existing definition call this command with the ');
                $output->write('<info>--allow-update</info> option.'.PHP_EOL);
            }
            throw $e;
        }
        $output->write(PHP_EOL.sprintf('Sucessfully registered system node types.') . PHP_EOL);
    }
}

Add a command to register system node types

registers the node type phpcr:managed without havin to create the file


<?php

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

namespace Surfnet\Stepup\Tests\Identity\Entity;

use Mockery as m;
use PHPUnit_Framework_TestCase as UnitTest;
use Surfnet\Stepup\Identity\Entity\SecondFactorCollection;
use Surfnet\Stepup\Identity\Entity\SecondFactor;
use Surfnet\StepupBundle\Service\SecondFactorTypeService;
use Surfnet\StepupBundle\Value\SecondFactorType;

class SecondFactorCollectionTest extends UnitTest
{
    /**
     * @test
     * @group domain
     */
    public function collection_can_return_second_factor_with_highest_loa()
    {
        $collection = new SecondFactorCollection([
            $this->mockVettedSecondFactor('sms'),
            $this->mockVettedSecondFactor('yubikey'),
        ]);

        $secondFactor = $collection->getSecondFactorWithHighestLoa(
            new SecondFactorTypeService([])
        );

        $this->assertNotNull($secondFactor, 'Collection should have returned a second factor object');
        $this->assertTrue($secondFactor->getType()->isYubikey(), 'Expected yubikey since it has a higher LoA than sms');
    }

    /**
     * @param string $type
     * @return SecondFactor
     */
    private function mockVettedSecondFactor($type)
    {
        $mock = m::mock('\Surfnet\Stepup\Identity\Entity\SecondFactor');
        $mock->shouldReceive('getType')
            ->andReturn(new SecondFactorType($type));

        return $mock;
    }
}

Add unit test for second factor collection


<?php

namespace Listabierta\Bundle\MunicipalesBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class ChangePasswordType extends AbstractType
{
	public function buildForm(FormBuilderInterface $builder, array $options)
	{
		$builder->add('oldPassword', 'password');
		$builder->add('newPassword', 'repeated', array(
				'type' => 'password',
				'invalid_message' => 'The password fields must match.',
				'required' => true,
				'first_options'  => array('label' => 'Contraseña'),
				'second_options' => array('label' => 'Repite contraseña'),
		));
	}

	public function setDefaultOptions(OptionsResolverInterface $resolver)
	{
		$resolver->setDefaults(array(
				'data_class' => 'Listabierta\Bundle\MunicipalesBundle\Form\Model\ChangePassword',
		));
	}

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

Add change password form type

Add change password form type


<?php

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

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

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

Add index for user_id on beatmapset_events


<?php

namespace Oro\Bundle\WorkflowBundle\Form\Handler;

use Symfony\Component\Form\Form;
use Symfony\Component\HttpFoundation\RequestStack;

use Oro\Bundle\EntityBundle\ORM\DoctrineHelper;

class TransitionFormHandler
{
    /** @var RequestStack */
    private $requestStack;

    /** @var DoctrineHelper */
    private $doctrineHelper;

    public function __construct(RequestStack $requestStack, DoctrineHelper $doctrineHelper)
    {
        $this->requestStack = $requestStack;
        $this->doctrineHelper = $doctrineHelper;
    }

    /**
     * @param Form $transitionForm
     * @param array $formAttributes
     * @return bool
     */
    public function handleTransitionForm(Form $transitionForm, array $formAttributes)
    {
        $request = $this->requestStack->getCurrentRequest();
        if (!$request->isMethod('POST')) {
            return false;
        }
        $doctrineHelper = $this->doctrineHelper;
        $transitionForm->submit($request);
        if ($transitionForm->isValid()) {
            foreach ($formAttributes as $value) {
                // Need to persist all new entities to allow serialization
                // and correct passing to API start method of all input data.
                // Form validation already performed, so all these entities are valid
                // and they can be used in workflow start action.
                if (is_object($value) && $doctrineHelper->isManageableEntity($value)) {
                    $entityManager = $doctrineHelper->getEntityManager($value);
                    $unitOfWork = $entityManager->getUnitOfWork();
                    if (!$unitOfWork->isInIdentityMap($value) || $unitOfWork->isScheduledForInsert($value)) {
                        $entityManager->persist($value);
                        $entityManager->flush($value);
                    }
                }
            }
            return true;
        }
        return false;
    }
}

BB-5906: Refactor WidgetController::startTransitionFormAction
- created handler for transition form


<?php

class Stripe_TokenTest extends Stripe_TestCase
{
  public function testUrls()
  {
    $this->assertSame(Stripe_Token::classUrl('Stripe_Token'), '/v1/tokens');
    $token = new Stripe_Token('abcd/efgh');
    $this->assertSame($token->instanceUrl(), '/v1/tokens/abcd%2Fefgh');
  }
}

Add PHPUnit test for Stripe_Token

Add PHPUnit test for Stripe_Token


<?php
namespace Onion\Framework\Router\Strategy;

class CompiledRegexStrategy
{
    private $routes = [];

    public function __construct(array $routes, int $groupCount = 10)
    {
        $compiledRoutes = [];
        foreach ($routes as $route) {
            foreach ($this->compile($route->getPattern()) as $pattern => $params) {
                $compiledRoutes[$pattern] = [$route, $params];
            }
        }
        $sections = round(count($compiledRoutes)/10)+1;

        for ($i=0; $i<$sections; $i++) {
            $handlers = [];
            $pattern = '(?|';
            $length = 0;
            foreach ($compiledRoutes as $key => $route) {
                $expansion = str_repeat('()', $length);
                $pattern .= "{$key}{$expansion}|";
                $index = ($length + count($route[1]));
                if (isset($handlers[$index])) {
                    throw new \RuntimeException("Possible route conflict");
                }
                $handlers[$index] = $route;

                $length++;
                if ($groupCount === $length) {
                    break;
                }
                unset($compiledRoutes[$key]);
            }

            $pattern = rtrim($pattern, '/|');
            $pattern .= ')';

            $this->routes[$pattern] = $handlers;
        }
    }

    public function resolve(string $method, string $path)
    {
        foreach ($this->routes as $pattern => $route) {
            if(!preg_match('~'.$pattern.'~', $path, $matches)) {
                continue;
            }

            $params = [];
            array_shift($matches);
            $index = count($matches);

            $matches = array_filter($matches, function ($value) {
                return $value !== '';
            });

            foreach ($matches as $i => $match) {
                if ($match === '') {
                    continue;
                }

                $params[$route[$index][1][$i]] = $match;
            }

            return [$route[$index][0], $params];
        }
    }

    private function compile(string $pattern)
    {
        $patterns = [];
        $params = [];
        preg_match('~([^\{]+)~i', $pattern, $prefix);
        $partial = rtrim($prefix[0] ?? '', '/');
        preg_match_all('~(\{(?P<name>.*)(?:\:\s?(?P<pattern>.*))?\}(?P<conditional>\?)?+)+~iuU', $pattern, $matches, PREG_SET_ORDER);
        if (!empty($matches)) {
            foreach ($matches as $param) {
                if (isset($param['conditional']) && !empty($param['conditional'])) {
                    $patterns[$partial] = $params;
                }

                $name = preg_replace('~([/\{]{1,2})~', '', $param['name']);
                $params[] = $name;
                $expr = $param['pattern'] ?? '[^/]';
                $partial = (rtrim($partial, '/') . "/({$expr})") . ($param['conditional'] ?? '');
                $patterns[$partial] = $params;
            }
        }

        return $patterns;
    }
}

Add compiled route strategy inspired by fast route


<?php

namespace Mimic\Test;

use PHPUnit_Framework_TestCase;
use Mimic\Functional as F;

use ArrayIterator;

/**
 * Unit Test for forgetFirst Mimic library function.
 *
 * @since 0.1.0
 */
class ForgetFirstFuncTest extends PHPUnit_Framework_TestCase {
	public function dataProvider() {
		return array(
			array(array(1, 2, 3), array(1, 2, 3), array(2, 3)),
			array(new ArrayIterator(array(1, 2, 3)), array(1, 2, 3), array(2, 3)),
			array(array('something', 'else'), array('something', 'else'), array('else')),
			array(array('else'), array('else'), array()),
			array(array(), array(), array()),
		);
	}

	/**
	 * @dataProvider dataProvider
	 * @covers ::Mimic\Functional\forgetFirst
	 */
	public function testResults($collection, $check, $expected) {
		$this->assertEquals($expected, F\forgetFirst($collection));
		$this->assertSame($check, $collection, 'collection has changed');
	}
}

Add forget first function test suite.

Add forget first function test suite.


<?php
// src/VersionContol/GitControlBundle/Entity/GitDiff.php

namespace VersionContol\GitControlBundle\Entity;

/**
 * Git Remote object
 *
 * @author fr_user
 */
class GitRemote {

    protected $shortName;

    protected $longName;

    protected $state;

    public function getShortName() {
        return $this->shortName;
    }

    public function getLongName() {
        return $this->longName;
    }

    public function getState() {
        return $this->state;
    }

    public function setShortName($shortName) {
        $this->shortName = $shortName;
        return $this;
    }

    public function setLongName($longName) {
        $this->longName = $longName;
        return $this;
    }

    public function setState($state) {
        $this->state = $state;
        return $this;
    }

}

Add Remote entity. Not in use yet

Add Remote entity. Not in use yet


<?php
/**
 *
 * @author newloki
 */

namespace Tests\Language\Languages\Indo\German;
use Language\Languages\Indo\English\EnglishAbstract,
    Language\Languages\Indo\IndoAbstract,
    Language\Languages\Indo\English\UK\Uk;

require_once realpath(LIBRARY_PATH . '/Language/Languages/Indo/English/EnglishAbstract.php');
require_once realpath(LIBRARY_PATH . '/Language/Languages/Indo/IndoAbstract.php');

class EnglishAbstractTest extends \PHPUnit_Framework_TestCase
{
    public function testIfYIsAVocalByDefault()
    {
        try {
            $language = $this->getMockForAbstractClass('EnglishAbstract');
        } catch(\Exception $e) {
            //handle Exception, because there is a bug in PHPUnit until version
            // 3.5.4 who prevent mocking abstract class
            $this->markTestSkipped('Can\'t get mock from EnglishAbstract class');
        }

        $mappingVC = $language->getCVMapping();
        $this->assertEquals($mappingVC['y'], IndoAbstract::VOCAL);
        $this->assertNotEquals($mappingVC['y'], IndoAbstract::CONSONANT);
    }

}

Add test for abstract english class

Add test for abstract english class


<?php

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

use App\Models\Attributes\Generic\Municipality;

/**
 * This is the municipality extractor test class.
 *
 * @author Fábio Santos <ffsantos92@gmail.com>
 */
class MunicipalityExtractorTest extends AbstractPropertyExtractorTest
{
    public function testExtractMunicipality()
    {
        $text = [
            'e descrito na Conservatória do Registo Predial de Seixal' => 'Seixal',
            'freguesia da Portimão concelho de Portimão'               => 'Portimão',
        ];

        foreach ($text as $input => $expected) {
            $municipalityId = $this->extractor->municipality($input, null);

            if ($this->assertNotNull($municipalityId)) {
                $this->assertSame($expected, Municipality::find($municipalityId)->name);
            }
        }
    }
}

Add the municipality extractor test

Add the municipality extractor test


<?php

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

class CreateMinecraftAuthCodes extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('minecraft_auth_codes', function (Blueprint $table) {
            $table->bigIncrements('minecraft_auth_code_id');
            $table->uuid('token');
            $table->integer('player_minecraft_id')->unsigned();
            $table->string('uuid', 60)->unique();
            $table->dateTime('expires_at');
            $table->timestamps();

            $table->index('token');
        });
    }

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

Create Minecraft auth code migration

Create Minecraft auth code migration


<?php
/**
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @author Stephane HULARD <s.hulard@chstudio.fr>
 * @package GitServiceMove\Command\BitBucket
 */
namespace GitServiceMove\Command\BitBucket;

use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

/**
 * Retrieve status of BitBucket connection
 * @package GitServiceMove\Command\BitBucket
 */
class Status extends Base
{
    /**
     * Basic configuration for beebot command.
     * Define standard and globals options for the command line
     */
    protected function configure()
    {
        parent::configure();
        $this->setDescription('Check BitBucket connection');
    }

    /**
     * @param InputInterface  $input  An InputInterface instance
     * @param OutputInterface $output An OutputInterface instance
     * @return null|int     null or 0 if everything went fine, or an error code
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $user = new \Bitbucket\API\User();
        $user->setCredentials($this->getAuth());

        // now you can access protected endpoints as $bb_user
        $response = $user->get();
        return $response->isSuccessful()?0:self::CODE_ERROR;
    }
}

Check that BitBucket credentials are valid


<?php

namespace Tests\Localization;

/*
 * This file is part of the Carbon package.
 *
 * (c) Brian Nesbitt <brian@nesbot.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

use Carbon\Carbon;
use Tests\AbstractTestCase;

class NlTest extends AbstractTestCase
{
    public function testDiffForHumansLocalizedInDutch()
    {
        Carbon::setLocale('nl');

        $scope = $this;
        $this->wrapWithTestNow(function () use ($scope) {

            $d = Carbon::now()->subSecond();
            $scope->assertSame('1 seconde geleden', $d->diffForHumans());

            $d = Carbon::now()->subSeconds(2);
            $scope->assertSame('2 seconden geleden', $d->diffForHumans());

            $d = Carbon::now()->subMinute();
            $scope->assertSame('1 minuut geleden', $d->diffForHumans());

            $d = Carbon::now()->subMinutes(2);
            $scope->assertSame('2 minuten geleden', $d->diffForHumans());

            $d = Carbon::now()->subHour();
            $scope->assertSame('1 uur geleden', $d->diffForHumans());

            $d = Carbon::now()->subHours(2);
            $scope->assertSame('2 uur geleden', $d->diffForHumans());

            $d = Carbon::now()->subDay();
            $scope->assertSame('1 dag geleden', $d->diffForHumans());

            $d = Carbon::now()->subDays(2);
            $scope->assertSame('2 dagen geleden', $d->diffForHumans());

            $d = Carbon::now()->subWeek();
            $scope->assertSame('1 week geleden', $d->diffForHumans());

            $d = Carbon::now()->subWeeks(2);
            $scope->assertSame('2 weken geleden', $d->diffForHumans());

            $d = Carbon::now()->subMonth();
            $scope->assertSame('1 maand geleden', $d->diffForHumans());

            $d = Carbon::now()->subMonths(2);
            $scope->assertSame('2 maanden geleden', $d->diffForHumans());

            $d = Carbon::now()->subYear();
            $scope->assertSame('1 jaar geleden', $d->diffForHumans());

            $d = Carbon::now()->subYears(2);
            $scope->assertSame('2 jaar geleden', $d->diffForHumans());

            $d = Carbon::now()->addSecond();
            $scope->assertSame('over 1 seconde', $d->diffForHumans());

            $d = Carbon::now()->addSecond();
            $d2 = Carbon::now();
            $scope->assertSame('1 seconde later', $d->diffForHumans($d2));
            $scope->assertSame('1 seconde eerder', $d2->diffForHumans($d));

            $scope->assertSame('1 seconde', $d->diffForHumans($d2, true));
            $scope->assertSame('2 seconden', $d2->diffForHumans($d->addSecond(), true));
        });
    }
}

Add tests for Dutch translation

Add tests for Dutch translation


<?php

/**
 * Generates minimal site-wide page chrome.
 * @see https://drupal.org/node/1728148
 **/

?>

<?php if (!empty($tabs['#primary'])): ?><?php print render($tabs); ?><?php endif; ?>
<?php print $messages; ?>

  <?php print $variables['navigation']; ?>

    <?php print render($page['content']); ?>

  <?php print $variables['footer']; ?>

Fix extra header on user profile page.

Fix extra header on user profile page.


<?php

namespace Tests\Regis\Application\CommandHandler\Team;

use Regis\Application\Command;
use Regis\Application\CommandHandler;
use Regis\Domain\Entity;
use Regis\Domain\Repository;

class AddRepositoryTest extends \PHPUnit_Framework_TestCase
{
    private $teamsRepo;
    private $reposRepo;
    /** @var CommandHandler\Team\AddRepository */
    private $handler;

    public function setUp()
    {
        $this->teamsRepo = $this->getMockBuilder(Repository\Teams::class)->getMock();
        $this->reposRepo = $this->getMockBuilder(Repository\Repositories::class)->getMock();

        $this->handler = new CommandHandler\Team\AddRepository($this->teamsRepo, $this->reposRepo);
    }

    public function testItAddsTheRepositoryToTheTeam()
    {
        $owner = $this->getMockBuilder(Entity\User::class)->disableOriginalConstructor()->getMock();
        $newRepo = $this->getMockBuilder(Entity\Repository::class)->disableOriginalConstructor()->getMock();
        $newRepoId = 'new-repo-id';
        $team = new Entity\Team($owner, 'super team');

        $command = new Command\Team\AddRepository($team, $newRepoId);

        $this->reposRepo->expects($this->once())
            ->method('find')
            ->with($newRepoId)
            ->will($this->returnValue($newRepo));

        $this->teamsRepo->expects($this->once())
            ->method('save')
            ->with($this->callback(function(Entity\Team $team) use ($newRepo) {
                return count($team->getRepositories()) === 1
                && in_array($newRepo, iterator_to_array($team->getRepositories()), true);
            }));

        $this->handler->handle($command);
    }

    public function testItDoesNothingIfTheRepositoryIsAlreadyInTheTeam()
    {
        $owner = $this->getMockBuilder(Entity\User::class)->disableOriginalConstructor()->getMock();
        $newRepo = $this->getMockBuilder(Entity\Repository::class)->disableOriginalConstructor()->getMock();
        $newRepoId = 'new-repo-id';
        $team = new Entity\Team($owner, 'super team');

        $command = new Command\Team\AddRepository($team, $newRepoId);

        $this->reposRepo->expects($this->once())
            ->method('find')
            ->with($newRepoId)
            ->will($this->returnValue($newRepo));

        $this->teamsRepo->expects($this->once())
            ->method('save')
            ->will($this->throwException(new Repository\Exception\UniqueConstraintViolation()));

        $this->handler->handle($command);
    }
}

Test the add repository handler

Test the add repository handler


<?php

class ManagerBusinessServiceControllerTest extends TestCase
{
    use CreateBusiness, CreateUser, CreateService;

    /**
     * @covers   App\Http\Controllers\Manager\BusinessServiceController::index
     * @test
     */
    public function it_lists_the_business_services_for_management()
    {
        $owner = $this->createUser();

        $business = $this->createBusiness();

        $business->owners()->save($owner);

        $service = $this->makeService();

        $business->services()->save($service);

        $this->actingAs($owner);

        $this->visit(route('manager.business.service.index', $business));

        $this->assertResponseOk();
        $this->see('Add as many services as you provide to configure availability for each of them');
        $this->see($service->name);
    }
}

Add Manager BusinessServiceController Test suite


<?php

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

   Copyright (C) 2009 Free Software Foundation, Inc

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

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

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

*/

require_once('database.php');
require_once('templating.php');
require_once('data/sanitize.php');
require_once('data/Server.php');
require_once('data/TagCloud.php');
require_once('artist-menu.php');

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

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

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

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

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

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

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

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

Add artist tagging page (missed from last commit)


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

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

// Visit https://code.google.com/apis/console?api=analytics 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');
$service = new apiAnalyticsService($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()) {
  $props = $service->webproperties->listManagementWebproperties("~all");
  print "
Web Properties

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

  $accounts = $service->accounts->listManagementAccounts();
  print "
Accounts

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

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

Add a sample application for the Google Analytics V3 API.

git-svn-id: 6c6eb0d3cc6e8d5f6d3a0c71e6b3abc7e9845ff1@289 6c5fc399-1a2c-022f-82ce-feb0d0b4916c


<?php
$yes = array('this', 'is', 'an array');

echo is_array($yes) ? 'Array' : 'not an Array';
echo "\n";

$no = 'this is a string';

echo is_array($no) ? 'Array' : 'not an Array';
?>

Check that variable is an array

Check that variable is an array


<?php

namespace AppBundle\Tests\Connections;

use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;

/**
 * @file
 * Project: orcid
 * File: RepositoryTest.php
 */
class RepositoryTest extends KernelTestCase
{
    private $container;

    public function setUp()
    {
        self::bootKernel();

        $this->container = self::$kernel->getContainer();
    }

    public function testRepository()
    {
        /* @var \AppBundle\Connections\Service $orcid */
        $orcid = $this->container->get('app.service.orcid');
        $this->assertInstanceOf(\AppBundle\Connections\Service::class, $orcid);

        /* @var \AppBundle\Connections\Repository $repository */
        $repository = $this->container->get('app.service.repository');
        $this->assertInstanceOf(\AppBundle\Connections\Repository::class, $repository);

        $this->assertTrue($repository->hasConnection('orcid'));

        $repository->removeConnection('orcid');
        $this->assertFalse($repository->hasConnection('orcid'));

        $this->assertTrue(is_array($repository->getAvailableConnections()));
        $this->assertTrue(empty($repository->getAvailableConnections()));

        $repository->addConnection($orcid);
        $this->assertTrue(is_array($repository->getAvailableConnections()));
        $this->assertFalse(empty($repository->getAvailableConnections()));
        $this->assertTrue($repository->hasConnection('orcid'));
    }
}

Add tests for checking the service repository.


<?php
/**
 * @file
 */

namespace CultuurNet\UDB3\Event\Events;

use CultuurNet\UDB3\Language;
use ValueObjects\String\String;

class TranslationDeletedTest extends \PHPUnit_Framework_TestCase
{
    public function serializationDataProvider()
    {
        return [
            'english' => [
                [
                    'event_id' => 'foo',
                    'language' => 'en'
                ],
                new TranslationDeleted(
                    new String('foo'),
                    new Language('en')
                ),
            ],
            'french' => [
                [
                    'event_id' => 'bar',
                    'language' => 'fr'
                ],
                new TranslationDeleted(
                    new String('bar'),
                    new Language('fr')
                ),
            ],
        ];
    }

    /**
     * @test
     * @dataProvider serializationDataProvider
     * @param array $expectedSerializedValue
     * @param TranslationDeleted $translationDeleted
     */
    public function it_can_be_serialized_into_an_array(
        $expectedSerializedValue,
        TranslationDeleted $translationDeleted
    ) {
        $this->assertEquals(
            $expectedSerializedValue,
            $translationDeleted->serialize()
        );
    }

    /**
     * @test
     * @dataProvider serializationDataProvider
     * @param array $serializedValue
     * @param TranslationDeleted $expectedTranslationDeleted
     */
    public function it_can_be_deserialized_from_an_array(
        $serializedValue,
        TranslationDeleted $expectedTranslationDeleted
    ) {
        $this->assertEquals(
            $expectedTranslationDeleted,
            TranslationDeleted::deserialize($serializedValue)
        );
    }
}

III-483: Add test for TranslationDeleted (de)serialization


<?php

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

class AddSiteNameToSettings extends Migration {

  /**
   * Run the migrations.
   *
   * @return void
   */
  public function up()
  {
    DB::table('settings')->insert([
      'key' => 'site_title',
      'value' => 'Voting App'
    ]);
  }

  /**
   * Reverse the migrations.
   *
   * @return void
   */
  public function down()
  {
    DB::table('settings')->delete(['key' => 'site_title']);
  }

}

Add default site name setting.

Add default site name setting.


<?php namespace System\Database\Migrations;

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

/**
 * customer_id can be NULL on addresses table
 */
class deleteUnusedColumnsFromActivitiesTable extends Migration
{
    public function up()
    {
        Schema::table('activities', function (Blueprint $table) {
            $table->dropColumn('domain');
            $table->dropColumn('context');
            $table->dropColumn('user');
            $table->dropColumn('action');
            $table->dropColumn('message');
            $table->dropColumn('status');

            $table->string('type')->nullable();
            $table->dateTime('read_at')->nullable();
            $table->softDeletes();
        });

        \System\Models\Activities_model::truncate();
    }

    public function down()
    {
        //
    }
}

Delete unused columns from activities table


<?php

namespace Omnipay\UnionPay\Tests;

use Omnipay\Tests\GatewayTestCase as Base;
use Omnipay\UnionPay\WtzGateway;

class GatewayTestCase extends Base
{

    /**
     * @var WtzGateway $gateway
     */
    protected $gateway;

    protected $options;

    protected function open($content)
    {
        $file = sprintf('./%s.html', md5(uniqid()));
        $fh   = fopen($file, 'w');
        fwrite($fh, $content);
        fclose($fh);

        exec(sprintf('open %s -a "/Applications/Google Chrome.app" && rm %s', $file, $file));
    }
}

Add open in browser util function

Add open in browser util function


<?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;
use Listabierta\Bundle\MunicipalesBundle\Validator\Constraints\DNI;

class TownStep6Type 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 'town_step_6';
    }
}

Add form for town step 6 type

Add form for town step 6 type


<?php
namespace VideoGamesRecords\CoreBundle\EventListener\Entity;

use Doctrine\ORM\Events;
use VideoGamesRecords\CoreBundle\Entity\Player;
use Doctrine\Common\EventSubscriber;
use Doctrine\ORM\Event\LoadClassMetadataEventArgs;

class DynamicRelationUser implements EventSubscriber
{
    /**
     * {@inheritDoc}
     */
    public function getSubscribedEvents()
    {
        return array(
            Events::loadClassMetadata,
        );
    }

    /**
     * @param LoadClassMetadataEventArgs $eventArgs
     */
    public function loadClassMetadata(LoadClassMetadataEventArgs $eventArgs)
    {
        // the $metadata is the whole mapping info for this class
        $metadata = $eventArgs->getClassMetadata();

        if ($metadata->getName() !== 'ProjetNormandie\UserBundle\Entity\User') {
            return;
        }

        $metadata->mapOneToOne(array(
            'targetEntity' => Player::class,
            'fieldName' => 'relation',
            'mappedBy' => 'user',
        ));
    }
}

Add dynamic relation from user to player


<?php

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

use App\Extractors\VehicleExtractorWrapper;

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

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

Add abstract vehicle extractor test

Add abstract vehicle extractor test


<?php

namespace Cerbero\ApiClient\Inflectors;

use BadMethodCallException;

/**
 * Trait to inflect resources.
 *
 * @author    Andrea Marco Sartori
 */
trait InflectsResources
{
    /**
     * The resource inflector.
     *
     * @author  Andrea Marco Sartori
     * @var     Cerbero\ApiClient\Inflectors\ResourceInflectorInterface
     */
    protected $inflector;

    /**
     * Set the resource inflector.
     *
     * @author    Andrea Marco Sartori
     * @param    Cerbero\ApiClient\Inflectors\ResourceInflectorInterface    $inflector
     * @return    $this
     */
    public function setInflector(ResourceInflectorInterface $inflector = null)
    {
        $this->inflector = $inflector ?: $this->defaultInflector();

        return $this;
    }

    /**
     * Retrieve the default inflector.
     *
     * @author    Andrea Marco Sartori
     * @return    Cerbero\ApiClient\Inflectors\ResourceInflectorInterface
     */
    protected function defaultInflector()
    {
        return new Psr4Inflector;
    }

    /**
     * Retrieve the resource to call by inflecting the given name.
     *
     * @author    Andrea Marco Sartori
     * @param    string    $name
     * @param    array    $arguments
     * @return    Cerbero\ApiClient\Resources\ResourceInterface
     */
    protected function inflectResource($name, array $arguments)
    {
        $resource = $this->inflector->namespace(get_called_class())
                                    ->version($this->version())
                                    ->inflect($name);

        if (class_exists($resource)) {
            return new $resource($arguments);
        }

        throw new BadMethodCallException("The resource [$resource] does not exist.");
    }
}

Create trait to inflect resources

Create trait to inflect resources


<?php

use Phinx\Migration\AbstractMigration;

class AddForeignKeyToMajorChangesAppearanceId extends AbstractMigration {
  public function change() {
    $this->table('major_changes')->addForeignKey('appearance_id', 'appearances', 'id', ['delete' => 'cascade', 'update' => 'cascade'])->update();
  }
}

Add foreign key to major_changes table appearance_id column


<?php
    namespace Library;

    class Validation
    {
        private $rule = array();

        public function __construct()
        {
            $this->addRule('username', '^[A-Za-z0-9_.]{5,16}$');
            $this->addRule('password', '^[A-Za-z0-9@#!$*&~;:,?_.-]{6,32}$');
            $this->addRule('email', '^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$');
        }

        public function addRule($name, $rule)
        {
            $this->rule[strtolower($name)] = $rule;
        }

        public function check($name, $subject)
        {
            if (!isset($this->rule[strtolower($name)]))
            {
                return false;
            }

            $regex = '/'.$this->rule[strtolower($name)].'/';
            return (bool)preg_match($regex, $subject);
        }

        public function username($subject)
        {
            return $this->check('username', $subject);
        }

        public function password($subject)
        {
            return $this->check('password', $subject);
        }

        public function email($subject)
        {
            return $this->check('email', $subject);
        }
    }

?>

Add validation class to validate string

Add validation class to validate string


<?php
header('Content-Type: application/json');
$dob = "8/17/1983";
$json = '{
    "person": {
        "age": {
            "years": 30,
            "months": 8,
            "weeks": 2,
            "days": 5,
            "hours": 2,
            "minutes": 39,
            "seconds": 59,
            "milliseconds": 927
        },
        "location": {
            "latitude": 41.8819,
            "longitude": -87.6278,
            "city": "Nevada",
            "state": "IA"
        },
        "languages": {
            "communication": ["English"],
            "programming": ["Javascript", "HTML", "CSS", "PHP"],
            "frameworks": ["WordPress", "Anchor", "LESS", "SASS", "jQuery", "PostgreSQL", "MariaDB", "MySQL"]
        }
    },
    "identifiers": {
        "image": "https://lh6.googleusercontent.com/-G_Cw2kSHK2w/UcwDnydyQyI/AAAAAAAAa4A/sQe4_fKbHf8/w320-h240-no/smh.gif",
        "home_url": "http://www.longren.org",
        "first_name": "Tyler",
        "last_name": "Longren",
        "externals": [{
            "name": "Twitter",
            "username": "tlongren",
            "html_url": "http://twitter.com/tlongren"
        }, {
            "name": "GitHub",
            "username": "tlongren",
            "html_url": "http://github.com/tlongren"
        }]
    },
    "blog": {
        "rss": "http://www.longren.org/feed/",
        "latest": [{
            "title": "Contributing To GitHub Projects is Easy",
            "url": "http://www.longren.org/contributing-to-github-projects-is-easy/",
            "date": "2013-12-13T04:15:28.513Z"
        }]
    },
    "_links": {
        "self": {
            "href": "/api"
        }
    }
}';

echo $json;
?>

Set some initial stuff up.

Set some initial stuff up.