<?php

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

class AddUniqueIndexToLanguageEntriesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        $model = new \Build\Core\Eloquent\Models\Language\Entry();
        $tableName = $model->getTable();

        // Delete entries that already have more then one entry
        DB::statement("delete FROM {$tableName}
            where {$tableName}.id in (
                select id from (
                    SELECT count(*) as counter, max(id) as id

                     FROM {$tableName}

                     group by language_id, dictionary_id

                     having counter > 1
                 ) as invalid_counters
             )");

        Schema::table('language_entries', function (Blueprint $table) {
           $table->unique(['language_id', 'dictionary_id'], 'language_entries_language_id_dictionary_id_unique');
        });
    }

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

Add migration to add unique index to language entries table


<?php namespace Mitch\LaravelDoctrine\Console;

use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Console\Input\InputOption;

class EnsureProductionSettingsCommand extends Command {

    protected $name = 'doctrine:ensure-production-settings';
    protected $description = 'Verify that Doctrine is properly configured for a production environment.';

    public function fire() {
        $entityManager = $this->laravel->make('Doctrine\ORM\EntityManagerInterface');
        try {
            $entityManager->getConfiguration()->ensureProductionSettings();
            if ($this->option('complete'))
                $entityManager->getConnection()->connect();
        } catch (\Exception $e) {
            $this->error($e->getMessage());
            return 1;
        }
        $this->info('Environment is correctly configured for production.');
    }

    protected function getOptions() {
        return [
            ['complete', null, InputOption::VALUE_NONE, 'Also inspect database connection existence.'],
        ];
    }
}

Add Ensure Production Settings command

Add Ensure Production Settings command


<?php
    include ("conectare_db.php");
    $sql = 'begin :rezultat :=  admin_pachet.update_intrebare(:v_id,:v_domeniu,:v_text,:v_dificultate,:v_tip,:v_r1,:v_r2,:v_r3,:v_rc);END;';
    $stid = oci_parse($connection, $sql);
    oci_bind_by_name($stid, ":v_id", $_POST["q_id"]);
    oci_bind_by_name($stid, ":v_domeniu", $_POST["domeniu"]);
    oci_bind_by_name($stid, ":v_text", $_POST["text"]);
    oci_bind_by_name($stid, ":v_dificultate", $_POST["dificultate"]);
    oci_bind_by_name($stid, ":v_tip", $_POST["tip_intrebare"]);
    oci_bind_by_name($stid, ":v_r1", $_POST["r_1"]);
    oci_bind_by_name($stid, ":v_r2", $_POST["r_2"]);
    oci_bind_by_name($stid, ":v_r3", $_POST["r_3"]);
    oci_bind_by_name($stid, ":v_rc", $_POST["r_c"]);
    oci_bind_by_name($stid, ':rezultat', $rezultat, 100);
    if(!oci_execute($stid))
    {
        $e = oci_error($stid);
        echo "Something went wrong :( <br/>";
        echo "Error: " . $e['message'];
    }
    oci_free_statement($stid);
    oci_close($connection);
    echo $rezultat;
?>

Add update question PHP module

Add update question PHP module


<?php

$aFilesDelete = array(
    'modules/base/text/template/account_link.html',
    'plugins/stripe/lib/Error',
    'plugins/stripe/lib/Util/AutoPagingIterator.php',
    'plugins/stripe/lib/FileUpload.php',
    'plugins/stripe/lib/IssuerFraudRecord.php',
    'plugins/stripe/.coveralls.yml',
    'plugins/stripe/.travis.yml',
    'plugins/stripe/phpunit.no_autoload.xml',
    'plugins/stripe/phpunit.xml',
    'studio/js/designs.js',
    'studio/js/languages.js',
    'studio/js/modules.js',
    'studio/template/css/designs.css',
    'studio/template/css/languages.css',
    'studio/template/css/modules.css',
    'studio/template/images/bx-std-bg-columns.png',
    'studio/template/dsn_js.html',
    'studio/template/lang_js.html',
    'studio/template/mod_action_result.html',
    'studio/template/mod_confirm.html',
    'studio/template/mod_js.html',
    'studio/languages.php',
    'studio/modules.php',
    'studio/templates.php',
    'template/images/icons/favicon.png',
    'template/form_field_location.html',
    'template/metatags_locations_map.html',
);

Upgrade script from 11.0.4 to 12.0.0-B1

Upgrade script from 11.0.4 to 12.0.0-B1


<?php
namespace nochso\Omni\Test;

use nochso\Omni\Exec;

class ExecTest extends \PHPUnit_Framework_TestCase
{
    public function testCreate_NoPrefix()
    {
        $runner = Exec::create();
        $this->assertSame(Exec::class, get_class($runner));
    }

    public function testGetCommand()
    {
        $runner = Exec::create();
        $this->assertSame('', $runner->getCommand());
        $this->assertSame("'foo'", $runner->getCommand('foo'));
    }

    public function testRun()
    {
        $runner = Exec::create('echo');
        $runner->run('test');
        $this->assertSame(['test'], $runner->getOutput());
        $this->assertSame(0, $runner->getStatus());
    }

    public function testRun_MultiplePrefixes()
    {
        $runner = Exec::create('echo', 'test');
        $runner->run();
        $this->assertSame(['test'], $runner->getOutput());
    }

    public function testCreate_SplatVariadic()
    {
        $runner = Exec::create(...['echo', 'test']);
        $runner->run();
        $this->assertSame(['test'], $runner->getOutput());
    }

    public function testRun_SplatVariadic()
    {
        $runner = Exec::create();
        $runner->run(...['echo', 'test']);
        $this->assertSame(['test'], $runner->getOutput());
    }

    public function testInvoke()
    {
        $runner = Exec::create('echo');
        $runner('test');
        $this->assertSame(['test'], $runner->getOutput());
        $this->assertSame(0, $runner->getStatus());
    }

    public function testInvoke_SplatVariadic()
    {
        $runner = Exec::create();
        $runner(...['echo', 'test']);
        $this->assertSame(['test'], $runner->getOutput());
    }

    public function testFluentInvoke()
    {
        $runner = Exec::create('echo');
        $this->assertSame(['test'], $runner('test')->getOutput());
    }

    public function testAllArgumentsAreEscaped()
    {
        $runner = Exec::create('escape me"!');
        $cmd = $runner->getCommand("needs more escaping' '\"");
        $this->assertSame("'escape me\"!' 'needs more escaping'\\'' '\\''\"'", $cmd);
    }
}

Add tests for new class Exec

test: Add tests for new class Exec


<?php
use \ParagonIE\Halite\Key;

/**
 * @backupGlobals disabled
 * @backupStaticAttributes disabled
 */
class KeyTest extends PHPUnit_Framework_TestCase
{
    public function testDerive()
    {
        $key = Key::deriveFromPassword(
            'apple',
            "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f".
            "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f"
        );
        $this->assertEquals(
            $key->get(),
            "\x36\xa6\xc2\xb9\x6a\x65\x0d\x80\xbf\x7e\x02\x5e\x0f\x58\xf3\xd6".
            "\x36\x33\x95\x75\xde\xfb\x37\x08\x01\xa5\x42\x13\xbd\x54\x58\x2d"
        );
    }

}

Add test case for Key::deriveFromPassword


<?php

namespace Listabierta\Bundle\MunicipalesBundle\Form\Type;

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

class TownStep3Type extends AbstractType
{
	public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
			     ->add('job_experience', 'choice', array(
			     		'multiple' => TRUE,
			     		'expanded' => TRUE,
			     		'choices' => array(
			     				'0' => 'No considero importante su experiencia laboral previa', // (no aparece el resto de opciones)
			     				'1' => 'Actividades físicas o deportivas',
			     				'2' => 'Administración o gestión',
			     				'3' => 'Agraria o pesquera',
			     				'4' => 'Arte o artesanía',
			     				'5' => 'Comercio y marketing',
			     				'6' => 'Edificación, obra civil',
			     				'7' => 'Energía o agua',
			     				'8' => 'Mecánica, electricidad o electrónica',
			     				'9' => 'Hostelería y turismo',
			     				'10' => 'Informática o comunicaciones',
			     				'11' => 'Industria',
			     				'12' => 'Sanidad',
			     				'13' => 'Medio Ambiente',
			     				'14' => 'Educación o servicios a la comunidad',
			     				'15' => 'Transporte',
			     				'16' => 'Finanzas',
			     		),
			     		'data_class' => NULL,
			     		'constraints' => array(
			     				new Assert\Count(array(
						            'max'        => 3,
						            'minMessage' => 'You must specify at least one email',
						            'maxMessage' => 'Sólo puedes seleccionar hasta {{ limit }} opciones como máximo',
						        ))
			     		)
			     ))
	            ->add('continue', 'submit', array('attr' => array('class' => 'submit')));
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
    }

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

Add town step 3 type form

Add town step 3 type form


<?php defined('SYSPATH') or die('No direct script access.');
/**
 * Sitemap generation class
 *
 * Copyright (C) 2009 Mathew Leigh Davies
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
 *
 * @author Mathew Leigh Davies <thepixeldeveloper@googlemail.com>
 */

/**
 * Tests Sitemap_Data
 *
 * @package Unittest
 * @author  Mathew Davies
 */
class Sitemap_DataTest extends PHPUnit_Framework_TestCase
{
	/**
	 * @return array Test data for test_encode.
	 */
	public function provider_encode()
	{
		return array
		(
			array(),
			array()
		);
	}
	/**
	 * @test
	 * @group sitemap
	 * @dataProvider provider_encode
	 */
	public function test_encode($timestamp, $expected)
	{
		$instance = new Sitemap_Data;
		$return = $instance->encode($timestamp);
		$this->assertSame($return, $expected);
	}

	/**
	 * @return array Test data for test_date_format.
	 */
	public function provider_date_format()
	{
		return array
		(
			array(),
			array()
		);
	}
	/**
	 * @test
	 * @group sitemap
	 * @dataProvider provider_date_format
	 */
	public function test_date_format($date, $expected)
	{
		$instance = new Sitemap_Data;
		$return = $instance->date_format($timestamp);
		$this->assertSame($return, $expected);
	}
}

Add skeleton test for the Sitemap_Data class.


<?PHP

include("class.krumo.php");

$fp = fopen(__FILE__,"r");

$a = array(
	'first'     => $fp,
	'last'      => new bar,
	'null_var'  => NULL,
	'float'     => pi(),
	'bool'      => true,
	'phones'    => array(5036541278,8714077831,'x253'),
	'long_str'  => "This is a really long string full of a\n bunch of crap that should eventually wrap. There once was a man from New Mexico...",
	'empty_arr' => array(),
	'func_str'  => 'preg_replace',
	'address'   => array('street' => '123 Fake Street', 'city' => 'Portland', 'state' => 'Maine'),
);

print "
krumo capture
\n";
$str = k(array('foo' => 'bar'),KRUMO_CAPTURE);
print $str;

print "
krumo
\n";
k(array('likes','kittens','and','dogs'));

print "
krumo passing multiple args
\n";
k('likes','kittens','and','dogs');

print "
krumo + die()
\n";
kd($a);
print "If you see this something is broken";

$k = new krumo;

class bar {
		public $b = 'bb';
		public $a = 'aa';

		function foo() {
			return 'bar';
		}
}

?>

Add a simple test suite

Add a simple test suite


<?php

namespace spec\FluxBB\Core;

use Illuminate\Contracts\Events\Dispatcher;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
use FluxBB\Core\Action;

class ActionSpec extends ObjectBehavior
{
    function let()
    {
        $this->beAnInstanceOf('spec\FluxBB\Core\ConcreteAction');
    }

    function it_can_raise_events(Dispatcher $dispatcher)
    {
        $this->beAnInstanceOf('spec\FluxBB\Core\EventAction');

        $dispatcher->fire('stdClass', [new \stdClass()])->shouldBeCalled();

        $this->setEvents($dispatcher);
        $this->execute();
    }
}

class ConcreteAction extends Action
{
    protected function run()
    {
        //
    }
}

class EventAction extends Action
{
    protected function run()
    {
        $this->raise(new \stdClass());
    }
}

Add tiny PhpSpec test for Action class.

Add tiny PhpSpec test for Action class.


<?php

	include '../index.php';

	class InitTest extends PHPUnit_Framework_TestCase
	{

		public function test_smooth_vars()
		{
			$this->assertTrue(defined('BASEPATH'));
			$this->assertTrue(defined('APPPATH'));
			$this->assertTrue(defined('SYSPATH'));
			$this->assertTrue(defined('WEBPATH'));
			$this->assertTrue(defined('CONTROLLER'));
			$this->assertTrue(defined('SMOOTH_V'));
			$this->assertTrue(isset($_SERVER['REQUEST_URI']));
		}

	}

Add the Init phpunit test

Add the Init phpunit test


<?php
namespace inklabs\kommerce\Entity;

class OrderAddressTest extends \PHPUnit_Framework_TestCase
{
    public function testCreate()
    {
        $orderAddress = new OrderAddress;
        $orderAddress->firstName = 'John';
        $orderAddress->lastName = 'Doe';
        $orderAddress->company = 'Acme Co.';
        $orderAddress->address1 = '123 Any St';
        $orderAddress->address2 = 'Ste 3';
        $orderAddress->city = 'Santa Monica';
        $orderAddress->state = 'CA';
        $orderAddress->zip5 = '90401';
        $orderAddress->zip4 = '3274';
        $orderAddress->phone = '555-123-4567';
        $orderAddress->email = 'john@example.com';

        $this->assertInstanceOf('inklabs\kommerce\Entity\OrderAddress', $orderAddress);
    }
}

Reorganize for 100% for OrderAddress.

Reorganize for 100% for OrderAddress.


<?php

namespace Http\React\Tests;

use Http\Client\Tests\HttpAsyncClientTest;
use Http\React\ReactHttpClient;

/**
 * @author Stéphane Hulard <s.hulard@gmail.com>
 */
class ReactHttpAsyncClientTest extends HttpAsyncClientTest
{
    /**
     * @return HttpClient
     */
    protected function createHttpAsyncClient()
    {
        $loop = \React\EventLoop\Factory::create();
        $dnsResolverFactory = new \React\Dns\Resolver\Factory();
        $dnsResolver = $dnsResolverFactory->createCached('8.8.8.8', $loop);
        $messageFactory = new \Http\Discovery\MessageFactory\GuzzleFactory();

        return new ReactHttpClient(
            $loop,
            $dnsResolver,
            $messageFactory
        );
    }
}

Add Async client test suite

Add Async client test suite


<?php

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

class MakeOrderDefaultNullOnHelpVideoTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        DB::statement("ALTER TABLE `help_videos` MODIFY `order` int(10) unsigned DEFAULT 0;");
        // Schema::table('help_videos', function (Blueprint $table) {
        //     $table->integer('order')->unsigned()->nullable()->default(0)->change();
        // });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        DB::statement("ALTER TABLE `help_videos` MODIFY `order` int(10) unsigned NOT NULL;");
        // Schema::table('help_videos', function (Blueprint $table) {
        //     $table->integer('order')->unsigned()->change();
        // });
    }
}

Allow null help_videos.order to fix sqlite errors


<?php

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

class AddTotalPointsToSnapshots extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		Schema::table('sprint_snapshots', function($t)
		{
			$t->integer('total_points');
		});
	}

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

}

Add migration for total points on snapshots.


<?php

namespace Tests\Regis\BitbucketContext\Application\EventListener;

use PHPUnit\Framework\TestCase;
use League\Tactician\CommandBus;
use Regis\BitbucketContext\Application\Command;
use Regis\BitbucketContext\Application\Event;
use Regis\BitbucketContext\Application\EventListener\PullRequestListener;
use Regis\BitbucketContext\Domain\Model\PullRequest;
use Regis\Kernel\Event\DomainEventWrapper;

class PullRequestListenerTest extends TestCase
{
    private $bus;
    private $violationsCache;
    private $listener;

    public function setUp()
    {
        $this->bus = $this->createMock(CommandBus::class);

        $this->listener = new PullRequestListener($this->bus);
    }

    public function testItListensToTheRightEvents()
    {
        $listenedEvents = PullRequestListener::getSubscribedEvents();

        $this->assertArrayHasKey(Event\PullRequestOpened::class, $listenedEvents);
        $this->assertArrayHasKey(Event\PullRequestUpdated::class, $listenedEvents);
    }

    public function testItSendsTheRightCommandToTheBusWhenAPRIsOpened()
    {
        $pr = $this->createMock(PullRequest::class);
        $event = new DomainEventWrapper(new Event\PullRequestOpened($pr));

        $this->bus->expects($this->once())
            ->method('handle')
            ->with($this->isInstanceOf(Command\Inspection\SchedulePullRequest::class));

        $this->listener->onPullRequestUpdated($event);
    }

    public function testItSendsTheRightCommandToTheBusWhenAPRIsUpdated()
    {
        $pr = $this->createMock(PullRequest::class);
        $event = new DomainEventWrapper(new Event\PullRequestUpdated($pr, 'before', 'after'));

        $this->bus->expects($this->once())
            ->method('handle')
            ->with($this->isInstanceOf(Command\Inspection\SchedulePullRequest::class));

        $this->listener->onPullRequestUpdated($event);
    }
}

Test the pull request listener

Test the pull request listener


<?php

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

class PhpdebugbarTableChangeMetaUriToText extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('phpdebugbar', function (Blueprint $table) {
            $table->renameColumn('meta_uri', 'meta_uri_old');
        });
        Schema::table('phpdebugbar', function (Blueprint $table) {
            $table->text('meta_uri');
        });

        // Copy existing data over
        DB::table('phpdebugbar')
            ->update([
                'meta_uri' => DB::raw('`meta_uri_old`'),
            ]);

        // Drop old column
        Schema::table('phpdebugbar', function (Blueprint $table) {
            $table->dropColumn('meta_uri_old');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('phpdebugbar', function (Blueprint $table) {
            $table->renameColumn('meta_uri', 'meta_uri_old');
        });
        Schema::table('phpdebugbar', function (Blueprint $table) {
            $table->text('meta_uri');
        });

        // Copy existing data over
        DB::table('phpdebugbar')
            ->update([
                'meta_uri' => DB::raw('`meta_uri_old`'),
            ]);

        // Drop old column
        Schema::table('phpdebugbar', function (Blueprint $table) {
            $table->dropColumn('meta_uri_old');
        });
    }
}

Fix truncated meta_uri in phpdebugbar

Fix truncated meta_uri in phpdebugbar


<?php

namespace Surfnet\StepupMiddleware\Migrations;

use Doctrine\DBAL\Migrations\AbstractMigration;
use Doctrine\DBAL\Schema\Schema;

/**
 * Auto-generated Migration: Please modify to your needs!
 */
class Version20160728074605 extends AbstractMigration
{
    /**
     * @param Schema $schema
     */
    public function up(Schema $schema)
    {
        // this up() migration is auto-generated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on \'mysql\'.');

        $this->addSql('CREATE TABLE institution_configuration_options (institution VARCHAR(255) NOT NULL, use_ra_locations_option TINYINT(1) NOT NULL, show_raa_contact_information_option TINYINT(1) NOT NULL, PRIMARY KEY(institution)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB');
    }

    /**
     * @param Schema $schema
     */
    public function down(Schema $schema)
    {
        // this down() migration is auto-generated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on \'mysql\'.');

        $this->addSql('DROP TABLE institution_configuration_options');
    }
}

Add migration for institution configuration options


<?php

/**
 * Copyright 2016 SURFnet B.V.
 *
 * 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 OpenConext\EngineBlockApiClientBundle\Service;

use OpenConext\EngineBlockApiClientBundle\Http\JsonApiClient;
use OpenConext\Profile\Value\Consent;
use OpenConext\Profile\Value\ConsentList;
use OpenConext\Profile\Value\SpecifiedConsent;
use OpenConext\Profile\Value\SpecifiedConsentList;
use OpenConext\ProfileBundle\Attribute\AttributeSetWithFallbacks;
use Surfnet\SamlBundle\SAML2\Attribute\Attribute;
use Surfnet\SamlBundle\SAML2\Attribute\AttributeSetInterface;

final class AttributeReleasePolicyService
{
    /**
     * @var JsonApiClient
     */
    private $jsonApiClient;

    public function __construct(JsonApiClient $jsonApiClient)
    {
        $this->jsonApiClient = $jsonApiClient;
    }

    /**
     * @param ConsentList $consentList
     * @param AttributeSetInterface $attributeSet
     * @return SpecifiedConsentList
     */
    public function applyAttributeReleasePolicies(ConsentList $consentList, AttributeSetInterface $attributeSet)
    {
        $entityIds = $consentList->map(function (Consent $consent) {
            return $consent->getServiceProvider()->getEntity()->getEntityId()->getEntityId();
        });

        $mappedAttributes = [];
        $definitions = [];
        foreach ($attributeSet as $attribute) {
            $name = $attribute->getAttributeDefinition()->getUrnMace();

            if ($name === null) {
                $name = $attribute->getAttributeDefinition()->getUrnOid();
            }

            $mappedAttributes[$name] = $attribute->getValue();
            $definitions[$name] = $attribute->getAttributeDefinition();
        }

        $response = $this->jsonApiClient->post('/arp', [
            'entityIds'  => $entityIds,
            'attributes' => $mappedAttributes
        ]);

        return SpecifiedConsentList::createWith(
            $consentList->map(
                function (Consent $consent) use ($response, $definitions) {
                    $entityId = $consent->getServiceProvider()->getEntity()->getEntityId()->getEntityId();

                    $attributes = [];
                    foreach ($response[$entityId] as $attributeName => $attributeValue) {
                        $attributes[] = new Attribute($definitions[$attributeName], $attributeValue);
                    }

                    return SpecifiedConsent::specifies($consent, AttributeSetWithFallbacks::create($attributes));
                }
            )
        );
    }
}

Add ARP service that connects to EB through JSON API

We might want to reconsider how we are retrieving a ConsentList and turning it into SpecifiedConstentList.


<?php

if ($_GET["password"] != "hunter2") die("Access denied.");

# direct call
#system("/home/florin/bin/bootIt/wakeIt.sh");

# remote call
system("ssh netpiExt /home/florin/bin/bootIt/wakeIt.sh");
?>

Add php script for calling bash script

Add php script for calling bash script


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

use Mandragora\FormFactory;
use PHPUnit_Framework_TestCase as TestCase;

class SearchTest extends TestCase
{
    /** @test */
    function it_can_be_created()
    {
        $this->assertInstanceOf(Search::class, $this->searchForm);
        $this->assertCount(2, $this->searchForm->getElements());
    }

    /** @before */
    function createForm()
    {
        $this->searchForm = (new FormFactory(true))->create('Search', 'Property');
    }

    /** @var Search */
    private $searchForm;
}

Add tests for the search form.

Add tests for the search form.


<?php declare(strict_types=1);

namespace hollodotme\Readis\Application\ReadModel\KeyDataBuilders;

use hollodotme\Readis\Application\Interfaces\ProvidesKeyInfo;
use hollodotme\Readis\Application\ReadModel\Interfaces\BuildsKeyData;
use hollodotme\Readis\Application\ReadModel\Interfaces\ProvidesKeyData;
use hollodotme\Readis\Application\ReadModel\Interfaces\ProvidesKeyName;
use hollodotme\Readis\Exceptions\KeyTypeNotImplemented;
use function array_merge;

final class KeyDataBuilder implements BuildsKeyData
{
	/** @var array|BuildsKeyData[] */
	private $builders;

	public function __construct( BuildsKeyData $builder, BuildsKeyData ...$builders )
	{
		$this->builders = array_merge( [$builder], $builders );
	}

	public function canBuildKeyData( ProvidesKeyInfo $keyInfo, ProvidesKeyName $keyName ) : bool
	{
		return true;
	}

	/**
	 * @param ProvidesKeyInfo $keyInfo
	 * @param ProvidesKeyName $keyName
	 *
	 * @throws KeyTypeNotImplemented
	 * @return ProvidesKeyData
	 */
	public function buildKeyData( ProvidesKeyInfo $keyInfo, ProvidesKeyName $keyName ) : ProvidesKeyData
	{
		foreach ( $this->builders as $builder )
		{
			if ( $builder->canBuildKeyData( $keyInfo, $keyName ) )
			{
				return $builder->buildKeyData( $keyInfo, $keyName );
			}
		}

		throw new KeyTypeNotImplemented( 'Key type not implemented or supported: ' . $keyInfo->getType() );
	}
}

Add composite key data builder

Add composite key data builder


<?php
    /*********************************************************************************
     * Zurmo is a customer relationship management program developed by
     * Zurmo, Inc. Copyright (C) 2014 Zurmo Inc.
     *
     * Zurmo is free software; you can redistribute it and/or modify it under
     * the terms of the GNU Affero General Public License version 3 as published by the
     * Free Software Foundation with the addition of the following permission added
     * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
     * IN WHICH THE COPYRIGHT IS OWNED BY ZURMO, ZURMO DISCLAIMS THE WARRANTY
     * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
     *
     * Zurmo 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 or write to the Free
     * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
     * 02110-1301 USA.
     *
     * You can contact Zurmo, Inc. with a mailing address at 27 North Wacker Drive
     * Suite 370 Chicago, IL 60606. or at email address contact@zurmo.com.
     *
     * The interactive user interfaces in original and modified versions
     * of this program must display Appropriate Legal Notices, as required under
     * Section 5 of the GNU Affero General Public License version 3.
     *
     * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
     * these Appropriate Legal Notices must retain the display of the Zurmo
     * logo and Zurmo copyright notice. If the display of the logo is not reasonably
     * feasible for technical reasons, the Appropriate Legal Notices must display the words
     * "Copyright Zurmo Inc. 2014. All rights reserved".
     ********************************************************************************/

    class UniqueIdentifierRedBeanModelAttributeValueToExportValueAdapter extends RedBeanModelAttributeValueToExportValueAdapter
    {
    }
?>

Fix for unique identifier export

Fix for unique identifier export

--HG--
rename : app/protected/modules/export/adapters/TextRedBeanModelAttributeValueToExportValueAdapter.php => app/protected/modules/export/adapters/UniqueIdentifierRedBeanModelAttributeValueToExportValueAdapter.php


<?php

namespace Oro\Bundle\UserBundle\Migrations\Schema\v1_24;

use Doctrine\DBAL\Schema\Schema;

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

class AddDisableLogin implements Migration
{
    /**
     * {@inheritdoc}
     */
    public function up(Schema $schema, QueryBag $queries)
    {
        $table = $schema->getTable('oro_user');
        $table->dropColumn('login_disabled');
    }
}

BB-6037: Fix migration issue related to upgrade from beta5 to master
- migration to remove unused login_disabled field


<?php

namespace SlackPHP\SlackAPI\Main;

use PHPUnit\Framework\TestCase;
use SlackPHP\SlackAPI\Main\SlackAPI;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use GuzzleHttp\ClientInterface;

/**
 * @author Dzianis Zhaunerchyk <dzhaunerchyk@gmail.com>
 * @covers SlackAPI
 */
class SlackAPITest extends TestCase
{
    private $dummyString = 'String';

    public function testConstruct()
    {
        $slackAPIObject = new SlackAPI($this->dummyString);
        $refSlackAPIObject = new \ReflectionObject($slackAPIObject);
        $tokenProperty = $refSlackAPIObject->getProperty('token');
        $tokenProperty->setAccessible(true);
        $clientProperty = $refSlackAPIObject->getProperty('client');
        $clientProperty->setAccessible(true);
        $eventDispatcherProperty = $refSlackAPIObject->getProperty('eventDispatcher');
        $eventDispatcherProperty->setAccessible(true);

        $this->assertEquals($this->dummyString, $tokenProperty->getValue($slackAPIObject));
        $this->assertInstanceOf(ClientInterface::class, $clientProperty->getValue($slackAPIObject));
        $this->assertInstanceOf(EventDispatcherInterface::class, $eventDispatcherProperty->getValue($slackAPIObject));
    }
}

Test for construct of SlackAPI

Test for construct of SlackAPI


<?php

/**
 * Class definition for DTS_Cookie.
 *
 * @package     DTS
 * @author      Eric Bollens
 * @copyright   Copyright (c) 2012 UC Regents
 * @license     BSD
 * @version     20120201
 */

/**
 * A static class that provides access to DTS cookies by name (excluding the DTS
 * cookie prefix). These are set by the DTS Javascript when on the SP domain.
 *
 * @package     DTS
 */
class DTS_Cookie
{
    /**
     * The prefix of all DTS cookies.
     *
     * This value should NOT be changed unless the value in dts.server is
     * also changed.
     *
     * @var string
     */
    const PREFIX = 'd_';

    /**
     * Recursive version of stripslashes for a deep operation through array.
     *
     * @param string|array $value
     * @return type
     */
    protected static function stripslashes_deep($value)
    {
        return is_array($value) ? array_map('stripslashes_deep', $value) : stripslashes($value);
    }

    /**
     * Get the value of the cookie by $name, excluding the DTS prefix value,
     * which will be automaticlaly prepended.
     *
     * @param string $name
     * @return string
     */
    public static function get($name)
    {
        $name = get_magic_quotes_gpc() ? addslashes(self::PREFIX.$name) : self::PREFIX.$name;

        if(!isset($_COOKIE[$name]))
            return null;

        return get_magic_quotes_gpc() ? self::stripslashes_deep($_COOKIE[$name]) : $_COOKIE[$name];
    }

    /**
     * Set the value of a cookie by $name, excluding the DTS prefix, which will
     * be automatically prepended.
     *
     * @param string $name
     * @param string $value
     * @param int $expire
     * @param string $path
     * @return boolean
     */
    public static function set($name, $value, $expire=0, $path='/')
    {
        return setcookie(self::PREFIX.$name, $value, $expire, $path);
    }

    /**
     * Get an array of all cookie names with the DTS prefix.
     *
     * @return array
     */
    public static function get_all_names()
    {
        $rv = array();
        foreach(array_keys($_COOKIE) as $name)
        {
            if(strpos($name,self::PREFIX)===0)
            {
                $rv[] = substr($name, strlen(self::PREFIX), strlen($name));
            }
        }
        return $rv;
    }
}

Add DTS_Cookie server-side cookie accessor.


<?php

/**
 * Provides support for the conversion of moodle1 backup to the moodle2 format
 *
 * @package    block_html
 * @copyright  2012 Paul Nicholls
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */

defined('MOODLE_INTERNAL') || die();

/**
 * Block conversion handler for html
 */
class moodle1_block_html_handler extends moodle1_block_handler {
    private $fileman = null;
    protected function convert_configdata(array $olddata) {
        $instanceid = $olddata['id'];
        $contextid  = $this->converter->get_contextid(CONTEXT_BLOCK, $olddata['id']);
        $configdata = unserialize(base64_decode($olddata['configdata']));

        // get a fresh new file manager for this instance
        $this->fileman = $this->converter->get_file_manager($contextid, 'block_html');

        // convert course files embedded in the block content
        $this->fileman->filearea = 'content';
        $this->fileman->itemid   = 0;
        $configdata->text = moodle1_converter::migrate_referenced_files($configdata->text, $this->fileman);
        $configdata->format = FORMAT_HTML;

        return base64_encode(serialize($configdata));
    }

    protected function write_inforef_xml($newdata, $data) {
        $this->open_xml_writer("course/blocks/{$data['name']}_{$data['id']}/inforef.xml");
        $this->xmlwriter->begin_tag('inforef');
        $this->xmlwriter->begin_tag('fileref');
        foreach ($this->fileman->get_fileids() as $fileid) {
            $this->write_xml('file', array('id' => $fileid));
        }
        $this->xmlwriter->end_tag('fileref');
        $this->xmlwriter->end_tag('inforef');
        $this->close_xml_writer();
    }
}

MDL-32880: Add moodle1 backup converter for html block.

This converter processes the HTML block's content, migrating any referenced files.


<?php

namespace Oro\Bundle\UserBundle\Tests\Unit\DependencyInjection\Compiler;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;

use Oro\Bundle\UserBundle\DependencyInjection\Compiler\PrivilegeCategoryPass;

class PrivilegeCategoryPassTest extends \PHPUnit_Framework_TestCase
{
    /** @var PrivilegeCategoryPass */
    protected $compilerPass;

    /** @var \PHPUnit_Framework_MockObject_MockObject|ContainerBuilder */
    protected $container;

    protected function setUp()
    {
        $this->container = $this
            ->getMockBuilder('Symfony\Component\DependencyInjection\ContainerBuilder')
            ->getMock();

        $this->compilerPass = new PrivilegeCategoryPass();
    }

    protected function tearDown()
    {
        unset($this->container, $this->compilerPass);
    }

    public function testServiceNotExists()
    {
        $this->container->expects($this->once())
            ->method('hasDefinition')
            ->with($this->equalTo(PrivilegeCategoryPass::REGISTRY_SERVICE))
            ->will($this->returnValue(false));

        $this->container->expects($this->never())
            ->method('getDefinition');

        $this->container->expects($this->never())
            ->method('findTaggedServiceIds');

        $this->compilerPass->process($this->container);
    }

    public function testServiceExistsNotTaggedServices()
    {
        $this->container->expects($this->once())
            ->method('hasDefinition')
            ->with($this->equalTo(PrivilegeCategoryPass::REGISTRY_SERVICE))
            ->will($this->returnValue(true));

        $this->container->expects($this->once())
            ->method('findTaggedServiceIds')
            ->with($this->equalTo(PrivilegeCategoryPass::TAG))
            ->will($this->returnValue([]));

        $this->container->expects($this->never())
            ->method('getDefinition');

        $this->compilerPass->process($this->container);
    }

    public function testServiceExistsWithTaggedServices()
    {
        $this->container->expects($this->once())
            ->method('hasDefinition')
            ->with($this->equalTo(PrivilegeCategoryPass::REGISTRY_SERVICE))
            ->will($this->returnValue(true));

        $definition = $this->getMock('Symfony\Component\DependencyInjection\Definition');

        $this->container->expects($this->once())
            ->method('getDefinition')
            ->with($this->equalTo(PrivilegeCategoryPass::REGISTRY_SERVICE))
            ->will($this->returnValue($definition));

        $taggedServices = [
            'service.name.1' => [[]],
            'service.name.2' => [[]],
        ];

        $definition
            ->expects($this->exactly(2))
            ->method('addMethodCall')
            ->withConsecutive(
                ['addProvider', [new Reference('service.name.1')]],
                ['addProvider', [new Reference('service.name.2')]]
            );

        $this->container->expects($this->once())
            ->method('findTaggedServiceIds')
            ->with($this->equalTo(PrivilegeCategoryPass::TAG))
            ->will($this->returnValue($taggedServices));

        $this->compilerPass->process($this->container);
    }
}

BAP-10749: Develop data-collection provider for Permissions and Capabilities


<?php

if (isset($_POST["lure"])) {

  $statement = "

    UPDATE " . DB_PREF . "extension_truncate
    SET lure = ?
    WHERE 1 = 1
  ";

  $query = $Database->getHandle()->prepare($statement);

  // Prevent SQL injections.
  $query->bindParam(1, $_POST["lure"]);

  $query->execute();

  if (!$query) {

    // Failed to update lure text.
    header("Location: ./edit_extension.php?title=" . $_GET["title"] . "&result=failure");
  }
  else {

    // Successfully updated lure text.
    header("Location: ./edit_extension.php?title=" . $_GET["title"] . "&result=success");
  }
}
else {

  if (isset($_GET["result"])) {

    if ($_GET["result"] == "failure") {

      echo "Failed to update lure text.";
    }
    else {

      echo "Lure text has been updated.";
    }

    echo "Return";
  }
  else {

    $statement = "

      SELECT lure
      FROM " . DB_PREF . "extension_truncate
      WHERE 1 = 1
    ";

    $query = $Database->getHandle()->query($statement);

    if (!$query || $query->rowCount() == 0) {

      // Query failed or is empty.

      echo "Error: failed to get lure text!";

      echo "Return";
    }
    else {

      // Fetch the result as an object.
      $result = $query->fetch(PDO::FETCH_OBJ);

      // Get lure text.
      $lure = $result->lure;

      echo "

        <form method=\"post\" class=\"edit_lure\">
          Lure Text
          <input type=\"text\" id=\"lure\" name=\"lure\" value=\"{$lure}\"
          required>
          <input type=\"submit\" value=\"Save\">
        </form>
      ";
    }
  }
}

?>

Edit lure text from admin panel

Edit lure text from admin panel


<?php

namespace Listabierta\Bundle\MunicipalesBundle\Form\Type;

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

class CandidacyStep1Type extends AbstractType
{
	public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('name', 'text', array('required' => true))
        	    ->add('lastname', 'text', array('required' => true))
        	    ->add('dni', 'text', array('required' => true))
        	    ->add('email', 'email', array('required' => true))
        	    ->add('province', 'text', array('required' => true))
        	    ->add('town', 'text', array('required' => true))
        	    ->add('phone', 'text', array('required' => true))
	            ->add('continue', 'submit', array('attr' => array('class' => 'submit')));
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
    }

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

Implement candidacy step 1 type form

Implement candidacy step 1 type form


<?php

namespace Laratrust\Tests\Models;

use Illuminate\Database\Eloquent\Model;
use Laratrust\Traits\LaratrustUserTrait;
use Illuminate\Database\Eloquent\SoftDeletes;

class Other extends Model
{
    use LaratrustUserTrait;
    use SoftDeletes;

    protected $guarded = [];
}

Add new model called other

Add new model called other


<?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');

if($_GET['token'] && $_GET['webservice_url']) {
	$token = $_GET['token'];
	$webservice_url = $_GET['webservice_url'];
	$sig = md5('api_key' . $lastfm_key . 'methodauth.getSession' . 'token' . $token  . $lastfm_secret);
	$xmlresponse = simplexml_load_file($webservice_url . '?method=auth.getSession&token=' . $token . '&api_key=' . $lastfm_key . '&api_sig=' . $sig);
	print_r($xmlresponse);
}

?>

Add simple callback handler for last.fm connection responses (only prints output so far)


<?php
/**
 * Tool for generation of package overview per organism, usable for checks.
 */
use Nette\Utils\Json;

include_once __DIR__ . '/../app/bootstrap.php';

function printHelp()
{
	print "Package overview\n";
	print "Usage: image-overview.php PACKAGE DESTINATION\n\n";
}

if (count ($argv) <= 2) {
	printHelp();
	exit(0);
}
$path = $argv[1];
$destination = $argv[2];

$wholePath = getcwd() . '/' . $path;
$wholeDestination = getcwd() . '/' . $destination;

if (!is_dir($wholePath)) {
	print "The specified path to package doesn't exists.\n";
	exit(1);
}
if (!is_dir($wholePath . '/files/')) {
	print "The specified path to package doesn't contain files folder.\n";
	exit(1);
}

if (!is_dir($wholeDestination)) {
	print "The specified path to destination doesn't exists.\n";
	exit(1);
}

if (!@mkdir($wholeDestination . '/files/') && !is_dir($wholeDestination . '/files/')) {
	print "The directory files could not been created in destination path.\n";
	exit(1);
}

// Load package data
$data = JSON::decode(file_get_contents($wholePath . '/package.json'));

$output = [];

foreach ($data->organism as $latinName => $organismData) {
	$output[] = sprintf('
%s
', $latinName);
	foreach ($organismData->names as $lang => $localName) {
		$output[] = sprintf('
%s: %s
', $lang, $localName);
	}
	$output[] = sprintf('
Concepts: %s
', implode(', ', $organismData->concepts));

	foreach ($organismData->representations as $representation) {
		copy($wholePath . '/files/' . $representation->hash, $wholeDestination . '/files/' . $representation->hash);
		$output[] = sprintf('%s:

', $representation->hash, $representation->hash, $representation->hash);
	}
	$output [] = '
';
}

$body = '<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Package overview</title>

    ' . implode("\n", $output) . '

';

file_put_contents($wholeDestination . '/overview.html', $body);

Add tool for package overview

Add tool for package overview


<?php

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

namespace Sylius\Bundle\PromotionBundle\Tests\DependencyInjection\Compiler;

use Matthias\SymfonyDependencyInjectionTest\PhpUnit\AbstractCompilerPassTestCase;
use Sylius\Bundle\PromotionBundle\DependencyInjection\Compiler\RegisterRuleCheckersPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Reference;

/**
 * @author Kamil Kokot <kamil.kokot@lakion.com>
 */
final class RegisterRuleCheckersPassTest extends AbstractCompilerPassTestCase
{
    /**
     * {@inheritdoc}
     */
    protected function registerCompilerPass(ContainerBuilder $container)
    {
        $container->addCompilerPass(new RegisterRuleCheckersPass());
    }

    /**
     * @test
     */
    public function it_registers_collected_rule_checkers_in_the_registry()
    {
        $this->setDefinition('sylius.registry_promotion_rule_checker', new Definition());
        $this->setDefinition(
            'custom_promotion_rule_checker',
            (new Definition())->addTag('sylius.promotion_rule_checker', ['type' => 'custom', 'label' => 'Label'])
        );

        $this->compile();

        $this->assertContainerBuilderHasServiceDefinitionWithMethodCall(
            'sylius.registry_promotion_rule_checker',
            'register',
            ['custom', new Reference('custom_promotion_rule_checker')]
        );
    }

    /**
     * @test
     */
    public function it_creates_parameter_which_maps_rule_type_to_label()
    {
        $this->setDefinition('sylius.registry_promotion_rule_checker', new Definition());
        $this->setDefinition(
            'custom_promotion_rule_checker',
            (new Definition())->addTag('sylius.promotion_rule_checker', ['type' => 'custom', 'label' => 'Label'])
        );

        $this->compile();

        $this->assertContainerBuilderHasParameter(
            'sylius.promotion_rules',
            ['custom' => 'Label']
        );
    }
}

Add integration tests for RegisterRuleCheckersPass


<?php

namespace Nwidart\Modules\Tests\Commands;

use Nwidart\Modules\Tests\BaseTestCase;

class PublishTranslationCommandTest extends BaseTestCase
{
    /**
     * @var \Illuminate\Filesystem\Filesystem
     */
    private $finder;
    /**
     * @var string
     */
    private $modulePath;

    public function setUp()
    {
        parent::setUp();
        $this->modulePath = base_path('modules/Blog');
        $this->finder = $this->app['files'];
        $this->artisan('module:make', ['name' => ['Blog']]);
    }

    public function tearDown()
    {
        $this->finder->deleteDirectory($this->modulePath);
        parent::tearDown();
    }

    /** @test */
    public function it_published_module_translations()
    {
        $this->artisan('module:publish-translation', ['module' => 'Blog']);

        $this->assertTrue(is_dir(base_path('resources/lang/blog')));
    }
}

Test module translations are getting published


<?php

namespace SimplyTestable\WorkerBundle\Tests\Live\Command\Task\Perform\HtmlValidation\XHTML10;

use SimplyTestable\WorkerBundle\Tests\Command\ConsoleCommandBaseTestCase;

class PerformHtmlValidationTest extends ConsoleCommandBaseTestCase {

    public static function setUpBeforeClass() {
        self::setupDatabase();
    }

    /**
     * @group live
     * @group live-travis
     */
    public function testMinimalBasicNoErrors() {
        $taskObject = $this->createTask('http://html-validation.simplytestable.com/xhtml10/minimal-basic-no-errors', 'HTML validation');

        $task = $this->getTaskService()->getById($taskObject->id);

        $response = $this->runConsole('simplytestable:task:perform', array(
            $task->getId() => true
        ));

        $this->assertEquals(0, $response);
        $this->assertEquals(0, $task->getOutput()->getErrorCount());
        $this->assertEquals('{"messages":[]}', $task->getOutput()->getOutput());
    }

    /**
     * @group live
     * @group live-travis
     */
    public function testMinimalFramesetNoErrors() {
        $taskObject = $this->createTask('http://html-validation.simplytestable.com/xhtml10/minimal-frameset-no-errors', 'HTML validation');

        $task = $this->getTaskService()->getById($taskObject->id);

        $response = $this->runConsole('simplytestable:task:perform', array(
            $task->getId() => true
        ));

        $this->assertEquals(0, $response);
        $this->assertEquals(0, $task->getOutput()->getErrorCount());
        $this->assertEquals('{"messages":[]}', $task->getOutput()->getOutput());
    }

    /**
     * @group live
     * @group live-travis
     */
    public function testMinimalStrictNoErrors() {
        $taskObject = $this->createTask('http://html-validation.simplytestable.com/xhtml10/minimal-strict-no-errors', 'HTML validation');

        $task = $this->getTaskService()->getById($taskObject->id);

        $response = $this->runConsole('simplytestable:task:perform', array(
            $task->getId() => true
        ));

        $this->assertEquals(0, $response);
        $this->assertEquals(0, $task->getOutput()->getErrorCount());
        $this->assertEquals('{"messages":[]}', $task->getOutput()->getOutput());
    }

    /**
     * @group live
     * @group live-travis
     */
    public function testMinimalTransitionalNoErrors() {
        $taskObject = $this->createTask('http://html-validation.simplytestable.com/xhtml10/minimal-transitional-no-errors', 'HTML validation');

        $task = $this->getTaskService()->getById($taskObject->id);

        $response = $this->runConsole('simplytestable:task:perform', array(
            $task->getId() => true
        ));

        $this->assertEquals(0, $response);
        $this->assertEquals(0, $task->getOutput()->getErrorCount());
        $this->assertEquals('{"messages":[]}', $task->getOutput()->getOutput());
    }

}

Add minimal xhtml 1.0 live tests

Add minimal xhtml 1.0 live tests


<?php

// Hardware-pairs a Pico remote to a set of Caseta dimmers.
// Useful for bypassing SmartThings' considerable latency and establishing
// instant and reliable Pico-to-Caseta communication.

// Pass a negative number for the caseta ID to remove instead of add.

$pico = intval(@$_REQUEST["pico"]) or emsg('No pico parameter');
$raw_caseta = intval(@$_REQUEST["caseta"]) or emsg('No caseta parameter');

$op = ($raw_caseta >= 0) ? "lutron_pico_add" : "lutron_pico_del";
$caseta = abs($raw_caseta);

function emsg($msg) {
  echo $msg;
  exit;
}

$db = "/database/apron.db";
$dbh = new SQLite3($db);
$dbh->busyTimeout(5000);

$device_result = $dbh->query("SELECT masterId FROM lutronDevice WHERE lNodeId = $pico");
$row = $device_result->fetchArray(SQLITE3_ASSOC) or emsg("No such device.");
$pico_master = $row["masterId"];
$device_result->finalize();

$device_result = $dbh->query("SELECT masterId FROM lutronDevice WHERE lNodeId = $caseta");
$row = $device_result->fetchArray(SQLITE3_ASSOC) or emsg("No such device.");
$caseta_master = $row["masterId"];
$device_result->finalize();

$dbh->close();
unset($dbh);
$cmd = "aprontest --$op $caseta_master -m $pico_master | sed 's/[[:space:]][[:space:]]*/ /g' | grep '^[[:space:]][[:alnum:]]*: [A-Za-z0-9\-_]*$' | sed 's/^ //'";

$output = `$cmd`;
$lines = explode(PHP_EOL, $output);

$data = array(
  "cmd" => $cmd,
  "serial" => $pico,
  "op" => $op,
  "value" => $caseta,
);

$result = array();
foreach ($lines as $line) {
  if (!$line) { continue; }
  list($key, $value) = explode(": ", $line);
  $result[$key] = $value;
}

$data["result"] = $result;

header('Content-Type: application/json');
header('X-Response: DEVICE_EVENT');

echo json_encode($data);

?>

Add the ability to hardware-pair Pico remotes and Caseta dimmers directly, for speed and reliability far beyond what SmartThings will ever be able to offer.


<?php

namespace mcordingley\Regression;

use callable;

/**
 * DataSeries
 *
 * Represents a single series of data used in a regression. By convention, the
 * first value in the series is statically set to 1 to represent the idea of
 * "constancy". The coefficient that the regression returns for this idea of
 * invariance is the intercept of the regression. If not provided, then no
 * intercept is calculated.
 */
class DataSeries
{
    protected $data;
    protected $inverse;
    protected $link;

    /**
     * __construct
     *
     * @param array|null $data Data to initialize the series with.
     * @param callable|null $link Function to linearize this data series. Defaults to the identity function.
     * @param callable|null $inverse Function to delinearize this data series. Defaults to the identity function.
     */
    public function __construct(array $data = null, callable $link = null, callable $inverse = null)
    {
        $this->data = $data;
        $this->link = $link ?: function($datum) { return $datum; };
        $this->inverse = $inverse ?: function($datum) { return $datum; };
    }

    /**
     * getData
     *
     * @return array $data
     */
    public function getData()
    {
        return $this->data;
    }

    /**
     * getInverse
     *
     * @return callable The inverse linking function used by this data series.
     */
    public function getInverse()
    {
        return $this->link;
    }

    /**
     * getLink
     *
     * @return callable The linking function used by this data series.
     */
    public function getLink()
    {
        return $this->link;
    }

    /**
     * setData
     *
     * @param array $data
     * @return self
     */
    public function setData(array $data)
    {
        $this->data = $data;

        return $this;
    }

    /**
     * setInverse
     *
     * Sets the inverse link function, which is used to delinearize the data for
     * non-linear regression.
     *
     * @param callable $inverse
     * @return self
     */
    public function setInverse(callable $inverse)
    {
        $this->inverse = $inverse;

        return $this;
    }

    /**
     * setLink
     *
     * Sets the link function, which is used to linearize the data for
     * non-linear regression.
     *
     * @param callable $link
     * @return self
     */
    public function setLink(callable $link)
    {
        $this->link = $link;

        return $this;
    }

    /**
     * getDesign
     *
     * Transforms and returns the data in this series for inclusion into the
     * design matrix used in the regression.
     *
     * @return array
     */
    public function getDesign()
    {
        return array_map($this->link, $this->data);
    }
}

Add in a data series object to bundle data with transforms.


<?php

namespace Bob\Library;

use Bob\Application;
use Bob\TaskLibraryInterface;
use Bob\BuildConfig as b;

class ComposerLibrary implements TaskLibraryInterface
{
    function register(Application $app)
    {
    }

    function boot(Application $app)
    {
        $app->task('composer.phar', function($task) {
            if (file_exists($task->name)) {
                return true;
            }

            $src = fopen('http://getcomposer.org/composer.phar', 'rb');
            $dest = fopen($task->name, 'wb');

            stream_copy_to_stream($src, $dest);
        });

        $app->task('composer:install', array('composer.phar'), function() {
            b\php(array('composer.phar', 'install'));
        });

        $app->task('composer:update', array('composer.phar'), function() {
            b\php(array('composer.phar', 'update'));
        });

        $app->fileTask('composer.lock', array('composer.phar', 'composer.json'), function($task) use ($app) {
            $app->task('composer:update')->invoke();
        });
    }
}

Add library with Composer tasks

Add library with Composer tasks


<?php

/* -------------------------------------------------------------------------
   This script generates rundeck.org compliant external resource model
   provider. It will generate a YAML file that lists all your nodes.
   Currently it dumps all known hosts.

   To enable it edit project.properties file for your project ie.

     $RUNDECK_HOME/projects/Default/etc/project.properties

   add following lines

    project.resources.file = /opt/rundeck/projects/Default/etc/resources.yaml
    project.resources.url = http://ganglia.local/ganglia/api/rundeck.php?nodes=all&ver=1.0

   In Rundeck web UI there will be a link that says

   Update nodes for Project Default

   Rundeck will download the file and copy it to the file name specified
   in projects.resources.file. It will overwrite any contents so
   be careful
--------------------------------------------------------------------------- */

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

$conf['ganglia_dir'] = dirname(dirname(__FILE__));

include_once $conf['ganglia_dir'] . "/eval_conf.php";
include_once $conf['ganglia_dir'] . "/functions.php";
include_once $conf['ganglia_dir'] . "/get_context.php";
$context = "cluster";
include_once $conf['ganglia_dir'] . "/ganglia.php";
include_once $conf['ganglia_dir'] . "/get_ganglia.php";

foreach ( $metrics as $node => $metric_array ) {

if ( isset($metric_array['os_name']['VAL']) ) {
print "$node:
  description: Rundeck node
  hostname: $node
  nodename: $node
  osArch: " . $metric_array['machine_type']['VAL'] . "
  osFamily: unix
  osName: " . $metric_array['os_name']['VAL'] . "
  osVersion: " . $metric_array['os_release']['VAL'] . "
  tags: ''
  username: root
";
}

}

?>

Add API directory and Rundeck Resource Model provider


<?php
/**
 * Created by PhpStorm.
 * User: Bruno
 * Date: 05/03/2018
 * Time: 22:20
 */

namespace AdobeConnectClient\Tests\Commands;

use AdobeConnectClient\Commands\PrincipalInfo;
use AdobeConnectClient\Entities\Principal;
use AdobeConnectClient\Exceptions\NoAccessException;

class PrincipalInfoTest extends TestCommandBase
{
    public function testPrincipalInfo()
    {
        $this->userLogin();

        $command = new PrincipalInfo(2006258745);
        $command->setClient($this->client);

        $principal = $command->execute();

        $this->assertInstanceOf(Principal::class, $principal);
        $this->assertEquals(2006258745, $principal->getPrincipalId());
        $this->assertEquals('Smith', $principal->getLastName());
    }

    public function testNoAccess()
    {
        $this->userLogout();

        $command = new PrincipalInfo(2006258745);
        $command->setClient($this->client);

        $this->expectException(NoAccessException::class);

        $command->execute();
    }
}

Create tests for PrincipalInfo command

Create tests for PrincipalInfo command


<?php

/**
 * @author Michael Croes <mycroes@gmail.com>
 */

/**
 * Main database class. This class maintains a mysql connection and serves as
 * a factory for tables classes.
 */

/**
 * @package Db
 */
class Db {

	/**
	 * Set up database connection.
	 *
	 */
	public function __construct() {

	}
}

Add Database class, no real code yet.

Add Database class, no real code yet.


<?php

namespace Doctrine\ODM\MongoDB\Tests\Mapping\Types;

use Doctrine\ODM\MongoDB\Types\DateType;
use Doctrine\ODM\MongoDB\Types\Type;

class DateTypeTest extends \PHPUnit_Framework_TestCase
{
    public function testConvertToDatabaseValue()
    {
        $type = Type::getType(Type::DATE);

        $this->assertNull($type->convertToDatabaseValue(null), 'null is not converted');

        $mongoDate = new \MongoDate();
        $this->assertSame($mongoDate, $type->convertToDatabaseValue($mongoDate), 'MongoDate objects are not converted');

        $yesterday = strtotime('yesterday');
        $mongoDate = new \MongoDate($yesterday);
        $dateTime = new \DateTime('@' . $yesterday);
        $this->assertEquals($mongoDate, $type->convertToDatabaseValue($dateTime), 'DateTime objects are converted to MongoDate objects');
        $this->assertEquals($mongoDate, $type->convertToDatabaseValue($yesterday), 'Numeric timestamps are converted to MongoDate objects');
        $this->assertEquals($mongoDate, $type->convertToDatabaseValue(date('c', $yesterday)), 'String dates are converted to MongoDate objects');
    }

    /**
     * @dataProvider provideInvalidDateValues
     * @expectedException InvalidArgumentException
     */
    public function testConvertToDatabaseValueWithInvalidValues($value)
    {
        $type = Type::getType(Type::DATE);
        $type->convertToDatabaseValue($value);
    }

    public function provideInvalidDateValues()
    {
        return array(
            'array'  => array(array()),
            'string' => array('whatever'),
            'bool'   => array(false),
            'object' => array(new \stdClass()),
        );
    }

    /**
     * @dataProvider provideDatabaseToPHPValues
     */
    public function testConvertToPHPValue($input, $output)
    {
        $type = Type::getType(Type::DATE);
        $return = $type->convertToPHPValue($input);

        $this->assertInstanceOf('DateTime', $return);
        $this->assertTimestampEquals($output, $return);
    }

    public function testConvertToPHPValueDoesNotConvertNull()
    {
        $type = Type::getType(Type::DATE);

        $this->assertNull($type->convertToPHPValue(null));
    }

    /**
     * @dataProvider provideDatabaseToPHPValues
     */
    public function testClosureToPHP($input, $output)
    {
        $type = Type::getType(Type::DATE);
        $return = null;

        call_user_func(function($value) use ($type, &$return) {
            eval($type->closureToPHP());
        }, $input);

        $this->assertInstanceOf('DateTime', $return);
        $this->assertTimestampEquals($output, $return);
    }

    public function provideDatabaseToPHPValues()
    {
        $yesterday = strtotime('yesterday');
        $mongoDate = new \MongoDate($yesterday);
        $dateTime = new \DateTime('@' . $yesterday);

        return array(
            array($mongoDate, $dateTime),
            array($yesterday, $dateTime),
            array(date('c', $yesterday), $dateTime),
        );
    }

    private function assertTimestampEquals(\DateTime $expected, \DateTime $actual)
    {
        $this->assertEquals($expected->getTimestamp(), $actual->getTimestamp());
    }
}

Add unit tests for DateType

Add unit tests for DateType


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

declare(strict_types=1);

namespace Tests\Pipeline;

use PHPUnit\Framework\TestCase;
use Pipeline\Standard;
use function Pipeline\take;

/**
 * @covers \Pipeline\Principal
 * @covers \Pipeline\Standard
 *
 * @internal
 */
final class CastTest extends TestCase
{
    public function testCastGenerator(): void
    {
        $result = [];

        foreach (take([1, 2, 3])->cast(function (int $i) {
            yield $i;
        }) as $generator) {
            $this->assertInstanceOf(\Generator::class, $generator);
            foreach ($generator as $item) {
                $result[] = $item;
            }
        }

        $this->assertSame([1, 2, 3], $result);
    }

    public function testCastNothing(): void
    {
        $this->assertSame([1, 2, 3], take([1, 2, 3])->cast()->toArray());
    }

    public function testCastSeedValue(): void
    {
        $pipeline = new Standard();

        $this->assertSame([M_PI], $pipeline->cast(function () {
            return M_PI;
        })->toArray());
    }
}

Add missing test for cast()

Add missing test for cast()


<?php

class Ebanx_Gateway_Block_Checkout_Success_Payment_Creditcardmx extends Ebanx_Gateway_Block_Checkout_Success_Creditcardpayment
{
	protected $currencyCode = 'MXN';

	protected function _construct()
	{
		parent::_construct();
	}
}

Add debit card success page block

Add debit card success page block


<?php

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

class AddIsSuspendedToCompaniesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('companies', function (Blueprint $table) {
            $table->boolean('is_suspended')->default(true);
        });
    }

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

Add suspension mark for Company

Add suspension mark for Company


<?php

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

class AddPeopleCounterIdToAttendance extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::table('attendance', static function (Blueprint $table): void {
            $table->unsignedInteger('people_counter_id')->nullable();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('attendance', static function (Blueprint $table): void {
            $table->dropColumn('people_counter_id');
        });
    }
}

Add people_counter_id column to attendance table for imports


<?php

namespace Zimbra\Mail\Tests\Struct;

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

/**
 * Testcase class for AddMsgSpec.
 */
class AddMsgSpecTest extends ZimbraMailTestCase
{
    public function testAddMsgSpec()
    {
        $content = $this->faker->word;
        $flags = $this->faker->word;
        $tags = $this->faker->word;
        $tagNames = $this->faker->word;
        $folder = $this->faker->word;
        $dateReceived = mt_rand(1, 100);
        $attachmentId = $this->faker->word;

        $m = new \Zimbra\Mail\Struct\AddMsgSpec(
            $content, $flags, $tags, $tagNames, $folder, true, $dateReceived, $attachmentId
        );
        $this->assertSame($content, $m->getContent());
        $this->assertSame($flags, $m->getFlags());
        $this->assertSame($tags, $m->getTags());
        $this->assertSame($tagNames, $m->getTagNames());
        $this->assertSame($folder, $m->getFolder());
        $this->assertTrue($m->getNoICal());
        $this->assertSame($dateReceived, $m->getDateReceived());
        $this->assertSame($attachmentId, $m->getAttachmentId());

        $m->setContent($content)
          ->setFlags($flags)
          ->setTags($tags)
          ->setTagNames($tagNames)
          ->setFolder($folder)
          ->setNoICal(true)
          ->setDateReceived($dateReceived)
          ->setAttachmentId($attachmentId);
        $this->assertSame($content, $m->getContent());
        $this->assertSame($flags, $m->getFlags());
        $this->assertSame($tags, $m->getTags());
        $this->assertSame($tagNames, $m->getTagNames());
        $this->assertSame($folder, $m->getFolder());
        $this->assertTrue($m->getNoICal());
        $this->assertSame($dateReceived, $m->getDateReceived());
        $this->assertSame($attachmentId, $m->getAttachmentId());

        $xml = '<?xml version="1.0"?>' . "\n"
            .'<m f="' . $flags . '" t="' . $tags . '" tn="' . $tagNames . '" l="' . $folder . '" noICal="true" d="' . $dateReceived . '" aid="' . $attachmentId . '">'
                .'<content>' . $content . '</content>'
            .'</m>';
        $this->assertXmlStringEqualsXmlString($xml, (string) $m);

        $array = array(
            'm' => array(
                'content' => $content,
                'f' => $flags,
                't' => $tags,
                'tn' => $tagNames,
                'l' => $folder,
                'noICal' => true,
                'd' => $dateReceived,
                'aid' => $attachmentId,
            ),
        );
        $this->assertEquals($array, $m->toArray());
    }
}

Add Test case for AddMsgSpec.

Add Test case for AddMsgSpec.


<?php

namespace Avalanche\Bundle\ImagineBundle\Imagine\Image;

use Assetic\Asset\AssetInterface;

class ImageAssetWrapper
{
    protected $asset;

    public function __construct(AssetInterface $asset)
    {
        $this->asset = $asset;
    }

    /**
     * @param string $realPath Real path where asset content should be dumped.
     * @param array  $options  Options are kept only for copatibilty reasons with ManipulatorInterface::save() method.
     */
    public function save($realPath, array $options = [])
    {
        file_put_contents($realPath, $this->asset->getContent());
    }
}

Add Image wrapper for AsssetInterface object

This was done to simplify cache manager process.


<?php
require_once 'letterScore.php';

function singleByteXOR($inputText, $chrKey) {
  $outputText = $inputText ^ str_repeat($chrKey, strlen($inputText));
  return $outputText;
}

function findSingleByteXOR($cipherText) {
  for ($kv=0; $kv < 256; $kv++) {
    $charScore = 0;

    $plainText = singleByteXOR($cipherText, chr($kv));
    $charScore = englishLetterWeight($plainText, 5);

    $scores[$kv] = $charScore;
  }

  return $scores;
}
?>

Move find byte, and decrypt into functions

Rewrite code to find the single byte key, and decrypt with
it to seprate functions, and move those functions into their
own file.


<?php

$config = array
(
    'staticpages/frontend/home'    => 'staticpages/frontend/view/1',
    'staticpages/frontend/carts'   => 'staticpages/frontend/view/3',
    'staticpages/frontend/compare' => 'staticpages/frontend/view/4',
    'staticpages/frontend/sanjesh' => 'staticpages/frontend/view/5',
    'staticpages/frontend/guide'   => 'staticpages/frontend/view/7',
);

Create router for static pages

Create router for static pages


<?php

/*
Copyright (C) 2016 Teclib'

This file is part of Armadito Plugin for GLPI.

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

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

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

**/

class PluginArmaditoJsonException extends Exception{

}

?>

Add jsonexception for pasring json errors


<?php

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

class AddIpAddressColumnToApiLogTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('api_log', function (Blueprint $table) {
            $table->string('ip_address')->nullable()->after('images');
        });
    }

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

Add ip_address column to api_log table

Add ip_address column to api_log table


    Список постов:

    <?php foreach($posts as $post) : ?>

                <?php echo $post->id; ?>

                <?php echo $post->title; ?>

                <?php echo substr($post->content, 0, 700).'...'; ?>

                <?php echo  $post->count_comments; ?>

    <?php endforeach; ?>

Add view for admin list posts

Add view for admin list posts


<?php

namespace Oro\Bundle\EntityBundle\Form\DataTransformer;

use Symfony\Component\Form\DataTransformerInterface;

use Oro\Bundle\EntityBundle\Entity\EntityFieldFallbackValue;

class EntityFieldFallbackTransformer implements DataTransformerInterface
{
    /**
     * {@inheritdoc}
     */
    public function transform($value)
    {
        if (!$value instanceof EntityFieldFallbackValue) {
            return $value;
        }

//        if (is_null($value->getFallback())) {
//            return $value->setScalarValue($value->getOwnValue());
//        }

        return $value;
    }

    /**
     * {@inheritdoc}
     */
    public function reverseTransform($value)
    {
        if (!$value instanceof EntityFieldFallbackValue) {
            return $value;
        }

        // set entity value to null, so entity will use fallback value
        $fallbackId = $value->getFallback();
        if (isset($fallbackId)) {
            $value->setScalarValue(null);
            $value->setArrayValue(null);

            return $value;
        }

        // not fallback, so make sure we clean fallback field
        $value->setFallback(null);

        if (is_array($value->getScalarValue())) {
            return $value
                ->setArrayValue($value->getScalarValue())
                ->setScalarValue(null);
        }

        return $value->setArrayValue(null);
    }
}

<?php

namespace Oro\Bundle\EntityBundle\Form\DataTransformer;

use Symfony\Component\Form\DataTransformerInterface;

use Oro\Bundle\EntityBundle\Entity\EntityFieldFallbackValue;

class EntityFieldFallbackTransformer implements DataTransformerInterface
{
    /**
     * {@inheritdoc}
     */
    public function transform($value)
    {
        if (!$value instanceof EntityFieldFallbackValue) {
            return $value;
        }

        if (is_null($value->getFallback()) && !$value->getArrayValue()) {
            return $value->setScalarValue($value->getOwnValue());
        }

        return $value;
    }

    /**
     * {@inheritdoc}
     */
    public function reverseTransform($value)
    {
        if (!$value instanceof EntityFieldFallbackValue) {
            return $value;
        }

        // set entity value to null, so entity will use fallback value
        $fallbackId = $value->getFallback();
        if (isset($fallbackId)) {
            $value->setScalarValue(null);
            $value->setArrayValue(null);

            return $value;
        }

        // not fallback, so make sure we clean fallback field
        $value->setFallback(null);

        if (is_array($value->getScalarValue())) {
            return $value
                ->setArrayValue($value->getScalarValue())
                ->setScalarValue(null);
        }

        return $value->setArrayValue(null);
    }
}

BB-7489: Test & Merge
- moved FrontendBundle files from commerce package to customer-portal
- removed test page templates


<?php
class Kwc_Newsletter_Subscribe_MailEditable_Events extends Kwc_Abstract_Events
{
    public function getListeners()
    {
        $ret = parent::getListeners();
        $ret[] = array(
            'class' => 'Kwc_Newsletter_Subscribe_MailEditable_Content_Component',
            'event' => 'Kwf_Component_Event_Component_HasContentChanged',
            'callback' => 'onContentChanged'
        );
        return $ret;
    }

    public function onContentChanged(Kwf_Component_Event_Component_HasContentChanged $event)
    {
        $this->fireEvent(
            new Kwf_Component_Event_Component_ContentChanged($this->_class, $event->component->parent)
        );
    }
}

Clear the cache when the content changes


<?php

/*
	WildPHP - a modular and easily extendable IRC bot written in PHP
	Copyright (C) 2016 WildPHP

	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU 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 General Public License for more details.

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

namespace WildPHP\Core\Events;

class EventEmitter
{
    /**
     * @var \Evenement\EventEmitter
     */
    protected static $emitter = null;

    public static function initialize()
    {
        self::$emitter = new \Evenement\EventEmitter();
    }

    public static function on(string $event, callable $listener)
    {
        self::$emitter->on($event, $listener);
    }

    public static function once(string $event, callable $listener)
    {
        self::$emitter->once($event, $listener);
    }

    public static function removeListener(string $event, callable $listener)
    {
        self::$emitter->removeListener($event, $listener);
    }

    public static function removeAllListeners($event = null)
    {
        self::$emitter->removeAllListeners($event);
    }

    public static function listeners(string $event)
    {
        return self::$emitter->listeners($event);
    }

    public function emit(string $event, array $arguments = [])
    {
        self::$emitter->emit($event, $arguments);
    }
}

Add Event emitter based on Evenement

Add Event emitter based on Evenement

Signed-off-by: Yoshi2889 <77953cd64cc4736aae27fa116356e02d2d97f7ce@gmail.com>


<?php

require dirname(__FILE__).'/../vendor/autoload.php';

use Alfatraining\Grpc\Authentication\AuthenticationServiceClient;
use Alfatraining\Grpc\Authentication\AuthenticationRequest;
use Alfatraining\Grpc\Authentication\AuthenticationReply;
use Alfatraining\Grpc\Authentication\AuthorizationCodeCredentials;
use Alfatraining\Grpc\Common\AccessInfo;
use Alfatraining\Grpc\Room\RoomListRequest;
use Alfatraining\Grpc\Room\RoomServiceClient;
use Alfatraining\Grpc\User\UserListRequest;
use Alfatraining\Grpc\User\UserServiceClient;
use Symfony\Component\Console\Application;

// configuration
$clientId = '';
$authCode = '';
$companyId = '';
$authServiceAddress = '';
$userServiceAddress = '';
$roomServiceAddress = '';

$credentials = new AuthorizationCodeCredentials();
$credentials->setClientId($clientId);
$credentials->setCode($authCode);
$credentials->setCompanyId($companyId);

$authRequest = new AuthenticationRequest();
$authRequest->setAuthorizationCodeCredentials($credentials);
$authRequest->setRequestId('testing-authentication');

$authClient = new AuthenticationServiceClient($authServiceAddress, ['credentials' => \Grpc\ChannelCredentials::createSsl()]);
list($authReply, $status) = $authClient->authenticate($authRequest)->wait();

if ($authReply === null) {
  print("Authentication failed!");
  die();
}
print("Authentication successful. Your user ID: ".$authReply->getUserId()."\n");

$accessInfo = new AccessInfo();
$accessInfo->setRequestId('should-be-used-for-logging'); // required by the room service, optional for the others
$accessInfo->setAccessToken($authReply->getAccessToken());

$userClient = new UserServiceClient($userServiceAddress, ['credentials' => \Grpc\ChannelCredentials::createSsl()]);
$userListRequest = new UserListRequest();
$userListRequest->setAccessInfo($accessInfo);
list($userListReply, $status) = $userClient->userList($userListRequest)->wait();

if ($userListReply !== null) {
  foreach ($userListReply->getUsers() as $userID => $user) {
    print("User ID ".$userID.": ".$user->getEmail().", first name: ".$user->getUserProfile()->getFirstname()." ".$user->getUserProfile()->getLastname()."\n");
  }
}

$roomClient = new RoomServiceClient($roomServiceAddress, ['credentials' => \Grpc\ChannelCredentials::createSsl()]);
$roomListRequest = new RoomListRequest();
$roomListRequest->setAccessInfo($accessInfo);
list($roomListReply, $status) = $roomClient->List($roomListRequest)->wait();

foreach ($roomListReply->getRooms() as $roomID => $room) {
  print("Room ID ".$roomID.": ".$room->getDisplayName()."\n");
  foreach ($room->getPermissions() as $userID => $permissions) {
    print("  User: ".$userID."\n");
  }
}

Add basic example (needs credentials)

Add basic example (needs credentials)


<?php

// Needed due to changes in File.php r6641, 2012-05-15

die; // mission complete, 2012-05-15

require_once('../core/core.php');
require_once('../core/files.php');
require_once('../core/File.php');
require_once('../core/XmlDocumentHandler.php');

$dir = '/var/www/admin-ivr.unicorn.se/uploads';

$page = XmlDocumentHandler::getInstance();
$page->setUploadPath($dir);

$content = dir_get_tree($dir);

foreach ($content as $c) {
    $name = basename($c);

    $new_path = File::getUploadPath($name);

    echo "Moving ".$c." to ".$new_path."\n";
    rename($c, $new_path);
}

?>

Revert "remove some old cruft"

Revert "remove some old cruft"

This reverts commit 17cb33b8f9e44cf33097b5a153c4eb7e06e0c004.


<?php
/*
 * Copyright 2011 Google 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.
 */
require_once '../../src/apiClient.php';
require_once '../../src/contrib/apiGanService.php';

session_start();

$client = new apiClient();
$client->setApplicationName("Google GAN PHP Starter Application");
// Visit https://code.google.com/apis/console?api=gan to generate your
// oauth2_client_id, oauth2_client_secret, and to register your oauth2_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_simple_api_key');
$gan = new apiGanService($client);

if (isset($_REQUEST['logout'])) {
  unset($_SESSION['access_token']);
}

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

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

if ($client->getAccessToken()) {
  $publishers = $gan->publishers->listPublishers("advertisers", "INSERT_ROLE_ID" /* The ID of the requesting advertiser or publisher */);
  $advertisers = $gan->advertisers->listAdvertisers("publishers", "INSERT_ROLE_ID" /* The ID of the requesting advertiser or publisher */);
  print "
" . print_r($publishers, true) . "
";
  print "
" . print_r($advertisers, true) . "
";

  // The access token may have been updated lazily.
  $_SESSION['access_token'] = $client->getAccessToken();
} else {
  $authUrl = $client->createAuthUrl();
}
?>

<?php
  if(isset($authUrl)) {
    print "Connect Me!";
  } else {
   print "Logout";
  }
?>

Add a sample application for the google affiliate network.


<?php namespace Flarum\Forum\Middleware;

use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Zend\Diactoros\Response\StringResponse;
use Zend\Stratigility\ErrorMiddlewareInterface;

class HandleErrors implements ErrorMiddlewareInterface
{
    protected $templateDir;

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

    /**
     * {@inheritdoc}
     */
    public function __invoke($error, Request $request, Response $response, callable $out = null)
    {
        $status = 500;

        // If it seems to be a valid HTTP status code, we pass on the
        // exception's status.
        $errorCode = $error->getCode();
        if (is_int($errorCode) && $errorCode >= 400 && $errorCode < 600) {
            $status = $errorCode;
        }

        $errorPage = $this->getErrorPage($status);

        return StringResponse::html($errorPage, $status);
    }

    protected function getErrorPage($status)
    {
        if (!file_exists($errorPage = $this->templateDir."/$status.html")) {
            $errorPage = $this->templateDir.'/500.html';
        }

        return file_get_contents($errorPage);
    }
}

Implement middleware for presenting pretty error pages


<?php

namespace App\Http\Middleware;

use Closure;
use \DirectoryIterator;

class CleanerMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $filePath  = sprintf("%s/app/", storage_path());
        foreach (new DirectoryIterator($filePath) as $fileInfo) {
            if(!$fileInfo->isDot() && $fileInfo->getExtension() === 'csv') {
                unlink($fileInfo->getPathname());
            }
        }
        return $next($request);
    }
}

Add middleware for clean temp files

Add middleware for clean temp files


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

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

Update Tickets index test since we're no longer showing description and instead showing updated at.


<?php

namespace Bolt\Storage\Database\Schema;

use Bolt\Exception\StorageException;
use Carbon\Carbon;
use Doctrine\DBAL\Schema\Schema;
use Symfony\Component\Filesystem\Exception\IOException;
use Symfony\Component\Filesystem\Filesystem;

/**
 * Schema validation check functionality.
 *
 * @author Gawain Lynch <gawain.lynch@gmail.com>
 */
class Timer
{
    /** @var \Symfony\Component\Filesystem\Filesystem */
    protected $filesystem;
    /** @var string */
    protected $timestampFile;
    /** @var boolean */
    protected $expired;

    const CHECK_INTERVAL = 1800;

    public function __construct($cachePath)
    {
        $this->timestampFile = $cachePath . '/dbcheck.ts';
        $this->filesystem = new Filesystem();
    }
}

<?php

namespace Bolt\Storage\Database\Schema;

use Bolt\Exception\StorageException;
use Carbon\Carbon;
use Doctrine\DBAL\Schema\Schema;
use Symfony\Component\Filesystem\Exception\IOException;
use Symfony\Component\Filesystem\Filesystem;

/**
 * Schema validation check functionality.
 *
 * @author Gawain Lynch <gawain.lynch@gmail.com>
 */
class Timer
{
    /** @var \Symfony\Component\Filesystem\Filesystem */
    protected $filesystem;
    /** @var string */
    protected $timestampFile;
    /** @var boolean */
    protected $expired;

    const CHECK_INTERVAL = 1800;

    public function __construct($cachePath)
    {
        $this->timestampFile = $cachePath . '/dbcheck.ts';
        $this->filesystem = new Filesystem();
    }

    /**
     * Check if we have determined that we need to do a database check.
     *
     * @return boolean
     */
    public function isCheckRequired()
    {
        if ($this->expired !== null) {
            return $this->expired;
        }

        if ($this->filesystem->exists($this->timestampFile)) {
            $expiryTimestamp = (integer) file_get_contents($this->timestampFile);
        } else {
            $expiryTimestamp = 0;
        }
        $ts = Carbon::createFromTimeStamp($expiryTimestamp + self::CHECK_INTERVAL);

        return $this->expired = $ts->isPast();
    }
}

Check to see if validation check is due

Check to see if validation check is due


<?php

namespace PhpAbac;

use PhpAbac\Configuration\ConfigurationInterface;
use PhpAbac\Configuration\Configuration;

use PhpAbac\Manager\PolicyRuleManager;
use PhpAbac\Manager\PolicyRuleManagerInterface;
use PhpAbac\Manager\AttributeManager;
use PhpAbac\Manager\AttributeManagerInterface;
use PhpAbac\Manager\CacheManager;
use PhpAbac\Manager\CacheManagerInterface;
use PhpAbac\Manager\ComparisonManager;
use PhpAbac\Manager\ComparisonManagerInterface;

final class AbacFactory
{
    /** @var ConfigurationInterface **/
    protected static $configuration;
    /** @var PolicyRuleManagerInterface **/
    protected static $policyRuleManager;
    /** @var AttributeManagerInterface **/
    protected static $attributeManager;
    /** @var CacheManagerInterface **/
    protected static $cacheManager;
    /** @var ComparisonManagerInterface **/
    protected static $comparisonManager;

    public static function setConfiguration(ConfigurationInterface $configuration)
    {
        self::$configuration = $configuration;
    }

    public static function setPolicyRuleManager(PolicyRuleManagerInterface $policyRuleManager)
    {
        self::$policyRuleManager = $policyRuleManager;
    }

    public static function setAttributeManager(AttributeManagerInterface $attributeManager)
    {
        self::$attributeManager = $attributeManager;
    }

    public static function setCacheManager(CacheManagerInterface $cacheManager)
    {
        self::$cacheManager = $cacheManager;
    }

    public static function setComparisonManager(ComparisonManagerInterface $comparisonManager)
    {
        self::$comparisonManager = $comparisonManager;
    }

    public static function getAbac(array $configurationFiles, string $configDir = null, array $attributeOptions = [], array $cacheOptions = [])
    {
        $configuration = (self::$configuration !== null) ? self::$configuration : new Configuration($configurationFiles, $configDir);
        $attributeManager = (self::$attributeManager !== null) ? self::$attributeManager : new AttributeManager($configuration, $attributeOptions);
        $policyRuleManager = (self::$policyRuleManager !== null) ? self::$policyRuleManager : new PolicyRuleManager($configuration, $attributeManager);
        $comparisonManager = (self::$comparisonManager !== null) ? self::$comparisonManager : new ComparisonManager($attributeManager);
        $cacheManager = (self::$cacheManager !== null) ? self::$cacheManager : new CacheManager($cacheOptions);

        return new Abac($policyRuleManager, $attributeManager, $comparisonManager, $cacheManager);
    }
}

Implement Factory design pattern to generate Abac object


<?php

require_once __DIR__ . '/CommandTestCase.php';

use Gaufrette\Adapter\InMemory;

class RollbackCommandTest extends CommandTestCase
{
    protected
        $mock;

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

        $this->app['sources.fileSystem.adapter'] = new InMemory(array(
        	'src/file' => '',
        ));

        $this->mock = $this->getMock(
            'Karma\Hydrator',
            array(),
            array($this->app['sources.fileSystem'], $this->app['configuration'])
        );
    }

    /**
     * @dataProvider providerTestOptions
     */
    public function testOptions($option, $expectedMethodCall)
    {
        $this->mock->expects($this->once())
            ->method($expectedMethodCall);

        $this->app['hydrator'] = $this->mock;

        $this->runCommand('rollback', array(
            $option => true,
            'sourcePath' => 'src/'
        ));
    }

    public function providerTestOptions()
    {
        return array(
        	array('--dry-run', 'setDryRun'),
        );
    }
}

Add rollback command unit test

Add rollback command unit test


<?php
/*
 * CodeMOOC TreasureHuntBot
 * ===================
 * UWiClab, University of Urbino
 * ===================
 * Generates individual certificate for a group.
 */

require_once(dirname(__FILE__) . '/game.php');
require_once(dirname(__FILE__) . '/lib.php');
require_once(dirname(__FILE__) . '/model/context.php');

require_once(dirname(__FILE__) . '/msg_processing_state.php');

if(!isset($argv[1]) || !isset($argv[2])) {
    die("Usage: " . basename(__FILE__) . " <GAME ID> <GROUP ID>\n");
}
$game_id = intval($argv[1]);
$group_id = intval($argv[2]);

// Load context
$context = new Context((int)$group_id);
$context->set_active_game($game_id, false, false);

// Generate certificate and montages
$intermediate_locations_count = db_scalar_query(sprintf(
    'SELECT `min_num_locations` FROM `events` WHERE `event_id` = %d',
    $context->game->event_id
));
$total_locations_count = $intermediate_locations_count + 2; // start and end

$rootdir = realpath(dirname(__FILE__) . '/..');
$identifier = "{$context->game->game_id}-{$context->get_internal_id()}";

echo "Generating montage with identifier: '" . $identifier . "'" . PHP_EOL;

exec("montage {$rootdir}/data/selfies/{$identifier}-*.jpg -background \"#0000\" -auto-orient -geometry 150x150 +polaroid -tile {$total_locations_count}x1 {$rootdir}/data/certificates/{$identifier}-montage.png");

exec("php {$rootdir}/html2pdf/cert-gen.php \"{$rootdir}/data/certificates/{$identifier}-certificate.pdf\" {$context->game->group_participants} \"{$context->game->group_name}\" \"completed\" \"{$context->game->game_name}\" \"{$identifier}\"");

echo "Delivering certificate" . PHP_EOL;

$context->comm->document("{$rootdir}/data/certificates/{$identifier}-certificate.pdf", __('questionnaire_attachment_caption'));
$context->comm->reply(__('questionnaire_finish_thankyou'));

bot_set_group_state($context, STATE_CERT_SENT);

Add script that completes game for a given group


<?php

namespace VirtualizorCompiler;

use App\Virtualizor\Lang\CPP;
use PHPUnit\Framework\TestCase;

class CPPTest extends TestCase
{
	public function test1()
	{
		$code = "
#include <iostream>
using namespace std;

int main()
{
    cout << \"hello world\";
    return 0;
}
		";
		$aa = new CPP($code);
		$this->assertTrue($aa->exec() == "hello world");
	}
}

Create CPP Bridge compiler test case

Create CPP Bridge compiler test case


<?php

declare(strict_types=1);

namespace Sylius\Component\Resource\Exception;

final class VariantWithNoOptionsValuesException extends \Exception
{
    public function __construct()
    {
        parent::__construct('sylius.product_variant.cannot_generate_variants');
    }
}

Add new exception, translation flashes and refactor


<?php

namespace Risan\OAuth1\Signature;

trait CanBuildBaseString
{
    /**
     * The BaseStringBuilder instance.
     *
     * @var \Risan\OAuth1\Signature\BaseStringBuilderInterface
     */
    protected $baseStringBuilder;

    /**
     * Build the signature base string.
     *
     * @param \Psr\Http\Message\UriInterface|string $uri
     * @param array $parameters
     * @param string $httpMethod
     * @return string
     */
    public function buildBaseString($uri, array $parameters = [], $httpMethod = 'POST')
    {
        return $this->getBaseStringBuilder()->build($httpMethod, $uri, $parameters);
    }

    /**
     * Get the BaseStringBuilder instance.
     *
     * @return \Risan\OAuth1\Signature\BaseStringBuilderInterface
     */
    public function getBaseStringBuilder()
    {
        if ($this->baseStringBuilder instanceof BaseStringBuilderInterface) {
            return $this->baseStringBuilder;
        }

        return $this->baseStringBuilder = new BaseStringBuilder;
    }
}

:sparkles: Add new trait to build signature base string.


<?php

namespace Http\Adapter;

use React\EventLoop\LoopInterface;
use React\EventLoop\Factory as EventLoopFactory;
use React\Dns\Resolver\Resolver as DnsResolver;
use React\Dns\Resolver\Factory as DnsResolverFactory;
use React\HttpClient\Factory as HttpClientFactory;
use React\HttpClient\Client as HttpClient;

/**
 * Factory wrapper for React instances
 * @author Stéphane Hulard <stephane@hlrd.me>
 */
class ReactFactory
{
    /**
     * Build a react Event Loop
     * @return LoopInterface
     */
    public static function buildEventLoop()
    {
        return EventLoopFactory::create();
    }

    /**
     * Build a React Dns Resolver
     * @param  LoopInterface $loop
     * @param  string        $dns
     * @return DnsResolver
     */
    public static function buildDnsResolver(
        LoopInterface $loop,
        $dns = '8.8.8.8'
    ) {
        $factory = new DnsResolverFactory();
        return $factory->createCached($dns, $loop);
    }

    /**
     * Build a React Http Client
     * @param  LoopInterface $loop
     * @param  Resolver      $dns
     * @return HttpClient
     */
    public static function buildHttpClient(
        LoopInterface $loop,
        DnsResolver $dns = null
    ) {
        if( null === $dns ) {
            $dns = self::buildDnsResolver($loop);
        }

        $factory = new HttpClientFactory();
        return $factory->create($loop, $dns);
    }
}

Add factory to build EventLoop, Client, DNSResolver

This allow to simplify the process of react instance creation


<?php

namespace Phug\Util;

use SplObjectStorage;

/**
 * Interface AttributesInterface.
 */
interface AttributesInterface
{
    /**
     * @return SplObjectStorage
     */
    public function getAttributes();
}

Align markup vs &attributes precedence with pug-js

split: dd5b6edb537be0b4c081b32fcc690e6c5fbbd46c