<?php

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

class AddUserColumnToEventsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('events', function (Blueprint $table) {
            $table->string('user')->after('content')->nullable()->index()->comment('Northstar ID of the user who did the action');
        });
    }

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

Add user column to the events table

Add user column to the events table


<{{'?'}}php namespace {{$namespace}};

/**
 * Main workflow class.
 *
@if($author)
 * @author	{{$author}}
@endif
 */
class {{$name}} implements {{$name}}Interface
{

	/**
	 * Trigger the workflow.
	 *
@if($author)
	 * @author	{{$author}}
@endif
	 * @param	$data
	 */
	public function {{$method}}($data = null)
	{
		//
	}

}

Add the main class template

Add the main class template


<?php namespace Modules\Translation\ValueObjects;

class TranslationGroup
{
    /**
     * @var array
     */
    private $translations;

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

    /**
     * Get a translation by key and optionally a locale
     * @param string $key
     * @param string|null $locale
     * @return string
     */
    public function getTranslation($key, $locale = null)
    {
        $locale = $locale ?: app()->getLocale();

        if (isset($this->translations[$locale][$key])) {
            return $this->translations[$locale][$key];
        }

        return '';
    }
}

Create a translation group VO

Create a translation group VO


<?php
namespace DreadLabs\VantomasWebsite\Archive;

class SearchDateRange {

	/**
	 *
	 * @var \DateTime
	 */
	protected $startDate;

	/**
	 *
	 * @var \DateTime
	 */
	protected $endDate;

	/**
	 * Constructs the archive search DateRange
	 *
	 * @param integer $month
	 * @param integer $year
	 */
	public function __construct($month, $year) {
		$this->startDate = new \DateTime();
		$this->startDate->setDate($year, $month, 1);
		$this->startDate->setTime(0, 0, 0);

		$interval = new \DateInterval('P1M');

		$this->endDate = clone $this->startDate;
		$this->endDate->add($interval);
	}

	/**
	 * Returns the start date
	 *
	 * @return \DateTime
	 */
	public function getStartDate() {
		return $this->startDate;
	}

	/**
	 * Returns the end date
	 *
	 * @return \DateTime
	 */
	public function getEndDate() {
		return $this->endDate;
	}
}

[TASK] Move archive search date range VO into domain


<?php

namespace InsaLan\TournamentBundle\Form;

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

class SetManagerName extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('gameName')
        ;
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'InsaLan\TournamentBundle\Entity\Manager'
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'insalan_tournamentbundle_manager';
    }
}

Add form for new manager name

Add form for new manager name


<?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\ResourceBundle\Tests\Form\Type;

use Prophecy\Prophecy\ObjectProphecy;
use Sylius\Bundle\ResourceBundle\Form\Type\ResourceTranslationsType;
use Sylius\Component\Resource\Translation\Provider\TranslationLocaleProviderInterface;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\PreloadedExtension;
use Symfony\Component\Form\Test\TypeTestCase;

/**
 * @author Kamil Kokot <kamil.kokot@lakion.com>
 */
final class ResourceTranslationsTypeTest extends TypeTestCase
{

    /**
     * {@inheritdoc}
     */
    protected function getExtensions()
    {
        /** @var TranslationLocaleProviderInterface|ObjectProphecy $translationLocaleProvider */
        $translationLocaleProvider = $this->prophesize(TranslationLocaleProviderInterface::class);
        $translationLocaleProvider->getDefaultLocaleCode()->willReturn('en_US');
        $translationLocaleProvider->getDefinedLocalesCodes()->willReturn(['en_US', 'pl_PL']);

        $resourceTranslationsType = new ResourceTranslationsType($translationLocaleProvider->reveal());

        return [
            new PreloadedExtension([$resourceTranslationsType], []),
        ];
    }

    /**
     * @test
     */
    public function it_respects_entry_options()
    {
        $form = $this->factory->create(
            ResourceTranslationsType::class,
            null,
            ['entry_type' => TextType::class, 'entry_options' => ['empty_data' => 'Default']]
        );

        // Testing child type because of `$event->getForm()->getParent()->getData()` inside ResourceTranslationsType::submit()
        $englishTranslationForm = $form->get('en_US');
        $englishTranslationForm->submit(null);

        $this->assertEquals('Default', $englishTranslationForm->getData());
    }
}

Make sure entry options are respected by ResourceTranslationsType


<?php
class dbConnection{

public static function connectedDB(){
      try{

      $base = new PDO('mysql:host=localhost; dbname=FirstConnection','root','7lp3cqmfF4:13');
      //echo "Connection with the database succesfully";
      //?
      $base-> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
      //formato
      $base->exec("SET CHARACTER SET utf8");

      return $base;

      }catch(Exception $ex){

      return die('Error: ' . $ex->GetMessage());

      }finally{
          $base = null;
      }
   }
}
?>

Add class connection to the database with PDO


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

//this script may only be included - so its better to die if called directly.
if (strpos($_SERVER["SCRIPT_NAME"], basename(__FILE__)) !== false) {
  header("location: index.php");
  exit;
}

function smarty_function_datetime_range($params, $smarty)
{
	global $prefs;
	$smarty = TikiLib::lib('smarty');
	$smarty->loadPlugin('smarty_modifier_tiki_date_format');

	if ( ! is_array($params) || ! isset($params['from']) || ! isset($params['to']) ) {
		trigger_error(tra("Missing 'to' or 'from' parameter"));
		return;
	}

	if ($params['datetime_separator']) {
		$datetime_separator = tra($params['datetime_separator']);
	} else {
		$datetime_separator = tra("at");
	}

	if ($params['range_separator']) {
		$range_separator = tra($params['range_separator']);
	} else {
		$range_separator = tra("to");
	}

	if ($params['type']  == 'long'){
		$fromDate = smarty_modifier_tiki_date_format($params['from'], $prefs['long_date_format']);
		$fromTime = smarty_modifier_tiki_date_format($params['from'], $prefs['long_time_format']);
		$toDate = smarty_modifier_tiki_date_format($params['to'], $prefs['long_date_format']);
		$toTime = smarty_modifier_tiki_date_format($params['to'], $prefs['long_time_format']);
	} else {
		$fromDate = smarty_modifier_tiki_date_format($params['from'], $prefs['short_date_format']);
		$fromTime = smarty_modifier_tiki_date_format($params['from'], $prefs['short_time_format']);
		$toDate = smarty_modifier_tiki_date_format($params['to'], $prefs['short_date_format']);
		$toTime = smarty_modifier_tiki_date_format($params['to'], $prefs['short_time_format']);
	}

	if ($fromDate == $toDate && $prefs['tiki_same_day_time_only'] == 'y') {
		$range = $fromDate.' '.$datetime_separator.' '.$fromTime.' '.$range_separator.' '.$toTime;
	} else {
		$range = $fromDate.' '.$datetime_separator.' '.$fromTime.' '.$range_separator.' '.$toDate.' '.$datetime_separator.' '.$toTime;
	}
	return $range;
}

[ENH] Add function to neatly display date + time ranges

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


<?php

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

class UpdatePostsTableWithVisibilityFields extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        $registerCommonFields = function (Blueprint $table) {
            $table->boolean('is_draft')->default(false);
            $table->boolean('is_private')->default(false);
        };

        Schema::table('posts', $registerCommonFields);
        Schema::table('post_revisions', $registerCommonFields);
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        $dropCommonFields = function (Blueprint $table) {
            $table->removeColumn('is_draft');
            $table->removeColumn('is_private');
        };

        Schema::table('posts', $dropCommonFields);
        Schema::table('post_revisions', $dropCommonFields);
    }
}

Add Visibility trait (lost migration for Post)


<?php

namespace Tests\Regis\Infrastructure\Repository;

use Doctrine\Common\Persistence\ObjectRepository;
use Doctrine\ORM\EntityManagerInterface;

use Regis\Domain\Entity;
use Regis\Infrastructure\Repository\DoctrineUsers;

class DoctrineUsersTest extends \PHPUnit_Framework_TestCase
{
    /** @var EntityManagerInterface */
    private $em;
    /** @var DoctrineUsers */
    private $usersRepo;

    public function setUp()
    {
        $this->em = $this->getMockBuilder(EntityManagerInterface::class)->getMock();

        $this->usersRepo = new DoctrineUsers($this->em);
    }

    public function testSaveInspection()
    {
        $user = $this->getMockBuilder(Entity\User::class)->disableOriginalConstructor()->getMock();

        $this->em->expects($this->once())
            ->method('persist')
            ->with($user);
        $this->em->expects($this->once())
            ->method('flush');

        $this->usersRepo->save($user);
    }
}

Add a few tests for the users repository


Hello world user testing page...

<?php
require_once '../Register_client.php';
require_once '../Client_read.php';

$client = new Register_client();
$client_read = new Client_read();

$client->setRequestDiscoveryUrl("https://seed.gluu.org/.well-known/openid-configuration");
$client->setRequestRedirectUrl("https://rs.gluu.org/resources");
$client->setRequestLogoutRedirectUrl("https://rs.gluu.org/resources");
$client->setRequestClientName("oxD Client");
$client->setRequestResponseTypes("code id_token token");
$client->setRequestAppType("web");
$client->setRequestGrantTypes("authorization_code implicit");
$client->setRequestContacts("mike@gluu.org, yuriy@gluu.org");
$client->setRequestJwksUri("https://seed.gluu.org/jwks");

$client->request();

echo '
Registration

ClientId: '.$client->getResponseClientId();
echo '
ClientSecret: '.$client->getResponseClientSecret();
echo '
RegistrationAccessToken: '.$client->getResponseRegistrationAccessToken();
echo '
ClientSecretExpiresAt: '.$client->getResponseClientSecretExpiresAt();
echo '
RegistrationClientUri: '.$client->getResponseRegistrationClientUri();
echo '
ClientIdIssuedAt: '.$client->getResponseClientIdIssuedAt();

$client_read->setRequestRegistrationAccessToken($client->getResponseRegistrationAccessToken());
$client_read->setRequestRegistrationClientUri($client->getResponseRegistrationClientUri());
$client_read->request();

echo '
Client Reading

ClientId: '.$client_read->getResponseClientId();
echo '
ClientIdIssuedAt: '.$client_read->getResponseClientIdIssuedAt();
echo '
ClientSecret: '.$client_read->getResponseClientSecret();
echo '
ClientSecretExpiresAt: '.$client_read->getResponseClientSecretExpiresAt();
echo '
RegistrationAccessToken: '.$client_read->getResponseRegistrationAccessToken();
echo '
RegistrationClientUri: '.$client_read->getResponseRegistrationClientUri();
$client_read->disconnect();

Test using oxd-php library for adding new client and reading information about client.


<?php

namespace Core;

use PHPUnit\Framework\TestCase;
use Prob\Handler\ParameterMap;
use JBZoo\Event\EventManager as ZooEventManager;

class EventManagerTest extends TestCase
{
    public function testGetEventManager()
    {
        $this->assertEquals(ZooEventManager::class, get_class(EventManager::getEventManager()));
    }

    public function testRegisterListener()
    {
        EventManager::registerListener([
            'test.event' => function () {
                echo 'test!';
            }
        ]);

        $this->expectOutputString('test!');
        EventManager::getEventManager()->trigger('test.event', [new ParameterMap]);
    }
}

Add EventManager unit test code

Add EventManager unit test code


<?php

namespace App\Console\Commands;

use App\Notifications\DearSanta as DearSantaNotification;
use App\Models\DearSanta;
use DrawCrypt;
use Illuminate\Console\Command;

class SendDearSanta extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'send:dearSanta {dearSanta : ID of the dearsanta} {iv : The decryption iv}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Send again an email to a santa';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $iv = base64_decode($this->argument('iv'));
        DrawCrypt::setIV($iv);

        $dearSanta = DearSanta::find($this->argument('dearSanta'));

        $dearSanta->sender->santa->notify(new DearSantaNotification($dearSanta));
        $this->info('DearSanta mail sent');
    }
}

Add command to resend DearSanta email

Add command to resend DearSanta email


<?php

namespace App\Form\Type;

use App\Entity\Framework\AdditionalField;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;

class AdditionalFieldType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name')
            ->add('displayName')
            ->add('appliesTo')
            ->add('type')
            ->add('typeInfo')
            ->add('save', SubmitType::class);
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => AdditionalField::class,
        ]);
    }
}

Add additional field form type file.

Add additional field form type file.


<?php
/**
 * @copyright Copyright (C) 2015-2018 AIZAWA Hina
 * @license https://github.com/fetus-hina/stat.ink/blob/master/LICENSE MIT
 * @author AIZAWA Hina <hina@bouhime.com>
 */
declare(strict_types=1);

use app\components\db\Migration;
use app\components\db\VersionMigration;

class m181126_075355_s2_v4_3 extends Migration
{
    use VersionMigration;

    public function safeUp()
    {
        $this->upVersion2(
            '4.3',
            '4.3.x',
            '4.3.0',
            '4.3.0',
            new DateTimeImmutable('2018-12-05T11:00:00+09:00')
        );
    }

    public function safeDown()
    {
        $this->downVersion2('4.3.0', '4.2.0');
    }
}

Add Splatoon 2 version 4.3 data

Add Splatoon 2 version 4.3 data

Signed-off-by: AIZAWA Hina <07c779d48779c322a7c5324109202f9012f7aebf@bouhime.com>


<?php namespace Lanin\Laravel\SetupWizard\Tests\Commands\Steps;

use Lanin\Laravel\SetupWizard\Commands\Setup;
use Lanin\Laravel\SetupWizard\Commands\Steps\Optimize;
use Lanin\Laravel\SetupWizard\Tests\TestCase;

class OptimizeTest extends TestCase
{

    /**
     * @return \Mockery\Mock
     */
    public function mockCommand()
    {
        $command = \Mockery::mock(Setup::class)->makePartial();
        $command->shouldReceive('confirm')->with('Everything is right?')->andReturn(true);

        return $command;
    }

    /** @test */
    public function it_has_prompt_text()
    {
        $step = new Optimize($this->mockCommand());
        $this->assertEquals('Do you want to optimize code?', $step->prompt());
    }

    /** @test */
    public function it_shows_preview()
    {
        $command = $this->mockCommand();
        $command->shouldReceive('info')->with(
            'This command will be executed: <comment>php artisan optimize --force --no-interaction</comment>'
        )->once();

        $step = new Optimize($command);
        $this->assertNull($step->preview(null));
    }

    /** @test */
    public function it_runs_seed_artisan_command()
    {
        $artisan = \Mockery::mock($this->app['Illuminate\Contracts\Console\Kernel']);
        $artisan->shouldReceive('call')->with('optimize', ['--force' => true, '--no-interaction' => true])->andReturn(0)->once();

        $this->app['Illuminate\Contracts\Console\Kernel'] = $artisan;

        $step = new Optimize($this->mockCommand());
        $this->assertTrue($step->finish(null));
    }
}

Cover optimize step with tests

Cover optimize step with tests


<?php

/*
 * This file is part of the Sonata package.
 *
 * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Sonata\AdminBundle\Filter\ORM;

use Symfony\Component\Form\FormFactory;
use Doctrine\ORM\QueryBuilder;

class ChoiceFilter extends Filter
{
    public function filter($queryBuilder, $alias, $field, $value)
    {
        if ($this->getField()->getAttribute('multiple')) {
            if (!is_array($value) || count($value) == 0) {
                return;
            }

            if (in_array('all', $value)) {
                return;
            }

            $queryBuilder->andWhere($queryBuilder->expr()->in(sprintf('%s.%s',
                $alias,
                $field
            ), $value));
        } else {

            if ($value === null || $value == 'all') {
                return;
            }

            $queryBuilder->andWhere(sprintf('%s.%s = :%s',
                $alias,
                $field,
                $this->getName()
            ));

            $queryBuilder->setParameter($this->getName(), $value);
        }
    }

    public function defineFieldBuilder(FormFactory $formFactory, $value = null)
    {
        $options = $this->getFieldDescription()->getOption('filter_field_options', array('required' => false));

        $this->field = $formFactory->createNamedBuilder('choice', $this->getName(), $value, $options)->getForm();
    }
}

<?php

/*
 * This file is part of the Sonata package.
 *
 * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Sonata\AdminBundle\Filter\ORM;

use Symfony\Component\Form\FormFactory;
use Doctrine\ORM\QueryBuilder;

class ChoiceFilter extends Filter
{
    public function filter($queryBuilder, $alias, $field, $value)
    {
        if ($this->getField()->getAttribute('multiple')) {
            if (!is_array($value) || count($value) == 0) {
                return;
            }

            if (in_array('all', $value)) {
                return;
            }

            $queryBuilder->andWhere($queryBuilder->expr()->in(sprintf('%s.%s',
                $alias,
                $field
            ), $value));
        } else {

            if (empty($value) || $value == 'all') {
                return;
            }

            $queryBuilder->andWhere(sprintf('%s.%s = :%s',
                $alias,
                $field,
                $this->getName()
            ));

            $queryBuilder->setParameter($this->getName(), $value);
        }
    }

    public function defineFieldBuilder(FormFactory $formFactory, $value = null)
    {
        $options = $this->getFieldDescription()->getOption('filter_field_options', array('required' => false));

        $this->field = $formFactory->createNamedBuilder('choice', $this->getName(), $value, $options)->getForm();
    }
}

Fix filter bug on empty value

Fix filter bug on empty value


<?php

namespace Bitcoin\Block;

/**
 * Class GenesisMiningBlockHeader
 * @package Bitcoin\Block
 */
class GenesisMiningBlockHeader extends BlockHeader
{
    public function getBlockHash()
    {
        return '0000000000000000000000000000000000000000000000000000000000000000';
    }
}

Add a class for mining genesis blocks.

Add a class for mining genesis blocks.


<?php

namespace FluxBB\Web;

use Carbon\Carbon;
use Illuminate\Contracts\Cookie\QueueingFactory;
use Illuminate\Session\DatabaseSessionHandler;
use Illuminate\Session\Store;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\HttpKernel\HttpKernelInterface;

class SessionWrapper implements HttpKernelInterface
{
    /**
     * The wrapped HTTP kernel instance.
     *
     * @var \Symfony\Component\HttpKernel\HttpKernelInterface
     */
    protected $wrapped;

    /**
     * The cookie jar instance.
     *
     * @var \Illuminate\Contracts\Cookie\QueueingFactory
     */
    protected $queue;

    /**
     * Create the session wrapper instance.
     *
     * @param \Symfony\Component\HttpKernel\HttpKernelInterface $wrapped
     * @param \Illuminate\Contracts\Cookie\QueueingFactory $queue
     */
    public function __construct(HttpKernelInterface $wrapped, QueueingFactory $queue)
    {
        $this->wrapped = $wrapped;
        $this->queue = $queue;
    }

    /**
     * @inheritDoc
     */
    public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = true)
    {
        $session = $this->startSession($request);
        $request->setSession($session);

        $response = $this->wrapped->handle($request, $type, $catch);

        $session->save();
        $this->writeSession($session, $response);
        $this->writeQueuedCookies($response);

        return $response;
    }

    /**
     * Prepare and start the session instance with data from the given request.
     *
     * @param \Symfony\Component\HttpFoundation\Request $request
     * @return \Symfony\Component\HttpFoundation\Session\SessionInterface
     */
    protected function startSession(Request $request)
    {
        $connection = app('Illuminate\Database\ConnectionInterface');
        $table = 'sessions';

        $handler = new DatabaseSessionHandler($connection, $table);
        $session = new Store('fluxbb_session', $handler);

        $session->setId($request->cookies->get('fluxbb_session'));
        $session->start();

        return $session;
    }

    /**
     * Write the session cookie to the response.
     *
     * @param \Symfony\Component\HttpFoundation\Session\SessionInterface $session
     * @param \Symfony\Component\HttpFoundation\Response $response
     * @return void
     */
    protected function writeSession(SessionInterface $session, Response $response)
    {
        // TODO: Take these values from config
        $lifetime = Carbon::now()->addMinutes(120);
        $path = '/';
        $domain = null;
        $secure = false;

        $response->headers->setCookie(new Cookie(
            $session->getName(), $session->getId(), $lifetime, $path, $domain, $secure
        ));
    }

    /**
     * Append all queued cookies to the response.
     *
     * @param \Symfony\Component\HttpFoundation\Response $response
     * @return void
     */
    protected function writeQueuedCookies(Response $response)
    {
        foreach ($this->queue->getQueuedCookies() as $cookie) {
            $response->headers->setCookie($cookie);
        }
    }
}

Create a session wrapper decorator for the HTTP kernel.


<?php

namespace Phansible\Roles;

use Phansible\BaseRole;

class Blackfire extends BaseRole
{
    protected $name = 'BlackFire';
    protected $slug = 'blackfire';
    protected $role = 'blackfire';

    public function getInitialValues()
    {
        return [
          'install' => 0,
          'server_id' => '',
          'server_token' => '',
        ];
    }

}

Fix blackfire io PR warning

Fix blackfire io PR warning


<?php

namespace Oro\Bundle\CalendarBundle\Form\EventListener;

use Doctrine\Common\Persistence\ManagerRegistry;
use Doctrine\Common\Collections\Collection;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;

use Oro\Bundle\CalendarBundle\Entity\Attendee;
use Oro\Bundle\UserBundle\Entity\User;

class AttendeesSubscriber implements EventSubscriberInterface
{
    /** @var ManagerRegistry */
    protected $registry;

    /**
     * @param ManagerRegistry $registry
     */
    public function __construct(ManagerRegistry $registry)
    {
        $this->registry = $registry;
    }

    /**
     * {@inheritdoc}
     */
    public static function getSubscribedEvents()
    {
        return [
            FormEvents::POST_SUBMIT => ['postSubmit', -100],
        ];
    }

    /**
     * @param FormEvent $event
     */
    public function postSubmit(FormEvent $event)
    {
        $attendees = $event->getData();
        if (!$attendees) {
            return;
        }

        $unboundAttendeesByEmail = $this->getUnboundAttendeesByEmail($attendees);
        if (!$unboundAttendeesByEmail) {
            return;
        }

        $users = $this->registry
            ->getRepository('OroUserBundle:User')
            ->findUsersByEmails(array_keys($unboundAttendeesByEmail));

        $this->bindUsersToAttendees($users, $unboundAttendeesByEmail);
    }

    /**
     * @param User[] $users
     * @param string[] $unboundAttendeesByEmail
     */
    protected function bindUsersToAttendees(array $users, array $unboundAttendeesByEmail)
    {
        foreach ($users as $user) {
            if (isset($unboundAttendeesByEmail[$user->getEmail()])) {
                $unboundAttendeesByEmail[$user->getEmail()]->setUser($user);
                unset($unboundAttendeesByEmail[$user->getEmail()]);
            }

            foreach ($user->getEmails() as $emailEntity) {
                $email = $emailEntity->getEmail();
                if (isset($unboundAttendeesByEmail[$email])) {
                    $unboundAttendeesByEmail[$email]->setUser($user);
                    unset($unboundAttendeesByEmail[$email]);
                }
            }
        }
    }

    /**
     * @param Collection|Attendee $attendees
     *
     * @return Attendee[]
     */
    protected function getUnboundAttendeesByEmail(Collection $attendees)
    {
        $unboundAttendeesByEmail = [];
        foreach ($attendees as $attendee) {
            if ($attendee->getId() || $attendee->getUser()) {
                continue;
            }

            $unboundAttendeesByEmail[$attendee->getEmail()] = $attendee;
        }

        return $unboundAttendeesByEmail;
    }
}

Update API REST and SOAP

AEIV-573: Update API REST and SOAP

Conflicts:
	src/Oro/Bundle/CalendarBundle/Form/EventListener/AttendeesSubscriber.php


<?php

/**
 * Unit tests for citation handling
 * REQUIREMENTS: web server running as specified in phpunit.xml + Selenium
 *
 * PHP Version 5.5
 *
 * @author  David P. Shorthouse <davidpshorthouse@gmail.com>
 * @link    http://github.com/dshorthouse/SimpleMappr
 * @license Copyright (C) 2013 David P. Shorthouse
 *
 */
class ShareTest extends SimpleMapprTest
{
    /**
     * Parent setUp function executed before each test.
     */
    public function setUp()
    {
        parent::setUp();
    }

    /**
     * Parent tearDown function executed after each test.
     */
    public function tearDown()
    {
        parent::tearDown();
    }

    /**
     * Test content of share list
     */
    public function testDefaultSharesList()
    {
        parent::setUpPage();
        parent::setSession();

        $link = $this->webDriver->findElement(WebDriverBy::linkText('Shared Maps'));
        $link->click();
        $this->assertContains("Sample Map Administrator", $this->shareContent());
    }

    /**
     * Test creation of share
     */
    public function testCreateShare()
    {
        parent::setUpPage();
        parent::setSession();

        $this->webDriver->findElement(WebDriverBy::cssSelector(".map-share"))->click();
        parent::waitOnAjax();
        $this->assertEquals("Unshare", $this->webDriver->findElement(WebDriverBy::cssSelector(".map-unshare"))->getText());

        $this->webDriver->findElement(WebDriverBy::linkText('Shared Maps'))->click();
        $this->assertContains("Sample Map User", $this->shareContent());
    }

    /**
     * Test removal of a share
     */
    public function testRemoveShare()
    {
        parent::setUpPage();
        parent::setSession();

        $this->webDriver->findElement(WebDriverBy::cssSelector(".map-unshare"))->click();
        parent::waitOnAjax();
        $this->assertEquals("Share", $this->webDriver->findElement(WebDriverBy::cssSelector(".map-share"))->getText());
        $this->assertNotContains("Sample User Map", $this->shareContent());
    }

    /**
     * Get the content of the default share message when none exists
     */
    private function shareContent()
    {
        $this->webDriver->findElement(WebDriverBy::linkText('Shared Maps'))->click();
        return $this->webDriver->findElement(WebDriverBy::id('sharedmaps'))->getText();
    }

}

Add some tests for Shares

Add some tests for Shares


<?php
class FACTFinder_Core_Model_System_Config_Source_Identifier
{
    /**
     * Get possible identifiers as Option Array
     *
     * @return array
     */
    public function toOptionArray()
    {
        return array(
            array(
                'value' => 'entity_id',
                'label' => Mage::helper('factfinder')->__('Product ID (default)')
            ),
            array(
                'value' => 'sku',
                'label' => Mage::helper('factfinder')->__('Product SKU')
            )
        );
    }
}

Add product identifier source model

[FACTFINDER-80] Add product identifier source model


<?php

/**
 * This file is part of the Statistical Classifier package.
 *
 * (c) Cam Spiers <camspiers@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Camspiers\StatisticalClassifier\Console\Command\Config;

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

use Camspiers\StatisticalClassifier\Console\Command\Config\Command;

use RuntimeException;

/**
 * @author Cam Spiers <camspiers@gmail.com>
 * @package Statistical Classifier
 */
class OpenCommand extends Command
{
    /**
     * Configure the commands options
     * @return null
     */
    protected function configure()
    {
        $this
            ->setName('config:open')
            ->setDescription('Opens the config')
            ->configureGlobal();
    }
    /**
     * Create the index using the specified name
     * @param  Input\InputInterface   $input  The input object
     * @param  Output\OutputInterface $output The output object
     * @return null
     */
    protected function execute(Input\InputInterface $input, Output\OutputInterface $output)
    {
        $filename = $this->getConfigFilename($input);
        if (file_exists($filename)) {
            if (PHP_OS === 'Darwin') {
                exec("open $filename");
            } elseif (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN') {
                exec("dxg-open $filename");
            } else {
                throw new RuntimeException('This command is not supported in windows');
            }
        } else {
            throw new RuntimeException('Please run config:create to set up a global config');
        }
    }
}

FEAUTRE: Enable the opening of the user and global configs


<?php
namespace TYPO3\SingleSignOn\Client\Command;

/*                                                                        *
 * This script belongs to the TYPO3 Flow package "TYPO3.SingleSignOn.Client".*
 *                                                                        *
 *                                                                        */

use TYPO3\Flow\Annotations as Flow;

/**
 * Command controller for key management
 *
 * @Flow\Scope("singleton")
 */
class SingleSignOnCommandController extends \TYPO3\Flow\Cli\CommandController {

	/**
	 * @var \TYPO3\Flow\Security\Cryptography\RsaWalletServiceInterface
	 * @Flow\Inject
	 */
	protected $rsaWalletService;

	/**
	 * Generate key pair command
	 *
	 * Creates a new key pair and imports it into the wallet.
	 * Useful for SSO client and server.
	 *
	 * @return void
	 */
	public function generateKeyPairCommand() {
		$keyUuid = $this->rsaWalletService->generateNewKeypair();
		$this->outputLine('Created key with uuid: ' . $keyUuid);
	}

	/**
	 * Export a public key
	 *
	 * @param string $keyPairUuid
	 * @return void
	 */
	public function exportPublicKeyCommand($keyPairUuid) {
		$publicKey = $this->rsaWalletService->getPublicKey($keyPairUuid);
		$this->output($publicKey->getKeyString());
	}

}

?>

Add command for key export

[TASK] Add command for key export


<?php

$path = __DIR__ . '/../src/DebugBar/Resources/vendor/font-awesome/css/font-awesome.min.css';
$contents = file_get_contents($path);

if (strpos($contents, 'PhpDebugbarFontAwesome') !== false ){
    exit('Already namespaced');
}

// namespace FontAwesome occurrences
$contents = str_replace(['FontAwesome', 'fa-', '.fa'], ['PhpDebugbarFontAwesome', 'phpdebugbar-fa-', '.phpdebugbar-fa'], $contents);

if (file_put_contents($path, $contents)) {
    echo "Updated font-awesome.min.css";
} else {
    echo "No content written";
}

Use PHP script for namespacing

Use PHP script for namespacing


<?php

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

class AddDefaultTransactionTypeColumnToUsersTable extends Migration
{
    public function up(): void
    {
        Schema::table('users', function (Blueprint $table) {
            $table->string('default_transaction_type')->default('earning')->after('weekly_report');
        });
    }

    public function down(): void
    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropColumn('default_transaction_type');
        });
    }
}

Add default_transaction_type column to users table


@extends('layouts.default')

@section('content')

Admin Dashboard

Support Tickets

    Open Tickets: {{ count($data['openTickets']) }} /
    In Progress Tickets: {{ count($data['inProgressTickets']) }}

Projects

    Open Projects: {{ count($data['openProjects']) }} /
    In Progress Projects: {{ count($data['inProgressProjects']) }}

Invoices:

    Open Invoices: {{ count($data['openInvoices']) }} /
    Total Open Amount: {{ $data['openInvoicesAmount'] }}

    Overdue Invoices: {{ count($data['overdueInvoices']) }} /
    Total Overdue Amount: {{ $data['overdueInvoicesAmount'] }}

@stop

Use paragraphs instead of BRs

Use paragraphs instead of BRs


<?php

namespace Orbt\ResourceMirror\Resource;

/**
 * A resource that exists locally, i.e. not on the backend server.
 *
 * A local resource contains content to be managed, not materialized.
 */
class LocalResource extends GenericResource
{
    /**
     * Resource content.
     * @var string
     */
    protected $content;

    /**
     * Creates a local resource with content.
     *
     * @param string $path
     *   Resource path.
     * @param $content
     *   Resource content.
     */
    public function __construct($path, $content)
    {
        parent::__construct($path);
        $this->content = $content;
    }

    /**
     * Updates resource content.
     * @param string $content
     */
    public function setContent($content)
    {
        $this->content = $content;
    }

    /**
     * Returns resource content.
     * @return string
     */
    public function getContent()
    {
        return $this->content;
    }
}

Test for nested directory and invalid directory names (to avoid permissive file system for testing).


<?php

$autoloader = require __DIR__ . '/../src/autoload.php';

if (!$autoloader()) {
    die('uh-oh');
}

$app = new Stratedge\Runcard\Console\Application();
$app->run();

Add the application file into the repo - not the final one, just a provisional one to get things working


<?php

/**
 * ROOD.Sendbirthdaysixteenmail API
 *
 * Sends a mail to all certain contacts on their x-th birthday
 * @param array $params
 * @return array API result descriptor
 * @see civicrm_api3_create_success
 * @see civicrm_api3_create_error
 * @throws API_Exception
 */
function civicrm_api3_rood_Sendbirthdaysixteenmail($params) {
    if (!CRM_Core_Permission::check("access CiviCRM")) {
        throw new API_Exception("Insufficient permissions");
    }
    $contactIds = civicrm_api3('Contact', 'Sendbirthdaymail', [
        'age' => 16,
        'membership_id' => 3, // 3 is ROOD membership
        'dont_send_mail' => true,
    ])['values'];
    if (empty($contactIds)) {
        return civicrm_api3_create_success('No contact ids',
                                           $params, 'ROOD', 'Sendbirthdaysixteenmail');
    }
    $message = "Beste ROOD,\r\n\r\nVandaag zijn de volgende leden 16 geworden:\r\n\r\n";
    foreach($contactIds as $contactId) {
        $message .= "Contactnummer: $contactId\r\n";
    }
    mail('rood@sp.nl', 'ROOD-leden 16 geworden', $message);
    return civicrm_api3_create_success('contact ids found',
                                       $params, 'ROOD', 'Sendbirthdaysixteenmail');
}

Add API method to remind about birthdays

People who turned 16 should be reminded that they could be
SP members too.


<?php

namespace Laravel\Passport;

class RefreshTokenRepository
{
    /**
     * Creates a new refresh token.
     *
     * @param  array  $attributes
     * @return \Laravel\Passport\RefreshToken
     */
    public function create($attributes)
    {
        return Passport::refreshToken()->create($attributes);
    }

    /**
     * Gets a refresh token by the given ID.
     *
     * @param  string  $id
     * @return \Laravel\Passport\RefreshToken
     */
    public function find($id)
    {
        return Passport::refreshToken()->where('id', $id)->first();
    }

    /**
     * Stores the given token instance.
     *
     * @param  \Laravel\Passport\RefreshToken  $token
     * @return void
     */
    public function save(RefreshToken $token)
    {
        $token->save();
    }

    /**
     * Revokes the refresh token.
     *
     * @param  string  $id
     * @return mixed
     */
    public function revokeRefreshToken($id)
    {
        return Passport::refreshToken()->where('id', $id)->update(['revoked' => true]);
    }

    /**
     * Checks if the refresh token has been revoked.
     *
     * @param  string  $id
     * @return bool
     */
    public function isRefreshTokenRevoked($id)
    {
        if ($token = $this->find($id)) {
            return $token->revoked;
        }

        return true;
    }
}

Add new refresh token repository

Add new refresh token repository


<?php

namespace Benrowe\Laravel\Widgets;

use Arrilot\Widgets\ServiceProvider as BaseServiceProvider;
use Benrowe\Laravel\Widgets\Factories\WidgetFactory;
use Arrilot\Widgets\Misc\LaravelApplicationWrapper;

/**
 * @package Benrowe\Laravel\Widgets
 */
class ServiceProvider extends BaseServiceProvider
{
    /**
     * Suplement the base provider with a different version of the widget factory
     *
     * @return nil
     */
    public function register()
    {
        parent::boot();

        $this->app->bind('arrilot.widget', function () {
            return new WidgetFactory(new LaravelApplicationWrapper());
        });

        $this->app->alias('arrilot.widget', 'Arrilot\Widgets\Factories\WidgetFactory');

    }

    /**
     * Register two additional blade directives
     *
     * @return nil
     */
    public function boot()
    {
        parent::boot();
        $this->registerBladeDirective('widget-begin', '$1<?php echo app("arrilot.widget")->begin$2; ?>');
        $this->registerBladeDirective('widget-end', '$1<?php echo app("arrilot.widget")->endw$2; ?>');
    }
}

Add new service provider to inject new factory


<?php

/**
 * Template Name: Page with Event Sidebar
 */

get_header();

if (Bunyad::posts()->meta('featured_slider')):
get_template_part('partial-sliders');
endif;

?>

      <?php if (have_posts()): the_post(); endif; // load the page ?>

      <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>

	<?php if (Bunyad::posts()->meta('page_title') == 'yes'): ?>

	  <?php if (has_post_thumbnail() && !Bunyad::posts()->meta('featured_disable')): ?>

	    <a href="<?php $url = wp_get_attachment_image_src(get_post_thumbnail_id(), 'full'); echo $url[0]; ?>" title="<?php the_title_attribute(); ?>">

	      <?php if ((!in_the_loop() && Bunyad::posts()->meta('layout_style') == 'full') OR Bunyad::core()->get_sidebar() == 'none'): // largest images - no sidebar? ?>

	      <?php the_post_thumbnail('main-full', array('title' => strip_tags(get_the_title()))); ?>

	      <?php else: ?>

	      <?php the_post_thumbnail('main-slider', array('title' => strip_tags(get_the_title()))); ?>

	      <?php endif; ?>

	  <?php endif; ?>

	    <?php the_title(); ?>

	<?php endif; ?>

	  <?php Bunyad::posts()->the_content(); ?>

	<?php if (!dynamic_sidebar('events-sidebar')) : ?>
	<?php _e("
Nothing yet.
", 'bunyad'); ?>
	<?php endif; ?>

<?php get_footer(); ?>

Add new page with events sidebar hard coded


<?php

use Illuminate\Support\Facades\Config;

class EntrustPermissionTest extends PHPUnit_Framework_TestCase
{
    public function tearDown()
    {
        Mockery::close();
    }

    public function testRoles()
    {
        /*
        |------------------------------------------------------------
        | Set
        |------------------------------------------------------------
        */

        $permission = Mockery::mock('Bbatsche\Entrust\EntrustPermission')->makePartial();

        $belongsToMany = new stdClass();

        $app    = Mockery::mock('app')->shouldReceive('instance')->getMock();
        $config = Mockery::mock('config');

        Config::setFacadeApplication($app);
        Config::swap($config);

        /*
        |------------------------------------------------------------
        | Expectation
        |------------------------------------------------------------
        */

        $permission->shouldReceive('belongsToMany')->with('RoleModelName', 'permission_role_table_name')
            ->andReturn($belongsToMany)->once();

        Config::shouldReceive('get')->with('entrust::role')
            ->andReturn('RoleModelName')->once();
        Config::shouldReceive('get')->with('entrust::permission_role_table')
            ->andReturn('permission_role_table_name')->once();

        /*
        |------------------------------------------------------------
        | Assertion
        |------------------------------------------------------------
        */

        $this->assertSame($belongsToMany, $permission->roles());
    }
}

Test for the one and only method in our permission model. Because.


<?php

namespace Chromabits\Nucleus\View\Common;

use Chromabits\Nucleus\View\Interfaces\Renderable;
use Chromabits\Nucleus\View\Node;

/**
 * Class Small
 *
 * @author Eduardo Trujillo <ed@chromabits.com>
 * @package Chromabits\Nucleus\View\Common
 */
class Small extends Node
{
    /**
     * Construct an instance of a Small.
     *
     * @param string[] $attributes
     * @param string|Renderable|string[]|Renderable[] $content
     */
    public function __construct($attributes, $content = '')
    {
        parent::__construct('small', $attributes, $content);
    }
}

Add <small> element rendering support

Add <small> element rendering support


<?php

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

namespace Sylius\Component\Payment;

class PaymentTransitions
{
    const SYLIUS_CREATE   = 'create';
    const SYLIUS_PROCESS  = 'process';
    const SYLIUS_COMPLETE = 'complete';
    const SYLIUS_FAIL     = 'fail';
    const SYLIUS_CANCEL   = 'cancel';
    const SYLIUS_REFUND   = 'refund';
    const SYLIUS_VOID     = 'void';
}

Use constant for transition names

Use constant for transition names


<?php

namespace Metroplex\Edifact\Tests;

use Metroplex\Edifact\Token;
use Metroplex\Edifact\Tokenizer;

class TokenizerTest extends \PHPUnit_Framework_TestCase
{
    protected $tokenizer;

    public function setUp()
    {
        $this->tokenizer = new Tokenizer;
    }

    protected function assertTokens($message, array $expected)
    {
        $tokens = $this->tokenizer->getTokens("{$message}'");

        $expected[] = new Token(Token::TERMINATOR, "'");

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

    public function testBasic()
    {
        $this->assertTokens("RFF+PD:50515", [
            new Token(Token::CONTENT, "RFF"),
            new Token(Token::DATA_SEPARATOR, "+"),
            new Token(Token::CONTENT, "PD"),
            new Token(Token::COMPONENT_SEPARATOR, ":"),
            new Token(Token::CONTENT, "50515"),
        ]);
    }

    public function testEscape()
    {
        $this->assertTokens("RFF+PD?:5", [
            new Token(Token::CONTENT, "RFF"),
            new Token(Token::DATA_SEPARATOR, "+"),
            new Token(Token::CONTENT, "PD:5"),
        ]);
    }
    public function testDoubleEscape()
    {
        $this->assertTokens("RFF+PD??:5", [
            new Token(Token::CONTENT, "RFF"),
            new Token(Token::DATA_SEPARATOR, "+"),
            new Token(Token::CONTENT, "PD?"),
            new Token(Token::COMPONENT_SEPARATOR, ":"),
            new Token(Token::CONTENT, "5"),
        ]);
    }
    public function testTripleEscape()
    {
        $this->assertTokens("RFF+PD???:5", [
            new Token(Token::CONTENT, "RFF"),
            new Token(Token::DATA_SEPARATOR, "+"),
            new Token(Token::CONTENT, "PD?:5"),
        ]);
    }
    public function testQuadrupleEscape()
    {
        $this->assertTokens("RFF+PD????:5", [
            new Token(Token::CONTENT, "RFF"),
            new Token(Token::DATA_SEPARATOR, "+"),
            new Token(Token::CONTENT, "PD??"),
            new Token(Token::COMPONENT_SEPARATOR, ":"),
            new Token(Token::CONTENT, "5"),
        ]);
    }

    public function testIgnoreWhitespace()
    {
        $this->assertTokens("RFF:5'\nDEF:6", [
            new Token(Token::CONTENT, "RFF"),
            new Token(Token::COMPONENT_SEPARATOR, ":"),
            new Token(Token::CONTENT, "5"),
            new Token(Token::TERMINATOR, "'"),
            new Token(Token::CONTENT, "DEF"),
            new Token(Token::COMPONENT_SEPARATOR, ":"),
            new Token(Token::CONTENT, "6"),
        ]);
    }

    public function testNoTerminator()
    {
        $this->setExpectedException("RuntimeException", "Unexpected end of EDI message");
        $this->tokenizer->getTokens("TEST");
    }
}

Add some tests for the Tokenizer

Add some tests for the Tokenizer


<?php

require_once "GoogleSpreadsheets.php";

$gs = new GoogleSpreadsheets();
// $gs->login("email@gmail.com", "");
$gs->setAuth("auth key");
$gs->key = "spreadsheetkey";
$gs->ws = "worksheetkey";
// $gs->getSpreadsheet("Test Data", "Sheet1");
$gs->getCellFeed();
$gs->getColumnHeads();
$gs->getAllRows();
// print_r($gs->rc);
// print_r($gs->colheads);
// print_r($gs->allRows2);
// $gs->deleteRow(11);
// $gs->addRow(array("sync_id"=>"2342423423", "state"=>"Mizoram", "country"=>"India", "sync_ts"=>"233242342"));
// $gs->updateCell("2", "2", "TNTN");
// $gs->updateCell("3", "2", "KA");
// $gs->pushUpdates();

Test code - very primitive code

Test code - very primitive code


<?php
/**
 * Plugin Name: E2E Enable Loopback
 * Description: Plugin to filter http requests to remove the port.
 *
 * @package   Google\Site_Kit
 * @copyright 2020 Google LLC
 * @license   https://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0
 * @link      https://sitekit.withgoogle.com
 */
add_filter(
	'pre_http_request',
	function ( $preempt, $args, $url ) {
		if ( 'localhost' === parse_url( $url, PHP_URL_HOST ) && 9002 === parse_url( $url, PHP_URL_PORT ) ) {
			$args['headers'] = wp_parse_args( array( 'Host' => $url ), $args['headers'] );
			$no_port_url     = str_replace( ':9002', '', $url );
			$preempt         = wp_remote_request( $no_port_url, $args );
		}
		return $preempt;
	},
	10,
	3
);

Add plugin to enable loopback.

Add plugin to enable loopback.


<?php
/**
 * Make first and last name required fields during registration and profile edit.
 */

/**
 * Require first and last names during registration
 *
 * @param array $posted Array of information sent to the form.
 *
 * @return void
 */
function ag_rcp_require_first_and_last_name_registration( $posted ) {
	if( is_user_logged_in() ) {
		return;
	}

	if( empty( $posted['rcp_user_first'] ) ) {
		rcp_errors()->add( 'first_name_required', __( 'Please enter your first name', 'rcp' ), 'register' );
	}

	if( empty( $posted['rcp_user_last'] ) ) {
		rcp_errors()->add( 'last_name_required', __( 'Please enter your last name', 'rcp' ), 'register' );
	}
}

add_action( 'rcp_form_errors', 'ag_rcp_require_first_and_last_name_registration' );

/**
 * Require first and last names during profile edit
 *
 * @param array $posted  Array of information sent to the form.
 * @param int   $user_id ID of the user editing their profile.
 *
 * @return void
 */
function ag_rcp_require_first_and_last_name_profile_edit( $posted, $user_id ) {

	if( empty( $posted['rcp_first_name'] ) ) {
		rcp_errors()->add( 'first_name_required', __( 'Please enter your first name', 'rcp' ) );
	}

	if( empty( $posted['rcp_last_name'] ) ) {
		rcp_errors()->add( 'last_name_required', __( 'Please enter your last name', 'rcp' ) );
	}

}

add_action( 'rcp_edit_profile_form_errors', 'ag_rcp_require_first_and_last_name_profile_edit', 10, 2 );

Add snippet for requiring first and last name


<?php

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

namespace Symfony\Component\DependencyInjection\Tests\ParameterBag;

use PHPUnit\Framework\TestCase;
use Psr\Container\ContainerInterface;
use Symfony\Component\DependencyInjection\Container;
use Symfony\Component\DependencyInjection\ParameterBag\ContainerBag;
use Symfony\Component\DependencyInjection\ParameterBag\ContainerBagInterface;
use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;

class ContainerBagTest extends TestCase
{
    /** @var ParameterBag */
    private $parameterBag;
    /** @var ContainerBag */
    private $containerBag;

    public function setUp()
    {
        $this->parameterBag = new ParameterBag(array('foo' => 'value'));
        $this->containerBag = new ContainerBag(new Container($this->parameterBag));
    }

    public function testGetAllParameters()
    {
        $this->assertSame(array('foo' => 'value'), $this->containerBag->all());
    }

    public function testHasAParameter()
    {
        $this->assertTrue($this->containerBag->has('foo'));
        $this->assertFalse($this->containerBag->has('bar'));
    }

    public function testGetParameter()
    {
        $this->assertSame('value', $this->containerBag->get('foo'));
    }

    /**
     * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
     */
    public function testGetParameterNotFound()
    {
        $this->containerBag->get('bar');
    }

    public function testInstanceOf()
    {
        $this->assertInstanceOf(FrozenParameterBag::class, $this->containerBag);
        $this->assertInstanceOf(ContainerBagInterface::class, $this->containerBag);
        $this->assertInstanceOf(ContainerInterface::class, $this->containerBag);
    }
}

Add tests on the ContainerBag

Add tests on the ContainerBag


<?php

namespace SimpleSAML\Logger;

/**
 * A logging handler that outputs all messages to standard error.
 *
 * @author Jaime Perez Crespo, UNINETT AS <jaime.perez@uninett.no>
 * @package SimpleSAMLphp
 */
class StandardError extends \SimpleSAML_Logger_LoggingHandlerFile
{

    /**
     * StandardError constructor.
     *
     * It runs the parent constructor and sets the log file to be the standard error descriptor.
     */
    public function __construct()
    {
        parent::__construct();
        $this->logFile = 'php://stderr';
    }
}

Add a new logger class that logs all messages to standard error.


<?php

use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;

class SyncCrontab extends Command {

	/**
	 * The console command name.
	 *
	 * @var string
	 */
	protected $name = 'crontab:sync';

	/**
	 * The console command description.
	 *
	 * @var string
	 */
	protected $description = 'Sync db with cnf file';

	/**
	 * Create a new command instance.
	 *
	 * @return void
	 */
	public function __construct()
	{
		parent::__construct();
	}

	/**
	 * Execute the console command.
	 *
	 * @return void
	 */
	public function fire()
	{
		//
	}

	/**
	 * Get the console command arguments.
	 *
	 * @return array
	 */
	protected function getArguments()
	{
		return array();
	}

	/**
	 * Get the console command options.
	 *
	 * @return array
	 */
	protected function getOptions()
	{
		return array();
	}

}

Add a command to sync the files with db values


<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class USerCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'hcms:user {--create-admin} {--name=} {--email=} {--username=} {--password=}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Creates admin users.';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();

    }

    public function handle(){

        $this->line("*****Administrator creation*****".PHP_EOL);

        if(!\App\HorizontCMS::isInstalled()){
            $this->info("HorizontCMS is not installed!");
            return -1;
        }

        $admin['name'] = empty($this->option("name"))? $this->ask('Name') : $this->option("name");
        $admin['email'] = empty($this->option("email"))? $this->ask('Email') : $this->option("email") ;
        $admin['username'] = empty($this->option("username"))? $this->ask('Username') : $this->option("username");
        $admin['password'] = empty($this->option("password"))? $this->secret('Password') : $this->option("password");

        try{

            $user = new \App\Model\User();
            $user->name = $admin["name"];
            $user->email = $admin['email'];
            $user->username =  $admin['username'];
            $user->slug = str_slug($admin['username']);
            $user->password = $admin['password'];
            $user->role_id = 6;
            $user->active = 1;

            $user->save();

            $this->info("User ".$user->username." created successfully!");
        }catch(\Exception $e){
            $this->error($e->getMessage());
        }

    }

}

Create admin user from CLI command added


<?php
/**
 * contentinum - accessibility websites
 *
 * LICENSE
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * @category contentinum components
 * @package Mapper
 * @author Michael Jochum, michael.jochum@jochum-mediaservices.de
 * @copyright Copyright (c) 2009-2013 jochum-mediaservices, Katja Jochum (http://www.jochum-mediaservices.de)
 * @license http://www.opensource.org/licenses/bsd-license
 * @since contentinum version 5.0
 * @link      https://github.com/Mikel1961/contentinum-components
 * @version   1.0.0
 */
namespace ContentinumComponents\Entity\Exeption;

/**
 * Exeption invalid values or parameters are given
 * @author Michael Jochum, michael.jochum@jochum-mediaservices.de
 *
 */
class InvalidValueToolsException extends \InvalidArgumentException
{
}

Add a exception in contentinum components tools package


<?php

require_once 'Swat/SwatDisclosure.php';
require_once 'Swat/SwatHtmlTag.php';
require_once 'YUI/YUI.php';

/**
 * A frame-like container to show and hide child widgets
 *
 * @package   Swat
 * @copyright 2006 silverorange
 * @license   http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
 */
class SwatFrameDisclosure extends SwatDisclosure
{
	// {{{ public function __construct()

	/**
	 * Creates a new frame disclosure container
	 *
	 * @param string $id a non-visible unique id for this widget.
	 *
	 * @see SwatWidget::__construct()
	 */
	public function __construct($id = null)
	{
		parent::__construct($id);

		$this->addStyleSheet('packages/swat/styles/swat-frame-disclosure.css',
			Swat::PACKAGE_ID);
	}

	// }}}
	// {{{ public function display()

	/**
	 * Displays this frame disclosure container
	 *
	 * Creates appropriate divs and outputs closed or opened based on the
	 * initial state.
	 *
	 * The disclosure is always displayed as opened in case the user has
	 * JavaScript turned off.
	 */
	public function display()
	{
		if (!$this->visible)
			return;

		$header_tag = new SwatHtmlTag('h2');
		$header_tag->class = 'swat-frame-title';

		$control_div = $this->getControlDivTag();
		$anchor = $this->getAnchorTag();
		$input = $this->getInputTag();
		$img = $this->getImgTag();
		$animate_div = $this->getAnimateDivTag();

		$container_div = $this->getContainerDivTag();
		$container_div->class.= ' swat-frame-contents';

		$control_div->open();
		$header_tag->open();
		$anchor->open();
		$input->display();
		$img->display();
		echo ' ';
		$anchor->displayContent();
		$anchor->close();
		$header_tag->close();

		$container_div->open();
		$animate_div->open();
		$this->displayChildren();
		$animate_div->close();
		$container_div->close();

		$this->displayInlineJavaScript($this->getInlineJavascript());

		$control_div->close();
	}

	// }}}
	// {{{ protected function getCSSClassNames()

	/**
	 * Gets the array of CSS classes that are applied to this disclosure
	 *
	 * @return array the array of CSS classes that are applied to this
	 *                disclosure.
	 */
	protected function getCSSClassNames()
	{
		$classes = array();
		$classes[] = 'swat-frame';
		$classes[] = 'swat-disclosure-control-opened';
		$classes[] = 'swat-frame-disclosure';
		$classes = array_merge($classes, $this->classes);
		return $classes;
	}

	// }}}
}

?>

Add a new container object, a subclass of SwatDisclosure that looks like a SwatFrame.

svn commit r13487


<?php

namespace Kibo\Phast\Parsing\HTML;

use Kibo\Phast\Parsing\HTML\HTMLStreamElements\ClosingTag;
use Kibo\Phast\Parsing\HTML\HTMLStreamElements\Element;
use Kibo\Phast\Parsing\HTML\HTMLStreamElements\Tag;

class PCRETokenizerTest extends \PHPUnit_Framework_TestCase {

    public function testSimpleDocument() {
        $html = "
            <!doctype html>

            <title>Hello, World!</title>

        ";

        $tokenizer = new PCRETokenizer();
        $tokens = $tokenizer->tokenize($html);

        $this->checkTokens([
            [Tag::class, '<!doctype html>'],
            [Tag::class, ''],
            [Tag::class, ''],
            [Tag::class, '<title>'],
            [Element::class, 'Hello, World!'],
            [ClosingTag::class, '</title>'],
            [ClosingTag::class, ''],
            [Tag::class, ''],
            [ClosingTag::class, ''],
            [ClosingTag::class, '']
        ], $tokens);
    }

    private function checkTokens(array $expected, \Traversable $actual) {
        foreach ($actual as $token) {
            if ($token instanceof Element && trim((string) $token) === '') {
                continue;
            }
            $this->assertNotEmpty($expected);
            $expectedToken = array_shift($expected);
            $this->assertEquals($expectedToken, [get_class($token), (string) $token]);
        }
        $this->assertEmpty($expected);
    }

}

Add a simple test for the PCRETokenizer

Add a simple test for the PCRETokenizer


<?php // basic (and dumb) HTTP client

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

// This is a very simple HTTP client that just prints the response without parsing.

use Amp\ByteStream\ResourceOutputStream;
use Amp\Loop;
use function Amp\asyncCoroutine;
use function Amp\Socket\connect;
use function Amp\Socket\cryptoConnect;
use Amp\Socket\Socket;
use Amp\Uri\Uri;

Loop::run(function () use ($argv) {
    $stdout = new ResourceOutputStream(STDOUT);

    if (count($argv) !== 2) {
        yield $stdout->write("Usage: examples/simple-http-client.php url" . PHP_EOL);
        exit(1);
    }

    $uri = new Uri($argv[1]);
    $host = $uri->getHost();

    if ($uri->getScheme() === "https") {
        /** @var Socket $socket */
        $socket = yield cryptoConnect("tcp://" . $host . ":" . $uri->getPort());
    } else {
        /** @var Socket $socket */
        $socket = yield connect("tcp://" . $host . ":" . $uri->getPort());
    }

    yield $socket->write("GET {$uri} HTTP/1.1\r\nHost: $host\r\nConnection: close\r\n\r\n");
    yield Amp\ByteStream\pipe($socket, $stdout);
});

Add simple HTTP client as example

Add simple HTTP client as example


<?php
/**
 * @author           Pierre-Henry Soria <hello@ph7cms.com>
 * @copyright        (c) 2017-2018, Pierre-Henry Soria. All Rights Reserved.
 * @license          GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
 * @package          PH7 / Test / Unit / Framework / Mvc/ Request
 */

namespace PH7\Test\Unit\Framework\Mvc\Request;

use PH7\Framework\Mvc\Request\Http as HttpRequest;
use PHPUnit_Framework_TestCase;

class HttpTest extends PHPUnit_Framework_TestCase
{
    /** @var HttpRequest */
    private $oHttpRequest;

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

        $this->oHttpRequest = new HttpRequest;
    }

    public function testGetMethodRequestWithIntCasting()
    {
        $_GET['string_id'] = '123';

        $sActual = $this->oHttpRequest->get('string_id', 'int');

        $this->assertSame(123, $sActual);
    }
}

Add new unit test to check the casting feature of HttpRequest


<?php

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

?>

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

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

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

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

Fix grouped campaign display with new page container.


<!doctype html>
<html lang="{{ config('app.locale') }}">
<head>
    <meta charset="utf-8" />
    <title>@yield('title', config('app.name'))</title>

    {{-- Meta Data --}}
    @include('cortex/foundation::common.partials.meta')
    @stack('head-elements')

    {{-- Styles --}}
    <link href="{{ mix('css/vendor.css', 'assets') }}" rel="stylesheet">
    <link href="{{ mix('css/theme-adminarea.css', 'assets') }}" rel="stylesheet">
    <link href="{{ mix('css/app.css', 'assets') }}" rel="stylesheet">
    @stack('styles')

    {{-- Scripts --}}
    <script>
        window.Laravel = <?php echo json_encode(['csrfToken' => csrf_token()]); ?>;
        window.Accessarea = "<?php echo request('accessarea'); ?>";
    </script>
    <script src="{{ mix('js/manifest.js', 'assets') }}" defer></script>
    <script src="{{ mix('js/vendor.js', 'assets') }}" defer></script>
    @stack('vendor-scripts')
    <script src="{{ mix('js/app.js', 'assets') }}" defer></script>
</head>
<body class="hold-transition login-page">
    {{-- Main content --}}
    <div class="wrapper">

        @yield('content')

    </div>

    {{-- Scripts --}}
    @stack('inline-scripts')

    {{-- Alerts --}}
    @alerts('default')
</body>
</html>

Add new adminarea auth layout

Add new adminarea auth layout


<?php
/**
 * Go! AOP framework
 *
 * @copyright Copyright 2014, Lisachenko Alexander <lisachenko.it@gmail.com>
 *
 * This source file is subject to the license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Go\Aop;

/**
 * Interface-enumeration of framework features to use in checking and configuration
 */
interface Features
{
    /**
     * Enables interception of system function.
     * By default this feature is disabled, because this option is very expensive.
     */
    const INTERCEPT_FUNCTIONS = 1;

    /**
     * Enables usage of traits and introductions as well, available since PHP5.4
     */
    const USE_TRAIT = 2;

    /**
     * Allows to use closures with binding, available since PHP5.4
     */
    const USE_CLOSURE = 4;

    /**
     * Enables usage of splat '...' operator, available since PHP5.6
     */
    const USE_SPLAT_OPERATOR = 8;

    /**
     * Do not check the cache presence and assume that cache is already prepared
     *
     * This flag is usable for read-only file systems (GAE, phar, etc)
     */
    const PREBUILT_CACHE = 16;
}

Add features enumeration to use instead of associative keys in the configuration


<?php

namespace Rusty\Tests;

use Rusty\PragmaParser;

class PragmaParserTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider inputProvider
     */
    public function testItParsesPragmaDirectives(string $input, array $expectedDirectives)
    {
        $parser = new PragmaParser();

        $this->assertEquals($expectedDirectives, $parser->getPragmaDirectives($input));
    }

    public function inputProvider()
    {
        return [
            [ '', [] ],

            // known directives
            [ 'ignore', [PragmaParser::IGNORE] ],
            [ 'no_run', [PragmaParser::NO_RUN] ],
            [ 'should_throw', [PragmaParser::SHOULD_THROW] ],

            // unknown directives are silently ignored
            [ 'unknown_directive', [] ],

            // it makes no sense (for the moment), but several directives can be recognized
            [ 'no_run should_throw', [PragmaParser::NO_RUN, PragmaParser::SHOULD_THROW] ],
        ];
    }
}

Add a few tests for the PragmaParser class


<?php
require_once '../../src/apiClient.php';
require_once '../../src/contrib/apiWebfontsService.php';

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

// Visit https://code.google.com/apis/console?api=webfonts
// to generate your developer key.
// $client->setDeveloperKey('insert_your_developer_key');
$service = new apiWebfontsService($client);
$fonts = $service->webfonts->listWebfonts();
print "
Fonts

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

Add a sample application for the webfonts API.

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


<?php

namespace AmpProject\Optimizer\Transformer;

use AmpProject\Dom\Document;
use AmpProject\Optimizer\Error;
use AmpProject\Optimizer\ErrorCollection;
use AmpProject\Tests\ErrorComparison;
use AmpProject\Tests\MarkupComparison;
use AmpProject\Tests\TestMarkup;
use PHPUnit\Framework\TestCase;

/**
 * Test the BrowserHints transformer.
 *
 * @package ampproject/amp-toolbox
 */
final class BrowserHintsTest extends TestCase
{
    use ErrorComparison;
    use MarkupComparison;

    /**
     * Provide the data to test the transform() method.
     *
     * @return array[] Associative array of data arrays.
     */
    public function dataTransform()
    {
        $input = static function ($head, $hints = '') {
            return TestMarkup::DOCTYPE . ''
                   . TestMarkup::META_CHARSET . TestMarkup::META_VIEWPORT . $hints . TestMarkup::SCRIPT_AMPRUNTIME
                   . TestMarkup::LINK_FAVICON . TestMarkup::LINK_CANONICAL . TestMarkup::STYLE_AMPBOILERPLATE . TestMarkup::NOSCRIPT_AMPBOILERPLATE
                   . $head
                   . '';
        };

        $output = static function ($head, $hints = '') {
            return TestMarkup::DOCTYPE . ''
                   . TestMarkup::META_CHARSET . TestMarkup::META_VIEWPORT . $hints . TestMarkup::SCRIPT_AMPRUNTIME
                   . TestMarkup::LINK_FAVICON . TestMarkup::LINK_CANONICAL . TestMarkup::STYLE_AMPBOILERPLATE . TestMarkup::NOSCRIPT_AMPBOILERPLATE
                   . $head
                   . '';
        };

        return [
            'documents with google fonts do preconnect' => [
                $input(
                    '<link href="https://fonts.googleapis.com/css?family=Karla&display=swap" rel="stylesheet">'
                ),
                $output(
                    '<link href="https://fonts.googleapis.com/css?family=Karla&display=swap" rel="stylesheet">',
                    '<link crossorigin href="https://fonts.gstatic.com/" rel="dns-prefetch preconnect">'
                ),
            ],

            'documents without google fonts do not preconnect' => [
                $input(''),
                $output(''),
            ],
        ];
    }

    /**
     * Test the transform() method.
     *
     * @covers       \AmpProject\Optimizer\Transformer\BrowserHints::transform()
     * @dataProvider dataTransform()
     *
     * @param string                  $source         String of source HTML.
     * @param string                  $expectedHtml   String of expected HTML output.
     * @param ErrorCollection|Error[] $expectedErrors Set of expected errors.
     * @param array                   $config         Configuration data to use.
     */
    public function testTransform($source, $expectedHtml, $expectedErrors = [], $config = [])
    {
        $document    = Document::fromHtml($source);
        $transformer = new BrowserHints();
        $errors      = new ErrorCollection();

        $transformer->transform($document, $errors);

        $this->assertSimilarMarkup($expectedHtml, $document->saveHTML());
        $this->assertSameErrors($expectedErrors, $errors);
    }
}

Add tests for Google Fonts preconnect

Add tests for Google Fonts preconnect


<?php
namespace Hipay\SilexIntegration\Command;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Console\Command\Command;

/**
 * File AbstractCommand.php
 *
 * @author    Ivanis Kouamé <ivanis.kouame@smile.fr>
 * @copyright 2015 Smile
 */
abstract class AbstractCommand extends Command
{
    /** @var EntityManagerInterface */
    protected $entityManager;

    /**
     * AbstractCommand constructor.
     * @param $entityManager
     */
    public function __construct(EntityManagerInterface $entityManager)
    {
        parent::__construct();
        $this->entityManager = $entityManager;
    }

}

Add abstract command class to regroup common class members


<?php
$currentPage = "link_3";
require_once("config.php");
?>
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <title>AdaptiveNav v2.0 - Responsive Navigation Menu</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <?php echo "\t\n"; ?>

    <link rel="stylesheet" type="text/css" href="<?php echo $config['paths']['css']['expanded'] . $config['info']['cacheVer']; ?>">

    <?php require_once(TEMPLATES_PATH . "/header.php"); ?>

Link 3

    <?php require_once(TEMPLATES_PATH . "/loadScripts.php"); ?>

Add example page for link 3

Add example page for link 3


<?php

namespace Mdd\QueryBuilder\Escapers;

use Mdd\QueryBuilder\Escaper;
use Doctrine\DBAL\Driver\Connection;

class DoctrineDbalAdapter implements Escaper
{
    private
        $db;

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

    public function escape($value)
    {
        return $this->db->quote($value);
    }
}

Add escaper implementation for Doctrine DBAL


<?php

namespace AmCharts\Chart\Axis;

class ValueTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var Value
     */
    protected $axis;

    public function setUp()
    {
        $this->axis = new Value;
    }

    public function testSetLabelsEnabled()
    {
        $this->axis->setLabelsEnabled(true);
        $this->assertTrue($this->axis->isLabelsEnabled());
    }

    public function testToArray()
    {
        $this->assertCount(2, $this->axis->toArray());
    }
}

Add unit tests to AmCharts\Chart\Axis\Value class


<?php

/**
 * Part of the Stripe package.
 *
 * NOTICE OF LICENSE
 *
 * Licensed under the 3-clause BSD License.
 *
 * This source file is subject to the 3-clause BSD License that is
 * bundled with this package in the LICENSE file.
 *
 * @package    Stripe
 * @version    2.1.3
 * @author     Cartalyst LLC
 * @license    BSD License (3-clause)
 * @copyright  (c) 2011-2018, Cartalyst LLC
 * @link       http://cartalyst.com
 */

namespace Cartalyst\Stripe\Api;

class ScheduledQueries extends Api
{
    /**
     * Retrieves an existing scheduled query.
     *
     * @param  string  $scheduleQueryRun
     * @return array
     */
    public function find($scheduleQueryRun)
    {
        return $this->_get("sigma/scheduled_query_runs/{$scheduleQueryRun}");
    }

    /**
     * Returns a list of all the scheduled queries.
     *
     * @param  array  $parameters
     * @return array
     */
    public function all(array $parameters = [])
    {
        return $this->_get('sigma/scheduled_query_runs', $parameters);
    }
}

Add Sigma Scheduled Queries API

chore: Add Sigma Scheduled Queries API

Signed-off-by: Bruno Gaspar <367518169777ee9ae71cfcee56304a59ac5423c1@gmail.com>


<?php

class CurlException extends Exception {

  private $curl_headers;

  public function __construct($message, $code = 0, Exception $previous = null, $headers = null) {
    parent::__construct($message, $code, $previous);
    $this->curl_headers = $headers;
  }

  public function getHeaders() {
    return $this->curl_headers;
  }

}

Add Curl custom exception class

Add Curl custom exception class


<?php

namespace Pulsestorm\Pestle\TestsIntegration;

require_once 'PestleTestIntegration.php';

class GenerateRouteTest extends PestleTestIntegration
{
    const COMMAND = 'generate_route Pulsestorm_HelloWorld frontend pulsestorm_helloworld';

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

    /**
     * Setup the integration test.
     */
    protected function setUp()
    {
        parent::setUp();

        $this->runCommand(GenerateModuleTest::COMMAND);
        $this->result = $this->runCommand();
    }

    /**
     * Check routes declaration file exists.
     *
     * @test
     */
    public function testRoutesFileExists()
    {
        $result = file_exists(__DIR__.'/../app/code/Pulsestorm/HelloWorld/etc/frontend/routes.xml');
        $this->assertTrue($result);
    }

    /**
     * Check module registration file exists.
     *
     * @test
     */
    public function testControllerFileExists()
    {
        $result = file_exists(__DIR__.'/../app/code/Pulsestorm/HelloWorld/Controller/Index/Index.php');
        $this->assertTrue($result);
    }
}

Add Generate Route integration test

ISSUE-119: Add Generate Route integration test


<?php

use Phillip\Assertion;
use Phillip\Exceptions\AssertionFailureException;

/*
 * Test `boolean()` method.
 */
test('Test boolean with true', function ($t) {
    $t->is(true)->boolean();
})
    ->covers(Assertion::class, 'boolean');

test('Test boolean with false', function ($t) {
    $t->is(false)->boolean();
})
    ->covers(Assertion::class, 'boolean');

test('Test boolean with int', function ($t) {
    $t->is(1)->boolean();
})
    ->expect(AssertionFailureException::class, '1 is not a boolean')
    ->covers(Assertion::class, 'boolean');

test('Test boolean with string', function ($t) {
    $t->is('true')->boolean();
})
    ->expect(AssertionFailureException::class, '"true" is not a boolean')
    ->covers(Assertion::class, 'boolean');

/*
 * Test `true()` method
 */

test('Test true with boolean', function ($t) {
    $t->is(true)->true();
})
    ->covers(Assertion::class, 'boolean');

test('Test true with string', function ($t) {
    $t->is('true')->true();
})
    ->expect(AssertionFailureException::class, '"true" is not true')
    ->covers(Assertion::class, 'true');

test('Test true with false boolean', function ($t) {
    $t->is(false)->true();
})
    ->expect(AssertionFailureException::class, 'FALSE is not true')
    ->covers(Assertion::class, 'true');

/*
 * Test `false()` method
 */

test('Test false with boolean', function ($t) {
    $t->is(false)->false();
})
    ->covers(Assertion::class, 'boolean');

test('Test false with string', function ($t) {
    $t->is('false')->false();
})
    ->expect(AssertionFailureException::class, '"false" is not false')
    ->covers(Assertion::class, 'true');

test('Test false with true boolean', function ($t) {
    $t->is(true)->false();
})
    ->expect(AssertionFailureException::class, 'TRUE is not false')
    ->covers(Assertion::class, 'false');

Add tests for new boolean assertions

Add tests for new boolean assertions


<?php

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

class m150406_135109_update_news_table_add_preview_column extends Migration
{
    private $_table = 'news';

    public function up()
    {
        $this->addColumn($this->_table, 'preview', Schema::TYPE_STRING . ' NOT NULL AFTER post');
    }

    public function down()
    {
        $this->dropColumn($this->_table, 'preview');
    }
}

Update news table. Add preview column.

Update news table. Add preview column.


Promote ownCloud

Help spread the word about ownCloud. Tell your friends about your experience.

		 Tweet about ownCloud

		 Share on Facebook

	 Post on Google+

Write a blog post, and get it included in our planet site (ask Tom Needham)

Organise an ownCloud event (talks, meetups, tradeshow booths)

Recommend ownCloud to your company, University or service provider

Work towards new promote page

Work towards new promote page


<?php

use SVG\Rasterization\Renderers\SVGRenderer;

/**
 * @SuppressWarnings(PHPMD)
 */
class SVGRendererTest extends PHPUnit_Framework_TestCase
{
    public function testRender()
    {
        $rast = new \SVG\Rasterization\SVGRasterizer(10, 20, null, 100, 200);
        $options = array(
            'option1' => 'option1-value',
            'option2' => 'option2-value',
        );
        $node = $this->getMockForAbstractClass('\SVG\Nodes\SVGNode');

        $params = array(
            'param1' => 'param1-value',
            'param2' => 'param2-value',
        );

        // should call prepareRenderParams with correct arguments
        $obj = $this->getMockForAbstractClass('\SVG\Rasterization\Renderers\SVGRenderer');
        $obj->expects($this->once())->method('prepareRenderParams')->with(
            $this->identicalTo($rast),
            $this->identicalTo($options)
        )->willReturn($params);
        $obj->render($rast, $options, $node);

        // should call renderFill with correct fill color
        $node->setStyle('fill', '#AAAAAA');
        $obj = $this->getMockForAbstractClass('\SVG\Rasterization\Renderers\SVGRenderer');
        $obj->method('prepareRenderParams')->willReturn($params);
        $obj->expects($this->once())->method('renderFill')->with(
            $this->isType('resource'),
            $this->identicalTo($params),
            $this->identicalTo(0xAAAAAA)
        );
        $obj->render($rast, $options, $node);

        // should not call renderFill with 'fill: none' style
        $node->setStyle('fill', 'none');
        $obj = $this->getMockForAbstractClass('\SVG\Rasterization\Renderers\SVGRenderer');
        $obj->method('prepareRenderParams')->willReturn($params);
        $obj->expects($this->never())->method('renderFill');
        $obj->render($rast, $options, $node);

        // should call renderStroke with correct stroke color and width
        $node->setStyle('stroke', '#BBBBBB');
        $node->setStyle('stroke-width', '2px');
        $obj = $this->getMockForAbstractClass('\SVG\Rasterization\Renderers\SVGRenderer');
        $obj->method('prepareRenderParams')->willReturn($params);
        $obj->expects($this->once())->method('renderStroke')->with(
            $this->isType('resource'),
            $this->identicalTo($params),
            $this->identicalTo(0xBBBBBB),
            $this->equalTo(20)
        );
        $obj->render($rast, $options, $node);

        // should not call renderStroke with 'stroke: none' style
        $node->setStyle('stroke', 'none');
        $obj = $this->getMockForAbstractClass('\SVG\Rasterization\Renderers\SVGRenderer');
        $obj->method('prepareRenderParams')->willReturn($params);
        $obj->expects($this->never())->method('renderStroke');
        $obj->render($rast, $options, $node);

        imagedestroy($rast->getImage());
    }
}

Add unit test for SVGRenderer::render

Add unit test for SVGRenderer::render


<?php
$input = array("red", "green", "blue", "yellow");
array_splice($input, 2);
// $input is now array("red", "green")

$input = array("red", "green", "blue", "yellow");
array_splice($input, 1, -1);
// $input is now array("red", "yellow")

$input = array("red", "green", "blue", "yellow");
array_splice($input, 1, count($input), "orange");
// $input is now array("red", "orange")

$input = array("red", "green", "blue", "yellow");
array_splice($input, -1, 1, array("black", "maroon"));
// $input is now array("red", "green",
//          "blue", "black", "maroon")

$input = array("red", "green", "blue", "yellow");
array_splice($input, 3, 0, "purple");
// $input is now array("red", "green",
//          "blue", "purple", "yellow");
?>

Remove a portion of the array and replace it with something else


<?php

/**
 * Generate Legislators Menu
 *
 * Query the database to generate a list of all legislators, to update the menu.
 * The resulting list is sent to stdout.
 **/

$database = new Database;
$db = $database->connect_mysqli();

/*
 * Get a list of all legislators.
 */
$sql = 'SELECT name_formatted, shortname, chamber
        FROM representatives
        WHERE date_ended IS NOT NULL OR date_ended >= now()
        ORDER BY chamber ASC, name ASC';
$result = mysqli_query($db, $sql);

$legislators = array('house' => array(), 'senate' => array());

/*
 * Build up an HTML-formatted array of legislators by chamber.
 */
while ($legislator = mysqli_fetch_assoc($result))
{

    $legislator = array_map('stripslashes', $legislator);
    $legislators[$legislator{'chamber'}][] = '
' . $legislator . '
';

}

/*
 *
 */
echo '

House »

A–Z »

                ' . implode("\t", $legislators['house']) . '

Senate »

A–Z »

                ' . implode("\t", $legislators['senate']) . '

';

Add rudimentary functionality to create legislators menu

Toward #296, this is really basic functionality that will create the legislators menu. It's not grouping alphabetically (that's going to require some thinking), but it's a start.


    <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">

    </button>
    {{ $brand or config('app.name', 'Laravel Application') }}

            @if (isset($menu))
                @foreach ($menu as $link)
                    @if (array_key_exists('links', $link))

                            {{ $link['title'] }}

                                @foreach ($link['links'] as $sublink)

{{ $sublink['title'] }}

                                @endforeach

                    @else

{{ $link['title'] }}

                    @endif
                @endforeach
            @endif
            @yield('navigation')
            @yield('secondary_navigation')
            @if (\Auth::check())

{{ \Auth::user()->name }}

            @endif
            @yield('navigation')

Create a bootstrap 4 configurable navbar.


<?php

use Doctrine\DBAL\Configuration;
use Doctrine\Common\EventManager;
use Doctrine\DBAL\Driver\PDOMySql\Driver;
use Pharako\DBAL\Connection;

class LargeDataCest
{
    public function _before(UnitTester $I)
    {
        $params = $I->getDbConfig();

        $this->dbal = new Connection(
            $params,
            new Driver(),
            new Configuration(),
            new EventManager()
        );

        $this
            ->dbal
            ->getConfiguration()
            ->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger());
    }

    public function _after(UnitTester $I)
    {
    }

    /**
     * @group insert
     * @group multiple
     * @group data
     */
    public function largeDataInsert(UnitTester $I)
    {
        $heroes = [];
        $n = 20000;
        for ($i = 0; $i < $n; $i++) {
            $heroes[] = [
                'name' => sq("Tupac Qatari $i -"),
                'an_integer' => rand(0, $n)
            ];
        }

        $this->dbal->insert('heroes', $heroes);

        foreach ($heroes as $hero) {
            $I->seeInDatabase('heroes', $hero);
        }
    }

    /**
     * All fields, except unique key (`name`), get updated
     * @group upsert
     * @group multiple
     * @group data
     */
    public function largeDataUpsert(UnitTester $I)
    {
        $heroes = [];
        $n = 20000;
        for ($i = 0; $i < $n; $i++) {
            $heroes[] = [
                'name' => sq("Tupac Qatari $i -"),
                'an_integer' => rand(0, $n)
            ];
        }

        $this->dbal->upsert('heroes', $heroes);

        foreach ($heroes as $hero) {
            $I->seeInDatabase('heroes', $hero);
        }
    }
}

Add test for large amounts of data

Add test for large amounts of data


<?php

require_once 'activity_data_source.php';

$db = init_db();

$team_ids = isset($_GET['team_id']) ? csv_to_string_array($_GET['team_id']) : array();
$problem_ids = isset($_GET['problem_id']) ? string_to_alpha_array($_GET['problem_id']) : array();
$granularity = isset($_GET['granularity']) ? intval($_GET['granularity']) : 5;
$granularity = max($granularity, 1);

$response = array();
$response['granularity'] = $granularity;

$problems = array();

$submissions = get_submission_activity($db, $team_ids, $problem_ids);
$sub = array();
foreach ($submissions as $judgment => $submission_list) {
    foreach ($submission_list as $submission) {
        if (!isset($sub[$submission['problem_id']]))
            $sub[$submission['problem_id']] = array();
        if (!isset($sub[$submission['problem_id']][$judgment]))
            $sub[$submission['problem_id']][$judgment] = array();
        $sub[$submission['problem_id']][$judgment][]
            = array(
                    'contest_time' => $submission['contest_time'],
                    'team_id' => $submission['team_id'],
                    'lang_id' => $submission['lang_id'],
                    'submission_id' => $submission['submission_id'],
                    );
    }
}

$edit_activity = get_edit_activity($db, $team_ids, $problem_ids, $granularity);
foreach ($edit_activity as $problem => $raw_activity) {
    $activity = array();
    foreach ($raw_activity as $minute => $edits) {
        $activity[] = array(
                            'contest_time' => $minute,
                            'num_edited_lines' => $edits,
                            );
    }
    $problems[] = array(
                        'problem_id' => $problem,
                        'edit_summary' => $activity,
                        'submissions' => isset($sub[$problem]) ? $sub[$problem] : array(),
                        );
}

$response['problems'] = $problems;

echo json_encode($response);

Add interface for retrieval of code activity data (for drawing graphs)


<?php

namespace ServerGrove\Bundle\TranslationEditorBundle\Translation\Exporter;

use Doctrine\Common\Collections\ArrayCollection;

/**
 * ExporterInterface
 *
 * @author Guilherme Blanco <guilhermeblanco@hotmail.com>
 */
interface ExporterInterface
{
    /**
     * Retrieve the file extension
     *
     * @return string
     */
    public function getFileExtension();

    /**
     * Exports the translation entries.
     *
     * @param string $filePath
     * @param \Doctrine\Common\Collections\ArrayCollection $translationList
     */
    public function exportFile($filePath, ArrayCollection $translationList);
}

<?php

namespace ServerGrove\Bundle\TranslationEditorBundle\Translation\Exporter;

use Doctrine\Common\Collections\ArrayCollection;

/**
 * ExporterInterface
 *
 * @author Guilherme Blanco <guilhermeblanco@hotmail.com>
 */
interface ExporterInterface
{
    /**
     * Retrieve the file extension
     *
     * @return string|array either a single string for a single extension or an array for multiple extensions for legacy support.
     */
    public function getFileExtension();

    /**
     * Exports the translation entries.
     *
     * @param string $filePath
     * @param \Doctrine\Common\Collections\ArrayCollection $translationList
     */
    public function exportFile($filePath, ArrayCollection $translationList);
}

Change the interface to allow "getFileExtension" to return either a string or an array.


<?php

namespace Orbt\ResourceMirror\Tests;

use Orbt\ResourceMirror\ResourceMirror;
use Symfony\Component\EventDispatcher\EventDispatcher;

class ResourceMirrorTest extends \PHPUnit_Framework_TestCase
{
    /**
     * A resource mirror can be instantiated.
     */
    public function testCreate()
    {
        $mirror = new ResourceMirror(new EventDispatcher(), 'http://example.com/');
        $this->assertInstanceOf('Orbt\ResourceMirror\ResourceMirror', $mirror);
    }

    /**
     * A resource mirror returns the base URL.
     */
    public function testGetBaseUrl()
    {
        $mirror = new ResourceMirror(new EventDispatcher(), 'http://example.com/');
        $this->assertEquals('http://example.com/', $mirror->getBaseUrl());
    }
}

Add test for resource mirror.

Add test for resource mirror.


<?php

require('./tempodb.php');
date_default_timezone_set("America/Chicago");

$tdb = new TempoDB("api-key", "api-secret");

$result = $tdb->get_series();
var_dump($result);

?>

Add examples for the get_series call

Add examples for the get_series call


<?php
namespace Sil\DevPortal\tests\unit;

class CostSchemeTest extends \CDbTestCase
{
    public $fixtures = array(
        'costSchemes' => 'CostScheme',
    );

    public function testHasAtLeastOnePrice()
    {
        $this->markTestIncomplete('Test not yet written.');
    }

    public function testHasBothOrNeither()
    {
        $this->markTestIncomplete('Test not yet written.');
    }
}

Add basic test class for CostScheme model.


<?php

use Mimic\Functional as F;

/**
 * Unit Test for every Mimic library function.
 *
 * @since 0.1.0
 */
class EveryFuncTest extends PHPUnit_Framework_TestCase {
	public function dataProvider_Passthrough() {
		return array( array(true), array(false) );
	}

	/**
	 * @dataProvider dataProvider_Passthrough
	 * @covers ::Mimic\Functional\every
	 */
	public function testPassthrough($passthrough) {
		$self = $this;
		$data = array(1, 1, 1, 1);

		$callback = function($element, $index, $collection) use ($data, $self, $passthrough) {
			$self->assertTrue((is_string($index) || is_numeric($index)), 'index is not correct type');
			$self->assertTrue(array_key_exists($index, $data), 'index does not exist in given data');
			$self->assertEquals($data[$index], $element, 'existing array does not match given element');
			$self->assertEquals($data, $collection, 'given collection does not match data');
			return $passthrough;
		};

		$this->assertEquals($passthrough, F\every($data, $callback));
	}
}

Complete every function unit tests.

Complete every function unit tests.


<?php

namespace Croogo\Acl;

use Acl\AclExtras;
use Cake\Database\Exception;
use Cake\Datasource\ConnectionInterface;
use Cake\ORM\TableRegistry;
use Croogo\Core\Plugin;

class AclGenerator extends AclExtras
{
    public function __construct()
    {
        $this->Aco = TableRegistry::get('Croogo/Acl.Acos');
        $this->_buildPrefixes();
    }

    public function insertAcos(ConnectionInterface $connection)
    {
        $this->Aco->connection($connection);

        $root = $this->_checkNode($this->rootNode, $this->rootNode, null);
        $plugins = Plugin::loaded();
        $this->_processControllers($root);
        $this->_processPrefixes($root);
        $this->_processPlugins($root, $plugins);
    }

    public function out($msg)
    {
        preg_match('/Created Aco node: \<success\>(.*)\<\/success\>/', $msg, $matches);
//        echo($matches[1] . PHP_EOL);
    }

    protected function _checkMethods($className, $controllerName, $node, $pluginPath = null, $prefixPath = null)
    {
        try {
            return parent::_checkMethods($className, $controllerName, $node, $pluginPath, $prefixPath);
        } catch (Exception $exception) {
        }

        return false;
    }
}

Add tool to generate Acls programatically


<?php

namespace Application\Migrations;

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

/**
 * A default value for the `surfconext_representative_approved` column was missing
 * in the Version20181107134447 migration. This is now added.
 *
 * The following default are set for:
 *
 *  | Column                                 | Value          | Matching Service entity constant
 *  |========================================|================|====================================
 *  | surfconext_representative_approved     | no             | Service::SURFCONEXT_APPROVED_NO
 */
class Version20190605093154 extends AbstractMigration
{
    /**
     * @param Schema $schema
     */
    public function up(Schema $schema)
    {
        $this->addSql(
            sprintf(
                'UPDATE service SET
                surfconext_representative_approved = "%s"
                WHERE surfconext_representative_approved IS NULL
                ',
                'no'
            )
        );
    }

    /**
     * @param Schema $schema
     */
    public function down(Schema $schema)
    {
        // Nothing is executed because at this point the state before couldn't be determined
    }
}

Add default value for `representative_approved` column.

A default column was missing what resulted in a service which could
not be saves because a validation error occurred and was not visible
if you tried to save the service with type=institute.


<?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\EngineBlockBundle\EventListener;

use OpenConext\EngineBlockBundle\Authentication\AuthenticationState;
use OpenConext\EngineBlockBundle\Controller\AuthenticationLoopThrottlingController;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;

final class AuthenticationStateInitializer
{
    /**
     * @var Session
     */
    private $session;

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

    public function onKernelController(FilterControllerEvent $event)
    {
        if (!$event->getController()[0] instanceof AuthenticationLoopThrottlingController) {
            return;
        }

        $authenticationState = $this->session->get('authentication_state');
        if ($authenticationState === null) {
            $this->session->set('authentication_state', new AuthenticationState);
        }
    }
}

Add a listener to guarantee initialized AuthenticationState


<?php

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

class AddSlotIdToWorldsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('worlds', function (Blueprint $table) {
            $table->integer('slot_id')->default(1);
        });
    }

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

Add slot ID column to worlds table.

Add slot ID column to worlds table.